@hogsend/engine 0.41.0 → 0.43.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/package.json +12 -9
- package/src/container.ts +192 -4
- package/src/env.ts +28 -0
- package/src/index.ts +53 -0
- package/src/journeys/execute-journey-run.ts +50 -17
- package/src/journeys/journey-boundary.ts +5 -1
- package/src/journeys/journey-context.ts +58 -0
- package/src/lib/blueprint-lock.ts +21 -0
- package/src/lib/blueprints.ts +273 -46
- package/src/lib/event-names.ts +143 -0
- package/src/lib/journey-suppress.ts +33 -2
- package/src/lib/outbound.ts +58 -0
- package/src/lib/phone.ts +19 -0
- package/src/lib/preferences.ts +32 -0
- package/src/lib/sms-frequency-cap.ts +47 -0
- package/src/lib/sms-inbound.ts +200 -0
- package/src/lib/sms-link-tracking.ts +160 -0
- package/src/lib/sms-mailer.ts +338 -0
- package/src/lib/sms-provider-registry.ts +35 -0
- package/src/lib/sms-providers-from-env.ts +100 -0
- package/src/lib/sms-service-types.ts +169 -0
- package/src/lib/sms-tracked.ts +590 -0
- package/src/lib/sms.ts +117 -0
- package/src/lib/tracking-event-names.ts +6 -0
- package/src/lib/tracking-events.ts +107 -1
- package/src/lib/tracking.ts +3 -6
- package/src/lib/webhook-signing.ts +17 -1
- package/src/lists/channels.ts +21 -0
- package/src/mcp/authoring-guide.ts +160 -0
- package/src/mcp/blueprint-tools.ts +38 -108
- package/src/middleware/require-admin.ts +13 -0
- package/src/routes/admin/api-keys.ts +72 -0
- package/src/routes/admin/blueprints.ts +94 -10
- package/src/routes/admin/events.ts +55 -0
- package/src/routes/email/unsubscribe.ts +1 -0
- package/src/routes/index.ts +6 -0
- package/src/routes/lists/index.ts +54 -7
- package/src/routes/tracking/click-pipeline.ts +83 -2
- package/src/routes/tracking/short.ts +61 -0
- package/src/routes/webhooks/index.ts +5 -1
- package/src/routes/webhooks/sms-provider.ts +110 -0
- package/src/workflows/import-contacts.ts +61 -4
- package/src/workflows/journey-blueprint-interpreter.ts +128 -33
|
@@ -20,6 +20,50 @@ const apiKeySchema = z.object({
|
|
|
20
20
|
createdAt: z.string(),
|
|
21
21
|
});
|
|
22
22
|
|
|
23
|
+
// The authenticated credential's identity, discriminated on how the request
|
|
24
|
+
// authenticated. The Bearer path echoes the key requireAdmin already resolved
|
|
25
|
+
// (id/name/scopes only — NEVER the key material); the cookie path echoes the
|
|
26
|
+
// session user.
|
|
27
|
+
const selfApiKeyActorSchema = z.object({
|
|
28
|
+
actor: z.literal("api-key"),
|
|
29
|
+
id: z.string(),
|
|
30
|
+
name: z.string(),
|
|
31
|
+
scopes: z.array(z.string()),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const selfSessionActorSchema = z.object({
|
|
35
|
+
actor: z.literal("session"),
|
|
36
|
+
email: z.string(),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const selfRoute = createRoute({
|
|
40
|
+
method: "get",
|
|
41
|
+
path: "/self",
|
|
42
|
+
tags: ["Admin — API Keys"],
|
|
43
|
+
summary: "Identify the authenticated credential",
|
|
44
|
+
description:
|
|
45
|
+
"Returns the identity this request authenticated as — the resolved API " +
|
|
46
|
+
"key (id, name, scopes; never the key material) for Bearer auth, or the " +
|
|
47
|
+
"session user's email for cookie auth.",
|
|
48
|
+
responses: {
|
|
49
|
+
200: {
|
|
50
|
+
content: {
|
|
51
|
+
"application/json": {
|
|
52
|
+
schema: z.discriminatedUnion("actor", [
|
|
53
|
+
selfApiKeyActorSchema,
|
|
54
|
+
selfSessionActorSchema,
|
|
55
|
+
]),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
description: "The authenticated credential's identity",
|
|
59
|
+
},
|
|
60
|
+
401: {
|
|
61
|
+
content: { "application/json": { schema: errorSchema } },
|
|
62
|
+
description: "No resolved credential on the request",
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
23
67
|
const listRoute = createRoute({
|
|
24
68
|
method: "get",
|
|
25
69
|
path: "/",
|
|
@@ -152,6 +196,34 @@ function serializeKey(row: typeof apiKeys.$inferSelect) {
|
|
|
152
196
|
}
|
|
153
197
|
|
|
154
198
|
export const apiKeysRouter = new OpenAPIHono<AppEnv>()
|
|
199
|
+
// Registered before any param route so a literal "self" can never be
|
|
200
|
+
// captured as an {id}.
|
|
201
|
+
.openapi(selfRoute, (c) => {
|
|
202
|
+
const apiKey = c.get("apiKey");
|
|
203
|
+
if (apiKey) {
|
|
204
|
+
return c.json(
|
|
205
|
+
{
|
|
206
|
+
actor: "api-key" as const,
|
|
207
|
+
id: apiKey.id,
|
|
208
|
+
name: apiKey.name,
|
|
209
|
+
scopes: apiKey.scopes,
|
|
210
|
+
},
|
|
211
|
+
200,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const sessionUser = c.get("user");
|
|
216
|
+
if (sessionUser) {
|
|
217
|
+
return c.json(
|
|
218
|
+
{ actor: "session" as const, email: sessionUser.email },
|
|
219
|
+
200,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// requireAdmin always resolves one of the two before this handler runs —
|
|
224
|
+
// defensive fallback only.
|
|
225
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
226
|
+
})
|
|
155
227
|
.openapi(listRoute, async (c) => {
|
|
156
228
|
const { db } = c.get("container");
|
|
157
229
|
const { limit, offset, includeRevoked } = c.req.valid("query");
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* Result → status mapping (uniform across handlers):
|
|
14
14
|
* - `invalid_graph` → 422 with the structured `BlueprintValidationIssue[]`
|
|
15
15
|
* verbatim (never a caught exception message)
|
|
16
|
-
* - `not_found` → 404, `conflict`/`promoted`/`in_flight`
|
|
16
|
+
* - `not_found` → 404, `conflict`/`promoted`/`already_promoted`/`in_flight`
|
|
17
|
+
* → 409
|
|
17
18
|
*
|
|
18
19
|
* A graph-changing update is REJECTED (`in_flight` → 409) while the
|
|
19
20
|
* blueprint has any active/waiting `journeyStates` rows — Hatchet's durable
|
|
@@ -40,6 +41,7 @@ import {
|
|
|
40
41
|
disableBlueprint,
|
|
41
42
|
enableBlueprint,
|
|
42
43
|
findBlueprintRow,
|
|
44
|
+
promoteBlueprint,
|
|
43
45
|
serializeBlueprint,
|
|
44
46
|
serializedBlueprintSchema,
|
|
45
47
|
updateBlueprint,
|
|
@@ -77,6 +79,24 @@ const invalidGraphSchema = z.object({
|
|
|
77
79
|
issues: z.array(validationIssueSchema),
|
|
78
80
|
});
|
|
79
81
|
|
|
82
|
+
/**
|
|
83
|
+
* 409 body: the neutral error message PLUS the machine-readable service `code`
|
|
84
|
+
* (`conflict` | `in_flight` | `promoted` | `already_promoted` |
|
|
85
|
+
* `version_conflict`). A programmatic caller (e.g. `@hogsend/mcp`) branches on
|
|
86
|
+
* `code` instead of sniffing the message. `error` stays present and unchanged
|
|
87
|
+
* for existing consumers.
|
|
88
|
+
*/
|
|
89
|
+
const conflictSchema = z.object({
|
|
90
|
+
error: z.string(),
|
|
91
|
+
code: z.enum([
|
|
92
|
+
"conflict",
|
|
93
|
+
"in_flight",
|
|
94
|
+
"promoted",
|
|
95
|
+
"already_promoted",
|
|
96
|
+
"version_conflict",
|
|
97
|
+
]),
|
|
98
|
+
});
|
|
99
|
+
|
|
80
100
|
/** The dry-run validate report — 200 either way (a failed validation is a
|
|
81
101
|
* successful validation CALL; this is the agent's iterate-in-a-loop surface). */
|
|
82
102
|
const validationReportSchema = z.object({
|
|
@@ -173,7 +193,7 @@ const createRouteDef = createRoute({
|
|
|
173
193
|
description: "Blueprint created",
|
|
174
194
|
},
|
|
175
195
|
409: {
|
|
176
|
-
content: { "application/json": { schema:
|
|
196
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
177
197
|
description:
|
|
178
198
|
"Blueprint id already exists, or collides with a registered code journey",
|
|
179
199
|
},
|
|
@@ -247,7 +267,9 @@ const patchRouteDef = createRoute({
|
|
|
247
267
|
"blueprint has any active/waiting enrollment, since a graph edit can " +
|
|
248
268
|
"desync Hatchet's replay journal for a run suspended mid-graph. " +
|
|
249
269
|
"Metadata-only edits do not bump and are never blocked. Status " +
|
|
250
|
-
"transitions go through /enable and /disable, not PATCH."
|
|
270
|
+
"transitions go through /enable and /disable, not PATCH. A blueprint " +
|
|
271
|
+
"promoted to code (see /promote) is frozen and rejects every update " +
|
|
272
|
+
"(409) — the code journey is the source of truth.",
|
|
251
273
|
request: {
|
|
252
274
|
params: z.object({ id: z.string() }),
|
|
253
275
|
body: {
|
|
@@ -268,9 +290,11 @@ const patchRouteDef = createRoute({
|
|
|
268
290
|
description: "Blueprint not found",
|
|
269
291
|
},
|
|
270
292
|
409: {
|
|
271
|
-
content: { "application/json": { schema:
|
|
293
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
272
294
|
description:
|
|
273
|
-
"Graph change rejected — the blueprint has active/waiting
|
|
295
|
+
"Graph change rejected — the blueprint has active/waiting " +
|
|
296
|
+
"enrollments, was promoted to code, or was edited concurrently " +
|
|
297
|
+
"(version conflict — re-read and retry)",
|
|
274
298
|
},
|
|
275
299
|
422: {
|
|
276
300
|
content: { "application/json": { schema: invalidGraphSchema } },
|
|
@@ -330,7 +354,7 @@ const enableRouteDef = createRoute({
|
|
|
330
354
|
description: "Blueprint not found",
|
|
331
355
|
},
|
|
332
356
|
409: {
|
|
333
|
-
content: { "application/json": { schema:
|
|
357
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
334
358
|
description:
|
|
335
359
|
"Blueprint was promoted to code — the code journey is the source of truth",
|
|
336
360
|
},
|
|
@@ -369,6 +393,47 @@ const disableRouteDef = createRoute({
|
|
|
369
393
|
},
|
|
370
394
|
});
|
|
371
395
|
|
|
396
|
+
const promoteRouteDef = createRoute({
|
|
397
|
+
method: "post",
|
|
398
|
+
path: "/{id}/promote",
|
|
399
|
+
tags: ["Admin — Blueprints"],
|
|
400
|
+
summary: "Mark a blueprint as promoted to a code journey",
|
|
401
|
+
description:
|
|
402
|
+
"Records that a generated code journey is now the source of truth " +
|
|
403
|
+
"(spec §11): stamps `promotedAt`/`promotedToJourneyId` and disables the " +
|
|
404
|
+
"blueprint in one update. A promoted blueprint can never be re-enabled. " +
|
|
405
|
+
"This is ONLY the DB state transition — codegen (blueprint → " +
|
|
406
|
+
"`defineJourney()` file) happens in the CLI, not here.",
|
|
407
|
+
request: {
|
|
408
|
+
params: z.object({ id: z.string() }),
|
|
409
|
+
body: {
|
|
410
|
+
content: {
|
|
411
|
+
"application/json": {
|
|
412
|
+
schema: z.object({ journeyId: z.string().min(1) }),
|
|
413
|
+
},
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
},
|
|
417
|
+
responses: {
|
|
418
|
+
200: {
|
|
419
|
+
content: {
|
|
420
|
+
"application/json": {
|
|
421
|
+
schema: z.object({ blueprint: blueprintSchema }),
|
|
422
|
+
},
|
|
423
|
+
},
|
|
424
|
+
description: "Blueprint promoted and disabled",
|
|
425
|
+
},
|
|
426
|
+
404: {
|
|
427
|
+
content: { "application/json": { schema: errorSchema } },
|
|
428
|
+
description: "Blueprint not found",
|
|
429
|
+
},
|
|
430
|
+
409: {
|
|
431
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
432
|
+
description: "Blueprint was already promoted",
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
|
|
372
437
|
// Byte-identical response shape to GET /v1/admin/journeys/{id}/graph — the
|
|
373
438
|
// SAME Studio flow-view component renders either without modification
|
|
374
439
|
// (spec §3/§9). `templateKey` needs no resolution cascade here: a blueprint
|
|
@@ -496,7 +561,7 @@ blueprintsRouter.openapi(createRouteDef, async (c) => {
|
|
|
496
561
|
if (result.code === "invalid_graph") {
|
|
497
562
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
498
563
|
}
|
|
499
|
-
return c.json({ error: result.error }, 409);
|
|
564
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
500
565
|
}
|
|
501
566
|
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 201);
|
|
502
567
|
});
|
|
@@ -568,8 +633,12 @@ blueprintsRouter.openapi(patchRouteDef, async (c) => {
|
|
|
568
633
|
if (result.code === "invalid_graph") {
|
|
569
634
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
570
635
|
}
|
|
571
|
-
if (
|
|
572
|
-
|
|
636
|
+
if (
|
|
637
|
+
result.code === "in_flight" ||
|
|
638
|
+
result.code === "promoted" ||
|
|
639
|
+
result.code === "version_conflict"
|
|
640
|
+
) {
|
|
641
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
573
642
|
}
|
|
574
643
|
return c.json({ error: result.error }, 404);
|
|
575
644
|
}
|
|
@@ -604,7 +673,7 @@ blueprintsRouter.openapi(enableRouteDef, async (c) => {
|
|
|
604
673
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
605
674
|
}
|
|
606
675
|
if (result.code === "promoted") {
|
|
607
|
-
return c.json({ error: result.error }, 409);
|
|
676
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
608
677
|
}
|
|
609
678
|
return c.json({ error: result.error }, 404);
|
|
610
679
|
}
|
|
@@ -622,6 +691,21 @@ blueprintsRouter.openapi(disableRouteDef, async (c) => {
|
|
|
622
691
|
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
|
|
623
692
|
});
|
|
624
693
|
|
|
694
|
+
blueprintsRouter.openapi(promoteRouteDef, async (c) => {
|
|
695
|
+
const container = c.get("container");
|
|
696
|
+
const { id } = c.req.valid("param");
|
|
697
|
+
const { journeyId } = c.req.valid("json");
|
|
698
|
+
|
|
699
|
+
const result = await promoteBlueprint({ container, id, journeyId });
|
|
700
|
+
if (!result.ok) {
|
|
701
|
+
if (result.code === "already_promoted") {
|
|
702
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
703
|
+
}
|
|
704
|
+
return c.json({ error: result.error }, 404);
|
|
705
|
+
}
|
|
706
|
+
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
|
|
707
|
+
});
|
|
708
|
+
|
|
625
709
|
blueprintsRouter.openapi(graphRouteDef, async (c) => {
|
|
626
710
|
const { db, templates } = c.get("container");
|
|
627
711
|
const { id } = c.req.valid("param");
|
|
@@ -2,6 +2,10 @@ import { contacts, userEvents } from "@hogsend/db";
|
|
|
2
2
|
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
3
|
import { and, count, desc, eq, gte, isNull, lte, or, sql } from "drizzle-orm";
|
|
4
4
|
import type { AppEnv } from "../../app.js";
|
|
5
|
+
import {
|
|
6
|
+
eventNameEntrySchema,
|
|
7
|
+
listEventNameVocabulary,
|
|
8
|
+
} from "../../lib/event-names.js";
|
|
5
9
|
import { ingestEvent } from "../../lib/ingestion.js";
|
|
6
10
|
|
|
7
11
|
const eventSchema = z.object({
|
|
@@ -114,6 +118,41 @@ const getRoute = createRoute({
|
|
|
114
118
|
},
|
|
115
119
|
});
|
|
116
120
|
|
|
121
|
+
const namesRoute = createRoute({
|
|
122
|
+
method: "get",
|
|
123
|
+
path: "/names",
|
|
124
|
+
tags: ["Admin — Events"],
|
|
125
|
+
summary: "List event names (observed + declared)",
|
|
126
|
+
description:
|
|
127
|
+
"Best-effort event-name vocabulary for authoring triggers, waits, and " +
|
|
128
|
+
"exitOn rules. Event names are an OPEN vocabulary (no closed registry " +
|
|
129
|
+
"exists anywhere in the engine), so this merges: events actually " +
|
|
130
|
+
"observed in the event store (with occurrence counts, most recently " +
|
|
131
|
+
"seen first) and events referenced as code-journey or blueprint " +
|
|
132
|
+
"triggers. Any other event name is also valid — it just hasn't been " +
|
|
133
|
+
"seen yet.",
|
|
134
|
+
request: {
|
|
135
|
+
query: z.object({
|
|
136
|
+
// Case-insensitive substring filter on the event name.
|
|
137
|
+
search: z.string().min(1).optional(),
|
|
138
|
+
limit: z.coerce.number().int().min(1).max(200).default(100),
|
|
139
|
+
}),
|
|
140
|
+
},
|
|
141
|
+
responses: {
|
|
142
|
+
200: {
|
|
143
|
+
content: {
|
|
144
|
+
"application/json": {
|
|
145
|
+
schema: z.object({
|
|
146
|
+
note: z.string(),
|
|
147
|
+
events: z.array(eventNameEntrySchema),
|
|
148
|
+
}),
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
description: "Merged observed + declared event-name vocabulary",
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
|
|
117
156
|
const exitSchema = z.object({
|
|
118
157
|
journeyId: z.string(),
|
|
119
158
|
stateId: z.string(),
|
|
@@ -217,6 +256,22 @@ export const eventsRouter = new OpenAPIHono<AppEnv>()
|
|
|
217
256
|
200,
|
|
218
257
|
);
|
|
219
258
|
})
|
|
259
|
+
// Registered before getRoute so the literal "names" is never captured as
|
|
260
|
+
// an {id}. Delegates to the shared vocabulary helper (lib/event-names.ts)
|
|
261
|
+
// — the same implementation the blueprint tools' `list_events` serves, so
|
|
262
|
+
// the HTTP surface and the in-process tool can never drift.
|
|
263
|
+
.openapi(namesRoute, async (c) => {
|
|
264
|
+
const { db, registry } = c.get("container");
|
|
265
|
+
const { search, limit } = c.req.valid("query");
|
|
266
|
+
|
|
267
|
+
const { note, events } = await listEventNameVocabulary({
|
|
268
|
+
db,
|
|
269
|
+
registry,
|
|
270
|
+
search,
|
|
271
|
+
limit,
|
|
272
|
+
});
|
|
273
|
+
return c.json({ note, events }, 200);
|
|
274
|
+
})
|
|
220
275
|
.openapi(getRoute, async (c) => {
|
|
221
276
|
const { db } = c.get("container");
|
|
222
277
|
const { id } = c.req.valid("param");
|
package/src/routes/index.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { feedRouter } from "./feed/index.js";
|
|
|
15
15
|
import { healthRouter } from "./health.js";
|
|
16
16
|
import { listsRouter } from "./lists/index.js";
|
|
17
17
|
import { trackingRouter } from "./tracking/index.js";
|
|
18
|
+
import { shortLinkRouter } from "./tracking/short.js";
|
|
18
19
|
import { vanityRouter } from "./tracking/vanity.js";
|
|
19
20
|
import { registerWebhookRoutes } from "./webhooks/index.js";
|
|
20
21
|
|
|
@@ -141,6 +142,11 @@ export function registerRoutes(
|
|
|
141
142
|
// surface (vanity links land in chats/posts/print).
|
|
142
143
|
app.route("/", vanityRouter);
|
|
143
144
|
|
|
145
|
+
// SMS short link redirect — root-mounted so the texted URL stays short
|
|
146
|
+
// (`${SMS_LINK_HOST ?? API_PUBLIC_URL}/s/:code`); every character counts
|
|
147
|
+
// against the GSM-7 segment budget. Unauthenticated like /l.
|
|
148
|
+
app.route("/", shortLinkRouter);
|
|
149
|
+
|
|
144
150
|
// Generic connector dispatch (oauth/interactions/ingress) — the static
|
|
145
151
|
// `connectors/` prefix is registered BEFORE the `:sourceId` webhook catch-all
|
|
146
152
|
// so it wins path matching. These routes self-authenticate (oauth state +
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
|
|
2
|
-
import { type Database, emailPreferences } from "@hogsend/db";
|
|
2
|
+
import { contacts, type Database, emailPreferences } from "@hogsend/db";
|
|
3
3
|
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
4
4
|
import { and, eq } from "drizzle-orm";
|
|
5
5
|
import type { AppEnv } from "../../app.js";
|
|
@@ -17,6 +17,8 @@ import {
|
|
|
17
17
|
upsertEmailPreference,
|
|
18
18
|
} from "../../lib/preferences.js";
|
|
19
19
|
import { errorSchema } from "../../lib/schemas.js";
|
|
20
|
+
import { grantPhoneConsent, recordPhoneOptOut } from "../../lib/sms-inbound.js";
|
|
21
|
+
import { SMS_CHANNEL_ID } from "../../lib/sms-tracked.js";
|
|
20
22
|
import { getListRegistry } from "../../lists/registry-singleton.js";
|
|
21
23
|
import {
|
|
22
24
|
gatePublishableIdentity,
|
|
@@ -319,12 +321,25 @@ async function applyListSubscription(opts: {
|
|
|
319
321
|
|
|
320
322
|
emitContactCreatedIfNew({ db, hatchet, logger, contactId, created });
|
|
321
323
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
324
|
+
try {
|
|
325
|
+
await applyListMembership({
|
|
326
|
+
db,
|
|
327
|
+
userId,
|
|
328
|
+
email,
|
|
329
|
+
lists: { [id]: subscribed },
|
|
330
|
+
});
|
|
331
|
+
} catch (err) {
|
|
332
|
+
// Phone-track fallback for the explicit-consent `sms` channel: a
|
|
333
|
+
// phone-only contact has no email, so `email_preferences` cannot hold
|
|
334
|
+
// its grant — record consent/opt-out on the phone-keyed
|
|
335
|
+
// `sms_suppressions` track instead (the same record an inbound
|
|
336
|
+
// START/STOP writes). Only the missing-email failure falls back; any
|
|
337
|
+
// other error keeps the normal failure path.
|
|
338
|
+
const fellBack =
|
|
339
|
+
id === SMS_CHANNEL_ID &&
|
|
340
|
+
(await applySmsPhoneTrackFallback({ db, contactId, subscribed, err }));
|
|
341
|
+
if (!fellBack) throw err;
|
|
342
|
+
}
|
|
328
343
|
} catch (err) {
|
|
329
344
|
return { kind: "failed", message: listMembershipError(err) };
|
|
330
345
|
}
|
|
@@ -332,6 +347,38 @@ async function applyListSubscription(opts: {
|
|
|
332
347
|
return { kind: "ok" };
|
|
333
348
|
}
|
|
334
349
|
|
|
350
|
+
/**
|
|
351
|
+
* The `sms` grant/revoke for a contact `applyListMembership` rejected for
|
|
352
|
+
* having no email. Returns true when the contact has a phone and the
|
|
353
|
+
* phone-track write happened; false re-raises the original failure (no phone
|
|
354
|
+
* either, or a different error entirely).
|
|
355
|
+
*/
|
|
356
|
+
async function applySmsPhoneTrackFallback(opts: {
|
|
357
|
+
db: Database;
|
|
358
|
+
contactId: string;
|
|
359
|
+
subscribed: boolean;
|
|
360
|
+
err: unknown;
|
|
361
|
+
}): Promise<boolean> {
|
|
362
|
+
const { db, contactId, subscribed, err } = opts;
|
|
363
|
+
const message = err instanceof Error ? err.message : "";
|
|
364
|
+
if (!message.includes("no email")) return false;
|
|
365
|
+
|
|
366
|
+
const rows = await db
|
|
367
|
+
.select({ phone: contacts.phone })
|
|
368
|
+
.from(contacts)
|
|
369
|
+
.where(eq(contacts.id, contactId))
|
|
370
|
+
.limit(1);
|
|
371
|
+
const phone = rows[0]?.phone;
|
|
372
|
+
if (!phone) return false;
|
|
373
|
+
|
|
374
|
+
if (subscribed) {
|
|
375
|
+
await grantPhoneConsent(db, phone, { reason: "api_grant" });
|
|
376
|
+
} else {
|
|
377
|
+
await recordPhoneOptOut(db, phone, "manual");
|
|
378
|
+
}
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
|
|
335
382
|
// The lists router does NOT re-apply auth internally — the data-plane prefix
|
|
336
383
|
// guards in `routes/index.ts` (decision #16) apply `requireApiKey` +
|
|
337
384
|
// `requireScope("ingest")` to `/v1/lists` (bare + `/*`) before requests reach
|
|
@@ -1,16 +1,27 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
emailSends,
|
|
4
|
+
linkClicks,
|
|
5
|
+
links,
|
|
6
|
+
smsSends,
|
|
7
|
+
trackedLinks,
|
|
8
|
+
} from "@hogsend/db";
|
|
3
9
|
import { and, eq, isNull, sql } from "drizzle-orm";
|
|
4
10
|
import type { Context } from "hono";
|
|
5
11
|
import type { AppEnv } from "../../app.js";
|
|
6
12
|
import { isBotOrPrefetch } from "../../lib/bot-prefetch.js";
|
|
7
13
|
import { generateIdentityToken } from "../../lib/identity-token.js";
|
|
8
14
|
import { emitOutbound } from "../../lib/outbound.js";
|
|
9
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
EMAIL_LINK_CLICKED,
|
|
17
|
+
SMS_LINK_CLICKED,
|
|
18
|
+
} from "../../lib/tracking-event-names.js";
|
|
10
19
|
import {
|
|
11
20
|
pushLinkClickEvent,
|
|
21
|
+
pushSmsTrackingEvent,
|
|
12
22
|
pushTrackingEvent,
|
|
13
23
|
resolveEmailSendContext,
|
|
24
|
+
resolveSmsSendContext,
|
|
14
25
|
} from "../../lib/tracking-events.js";
|
|
15
26
|
import { confirmSemanticClickTask } from "../../workflows/confirm-semantic-click.js";
|
|
16
27
|
|
|
@@ -21,6 +32,10 @@ export const clickSelection = {
|
|
|
21
32
|
id: trackedLinks.id,
|
|
22
33
|
originalUrl: trackedLinks.originalUrl,
|
|
23
34
|
emailSendId: trackedLinks.emailSendId,
|
|
35
|
+
// The SMS send this per-send short link belongs to (`/s/:code` rewrites).
|
|
36
|
+
// Selected on EVERY resolver, so an SMS row clicked via its raw
|
|
37
|
+
// `/v1/t/c/:id` URL still gets full SMS semantics.
|
|
38
|
+
smsSendId: trackedLinks.smsSendId,
|
|
24
39
|
distinctId: trackedLinks.distinctId,
|
|
25
40
|
source: trackedLinks.source,
|
|
26
41
|
// `event` gates the semantic-confirm dispatch; the confirm task re-reads the
|
|
@@ -41,6 +56,7 @@ export type ResolvedClickLink = {
|
|
|
41
56
|
id: string;
|
|
42
57
|
originalUrl: string;
|
|
43
58
|
emailSendId: string | null;
|
|
59
|
+
smsSendId: string | null;
|
|
44
60
|
distinctId: string | null;
|
|
45
61
|
source: string | null;
|
|
46
62
|
event: string | null;
|
|
@@ -127,6 +143,20 @@ export async function handleTrackedClick(
|
|
|
127
143
|
),
|
|
128
144
|
]
|
|
129
145
|
: []),
|
|
146
|
+
// SMS first-touch mirror: set sms_sends.clickedAt exactly once.
|
|
147
|
+
...(link.smsSendId
|
|
148
|
+
? [
|
|
149
|
+
db
|
|
150
|
+
.update(smsSends)
|
|
151
|
+
.set({
|
|
152
|
+
clickedAt: new Date(),
|
|
153
|
+
updatedAt: new Date(),
|
|
154
|
+
})
|
|
155
|
+
.where(
|
|
156
|
+
and(eq(smsSends.id, link.smsSendId), isNull(smsSends.clickedAt)),
|
|
157
|
+
),
|
|
158
|
+
]
|
|
159
|
+
: []),
|
|
130
160
|
]);
|
|
131
161
|
|
|
132
162
|
const { hatchet, registry, logger } = c.get("container");
|
|
@@ -275,6 +305,57 @@ export async function handleTrackedClick(
|
|
|
275
305
|
}
|
|
276
306
|
})
|
|
277
307
|
.catch(logger.warn);
|
|
308
|
+
} else if (link.smsSendId) {
|
|
309
|
+
// SMS short link (`/s/:code`): re-ingest the first-party
|
|
310
|
+
// `sms.link_clicked` bus event and emit the per-hit `sms.clicked`
|
|
311
|
+
// outbound — the SMS sibling of the email branch above. The bus
|
|
312
|
+
// re-ingest is GATED on `!isBot` (iMessage/WhatsApp/RCS link-preview
|
|
313
|
+
// bots prefetch texted URLs — a phantom-enrollment risk the email
|
|
314
|
+
// branch doesn't share because inbox clicks aren't unfurl-prefetched
|
|
315
|
+
// the same way) AND on a resolved contact key (phone is NOT a contact
|
|
316
|
+
// `Kind`; a userless raw send has no subject to ingest).
|
|
317
|
+
const smsSendId = link.smsSendId;
|
|
318
|
+
void resolveSmsSendContext(db, smsSendId)
|
|
319
|
+
.then(async (ctx) => {
|
|
320
|
+
if (!isBot && ctx?.userId) {
|
|
321
|
+
await pushSmsTrackingEvent({
|
|
322
|
+
db,
|
|
323
|
+
hatchet,
|
|
324
|
+
registry,
|
|
325
|
+
logger,
|
|
326
|
+
event: SMS_LINK_CLICKED,
|
|
327
|
+
smsSendId,
|
|
328
|
+
properties: { linkUrl: link.originalUrl, linkId: link.id },
|
|
329
|
+
resolvedContext: ctx,
|
|
330
|
+
}).catch((err) => {
|
|
331
|
+
logger.warn("Failed to push sms click tracking event", {
|
|
332
|
+
linkId: link.id,
|
|
333
|
+
error: err instanceof Error ? err.message : String(err),
|
|
334
|
+
});
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
// Per-hit outbound — mirrors the email click emit (every destination
|
|
338
|
+
// gets every click; NO dedupeKey). Gated on a resolved send row only.
|
|
339
|
+
if (ctx) {
|
|
340
|
+
await emitOutbound({
|
|
341
|
+
db,
|
|
342
|
+
hatchet,
|
|
343
|
+
logger,
|
|
344
|
+
event: "sms.clicked",
|
|
345
|
+
payload: {
|
|
346
|
+
smsSendId,
|
|
347
|
+
messageId: ctx.messageId ?? null,
|
|
348
|
+
templateKey: ctx.templateKey ?? null,
|
|
349
|
+
userId: ctx.userId ?? null,
|
|
350
|
+
to: ctx.to,
|
|
351
|
+
at: new Date().toISOString(),
|
|
352
|
+
linkUrl: link.originalUrl,
|
|
353
|
+
linkId: link.id,
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
})
|
|
358
|
+
.catch(logger.warn);
|
|
278
359
|
} else {
|
|
279
360
|
// Non-email tracked link: emit the catalogued `link.clicked` (NOT
|
|
280
361
|
// `email.clicked`). `userId` is the link's stitch subject when
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { links, trackedLinks } from "@hogsend/db";
|
|
2
|
+
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
import type { AppEnv } from "../../app.js";
|
|
5
|
+
import { clickSelection, handleTrackedClick } from "./click-pipeline.js";
|
|
6
|
+
|
|
7
|
+
// The SMS short path — `/s/:code` layered over `/v1/t/c/:id`, mirroring the
|
|
8
|
+
// vanity `/l/:slug` route. Mounted at the APP ROOT so the texted URL stays
|
|
9
|
+
// short (every character counts against the GSM-7 segment budget); `/s`
|
|
10
|
+
// collides with nothing (`/v1`, `/l`, `/studio`, `/docs`, `/api/auth`,
|
|
11
|
+
// `/connectors`, webhooks).
|
|
12
|
+
const shortRoute = createRoute({
|
|
13
|
+
method: "get",
|
|
14
|
+
path: "/s/:code",
|
|
15
|
+
tags: ["Tracking"],
|
|
16
|
+
summary: "SMS short link redirect",
|
|
17
|
+
request: {
|
|
18
|
+
params: z.object({
|
|
19
|
+
code: z.string(),
|
|
20
|
+
}),
|
|
21
|
+
},
|
|
22
|
+
responses: {
|
|
23
|
+
302: { description: "Redirect to original URL" },
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Lenient superset of minted codes (8-char lowercase base32): tolerate a
|
|
28
|
+
// hand-retyped code without rejecting future length changes.
|
|
29
|
+
const SHORT_CODE_RE = /^[a-z0-9]{4,32}$/;
|
|
30
|
+
|
|
31
|
+
export const shortLinkRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
32
|
+
shortRoute,
|
|
33
|
+
async (c) => {
|
|
34
|
+
const { code } = c.req.valid("param");
|
|
35
|
+
const { db, env } = c.get("container");
|
|
36
|
+
|
|
37
|
+
// Codes are minted lowercase; normalize a cased retype. A malformed code
|
|
38
|
+
// can't match anything — treat it like an unknown link (redirect home),
|
|
39
|
+
// mirroring the vanity route's malformed-slug behavior.
|
|
40
|
+
const normalized = code.trim().toLowerCase();
|
|
41
|
+
if (!SHORT_CODE_RE.test(normalized)) {
|
|
42
|
+
return c.redirect(env.API_PUBLIC_URL, 302);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// LEFT JOIN links purely to satisfy the shared clickSelection shape —
|
|
46
|
+
// SMS-minted rows have `link_id` NULL (mirrors the UUID route).
|
|
47
|
+
const rows = await db
|
|
48
|
+
.select(clickSelection)
|
|
49
|
+
.from(trackedLinks)
|
|
50
|
+
.leftJoin(links, eq(trackedLinks.linkId, links.id))
|
|
51
|
+
.where(eq(trackedLinks.shortCode, normalized))
|
|
52
|
+
.limit(1);
|
|
53
|
+
|
|
54
|
+
const link = rows[0];
|
|
55
|
+
if (!link) {
|
|
56
|
+
return c.redirect(env.API_PUBLIC_URL, 302);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return handleTrackedClick(c, link);
|
|
60
|
+
},
|
|
61
|
+
);
|
|
@@ -3,6 +3,7 @@ import type { AppEnv } from "../../app.js";
|
|
|
3
3
|
import type { DefinedConnector } from "../../connectors/define-connector.js";
|
|
4
4
|
import { registerEmailProviderRoutes } from "./email-provider.js";
|
|
5
5
|
import { resendWebhookRouter } from "./resend.js";
|
|
6
|
+
import { registerSmsProviderRoutes } from "./sms-provider.js";
|
|
6
7
|
import { registerWebhookSourceRoutes } from "./sources.js";
|
|
7
8
|
|
|
8
9
|
export interface RegisterWebhookRoutesOptions {
|
|
@@ -17,8 +18,11 @@ export function registerWebhookRoutes(
|
|
|
17
18
|
// 1. the thin `/v1/webhooks/resend` alias (static),
|
|
18
19
|
// 2. the `/v1/webhooks/email/:providerId` id-dispatched route (static
|
|
19
20
|
// `email/` prefix — MUST come before the catch-all),
|
|
20
|
-
// 3. the `/v1/webhooks/:
|
|
21
|
+
// 3. the `/v1/webhooks/sms/:providerId` id-dispatched route (static `sms/`
|
|
22
|
+
// prefix — MUST come before the catch-all),
|
|
23
|
+
// 4. the `/v1/webhooks/:sourceId` consumer-source catch-all (LAST).
|
|
21
24
|
app.route("/v1/webhooks", resendWebhookRouter);
|
|
22
25
|
registerEmailProviderRoutes(app);
|
|
26
|
+
registerSmsProviderRoutes(app);
|
|
23
27
|
registerWebhookSourceRoutes(app, opts.webhookConnectors);
|
|
24
28
|
}
|