@hookflo/tern 4.0.0 → 4.0.3

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/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare class WebhookVerificationService {
8
8
  static verifyWithPlatformConfig<TPayload = unknown>(request: Request, platform: WebhookPlatform, secret: string, toleranceInSeconds?: number, normalize?: boolean | NormalizeOptions): Promise<WebhookVerificationResult<TPayload>>;
9
9
  static verifyAny<TPayload = unknown>(request: Request, secrets: MultiPlatformSecrets, toleranceInSeconds?: number, normalize?: boolean | NormalizeOptions): Promise<WebhookVerificationResult<TPayload>>;
10
10
  private static resolveCanonicalEventId;
11
+ private static pickString;
11
12
  private static resolveRawEventId;
12
13
  static detectPlatform(request: Request): WebhookPlatform;
13
14
  static getPlatformsUsingAlgorithm(algorithm: string): WebhookPlatform[];
package/dist/index.js CHANGED
@@ -48,7 +48,7 @@ class WebhookVerificationService {
48
48
  // Ensure the platform is set correctly in the result
49
49
  if (result.isValid) {
50
50
  result.platform = config.platform;
51
- result.eventId = this.resolveCanonicalEventId(config.platform, result.metadata);
51
+ result.eventId = this.resolveCanonicalEventId(config.platform, result.metadata, result.payload) ?? undefined;
52
52
  if (config.normalize) {
53
53
  result.payload = (0, simple_1.normalizePayload)(config.platform, result.payload, config.normalize);
54
54
  }
@@ -132,16 +132,71 @@ class WebhookVerificationService {
132
132
  },
133
133
  };
134
134
  }
135
- static resolveCanonicalEventId(platform, metadata) {
136
- const rawId = this.resolveRawEventId(platform, metadata);
135
+ static resolveCanonicalEventId(platform, metadata, payload) {
136
+ const rawId = this.resolveRawEventId(platform, metadata, payload);
137
+ if (!rawId)
138
+ return null;
137
139
  return `${platform}_${rawId}`;
138
140
  }
139
- static resolveRawEventId(platform, metadata) {
140
- const candidate = metadata?.id || metadata?.delivery || metadata?.requestId || metadata?.timestamp;
141
- if (candidate !== undefined && candidate !== null && `${candidate}`.trim().length > 0) {
142
- return `${candidate}`.trim();
141
+ static pickString(...candidates) {
142
+ for (const candidate of candidates) {
143
+ if (candidate === undefined || candidate === null) {
144
+ continue;
145
+ }
146
+ const normalized = `${candidate}`.trim();
147
+ if (normalized.length > 0 && normalized !== 'undefined' && normalized !== 'null') {
148
+ return normalized;
149
+ }
150
+ }
151
+ return undefined;
152
+ }
153
+ static resolveRawEventId(platform, metadata, payload) {
154
+ switch (platform) {
155
+ case 'stripe':
156
+ return this.pickString(payload?.request?.idempotency_key, payload?.id) || null;
157
+ case 'github':
158
+ return this.pickString(metadata?.delivery) || null;
159
+ case 'clerk':
160
+ return this.pickString(metadata?.id) || null;
161
+ case 'shopify':
162
+ return this.pickString(metadata?.id, payload?.id) || null;
163
+ case 'paddle':
164
+ return this.pickString(payload?.event_id, payload?.data?.id) || null;
165
+ case 'polar':
166
+ return this.pickString(payload?.data?.id, payload?.id) || null;
167
+ case 'dodopayments':
168
+ return this.pickString(payload?.data?.payment_id, payload?.data?.subscription_id, payload?.data?.id) || null;
169
+ case 'falai':
170
+ return this.pickString(payload?.request_id) || null;
171
+ case 'replicateai':
172
+ case 'replicate':
173
+ return this.pickString(payload?.id) || null;
174
+ case 'workos':
175
+ case 'sentry':
176
+ case 'vercel':
177
+ return this.pickString(payload?.id) || null;
178
+ case 'doppler':
179
+ return this.pickString(payload?.event?.id, metadata?.id) || null;
180
+ case 'sanity':
181
+ return this.pickString(payload?.transactionId, payload?._id) || null;
182
+ case 'razorpay':
183
+ return this.pickString(payload?.payload?.payment?.entity?.id, payload?.payload?.order?.entity?.id, payload?.payload?.subscription?.entity?.id) || null;
184
+ case 'lemonsqueezy': {
185
+ const dataId = this.pickString(payload?.data?.id);
186
+ if (!dataId)
187
+ return null;
188
+ const eventName = this.pickString(payload?.meta?.event_name);
189
+ return eventName ? `${eventName}_${dataId}` : null;
190
+ }
191
+ case 'gitlab':
192
+ return this.pickString(payload?.object_attributes?.id?.toString()) || null;
193
+ case 'grafana':
194
+ return this.pickString(payload?.groupKey, payload?.alerts?.[0]?.fingerprint) || null;
195
+ case 'woocommerce':
196
+ return this.pickString(payload?.id?.toString()) || null;
197
+ default:
198
+ return this.pickString(payload?.idempotency_key, payload?.event_id, payload?.webhook_id, payload?.id, metadata?.id, metadata?.delivery) || null;
143
199
  }
144
- return `generated-${Date.now().toString(36)}-${platform}`;
145
200
  }
146
201
  static detectPlatform(request) {
147
202
  const headers = request.headers;
@@ -183,7 +183,7 @@ async function handleReceive(request, platform, secret, queueConfig, toleranceIn
183
183
  metadata: verificationResult.metadata || {},
184
184
  };
185
185
  const deduplicationId = await resolveDeduplicationId(request, verificationResult);
186
- if (process.env.NODE_ENV == 'production') {
186
+ if (process.env.NODE_ENV !== 'production') {
187
187
  console.log(`[tern] deduplication-id: ${deduplicationId} (platform: ${platform})`);
188
188
  }
189
189
  const publishPayload = {
@@ -197,11 +197,60 @@ async function handleReceive(request, platform, secret, queueConfig, toleranceIn
197
197
  if (queueConfig.retries !== undefined) {
198
198
  publishPayload.retries = queueConfig.retries;
199
199
  }
200
- await client.publishJSON(publishPayload);
201
- return new Response(JSON.stringify({ queued: true }), {
202
- status: 200,
203
- headers: { 'Content-Type': 'application/json' },
204
- });
200
+ try {
201
+ await client.publishJSON(publishPayload);
202
+ return new Response(JSON.stringify({ queued: true }), {
203
+ status: 200,
204
+ headers: { 'Content-Type': 'application/json' },
205
+ });
206
+ }
207
+ catch (error) {
208
+ const status = error?.status ?? 0;
209
+ const errorBody = error?.body
210
+ ? (() => {
211
+ try {
212
+ return JSON.parse(error.body);
213
+ }
214
+ catch {
215
+ return {};
216
+ }
217
+ })()
218
+ : {};
219
+ console.error('[tern] QStash publish failed:', {
220
+ status,
221
+ message: String(error),
222
+ });
223
+ if (status === 400) {
224
+ return new Response(JSON.stringify({
225
+ error: 'Invalid payload — could not enqueue',
226
+ detail: errorBody?.error,
227
+ }), {
228
+ status: 489,
229
+ headers: {
230
+ 'Content-Type': 'application/json',
231
+ 'Upstash-NonRetryable-Error': 'true',
232
+ },
233
+ });
234
+ }
235
+ if (status === 401) {
236
+ return new Response(JSON.stringify({
237
+ error: '[tern] QStash token invalid — check QSTASH_TOKEN in env',
238
+ }), {
239
+ status: 503,
240
+ headers: { 'Content-Type': 'application/json' },
241
+ });
242
+ }
243
+ if (status === 429) {
244
+ return new Response(JSON.stringify({ error: 'QStash rate limited — retry shortly' }), {
245
+ status: 503,
246
+ headers: { 'Content-Type': 'application/json' },
247
+ });
248
+ }
249
+ return new Response(JSON.stringify({ error: 'Queue temporarily unavailable' }), {
250
+ status: 503,
251
+ headers: { 'Content-Type': 'application/json' },
252
+ });
253
+ }
205
254
  }
206
255
  async function handleProcess(request, handler, queueConfig) {
207
256
  const signature = request.headers.get('upstash-signature');
@@ -217,11 +266,22 @@ async function handleProcess(request, handler, queueConfig) {
217
266
  url: request.url,
218
267
  });
219
268
  if (verification === false) {
220
- return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' } });
269
+ return nonRetryableResponse('Invalid QStash signature', 401);
221
270
  }
222
271
  }
223
- catch {
224
- return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' } });
272
+ catch (error) {
273
+ const message = String(error).toLowerCase();
274
+ if (message.includes('invalid signature') ||
275
+ message.includes('signature') ||
276
+ message.includes('unauthorized') ||
277
+ message.includes('forbidden')) {
278
+ return nonRetryableResponse('Invalid QStash signature', 401);
279
+ }
280
+ console.error('[tern] QStash signature verification error:', String(error));
281
+ return new Response(JSON.stringify({ error: 'Signature verification temporarily unavailable' }), {
282
+ status: 503,
283
+ headers: { 'Content-Type': 'application/json' },
284
+ });
225
285
  }
226
286
  if (!handler) {
227
287
  return nonRetryableResponse('Queue processing requires a handler function');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hookflo/tern",
3
- "version": "4.0.0",
3
+ "version": "4.0.3",
4
4
  "description": "A robust, scalable webhook verification framework supporting multiple platforms and signature algorithms",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",