@unifiedcommerce/core 0.0.4 → 0.1.1

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 (179) hide show
  1. package/dist/auth/auth-schema.d.ts +92 -0
  2. package/dist/auth/auth-schema.d.ts.map +1 -1
  3. package/dist/auth/auth-schema.js +7 -0
  4. package/dist/auth/setup.d.ts.map +1 -1
  5. package/dist/auth/setup.js +3 -1
  6. package/package.json +1 -2
  7. package/src/adapters/console-email.ts +0 -43
  8. package/src/auth/access.ts +0 -187
  9. package/src/auth/auth-schema.ts +0 -131
  10. package/src/auth/middleware.ts +0 -161
  11. package/src/auth/org.ts +0 -41
  12. package/src/auth/permissions.ts +0 -28
  13. package/src/auth/setup.ts +0 -165
  14. package/src/auth/system-actor.ts +0 -19
  15. package/src/auth/types.ts +0 -10
  16. package/src/config/defaults.ts +0 -82
  17. package/src/config/define-config.ts +0 -53
  18. package/src/config/types.ts +0 -299
  19. package/src/generated/plugin-capabilities.d.ts +0 -20
  20. package/src/generated/plugin-manifest.ts +0 -23
  21. package/src/generated/plugin-repositories.d.ts +0 -20
  22. package/src/hooks/checkout-completion.ts +0 -262
  23. package/src/hooks/checkout.ts +0 -677
  24. package/src/hooks/order-emails.ts +0 -62
  25. package/src/index.ts +0 -214
  26. package/src/interfaces/mcp/agent-prompt.ts +0 -174
  27. package/src/interfaces/mcp/context-enrichment.ts +0 -177
  28. package/src/interfaces/mcp/server.ts +0 -617
  29. package/src/interfaces/mcp/transport.ts +0 -68
  30. package/src/interfaces/rest/customer-portal.ts +0 -299
  31. package/src/interfaces/rest/index.ts +0 -74
  32. package/src/interfaces/rest/router.ts +0 -334
  33. package/src/interfaces/rest/routes/admin-jobs.ts +0 -58
  34. package/src/interfaces/rest/routes/audit.ts +0 -50
  35. package/src/interfaces/rest/routes/carts.ts +0 -89
  36. package/src/interfaces/rest/routes/catalog.ts +0 -493
  37. package/src/interfaces/rest/routes/checkout.ts +0 -283
  38. package/src/interfaces/rest/routes/inventory.ts +0 -70
  39. package/src/interfaces/rest/routes/media.ts +0 -86
  40. package/src/interfaces/rest/routes/orders.ts +0 -78
  41. package/src/interfaces/rest/routes/payments.ts +0 -60
  42. package/src/interfaces/rest/routes/pricing.ts +0 -57
  43. package/src/interfaces/rest/routes/promotions.ts +0 -92
  44. package/src/interfaces/rest/routes/search.ts +0 -71
  45. package/src/interfaces/rest/routes/webhooks.ts +0 -46
  46. package/src/interfaces/rest/schemas/admin-jobs.ts +0 -40
  47. package/src/interfaces/rest/schemas/audit.ts +0 -46
  48. package/src/interfaces/rest/schemas/carts.ts +0 -125
  49. package/src/interfaces/rest/schemas/catalog.ts +0 -450
  50. package/src/interfaces/rest/schemas/checkout.ts +0 -66
  51. package/src/interfaces/rest/schemas/customer-portal.ts +0 -195
  52. package/src/interfaces/rest/schemas/inventory.ts +0 -138
  53. package/src/interfaces/rest/schemas/media.ts +0 -75
  54. package/src/interfaces/rest/schemas/orders.ts +0 -104
  55. package/src/interfaces/rest/schemas/pricing.ts +0 -80
  56. package/src/interfaces/rest/schemas/promotions.ts +0 -110
  57. package/src/interfaces/rest/schemas/responses.ts +0 -85
  58. package/src/interfaces/rest/schemas/search.ts +0 -58
  59. package/src/interfaces/rest/schemas/shared.ts +0 -62
  60. package/src/interfaces/rest/schemas/webhooks.ts +0 -68
  61. package/src/interfaces/rest/utils.ts +0 -104
  62. package/src/interfaces/rest/webhook-router.ts +0 -50
  63. package/src/kernel/compensation/executor.ts +0 -61
  64. package/src/kernel/compensation/types.ts +0 -26
  65. package/src/kernel/database/adapter.ts +0 -13
  66. package/src/kernel/database/drizzle-db.ts +0 -56
  67. package/src/kernel/database/migrate.ts +0 -76
  68. package/src/kernel/database/plugin-types.ts +0 -34
  69. package/src/kernel/database/schema.ts +0 -49
  70. package/src/kernel/database/scoped-db.ts +0 -68
  71. package/src/kernel/database/tx-context.ts +0 -46
  72. package/src/kernel/error-mapper.ts +0 -15
  73. package/src/kernel/errors.ts +0 -89
  74. package/src/kernel/factory/repository-factory.ts +0 -242
  75. package/src/kernel/hooks/create-context.ts +0 -43
  76. package/src/kernel/hooks/executor.ts +0 -88
  77. package/src/kernel/hooks/registry.ts +0 -74
  78. package/src/kernel/hooks/types.ts +0 -52
  79. package/src/kernel/http-error.ts +0 -44
  80. package/src/kernel/jobs/adapter.ts +0 -36
  81. package/src/kernel/jobs/drizzle-adapter.ts +0 -58
  82. package/src/kernel/jobs/runner.ts +0 -153
  83. package/src/kernel/jobs/schema.ts +0 -46
  84. package/src/kernel/jobs/types.ts +0 -30
  85. package/src/kernel/local-api.ts +0 -185
  86. package/src/kernel/plugin/manifest.ts +0 -253
  87. package/src/kernel/query/executor.ts +0 -184
  88. package/src/kernel/query/registry.ts +0 -46
  89. package/src/kernel/result.ts +0 -33
  90. package/src/kernel/schema/extra-columns.ts +0 -37
  91. package/src/kernel/service-registry.ts +0 -76
  92. package/src/kernel/service-timing.ts +0 -89
  93. package/src/kernel/state-machine/machine.ts +0 -101
  94. package/src/modules/analytics/drizzle-adapter.ts +0 -426
  95. package/src/modules/analytics/hooks.ts +0 -11
  96. package/src/modules/analytics/models.ts +0 -125
  97. package/src/modules/analytics/repository/index.ts +0 -6
  98. package/src/modules/analytics/service.ts +0 -245
  99. package/src/modules/analytics/types.ts +0 -180
  100. package/src/modules/audit/hooks.ts +0 -78
  101. package/src/modules/audit/schema.ts +0 -33
  102. package/src/modules/audit/service.ts +0 -151
  103. package/src/modules/cart/access.ts +0 -27
  104. package/src/modules/cart/matcher.ts +0 -26
  105. package/src/modules/cart/repository/index.ts +0 -234
  106. package/src/modules/cart/schema.ts +0 -42
  107. package/src/modules/cart/schemas.ts +0 -38
  108. package/src/modules/cart/service.ts +0 -541
  109. package/src/modules/catalog/repository/index.ts +0 -772
  110. package/src/modules/catalog/schema.ts +0 -203
  111. package/src/modules/catalog/schemas.ts +0 -104
  112. package/src/modules/catalog/service.ts +0 -1544
  113. package/src/modules/customers/repository/index.ts +0 -327
  114. package/src/modules/customers/schema.ts +0 -64
  115. package/src/modules/customers/service.ts +0 -171
  116. package/src/modules/fulfillment/repository/index.ts +0 -426
  117. package/src/modules/fulfillment/schema.ts +0 -101
  118. package/src/modules/fulfillment/service.ts +0 -555
  119. package/src/modules/fulfillment/types.ts +0 -59
  120. package/src/modules/inventory/repository/index.ts +0 -509
  121. package/src/modules/inventory/schema.ts +0 -94
  122. package/src/modules/inventory/schemas.ts +0 -38
  123. package/src/modules/inventory/service.ts +0 -490
  124. package/src/modules/media/adapter.ts +0 -17
  125. package/src/modules/media/repository/index.ts +0 -274
  126. package/src/modules/media/schema.ts +0 -41
  127. package/src/modules/media/service.ts +0 -151
  128. package/src/modules/orders/repository/index.ts +0 -287
  129. package/src/modules/orders/schema.ts +0 -66
  130. package/src/modules/orders/service.ts +0 -619
  131. package/src/modules/orders/stale-order-cleanup.ts +0 -76
  132. package/src/modules/organization/service.ts +0 -191
  133. package/src/modules/payments/adapter.ts +0 -47
  134. package/src/modules/payments/repository/index.ts +0 -6
  135. package/src/modules/payments/service.ts +0 -107
  136. package/src/modules/pricing/repository/index.ts +0 -291
  137. package/src/modules/pricing/schema.ts +0 -71
  138. package/src/modules/pricing/schemas.ts +0 -38
  139. package/src/modules/pricing/service.ts +0 -494
  140. package/src/modules/promotions/repository/index.ts +0 -325
  141. package/src/modules/promotions/schema.ts +0 -62
  142. package/src/modules/promotions/schemas.ts +0 -38
  143. package/src/modules/promotions/service.ts +0 -598
  144. package/src/modules/search/adapter.ts +0 -57
  145. package/src/modules/search/hooks.ts +0 -12
  146. package/src/modules/search/repository/index.ts +0 -6
  147. package/src/modules/search/service.ts +0 -315
  148. package/src/modules/shipping/calculator.ts +0 -188
  149. package/src/modules/shipping/repository/index.ts +0 -6
  150. package/src/modules/shipping/service.ts +0 -51
  151. package/src/modules/tax/adapter.ts +0 -60
  152. package/src/modules/tax/repository/index.ts +0 -6
  153. package/src/modules/tax/service.ts +0 -53
  154. package/src/modules/webhooks/hook.ts +0 -34
  155. package/src/modules/webhooks/repository/index.ts +0 -278
  156. package/src/modules/webhooks/schema.ts +0 -56
  157. package/src/modules/webhooks/service.ts +0 -117
  158. package/src/modules/webhooks/signing.ts +0 -6
  159. package/src/modules/webhooks/ssrf-guard.ts +0 -71
  160. package/src/modules/webhooks/tasks.ts +0 -52
  161. package/src/modules/webhooks/worker.ts +0 -134
  162. package/src/runtime/commerce.ts +0 -145
  163. package/src/runtime/kernel.ts +0 -419
  164. package/src/runtime/logger.ts +0 -36
  165. package/src/runtime/server.ts +0 -349
  166. package/src/runtime/shutdown.ts +0 -43
  167. package/src/test-utils/create-pglite-adapter.ts +0 -129
  168. package/src/test-utils/create-plugin-test-app.ts +0 -128
  169. package/src/test-utils/create-repository-test-harness.ts +0 -16
  170. package/src/test-utils/create-test-config.ts +0 -190
  171. package/src/test-utils/create-test-kernel.ts +0 -7
  172. package/src/test-utils/create-test-plugin-context.ts +0 -75
  173. package/src/test-utils/rest-api-test-utils.ts +0 -265
  174. package/src/test-utils/test-actors.ts +0 -62
  175. package/src/test-utils/typed-hooks.ts +0 -54
  176. package/src/types/commerce-types.ts +0 -34
  177. package/src/utils/id.ts +0 -3
  178. package/src/utils/logger.ts +0 -18
  179. package/src/utils/pagination.ts +0 -22
