@cslug/webhook 0.1.0 → 0.2.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/README.md +5 -2
- package/docs/README.md +40 -3
- package/docs/api.md +11 -0
- package/migrations/00000000_000300_cslug_webhook_inbox.sql +14 -0
- package/package.json +11 -4
- package/src/inbox.ts +82 -0
- package/src/index.ts +5 -4
- package/src/provider.ts +26 -0
- package/src/signature.ts +122 -0
package/README.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# @cslug/webhook
|
|
2
2
|
|
|
3
|
-
Webhook signature verification and an exactly-once
|
|
3
|
+
Webhook signature verification (`verifySignature`, HMAC in constant time, timestamp tolerance) and an exactly-once
|
|
4
|
+
inbox (`WebhookInbox`): an event delivered ten times has one effect. List `WebhookProvider` in
|
|
5
|
+
`bootstrap/providers.ts`.
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
8
|
+
[guide 17](../../guides/17-storage-and-webhooks.md).
|
package/docs/README.md
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
# @cslug/webhook
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
List `WebhookProvider` (after `DatabaseProvider`) in `bootstrap/providers.ts`. It registers the
|
|
4
|
+
`cslug_webhook_inbox` migration (`cslug migrate` creates the table) and `cslug webhooks:replay`.
|
|
5
|
+
The guide is [guide 17](../../../guides/17-storage-and-webhooks.md#webhooks).
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
## Signatures
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// config/webhooks.ts
|
|
11
|
+
export default defineConfig({
|
|
12
|
+
payments: { secret: env.PAYMENTS_WEBHOOK_SECRET, header: 'X-Signature', format: 't={timestamp},v1={signature}', tolerance: '5m' },
|
|
13
|
+
whatsapp: { secret: env.WHATSAPP_APP_SECRET, header: 'X-Hub-Signature-256', format: 'sha256={signature}' },
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
r.post('/webhooks/payments', [PaymentWebhookController, 'handle']).middleware(verifySignature('payments'))
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`verifySignature(name)` reads the raw body (`request.raw()`, cached, so `request.body()` still works), computes the
|
|
20
|
+
HMAC (`algorithm`: `sha256` default, `sha1`, `sha512`; Web Crypto) and compares it in constant time
|
|
21
|
+
(`crypto.subtle.verify`). The header is parsed with `format`: `{signature}` (hex, or base64 with
|
|
22
|
+
`encoding: 'base64'`) and optionally `{timestamp}` (Unix seconds); with a timestamp, `${timestamp}.${rawBody}` is
|
|
23
|
+
signed and the timestamp must be within `tolerance` of `Clock` (default 5 min). A mismatch is a `401` problem
|
|
24
|
+
`webhook.bad_signature`. Other schemes: `verifySignature((request, raw) => boolean)`.
|
|
25
|
+
|
|
26
|
+
In tests, `signWebhook(name, rawBody, { timestamp? })` returns the headers the sender would send:
|
|
27
|
+
`t.post(url).headers(await signWebhook('payments', JSON.stringify(event))).json(event)`.
|
|
28
|
+
|
|
29
|
+
## The inbox
|
|
30
|
+
|
|
31
|
+
`WebhookInbox` (an `@inject` class) stores each `(source, externalId)` once:
|
|
32
|
+
|
|
33
|
+
- `receive(source, externalId, payload, then?)`: in a transaction, `insert … on conflict do nothing`; for a new
|
|
34
|
+
event runs `then` (else the source's processor) in that transaction and returns `true`; a replay returns
|
|
35
|
+
`false` and runs nothing, even under concurrent deliveries. Pair it with a durable job:
|
|
36
|
+
`() => ProcessPaymentEventJob.dispatch({ eventId }).durable()`.
|
|
37
|
+
- `process(source, fn)`: the processor of a source (register it in a provider's `boot()`); used by `receive`
|
|
38
|
+
without `then` and by `replay`.
|
|
39
|
+
- `payload(source, externalId, schema?)`: the stored payload, validated with a `v` schema; `NotFoundError` if absent.
|
|
40
|
+
- `replay(source, externalId)`: run the processor again (`cslug webhooks:replay <source> <id>`), recording
|
|
41
|
+
`replayed_at`.
|
|
42
|
+
- `prune(olderThan, source?)`: delete old events (a delivery after that is processed again). Schedule it with
|
|
43
|
+
`s.call('webhooks:prune', ({ resolve }) => resolve(WebhookInbox).prune('90d')).daily()`.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @cslug/webhook: API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `verifySignature(name \| (request, raw) => boolean)` | Middleware: 401 `webhook.bad_signature` unless signed |
|
|
6
|
+
| `checkSignature(name, request)` | The check itself → boolean |
|
|
7
|
+
| `signWebhook(name, rawBody, { timestamp? })` | Headers that sign `rawBody` as `name` would (tests) |
|
|
8
|
+
| `WebhookSource` | Config `webhooks.<name>`: `secret`, `header`, `algorithm` (`sha256`), `format` (`'{signature}'`), `encoding` (`hex`), `tolerance` (`'5m'`) |
|
|
9
|
+
| `WebhookInbox` | `receive(source, externalId, payload, then?)` → `true` (new) / `false` (replay), `process(source, fn)`, `payload(source, externalId, schema?)`, `replay(source, externalId)`, `prune(olderThan, source?)` |
|
|
10
|
+
| `WebhookProvider` | Registers the `cslug_webhook_inbox` migration and `WebhooksReplayCommand` (`webhooks:replay <source> <externalId>`) |
|
|
11
|
+
| `WEBHOOK_MIGRATIONS` | The migration folder |
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
-- up
|
|
2
|
+
create table cslug_webhook_inbox (
|
|
3
|
+
id uuid primary key,
|
|
4
|
+
source text not null,
|
|
5
|
+
external_id text not null,
|
|
6
|
+
payload jsonb not null,
|
|
7
|
+
received_at timestamptz not null default now(),
|
|
8
|
+
replayed_at timestamptz,
|
|
9
|
+
unique (source, external_id)
|
|
10
|
+
);
|
|
11
|
+
create index cslug_webhook_inbox_received_at_idx on cslug_webhook_inbox (received_at);
|
|
12
|
+
|
|
13
|
+
-- down
|
|
14
|
+
drop table cslug_webhook_inbox;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/webhook",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Webhook signature verification and an exactly-once inbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"src",
|
|
23
|
+
"migrations",
|
|
23
24
|
"docs",
|
|
24
25
|
"stubs",
|
|
25
26
|
"README.md"
|
|
@@ -28,8 +29,14 @@
|
|
|
28
29
|
"bun": ">=1.3.14"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
31
|
-
"@cslug/core": "0.
|
|
32
|
-
"@cslug/http": "0.
|
|
33
|
-
"@cslug/database": "0.
|
|
32
|
+
"@cslug/core": "0.2.0",
|
|
33
|
+
"@cslug/http": "0.2.0",
|
|
34
|
+
"@cslug/database": "0.2.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@cslug/testing": "workspace:*",
|
|
38
|
+
"@cslug/queue": "workspace:*",
|
|
39
|
+
"@cslug/redis": "workspace:*",
|
|
40
|
+
"@cslug/validation": "workspace:*"
|
|
34
41
|
}
|
|
35
42
|
}
|
package/src/inbox.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { Clock, type Duration, inject, NotFoundError, parseDuration } from '@cslug/core'
|
|
3
|
+
import { Database, sql } from '@cslug/database'
|
|
4
|
+
|
|
5
|
+
export const WEBHOOK_MIGRATIONS = join(import.meta.dir, '../migrations')
|
|
6
|
+
|
|
7
|
+
/** What processes an event: run in the receiving transaction, and again by `webhooks:replay`. */
|
|
8
|
+
export type WebhookProcessor = (externalId: string, payload: unknown) => unknown
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Exactly-once receipt of webhook events: each `(source, externalId)` is stored once (`cslug_webhook_inbox`,
|
|
12
|
+
* unique); a replay of the same event does nothing. Respond 200 fast and do the work in a (durable) job.
|
|
13
|
+
*/
|
|
14
|
+
@inject(Database, Clock)
|
|
15
|
+
export class WebhookInbox {
|
|
16
|
+
private readonly processors = new Map<string, WebhookProcessor>()
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
private readonly db: Database,
|
|
20
|
+
private readonly clock: Clock,
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
/** The processor of a source (in a provider's `boot()`), used by `receive()` without `then` and by replays. */
|
|
24
|
+
process(source: string, processor: WebhookProcessor): this {
|
|
25
|
+
this.processors.set(source, processor)
|
|
26
|
+
return this
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Store the event; if it is new, run `then` (else the source's processor) in the same transaction, so a durable
|
|
31
|
+
* job and the inbox row commit together. Returns false for a replay (nothing runs).
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* await this.inbox.receive('payments', event.id, event, () => ProcessPaymentEventJob.dispatch({ eventId: event.id }).durable())
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
async receive(source: string, externalId: string, payload: unknown, then?: () => unknown): Promise<boolean> {
|
|
38
|
+
return this.db.transaction(async () => {
|
|
39
|
+
const id = await this.db.value(
|
|
40
|
+
sql`insert into cslug_webhook_inbox (id, source, external_id, payload)
|
|
41
|
+
values (${Bun.randomUUIDv7()}, ${source}, ${externalId}, ${sql.json(payload)})
|
|
42
|
+
on conflict (source, external_id) do nothing returning id`,
|
|
43
|
+
)
|
|
44
|
+
if (id === undefined) return false
|
|
45
|
+
if (then) await then()
|
|
46
|
+
else await this.processors.get(source)?.(externalId, payload)
|
|
47
|
+
return true
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The stored payload, validated by `schema` if given (`v` schema or anything with `parse`). */
|
|
52
|
+
async payload<T = unknown>(source: string, externalId: string, schema?: { parse(value: unknown): T }): Promise<T> {
|
|
53
|
+
const row = await this.db.maybeOne<{ payload: unknown }>(
|
|
54
|
+
sql`select payload from cslug_webhook_inbox where source = ${source} and external_id = ${externalId}`,
|
|
55
|
+
)
|
|
56
|
+
if (!row) throw new NotFoundError('webhook.not_found', `No ${source} webhook event ${externalId}`)
|
|
57
|
+
return schema ? schema.parse(row.payload) : (row.payload as T)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Run the source's processor again for a stored event (after a bug fix), in a transaction. */
|
|
61
|
+
async replay(source: string, externalId: string): Promise<void> {
|
|
62
|
+
const processor = this.processors.get(source)
|
|
63
|
+
if (!processor)
|
|
64
|
+
throw new NotFoundError('webhook.no_processor', `No processor for ${source}: register one with inbox.process()`)
|
|
65
|
+
const payload = await this.payload(source, externalId)
|
|
66
|
+
await this.db.transaction(async () => {
|
|
67
|
+
await processor(externalId, payload)
|
|
68
|
+
await this.db.exec(
|
|
69
|
+
sql`update cslug_webhook_inbox set replayed_at = ${this.clock.now()}
|
|
70
|
+
where source = ${source} and external_id = ${externalId}`,
|
|
71
|
+
)
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Delete events received more than `olderThan` ago (a replay after that is processed again). Returns the count. */
|
|
76
|
+
async prune(olderThan: Duration, source?: string): Promise<number> {
|
|
77
|
+
const before = new Date(this.clock.now().getTime() - parseDuration(olderThan))
|
|
78
|
+
return this.db.exec(
|
|
79
|
+
sql`delete from cslug_webhook_inbox where received_at < ${before}${source ? sql` and source = ${source}` : sql``}`,
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @cslug/webhook:
|
|
3
|
-
*
|
|
4
|
-
* Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
|
|
2
|
+
* @cslug/webhook: signature verification (`verifySignature`) and an exactly-once inbox (`WebhookInbox`) for the
|
|
3
|
+
* webhooks your providers send.
|
|
5
4
|
*/
|
|
6
|
-
export {}
|
|
5
|
+
export { WEBHOOK_MIGRATIONS, WebhookInbox, type WebhookProcessor } from './inbox'
|
|
6
|
+
export { WebhookProvider, WebhooksReplayCommand } from './provider'
|
|
7
|
+
export { checkSignature, type SignatureCheck, signWebhook, verifySignature, type WebhookSource } from './signature'
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { arg, Command, ServiceProvider } from '@cslug/core'
|
|
2
|
+
import { addMigrations, DatabaseProvider } from '@cslug/database'
|
|
3
|
+
import { WEBHOOK_MIGRATIONS, WebhookInbox } from './inbox'
|
|
4
|
+
|
|
5
|
+
/** `cslug webhooks:replay <source> <externalId>`: run the source's processor again for one stored event. */
|
|
6
|
+
export class WebhooksReplayCommand extends Command {
|
|
7
|
+
static signature = 'webhooks:replay'
|
|
8
|
+
static description = 'Process a stored webhook event again'
|
|
9
|
+
static args = { source: arg.string(), externalId: arg.string() }
|
|
10
|
+
|
|
11
|
+
async handle({ source, externalId }: Command.Args<typeof WebhooksReplayCommand>) {
|
|
12
|
+
await this.app.resolve(WebhookInbox).replay(source, externalId)
|
|
13
|
+
this.success(`Replayed ${source} ${externalId}`)
|
|
14
|
+
return 0
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Registers the `cslug_webhook_inbox` migration and `webhooks:replay`. `WebhookInbox` is an `@inject` class. */
|
|
19
|
+
export class WebhookProvider extends ServiceProvider {
|
|
20
|
+
static dependsOn = [DatabaseProvider]
|
|
21
|
+
|
|
22
|
+
register() {
|
|
23
|
+
addMigrations(WEBHOOK_MIGRATIONS)
|
|
24
|
+
this.commands([WebhooksReplayCommand])
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/signature.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Clock, CslugError, currentApp, type Duration, parseDuration, UnauthorizedError } from '@cslug/core'
|
|
2
|
+
import type { HttpContext, HttpRequest, MiddlewareFn } from '@cslug/http'
|
|
3
|
+
|
|
4
|
+
/** One sender in `config/webhooks.ts`. */
|
|
5
|
+
export type WebhookSource = {
|
|
6
|
+
secret: string
|
|
7
|
+
/** The header carrying the signature (`X-Signature`). */
|
|
8
|
+
header: string
|
|
9
|
+
algorithm?: 'sha1' | 'sha256' | 'sha512'
|
|
10
|
+
/**
|
|
11
|
+
* How the header reads, with `{signature}` and optionally `{timestamp}` (`'t={timestamp},v1={signature}'`).
|
|
12
|
+
* With a timestamp, `${timestamp}.${rawBody}` is signed. Default `'{signature}'`.
|
|
13
|
+
*/
|
|
14
|
+
format?: string
|
|
15
|
+
/** How the signature is written. Default `'hex'`. */
|
|
16
|
+
encoding?: 'hex' | 'base64'
|
|
17
|
+
/** With `{timestamp}`: requests older (or newer) than this are rejected. Default `'5m'`. */
|
|
18
|
+
tolerance?: Duration
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Your own scheme: `verifySignature((req, raw) => mySdk.verify(raw, req.headers))`. */
|
|
22
|
+
export type SignatureCheck = (request: HttpRequest, raw: Uint8Array) => boolean | Promise<boolean>
|
|
23
|
+
|
|
24
|
+
const HASH = { sha1: 'SHA-1', sha256: 'SHA-256', sha512: 'SHA-512' } as const
|
|
25
|
+
const encoder = new TextEncoder()
|
|
26
|
+
|
|
27
|
+
function sourceConfig(name: string): WebhookSource {
|
|
28
|
+
const source = currentApp().config<WebhookSource | undefined>(`webhooks.${name}`)
|
|
29
|
+
if (!source?.secret || !source.header)
|
|
30
|
+
throw new CslugError('webhook.no_source', `config/webhooks.ts has no source "${name}" with a secret and a header`)
|
|
31
|
+
return source
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const key = (secret: string, algorithm: keyof typeof HASH, usage: KeyUsage) =>
|
|
35
|
+
crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: HASH[algorithm] }, false, [usage])
|
|
36
|
+
|
|
37
|
+
/** The signed bytes: the raw body, or `${timestamp}.${rawBody}`. */
|
|
38
|
+
const signed = (raw: Uint8Array, timestamp?: string): Uint8Array<ArrayBuffer> =>
|
|
39
|
+
timestamp === undefined ? new Uint8Array(raw) : new Uint8Array([...encoder.encode(`${timestamp}.`), ...raw])
|
|
40
|
+
|
|
41
|
+
const decode = (text: string, encoding: 'hex' | 'base64'): Uint8Array<ArrayBuffer> | undefined => {
|
|
42
|
+
if (encoding === 'base64') return Uint8Array.from(Buffer.from(text, 'base64'))
|
|
43
|
+
return /^([0-9a-f]{2})+$/i.test(text) ? Uint8Array.from(Buffer.from(text, 'hex')) : undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `{timestamp}` and `{signature}` out of a header written in `format`. */
|
|
47
|
+
function parseHeader(header: string, format: string): { signature?: string; timestamp?: string } {
|
|
48
|
+
const pattern = format
|
|
49
|
+
.split(/(\{signature\}|\{timestamp\})/)
|
|
50
|
+
.map((part) =>
|
|
51
|
+
part === '{signature}'
|
|
52
|
+
? '(?<signature>[A-Za-z0-9+/=_-]+)'
|
|
53
|
+
: part === '{timestamp}'
|
|
54
|
+
? '(?<timestamp>\\d+)'
|
|
55
|
+
: part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
|
|
56
|
+
)
|
|
57
|
+
.join('')
|
|
58
|
+
return new RegExp(`^${pattern}$`).exec(header.trim())?.groups ?? {}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Check a webhook request against `config/webhooks.ts` → `name`: HMAC over the raw bytes, compared in constant
|
|
63
|
+
* time (`crypto.subtle.verify`), and the timestamp within `tolerance`. True when valid.
|
|
64
|
+
*/
|
|
65
|
+
export async function checkSignature(name: string, request: HttpRequest): Promise<boolean> {
|
|
66
|
+
const source = sourceConfig(name)
|
|
67
|
+
const header = request.header(source.header)
|
|
68
|
+
if (!header) return false
|
|
69
|
+
const { signature, timestamp } = parseHeader(header, source.format ?? '{signature}')
|
|
70
|
+
if (!signature) return false
|
|
71
|
+
if (timestamp !== undefined) {
|
|
72
|
+
const now = currentApp().resolve(Clock).now().getTime()
|
|
73
|
+
if (Math.abs(now - Number(timestamp) * 1000) > parseDuration(source.tolerance ?? '5m')) return false
|
|
74
|
+
}
|
|
75
|
+
const bytes = decode(signature, source.encoding ?? 'hex')
|
|
76
|
+
if (!bytes) return false
|
|
77
|
+
const raw = await request.raw()
|
|
78
|
+
const hmac = await key(source.secret, source.algorithm ?? 'sha256', 'verify')
|
|
79
|
+
return crypto.subtle.verify('HMAC', hmac, bytes, signed(raw, timestamp))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Middleware: 401 unless the request is signed by the sender `name` (config/webhooks.ts), or your own check passes.
|
|
84
|
+
* Reads the raw body first; `request.body()` still works afterwards (the bytes are cached).
|
|
85
|
+
*
|
|
86
|
+
* ```ts
|
|
87
|
+
* r.post('/webhooks/payments', [PaymentWebhookController, 'handle']).middleware(verifySignature('payments'))
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export function verifySignature(source: string | SignatureCheck): MiddlewareFn {
|
|
91
|
+
return async (ctx: HttpContext, next) => {
|
|
92
|
+
const ok =
|
|
93
|
+
typeof source === 'string'
|
|
94
|
+
? await checkSignature(source, ctx.request)
|
|
95
|
+
: await source(ctx.request, await ctx.request.raw())
|
|
96
|
+
if (!ok) throw new UnauthorizedError('webhook.bad_signature', 'The webhook signature is missing or invalid.')
|
|
97
|
+
return next()
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Headers that sign `rawBody` as the sender `name` would (for tests):
|
|
103
|
+
* `t.post('/webhooks/payments').headers(await signWebhook('payments', JSON.stringify(event))).json(event)`.
|
|
104
|
+
*/
|
|
105
|
+
export async function signWebhook(
|
|
106
|
+
name: string,
|
|
107
|
+
rawBody: string | Uint8Array,
|
|
108
|
+
options: { timestamp?: number } = {},
|
|
109
|
+
): Promise<Record<string, string>> {
|
|
110
|
+
const source = sourceConfig(name)
|
|
111
|
+
const format = source.format ?? '{signature}'
|
|
112
|
+
const raw = typeof rawBody === 'string' ? encoder.encode(rawBody) : rawBody
|
|
113
|
+
const timestamp = format.includes('{timestamp}')
|
|
114
|
+
? String(options.timestamp ?? Math.floor(currentApp().resolve(Clock).now().getTime() / 1000))
|
|
115
|
+
: undefined
|
|
116
|
+
const hmac = await key(source.secret, source.algorithm ?? 'sha256', 'sign')
|
|
117
|
+
const mac = Buffer.from(await crypto.subtle.sign('HMAC', hmac, signed(raw, timestamp)))
|
|
118
|
+
const signature = mac.toString(source.encoding === 'base64' ? 'base64' : 'hex')
|
|
119
|
+
return {
|
|
120
|
+
[source.header]: format.replace('{signature}', signature).replace('{timestamp}', timestamp ?? ''),
|
|
121
|
+
}
|
|
122
|
+
}
|