@terreno/api 57.2.0 → 57.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -0,0 +1,83 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {APIError} from "../../errors";
4
+ import type {WebhookClaimArgs, WebhookClaimResult, WebhookIdempotencyStore} from "./memoryStore";
5
+ import {
6
+ DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS,
7
+ getWebhookReceiptModel,
8
+ WEBHOOK_RECEIPTS_COLLECTION,
9
+ } from "./webhookReceipt";
10
+
11
+ const isDuplicateKeyError = (error: unknown): boolean => {
12
+ if (!error || typeof error !== "object" || !("code" in error)) {
13
+ return false;
14
+ }
15
+ return (error as {code: unknown}).code === 11000;
16
+ };
17
+
18
+ export const createMongoIdempotencyStore = ({
19
+ ttlDays = DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS,
20
+ }: {
21
+ ttlDays?: number;
22
+ } = {}): WebhookIdempotencyStore => {
23
+ if (!Number.isFinite(ttlDays) || ttlDays <= 0) {
24
+ throw new APIError({
25
+ status: 500,
26
+ title: "Mongo webhook idempotency ttlDays must be a positive number",
27
+ });
28
+ }
29
+ const expireAfterSeconds = Math.round(ttlDays * 86_400);
30
+ let indexesReady: Promise<void> | undefined;
31
+
32
+ const ensureIndexes = async (): Promise<void> => {
33
+ if (!indexesReady) {
34
+ indexesReady = getWebhookReceiptModel()
35
+ .syncIndexes()
36
+ .then(async () => {
37
+ const db = mongoose.connection.db;
38
+ if (!db) {
39
+ return;
40
+ }
41
+ await db.command({
42
+ collMod: WEBHOOK_RECEIPTS_COLLECTION,
43
+ index: {
44
+ expireAfterSeconds,
45
+ keyPattern: {created: 1},
46
+ },
47
+ });
48
+ })
49
+ .catch((error: unknown) => {
50
+ indexesReady = undefined;
51
+ throw error;
52
+ });
53
+ }
54
+ await indexesReady;
55
+ };
56
+
57
+ const claim = async (args: WebhookClaimArgs): Promise<WebhookClaimResult> => {
58
+ if (!mongoose.connection.db) {
59
+ throw new APIError({
60
+ status: 500,
61
+ title: "Mongo webhook idempotency store requires an open mongoose connection",
62
+ });
63
+ }
64
+ await ensureIndexes();
65
+ const WebhookReceipt = getWebhookReceiptModel();
66
+ try {
67
+ await WebhookReceipt.create({eventId: args.eventId, source: args.source});
68
+ return "claimed";
69
+ } catch (error) {
70
+ if (isDuplicateKeyError(error)) {
71
+ return "duplicate";
72
+ }
73
+ throw error;
74
+ }
75
+ };
76
+
77
+ const release = async (args: WebhookClaimArgs): Promise<void> => {
78
+ const WebhookReceipt = getWebhookReceiptModel();
79
+ await WebhookReceipt.deleteOne({eventId: args.eventId, source: args.source});
80
+ };
81
+
82
+ return {claim, release};
83
+ };
@@ -0,0 +1,70 @@
1
+ import {DateTime} from "luxon";
2
+ import mongoose from "mongoose";
3
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../../plugins";
4
+ import {findExactlyOne, findOneOrNone} from "../../plugins";
5
+
6
+ export const WEBHOOK_RECEIPTS_COLLECTION = "webhookReceipts";
7
+ export const DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS = 7;
8
+
9
+ export type WebhookReceiptMethods = Record<string, never>;
10
+
11
+ export interface WebhookReceiptStatics
12
+ extends FindExactlyOnePlugin<WebhookReceiptDocument>,
13
+ FindOneOrNonePlugin<WebhookReceiptDocument> {}
14
+
15
+ export interface WebhookReceiptModel
16
+ extends mongoose.Model<WebhookReceiptDocument, object, WebhookReceiptMethods>,
17
+ WebhookReceiptStatics {}
18
+
19
+ export interface WebhookReceiptDocument extends mongoose.Document {
20
+ _id: mongoose.Types.ObjectId;
21
+ created: Date;
22
+ eventId: string;
23
+ source: string;
24
+ }
25
+
26
+ const secondsPerDay = 86_400;
27
+
28
+ export const webhookReceiptSchema = new mongoose.Schema<
29
+ WebhookReceiptDocument,
30
+ WebhookReceiptModel
31
+ >(
32
+ {
33
+ created: {
34
+ default: () => DateTime.utc().toJSDate(),
35
+ description: "When this webhook event id was first claimed",
36
+ required: true,
37
+ type: Date,
38
+ },
39
+ eventId: {
40
+ description: "Provider event id claimed for this source",
41
+ required: true,
42
+ type: String,
43
+ },
44
+ source: {
45
+ description: "Webhook source label (for example stripe or sendgrid)",
46
+ required: true,
47
+ type: String,
48
+ },
49
+ },
50
+ {collection: WEBHOOK_RECEIPTS_COLLECTION, strict: "throw"}
51
+ );
52
+
53
+ webhookReceiptSchema.index({eventId: 1, source: 1}, {unique: true});
54
+ webhookReceiptSchema.index(
55
+ {created: 1},
56
+ {expireAfterSeconds: DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS * secondsPerDay}
57
+ );
58
+
59
+ webhookReceiptSchema.plugin(findOneOrNone);
60
+ webhookReceiptSchema.plugin(findExactlyOne);
61
+
62
+ export const getWebhookReceiptModel = (): WebhookReceiptModel => {
63
+ return (
64
+ (mongoose.models.WebhookReceipt as WebhookReceiptModel | undefined) ??
65
+ mongoose.model<WebhookReceiptDocument, WebhookReceiptModel>(
66
+ "WebhookReceipt",
67
+ webhookReceiptSchema
68
+ )
69
+ );
70
+ };
@@ -0,0 +1,74 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type {Application, Request} from "express";
4
+ import supertest from "supertest";
5
+
6
+ import type {UserModel as AuthUserModel} from "../auth";
7
+ import {TerrenoApp} from "../terrenoApp";
8
+ import {UserModel} from "../tests";
9
+
10
+ const buildEchoApp = (): Application => {
11
+ return new TerrenoApp({
12
+ configureApp: (app) => {
13
+ app.post("/__raw-body-echo", (req: Request, res) => {
14
+ if (req.body && typeof req.body === "object") {
15
+ (req.body as {mutated?: boolean}).mutated = true;
16
+ }
17
+ const rawBody = req.rawBody;
18
+ res.json({
19
+ body: req.body,
20
+ rawBodyUtf8: rawBody ? rawBody.toString("utf8") : null,
21
+ });
22
+ });
23
+ },
24
+ logRequests: false,
25
+ skipListen: true,
26
+ userModel: UserModel as unknown as AuthUserModel,
27
+ }).build();
28
+ };
29
+
30
+ describe("TerrenoApp raw body capture", () => {
31
+ it("stores JSON request bytes on req.rawBody and still parses req.body", async () => {
32
+ const app = buildEchoApp();
33
+ const payload = `{"hello":"world"}`;
34
+
35
+ const res = await supertest(app)
36
+ .post("/__raw-body-echo")
37
+ .set("Content-Type", "application/json")
38
+ .send(payload)
39
+ .expect(200);
40
+
41
+ assert.strictEqual(res.body.rawBodyUtf8, payload);
42
+ assert.strictEqual(res.body.body.hello, "world");
43
+ });
44
+
45
+ it("does not change rawBody when the parsed JSON object is mutated", async () => {
46
+ const app = buildEchoApp();
47
+ const payload = `{"hello":"world"}`;
48
+
49
+ const res = await supertest(app)
50
+ .post("/__raw-body-echo")
51
+ .set("Content-Type", "application/json")
52
+ .send(payload)
53
+ .expect(200);
54
+
55
+ assert.strictEqual(res.body.body.mutated, true);
56
+ assert.strictEqual(res.body.rawBodyUtf8, payload);
57
+ assert.notInclude(res.body.rawBodyUtf8, "mutated");
58
+ });
59
+
60
+ it("stores urlencoded request bytes on req.rawBody", async () => {
61
+ const app = buildEchoApp();
62
+ const payload = "MessageSid=SM123&MessageStatus=delivered";
63
+
64
+ const res = await supertest(app)
65
+ .post("/__raw-body-echo")
66
+ .set("Content-Type", "application/x-www-form-urlencoded")
67
+ .send(payload)
68
+ .expect(200);
69
+
70
+ assert.strictEqual(res.body.rawBodyUtf8, payload);
71
+ assert.strictEqual(res.body.body.MessageSid, "SM123");
72
+ assert.strictEqual(res.body.body.MessageStatus, "delivered");
73
+ });
74
+ });
@@ -0,0 +1,23 @@
1
+ import type {IncomingMessage, OutgoingMessage} from "node:http";
2
+ import type {Request} from "express";
3
+
4
+ /**
5
+ * Copies the parsed request buffer onto `req.rawBody`.
6
+ * Express may reuse `buf`; webhook signatures need the original bytes.
7
+ */
8
+ export const captureRawBody = (req: IncomingMessage, _res: OutgoingMessage, buf: Buffer): void => {
9
+ if (!Buffer.isBuffer(buf)) {
10
+ return;
11
+ }
12
+ (req as Request).rawBody = Buffer.from(buf);
13
+ };
14
+
15
+ export const jsonBodyParserOptions = {
16
+ limit: "50mb" as const,
17
+ verify: captureRawBody,
18
+ };
19
+
20
+ export const urlencodedBodyParserOptions = {
21
+ extended: false as const,
22
+ verify: captureRawBody,
23
+ };
@@ -0,0 +1,16 @@
1
+ import crypto from "node:crypto";
2
+
3
+ export const timingSafeEqualUtf8 = ({
4
+ expected,
5
+ provided,
6
+ }: {
7
+ expected: string;
8
+ provided: string;
9
+ }): boolean => {
10
+ const expectedBuf = Buffer.from(expected, "utf8");
11
+ const providedBuf = Buffer.from(provided, "utf8");
12
+ if (expectedBuf.length !== providedBuf.length) {
13
+ return false;
14
+ }
15
+ return crypto.timingSafeEqual(expectedBuf, providedBuf);
16
+ };
@@ -0,0 +1,110 @@
1
+ import {describe, it} from "bun:test";
2
+ import crypto from "node:crypto";
3
+ import {assert} from "chai";
4
+ import type {Request} from "express";
5
+ import {DateTime} from "luxon";
6
+
7
+ import {hmacSignature} from "./hmac";
8
+
9
+ const SECRET = "whsec_test";
10
+ const BODY = Buffer.from(`{"id":"evt_1"}`);
11
+ const VALID_HEX = "030fa3b2413d1993c551364bd53bb9b3edb5c0c34d55dba6ada6041245632811";
12
+
13
+ const hmacHex = (payload: Buffer | string): string => {
14
+ return crypto.createHmac("sha256", SECRET).update(payload).digest("hex");
15
+ };
16
+
17
+ const fakeReq = ({
18
+ signature,
19
+ timestamp,
20
+ rawBody = BODY,
21
+ }: {
22
+ rawBody?: Buffer;
23
+ signature?: string;
24
+ timestamp?: string;
25
+ }): Request => {
26
+ const headers: Record<string, string> = {};
27
+ if (signature !== undefined) {
28
+ headers["x-webhook-signature"] = signature;
29
+ }
30
+ if (timestamp !== undefined) {
31
+ headers["x-webhook-timestamp"] = timestamp;
32
+ }
33
+ return {headers, rawBody} as Request;
34
+ };
35
+
36
+ describe("hmacSignature", () => {
37
+ it("accepts a matching hex HMAC of the raw body", () => {
38
+ const verify = hmacSignature({header: "X-Webhook-Signature", secret: SECRET});
39
+ assert.isTrue(verify(fakeReq({signature: VALID_HEX})));
40
+ });
41
+
42
+ it("rejects a shorter signature instead of throwing", () => {
43
+ const verify = hmacSignature({header: "X-Webhook-Signature", secret: SECRET});
44
+ assert.isFalse(verify(fakeReq({signature: VALID_HEX.slice(0, 8)})));
45
+ });
46
+
47
+ it("rejects a timestamp outside the tolerance window", () => {
48
+ const verify = hmacSignature({
49
+ header: "X-Webhook-Signature",
50
+ secret: SECRET,
51
+ timestampHeader: "X-Webhook-Timestamp",
52
+ toleranceSec: 300,
53
+ });
54
+ const stale = String(DateTime.utc().toUnixInteger() - 301);
55
+ const signature = hmacHex(`${stale}.{"id":"evt_1"}`);
56
+ assert.isFalse(verify(fakeReq({signature, timestamp: stale})));
57
+ });
58
+
59
+ it("accepts HMAC of timestamp plus raw body inside the tolerance window", () => {
60
+ const verify = hmacSignature({
61
+ header: "X-Webhook-Signature",
62
+ secret: SECRET,
63
+ timestampHeader: "X-Webhook-Timestamp",
64
+ toleranceSec: 300,
65
+ });
66
+ const now = String(DateTime.utc().toUnixInteger());
67
+ const signature = hmacHex(`${now}.{"id":"evt_1"}`);
68
+ assert.isTrue(verify(fakeReq({signature, timestamp: now})));
69
+ });
70
+
71
+ it("rejects a body-only HMAC when a timestamp header is required", () => {
72
+ const verify = hmacSignature({
73
+ header: "X-Webhook-Signature",
74
+ secret: SECRET,
75
+ timestampHeader: "X-Webhook-Timestamp",
76
+ toleranceSec: 300,
77
+ });
78
+ const now = String(DateTime.utc().toUnixInteger());
79
+ assert.isFalse(verify(fakeReq({signature: VALID_HEX, timestamp: now})));
80
+ });
81
+
82
+ it("rejects a missing raw body", () => {
83
+ const verify = hmacSignature({header: "X-Webhook-Signature", secret: SECRET});
84
+ const req = {headers: {"x-webhook-signature": VALID_HEX}} as Request;
85
+ assert.isFalse(verify(req));
86
+ });
87
+
88
+ it("rejects a missing signature", () => {
89
+ const verify = hmacSignature({header: "X-Webhook-Signature", secret: SECRET});
90
+ assert.isFalse(verify(fakeReq({})));
91
+ });
92
+
93
+ it("rejects a missing timestamp when timestampHeader is set", () => {
94
+ const verify = hmacSignature({
95
+ header: "X-Webhook-Signature",
96
+ secret: SECRET,
97
+ timestampHeader: "X-Webhook-Timestamp",
98
+ });
99
+ assert.isFalse(verify(fakeReq({signature: VALID_HEX})));
100
+ });
101
+
102
+ it("rejects a non-numeric timestamp", () => {
103
+ const verify = hmacSignature({
104
+ header: "X-Webhook-Signature",
105
+ secret: SECRET,
106
+ timestampHeader: "X-Webhook-Timestamp",
107
+ });
108
+ assert.isFalse(verify(fakeReq({signature: VALID_HEX, timestamp: "not-a-number"})));
109
+ });
110
+ });
@@ -0,0 +1,54 @@
1
+ import crypto from "node:crypto";
2
+ import type {Request} from "express";
3
+ import {DateTime} from "luxon";
4
+
5
+ import {headerValue} from "../headerValue";
6
+ import {timingSafeEqualUtf8} from "../timingSafeEqual";
7
+
8
+ export interface HmacSignatureOptions {
9
+ algorithm?: "sha256" | "sha1" | "sha512";
10
+ encoding?: "hex" | "base64";
11
+ header: string;
12
+ secret: string;
13
+ timestampHeader?: string;
14
+ toleranceSec?: number;
15
+ }
16
+
17
+ /**
18
+ * Verifies `header` against HMAC of `req.rawBody`.
19
+ * When `timestampHeader` is set, the MAC is HMAC(`${timestamp}.${rawBody}`) and
20
+ * timestamps outside `toleranceSec` (default 300) are rejected.
21
+ */
22
+ export const hmacSignature = (options: HmacSignatureOptions): ((req: Request) => boolean) => {
23
+ const algorithm = options.algorithm ?? "sha256";
24
+ const encoding = options.encoding ?? "hex";
25
+ const toleranceSec = options.toleranceSec ?? 300;
26
+
27
+ return (req: Request): boolean => {
28
+ const provided = headerValue(req, options.header);
29
+ if (!provided) {
30
+ return false;
31
+ }
32
+ if (!req.rawBody) {
33
+ return false;
34
+ }
35
+ const mac = crypto.createHmac(algorithm, options.secret);
36
+ if (options.timestampHeader) {
37
+ const timestampRaw = headerValue(req, options.timestampHeader);
38
+ if (!timestampRaw) {
39
+ return false;
40
+ }
41
+ const timestamp = Number(timestampRaw);
42
+ if (!Number.isFinite(timestamp)) {
43
+ return false;
44
+ }
45
+ const nowSec = DateTime.utc().toUnixInteger();
46
+ if (Math.abs(nowSec - timestamp) > toleranceSec) {
47
+ return false;
48
+ }
49
+ mac.update(`${timestampRaw}.`);
50
+ }
51
+ const expected = mac.update(req.rawBody).digest(encoding);
52
+ return timingSafeEqualUtf8({expected, provided});
53
+ };
54
+ };