@@ -1,34 +0,0 @@
1
- import type { AfterHook } from "../../kernel/hooks/types.js";
2
-
3
- /**
4
- * Webhook delivery hook — enqueues delivery jobs instead of blocking.
5
- *
6
- * Previously, this hook made synchronous HTTP calls to each webhook endpoint
7
- * inside the request handler, blocking the response for seconds if endpoints
8
- * were slow or down.
9
- *
10
- * Now it enqueues a background job per endpoint. The job runner delivers
11
- * asynchronously with retries. The HTTP response returns immediately.
12
- */
13
- export const deliverWebhooks: AfterHook<unknown> = async ({ result, operation, context }) => {
14
- const eventName = `${String(context.context.moduleName ?? "unknown")}.${operation}`;
15
- const webhooksService = context.services.webhooks as {
16
- getEndpointsForEvent(event: string): Promise<{ ok: boolean; value: Array<{ id: string; url: string; secret: string }> }>;
17
- };
18
-
19
- const endpoints = await webhooksService.getEndpointsForEvent(eventName);
20
- if (!endpoints.ok) return;
21
-
22
- for (const endpoint of endpoints.value) {
23
- await context.jobs.enqueue("webhooks/deliver", {
24
- endpointId: endpoint.id,
25
- endpointUrl: endpoint.url,
26
- endpointSecret: endpoint.secret,
27
- eventName,
28
- payload: result,
29
- }, {
30
- maxAttempts: 5,
31
- queue: "webhooks",
32
- });
33
- }
34
- };
@@ -1,278 +0,0 @@
1
- import { eq, and, lte, isNull, or, desc, sql } from "drizzle-orm";
2
- import type { TxContext } from "../../../kernel/database/tx-context.js";
3
- import type {
4
- DrizzleDatabase,
5
- DbOrTx,
6
- } from "../../../kernel/database/drizzle-db.js";
7
- import { webhookEndpoints, webhookDeliveries } from "../schema.js";
8
-
9
- // Infer types from Drizzle schema
10
- export type WebhookEndpoint = typeof webhookEndpoints.$inferSelect;
11
- export type WebhookEndpointInsert = typeof webhookEndpoints.$inferInsert;
12
- export type WebhookDelivery = typeof webhookDeliveries.$inferSelect;
13
- export type WebhookDeliveryInsert = typeof webhookDeliveries.$inferInsert;
14
-
15
- /**
16
- * WebhooksRepository provides type-safe database operations for webhooks.
17
- *
18
- * This repository manages webhook endpoints and their delivery tracking.
19
- * All methods support an optional TxContext parameter for transaction participation.
20
- */
21
- export class WebhooksRepository {
22
- constructor(private readonly db: DrizzleDatabase) {}
23
-
24
- private getDb(ctx?: TxContext): DbOrTx {
25
- return (ctx?.tx as DbOrTx | undefined) ?? this.db;
26
- }
27
-
28
- // ─────────────────────────────────────────────────────────────────────────────
29
- // Webhook Endpoints
30
- // ─────────────────────────────────────────────────────────────────────────────
31
-
32
- async findEndpointById(
33
- id: string,
34
- ctx?: TxContext,
35
- ): Promise<WebhookEndpoint | undefined> {
36
- const db = this.getDb(ctx);
37
- const rows = await db
38
- .select()
39
- .from(webhookEndpoints)
40
- .where(eq(webhookEndpoints.id, id));
41
- return rows[0];
42
- }
43
-
44
- async findAllEndpoints(ctx?: TxContext): Promise<WebhookEndpoint[]> {
45
- const db = this.getDb(ctx);
46
- return db.select().from(webhookEndpoints);
47
- }
48
-
49
- async findActiveEndpoints(ctx?: TxContext): Promise<WebhookEndpoint[]> {
50
- const db = this.getDb(ctx);
51
- return db
52
- .select()
53
- .from(webhookEndpoints)
54
- .where(eq(webhookEndpoints.isActive, true));
55
- }
56
-
57
- async findEndpointsForEvent(
58
- eventName: string,
59
- ctx?: TxContext,
60
- ): Promise<WebhookEndpoint[]> {
61
- const active = await this.findActiveEndpoints(ctx);
62
- // Filter endpoints that subscribe to this event
63
- return active.filter((endpoint) => {
64
- const events = endpoint.events as string[];
65
- return events.includes(eventName) || events.includes("*");
66
- });
67
- }
68
-
69
- async createEndpoint(
70
- data: WebhookEndpointInsert,
71
- ctx?: TxContext,
72
- ): Promise<WebhookEndpoint> {
73
- const db = this.getDb(ctx);
74
- const rows = await db.insert(webhookEndpoints).values(data).returning();
75
- return rows[0]!;
76
- }
77
-
78
- async updateEndpoint(
79
- id: string,
80
- data: Partial<Omit<WebhookEndpointInsert, "id">>,
81
- ctx?: TxContext,
82
- ): Promise<WebhookEndpoint | undefined> {
83
- const db = this.getDb(ctx);
84
- const rows = await db
85
- .update(webhookEndpoints)
86
- .set(data)
87
- .where(eq(webhookEndpoints.id, id))
88
- .returning();
89
- return rows[0];
90
- }
91
-
92
- async deleteEndpoint(id: string, ctx?: TxContext): Promise<boolean> {
93
- const db = this.getDb(ctx);
94
- const result = await db
95
- .delete(webhookEndpoints)
96
- .where(eq(webhookEndpoints.id, id))
97
- .returning();
98
- return result.length > 0;
99
- }
100
-
101
- async activateEndpoint(
102
- id: string,
103
- ctx?: TxContext,
104
- ): Promise<WebhookEndpoint | undefined> {
105
- return this.updateEndpoint(id, { isActive: true }, ctx);
106
- }
107
-
108
- async deactivateEndpoint(
109
- id: string,
110
- ctx?: TxContext,
111
- ): Promise<WebhookEndpoint | undefined> {
112
- return this.updateEndpoint(id, { isActive: false }, ctx);
113
- }
114
-
115
- // ─────────────────────────────────────────────────────────────────────────────
116
- // Webhook Deliveries
117
- // ─────────────────────────────────────────────────────────────────────────────
118
-
119
- async findDeliveryById(
120
- id: string,
121
- ctx?: TxContext,
122
- ): Promise<WebhookDelivery | undefined> {
123
- const db = this.getDb(ctx);
124
- const rows = await db
125
- .select()
126
- .from(webhookDeliveries)
127
- .where(eq(webhookDeliveries.id, id));
128
- return rows[0];
129
- }
130
-
131
- async findDeliveriesByEndpointId(
132
- endpointId: string,
133
- options?: { limit?: number },
134
- ctx?: TxContext,
135
- ): Promise<WebhookDelivery[]> {
136
- const db = this.getDb(ctx);
137
- let query = db
138
- .select()
139
- .from(webhookDeliveries)
140
- .where(eq(webhookDeliveries.endpointId, endpointId))
141
- .orderBy(desc(webhookDeliveries.createdAt))
142
- .$dynamic();
143
-
144
- if (options?.limit !== undefined) {
145
- query = query.limit(options.limit);
146
- }
147
-
148
- return query;
149
- }
150
-
151
- async findPendingDeliveries(ctx?: TxContext): Promise<WebhookDelivery[]> {
152
- const db = this.getDb(ctx);
153
- const now = new Date();
154
-
155
- return db
156
- .select()
157
- .from(webhookDeliveries)
158
- .where(
159
- and(
160
- isNull(webhookDeliveries.deliveredAt),
161
- isNull(webhookDeliveries.failedAt),
162
- or(
163
- isNull(webhookDeliveries.nextRetryAt),
164
- lte(webhookDeliveries.nextRetryAt, now),
165
- ),
166
- ),
167
- )
168
- .orderBy(webhookDeliveries.createdAt);
169
- }
170
-
171
- async findFailedDeliveries(
172
- endpointId?: string,
173
- ctx?: TxContext,
174
- ): Promise<WebhookDelivery[]> {
175
- const db = this.getDb(ctx);
176
-
177
- if (endpointId) {
178
- return db
179
- .select()
180
- .from(webhookDeliveries)
181
- .where(
182
- and(
183
- eq(webhookDeliveries.endpointId, endpointId),
184
- sql`${webhookDeliveries.failedAt} IS NOT NULL`,
185
- ),
186
- )
187
- .orderBy(desc(webhookDeliveries.failedAt));
188
- }
189
-
190
- return db
191
- .select()
192
- .from(webhookDeliveries)
193
- .where(sql`${webhookDeliveries.failedAt} IS NOT NULL`)
194
- .orderBy(desc(webhookDeliveries.failedAt));
195
- }
196
-
197
- async createDelivery(
198
- data: WebhookDeliveryInsert,
199
- ctx?: TxContext,
200
- ): Promise<WebhookDelivery> {
201
- const db = this.getDb(ctx);
202
- const rows = await db.insert(webhookDeliveries).values(data).returning();
203
- return rows[0]!;
204
- }
205
-
206
- async updateDelivery(
207
- id: string,
208
- data: Partial<Omit<WebhookDeliveryInsert, "id">>,
209
- ctx?: TxContext,
210
- ): Promise<WebhookDelivery | undefined> {
211
- const db = this.getDb(ctx);
212
- const rows = await db
213
- .update(webhookDeliveries)
214
- .set(data)
215
- .where(eq(webhookDeliveries.id, id))
216
- .returning();
217
- return rows[0];
218
- }
219
-
220
- async markDelivered(
221
- id: string,
222
- statusCode: number,
223
- ctx?: TxContext,
224
- ): Promise<WebhookDelivery | undefined> {
225
- return this.updateDelivery(
226
- id,
227
- {
228
- statusCode,
229
- deliveredAt: new Date(),
230
- nextRetryAt: null,
231
- },
232
- ctx,
233
- );
234
- }
235
-
236
- async markFailed(
237
- id: string,
238
- statusCode: number | null,
239
- nextRetryAt?: Date,
240
- ctx?: TxContext,
241
- ): Promise<WebhookDelivery | undefined> {
242
- const delivery = await this.findDeliveryById(id, ctx);
243
- if (!delivery) return undefined;
244
-
245
- const data: Partial<WebhookDeliveryInsert> = {
246
- statusCode: statusCode ?? undefined,
247
- attemptCount: delivery.attemptCount + 1,
248
- };
249
-
250
- if (nextRetryAt) {
251
- data.nextRetryAt = nextRetryAt;
252
- } else {
253
- data.failedAt = new Date();
254
- data.nextRetryAt = null;
255
- }
256
-
257
- return this.updateDelivery(id, data, ctx);
258
- }
259
-
260
- async deleteDelivery(id: string, ctx?: TxContext): Promise<boolean> {
261
- const db = this.getDb(ctx);
262
- const result = await db
263
- .delete(webhookDeliveries)
264
- .where(eq(webhookDeliveries.id, id))
265
- .returning();
266
- return result.length > 0;
267
- }
268
-
269
- async deleteDeliveriesByEndpointId(
270
- endpointId: string,
271
- ctx?: TxContext,
272
- ): Promise<void> {
273
- const db = this.getDb(ctx);
274
- await db
275
- .delete(webhookDeliveries)
276
- .where(eq(webhookDeliveries.endpointId, endpointId));
277
- }
278
- }
@@ -1,56 +0,0 @@
1
- import {
2
- boolean,
3
- index,
4
- integer,
5
- jsonb,
6
- pgTable,
7
- text,
8
- timestamp,
9
- uuid,
10
- } from "drizzle-orm/pg-core";
11
- import { organization } from "../../auth/auth-schema.js";
12
-
13
- export const webhookEndpoints = pgTable(
14
- "webhook_endpoints",
15
- {
16
- id: uuid("id").defaultRandom().primaryKey(),
17
- organizationId: text("organization_id")
18
- .notNull()
19
- .references(() => organization.id, { onDelete: "cascade" }),
20
- url: text("url").notNull(),
21
- secret: text("secret").notNull(),
22
- events: jsonb("events").$type<string[]>().notNull(),
23
- isActive: boolean("is_active").notNull().default(true),
24
- metadata: jsonb("metadata").$type<Record<string, unknown>>().default({}),
25
- },
26
- (table) => ({
27
- orgIdx: index("idx_webhook_endpoints_org").on(table.organizationId),
28
- }),
29
- );
30
-
31
- /**
32
- * Tracks processed incoming webhook events for idempotency.
33
- * Prevents double-processing when Stripe (or other providers) retry delivery.
34
- */
35
- export const processedWebhookEvents = pgTable("processed_webhook_events", {
36
- id: uuid("id").defaultRandom().primaryKey(),
37
- eventId: text("event_id").notNull().unique(),
38
- provider: text("provider").notNull(), // "stripe", "paypal", etc.
39
- eventType: text("event_type").notNull(),
40
- processedAt: timestamp("processed_at", { withTimezone: true }).defaultNow().notNull(),
41
- });
42
-
43
- export const webhookDeliveries = pgTable("webhook_deliveries", {
44
- id: uuid("id").defaultRandom().primaryKey(),
45
- endpointId: uuid("endpoint_id")
46
- .references(() => webhookEndpoints.id)
47
- .notNull(),
48
- eventName: text("event_name").notNull(),
49
- payload: jsonb("payload").notNull(),
50
- statusCode: integer("status_code"),
51
- attemptCount: integer("attempt_count").notNull().default(0),
52
- nextRetryAt: timestamp("next_retry_at", { withTimezone: true }),
53
- deliveredAt: timestamp("delivered_at", { withTimezone: true }),
54
- failedAt: timestamp("failed_at", { withTimezone: true }),
55
- createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
56
- });
@@ -1,117 +0,0 @@
1
- import { resolveOrgId } from "../../auth/org.js";
2
- import type { Actor } from "../../auth/types.js";
3
- import { CommerceNotFoundError, CommerceValidationError } from "../../kernel/errors.js";
4
- import { Err, Ok, type Result } from "../../kernel/result.js";
5
- import type { TxContext } from "../../kernel/database/tx-context.js";
6
- import type { WebhooksRepository, WebhookEndpoint } from "./repository/index.js";
7
-
8
- /**
9
- * Checks whether a URL points to a private/internal IP address.
10
- * Blocks: loopback (127.x), link-local (169.254.x), private (10.x, 172.16-31.x, 192.168.x),
11
- * cloud metadata (169.254.169.254, metadata.google.internal), and localhost.
12
- */
13
- function isPrivateUrl(urlStr: string): boolean {
14
- try {
15
- const parsed = new URL(urlStr);
16
- // Strip IPv6 brackets: URL.hostname returns "[::1]" not "::1"
17
- const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
18
-
19
- // Loopback (IPv4 + IPv6)
20
- if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") return true;
21
- if (hostname.endsWith(".localhost")) return true;
22
-
23
- // IPv6 loopback and link-local patterns
24
- if (hostname.startsWith("::ffff:")) return true; // IPv6-mapped IPv4 (e.g., ::ffff:127.0.0.1)
25
- if (hostname.startsWith("fe80:")) return true; // IPv6 link-local
26
- if (hostname === "::") return true; // Unspecified address
27
-
28
- // Cloud metadata endpoints
29
- if (hostname === "169.254.169.254") return true;
30
- if (hostname === "metadata.google.internal") return true;
31
-
32
- // Private IP ranges (RFC 1918 + link-local)
33
- const parts = hostname.split(".").map(Number);
34
- if (parts.length === 4 && parts.every((n) => !isNaN(n))) {
35
- const [a, b] = parts;
36
- if (a === 10) return true;
37
- if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true;
38
- if (a === 192 && b === 168) return true;
39
- if (a === 169 && b === 254) return true;
40
- if (a === 127) return true; // Full 127.0.0.0/8 range
41
- if (a === 0) return true;
42
- }
43
-
44
- return false;
45
- } catch {
46
- return true; // Invalid URLs are blocked
47
- }
48
- }
49
-
50
- interface WebhookServiceDeps {
51
- repository: WebhooksRepository;
52
- }
53
-
54
- export class WebhookService {
55
- private readonly repo: WebhooksRepository;
56
-
57
- constructor(private deps: WebhookServiceDeps) {
58
- this.repo = deps.repository;
59
- }
60
-
61
- async createEndpoint(
62
- input: {
63
- url: string;
64
- secret: string;
65
- events: string[];
66
- metadata?: Record<string, unknown>;
67
- },
68
- actor?: Actor | null,
69
- ctx?: TxContext,
70
- ): Promise<Result<WebhookEndpoint>> {
71
- if (isPrivateUrl(input.url)) {
72
- return Err(
73
- new CommerceValidationError(
74
- "Webhook URL must not point to a private or internal address.",
75
- ),
76
- );
77
- }
78
-
79
- const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
80
-
81
- const endpoint = await this.repo.createEndpoint(
82
- {
83
- organizationId: orgId,
84
- url: input.url,
85
- secret: input.secret,
86
- events: input.events,
87
- isActive: true,
88
- metadata: input.metadata ?? {},
89
- },
90
- ctx,
91
- );
92
- return Ok(endpoint);
93
- }
94
-
95
- async listEndpoints(ctx?: TxContext): Promise<Result<WebhookEndpoint[]>> {
96
- const endpoints = await this.repo.findAllEndpoints(ctx);
97
- return Ok(endpoints);
98
- }
99
-
100
- async deleteEndpoint(id: string, ctx?: TxContext): Promise<Result<void>> {
101
- const existing = await this.repo.findEndpointById(id, ctx);
102
- if (!existing) {
103
- return Err(new CommerceNotFoundError("Webhook endpoint not found."));
104
- }
105
-
106
- await this.repo.deleteEndpoint(id, ctx);
107
- return Ok(undefined);
108
- }
109
-
110
- async getEndpointsForEvent(
111
- eventName: string,
112
- ctx?: TxContext,
113
- ): Promise<Result<WebhookEndpoint[]>> {
114
- const endpoints = await this.repo.findEndpointsForEvent(eventName, ctx);
115
- return Ok(endpoints);
116
- }
117
- }
@@ -1,6 +0,0 @@
1
- import { createHmac } from "node:crypto";
2
-
3
- export function signWebhookPayload(secret: string, payload: unknown): string {
4
- const body = typeof payload === "string" ? payload : JSON.stringify(payload);
5
- return createHmac("sha256", secret).update(body).digest("hex");
6
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * Shared SSRF prevention utilities.
3
- *
4
- * Used by both webhook delivery (DNS rebinding check) and connector URL
5
- * validation (store URL check) to reject private/internal IP addresses.
6
- */
7
-
8
- /**
9
- * Returns true if the given IP address falls within a private, loopback,
10
- * link-local, or otherwise non-routable range.
11
- */
12
- export function isPrivateIp(ip: string): boolean {
13
- // IPv6 loopback / link-local / mapped
14
- if (ip === "::1" || ip === "::") return true;
15
- if (ip.startsWith("fe80:")) return true;
16
-
17
- // IPv6-mapped IPv4 (e.g. ::ffff:127.0.0.1) — extract the IPv4 portion
18
- const mappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
19
- if (mappedMatch) {
20
- return isPrivateIpv4(mappedMatch[1]!);
21
- }
22
-
23
- return isPrivateIpv4(ip);
24
- }
25
-
26
- function isPrivateIpv4(ip: string): boolean {
27
- const parts = ip.split(".").map(Number);
28
- if (parts.length !== 4 || parts.some((n) => isNaN(n))) return false;
29
-
30
- const [a, b] = parts;
31
- if (a === undefined || b === undefined) return false;
32
-
33
- if (a === 127) return true; // loopback 127.0.0.0/8
34
- if (a === 10) return true; // RFC 1918 class A
35
- if (a === 172 && b >= 16 && b <= 31) return true; // RFC 1918 class B
36
- if (a === 192 && b === 168) return true; // RFC 1918 class C
37
- if (a === 169 && b === 254) return true; // link-local / AWS IMDS
38
- if (a === 0) return true; // unspecified
39
-
40
- return false;
41
- }
42
-
43
- /**
44
- * Checks whether a URL string points to a private/internal IP address or
45
- * hostname. This performs a string-level check only (no DNS resolution).
46
- *
47
- * For DNS rebinding protection, use `isPrivateIp` after resolving the hostname.
48
- */
49
- export function isPrivateUrl(urlStr: string): boolean {
50
- try {
51
- const parsed = new URL(urlStr);
52
- const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
53
-
54
- // Direct hostname matches
55
- if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
56
- if (hostname === "::1" || hostname === "::") return true;
57
- if (hostname.startsWith("::ffff:")) return true;
58
- if (hostname.startsWith("fe80:")) return true;
59
- if (hostname.endsWith(".local")) return true;
60
- if (hostname.endsWith(".internal")) return true;
61
-
62
- // Cloud metadata endpoints
63
- if (hostname === "169.254.169.254") return true;
64
- if (hostname === "metadata.google.internal") return true;
65
-
66
- // Check if hostname is a raw IP in private ranges
67
- return isPrivateIpv4(hostname);
68
- } catch {
69
- return true; // Invalid URLs are blocked
70
- }
71
- }
@@ -1,52 +0,0 @@
1
- import type { TaskDefinition } from "../../kernel/jobs/types.js";
2
- import { WebhookDeliveryWorker } from "./worker.js";
3
- import type { WebhooksRepository } from "./repository/index.js";
4
-
5
- /**
6
- * Background task for async webhook delivery.
7
- *
8
- * Instead of blocking the HTTP response with inline webhook HTTP calls,
9
- * the deliverWebhooks hook enqueues this task. The job runner picks it up
10
- * and delivers asynchronously with retries.
11
- */
12
- export const webhookDeliveryTask: TaskDefinition<{
13
- endpointId: string;
14
- endpointUrl: string;
15
- endpointSecret: string;
16
- eventName: string;
17
- payload: unknown;
18
- }> = {
19
- slug: "webhooks/deliver",
20
-
21
- async handler({ input, ctx }) {
22
- const webhooksService = ctx.services.webhooks as {
23
- repository?: WebhooksRepository;
24
- };
25
-
26
- // Build a minimal worker — the repository is needed for delivery tracking
27
- const repository = webhooksService?.repository;
28
- if (!repository) {
29
- ctx.logger.warn("Webhook delivery skipped: no webhooks repository available");
30
- return { output: {} };
31
- }
32
-
33
- const worker = new WebhookDeliveryWorker({ repository });
34
-
35
- await worker.deliver({
36
- endpoint: {
37
- id: input.endpointId,
38
- url: input.endpointUrl,
39
- secret: input.endpointSecret,
40
- },
41
- eventName: input.eventName,
42
- payload: input.payload,
43
- });
44
-
45
- return { output: {} };
46
- },
47
-
48
- retries: {
49
- attempts: 5,
50
- backoff: { type: "exponential", delay: 2000 },
51
- },
52
- };