@hogsend/engine 0.65.0 → 0.67.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 -12
- package/src/account-links/battlenet.ts +84 -0
- package/src/account-links/epic.ts +87 -0
- package/src/account-links/index.ts +12 -5
- package/src/account-links/riot.ts +82 -0
- package/src/account-links/xbox.ts +92 -0
- package/src/app.ts +9 -1
- package/src/container.ts +77 -0
- package/src/env.ts +18 -2
- package/src/index.ts +84 -0
- package/src/lib/account-links-from-env.ts +94 -30
- package/src/lib/contacts.ts +94 -2
- package/src/lib/ingestion.ts +61 -0
- package/src/lib/links.ts +94 -11
- package/src/lib/outbound.ts +94 -0
- package/src/lib/referral-intent.ts +723 -0
- package/src/lib/referral-link.ts +200 -0
- package/src/lib/referral-registry.ts +83 -0
- package/src/lib/referral-report.ts +739 -0
- package/src/lib/referral-runtime.ts +49 -0
- package/src/lib/referrals-no-emit.test.ts +109 -0
- package/src/lib/referrals.ts +712 -0
- package/src/lib/snippet.ts +76 -0
- package/src/lib/webhook-signing.ts +10 -0
- package/src/routes/admin/api-keys.ts +5 -0
- package/src/routes/admin/index.ts +2 -0
- package/src/routes/admin/links.ts +14 -5
- package/src/routes/admin/referrals.ts +565 -0
- package/src/routes/contacts/index.ts +78 -0
- package/src/routes/index.ts +45 -0
- package/src/routes/referrals/index.ts +41 -0
- package/src/routes/referrals/me.ts +123 -0
- package/src/routes/referrals/report.ts +285 -0
- package/src/routes/referrals/shared.ts +34 -0
- package/src/routes/referrals/touch.ts +313 -0
- package/src/routes/snippet.test.ts +70 -0
- package/src/routes/snippet.ts +58 -0
- package/src/routes/tracking/arrive.ts +90 -0
- package/src/routes/tracking/click-pipeline.ts +8 -0
- package/src/workflows/import-contacts.ts +6 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { DEFAULT_REFERRAL_ID } from "@hogsend/core";
|
|
2
|
+
import type { Database } from "@hogsend/db";
|
|
3
|
+
import { links } from "@hogsend/db";
|
|
4
|
+
import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
|
|
5
|
+
import { and, eq, isNull } from "drizzle-orm";
|
|
6
|
+
import type { AppEnv } from "../../app.js";
|
|
7
|
+
import { touchReferral } from "../../lib/referral-intent.js";
|
|
8
|
+
import { recordTouch } from "../../lib/referrals.js";
|
|
9
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
10
|
+
import { resolveNamedContactId, resolveReferralId } from "./shared.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `POST /v1/referrals/touch` and `POST /v1/referrals/import` (PRD 05 §7.2).
|
|
14
|
+
*
|
|
15
|
+
* The two routes look alike and are deliberately NOT the same call:
|
|
16
|
+
*
|
|
17
|
+
* - `/touch` goes through `touchReferral` (the INTENT layer), so a fresh edge
|
|
18
|
+
* emits `referral.touched` / `referral.bound` on both planes and a reward
|
|
19
|
+
* journey fires. That is what an invite, a typed code or an operator
|
|
20
|
+
* correction IS.
|
|
21
|
+
* - `/import` goes through `recordTouch` (the STORE), which never emits. An
|
|
22
|
+
* import is SILENT HISTORY, exactly like `POST /v1/accounts/import`: back-
|
|
23
|
+
* filling a year of a competitor's referral ledger must not send a year of
|
|
24
|
+
* reward emails. It is also insert-only - an existing edge is reported as
|
|
25
|
+
* `existing`, never rewritten.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const MAX_IMPORT_ROWS = 1000;
|
|
29
|
+
|
|
30
|
+
const sourceSchema = z.enum(["slug_entry", "invite", "manual"]);
|
|
31
|
+
|
|
32
|
+
const touchRoute = createRoute({
|
|
33
|
+
method: "post",
|
|
34
|
+
path: "/touch",
|
|
35
|
+
tags: ["Referrals"],
|
|
36
|
+
summary: "Record a referral touch",
|
|
37
|
+
description:
|
|
38
|
+
"Secret key + the `referrals` scope. Names the referrer by `referrerContactId`, `referrerKey` or the `slug` of their shared link (which also selects the referral). A `refereeContactId`/`refereeKey` that resolves to a contact BINDS the edge immediately; a bare `refereeKey` records the cold edge under that key. Emits `referral.touched` (and `referral.bound`) on a fresh write only.",
|
|
39
|
+
request: {
|
|
40
|
+
body: {
|
|
41
|
+
content: {
|
|
42
|
+
"application/json": {
|
|
43
|
+
schema: z
|
|
44
|
+
.object({
|
|
45
|
+
referral: z.string().min(1).optional(),
|
|
46
|
+
referrerContactId: z.string().min(1).optional(),
|
|
47
|
+
referrerKey: z.string().min(1).optional(),
|
|
48
|
+
slug: z.string().min(1).optional(),
|
|
49
|
+
refereeContactId: z.string().min(1).optional(),
|
|
50
|
+
refereeKey: z.string().min(1).optional(),
|
|
51
|
+
source: sourceSchema,
|
|
52
|
+
properties: z.record(z.string(), z.unknown()).optional(),
|
|
53
|
+
idempotencyKey: z.string().min(1).optional(),
|
|
54
|
+
})
|
|
55
|
+
.refine(
|
|
56
|
+
(b) => Boolean(b.referrerContactId ?? b.referrerKey ?? b.slug),
|
|
57
|
+
{
|
|
58
|
+
message:
|
|
59
|
+
"one of referrerContactId, referrerKey or slug is required",
|
|
60
|
+
},
|
|
61
|
+
)
|
|
62
|
+
.refine((b) => Boolean(b.refereeContactId ?? b.refereeKey), {
|
|
63
|
+
message: "one of refereeContactId or refereeKey is required",
|
|
64
|
+
}),
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
responses: {
|
|
70
|
+
200: {
|
|
71
|
+
content: {
|
|
72
|
+
"application/json": {
|
|
73
|
+
schema: z.object({
|
|
74
|
+
touchId: z.string().nullable(),
|
|
75
|
+
referral: z.string(),
|
|
76
|
+
referrerContactId: z.string(),
|
|
77
|
+
refereeContactId: z.string().nullable(),
|
|
78
|
+
status: z.string(),
|
|
79
|
+
created: z.boolean(),
|
|
80
|
+
rejected: z.boolean(),
|
|
81
|
+
}),
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
description: "The touch (fresh or recovered)",
|
|
85
|
+
},
|
|
86
|
+
404: {
|
|
87
|
+
content: { "application/json": { schema: errorSchema } },
|
|
88
|
+
description: "No such referrer, slug or referral",
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const importRoute = createRoute({
|
|
94
|
+
method: "post",
|
|
95
|
+
path: "/import",
|
|
96
|
+
tags: ["Referrals"],
|
|
97
|
+
summary: "Import historical referral touches",
|
|
98
|
+
description:
|
|
99
|
+
'Secret key + the `referrals` scope. INSERT-ONLY and SILENT: every row is written with `source: "import"` at its own `touchedAt`, and NOTHING is emitted - no `referral.touched`, no `referral.bound`, no journey. A row carrying a referee that resolves to a contact is written already `bound` (the self-referral check still applies). An existing edge is counted as `existing` and left untouched.',
|
|
100
|
+
request: {
|
|
101
|
+
body: {
|
|
102
|
+
content: {
|
|
103
|
+
"application/json": {
|
|
104
|
+
schema: z.object({
|
|
105
|
+
referral: z.string().min(1).optional(),
|
|
106
|
+
touches: z
|
|
107
|
+
.array(
|
|
108
|
+
z.object({
|
|
109
|
+
referrerContactId: z.string().min(1).optional(),
|
|
110
|
+
referrerKey: z.string().min(1).optional(),
|
|
111
|
+
refereeContactId: z.string().min(1).optional(),
|
|
112
|
+
refereeKey: z.string().min(1).optional(),
|
|
113
|
+
touchedAt: z.string(),
|
|
114
|
+
properties: z.record(z.string(), z.unknown()).optional(),
|
|
115
|
+
idempotencyKey: z.string().min(1).optional(),
|
|
116
|
+
}),
|
|
117
|
+
)
|
|
118
|
+
.min(1)
|
|
119
|
+
.max(MAX_IMPORT_ROWS),
|
|
120
|
+
}),
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
responses: {
|
|
126
|
+
200: {
|
|
127
|
+
content: {
|
|
128
|
+
"application/json": {
|
|
129
|
+
schema: z.object({
|
|
130
|
+
referral: z.string(),
|
|
131
|
+
inserted: z.number(),
|
|
132
|
+
existing: z.number(),
|
|
133
|
+
rejected: z.number(),
|
|
134
|
+
skipped: z.number(),
|
|
135
|
+
}),
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
description: "Per-row outcome counts",
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
/** The live `shared` link behind a slug: its owner AND its referral. */
|
|
144
|
+
async function resolveSlug(
|
|
145
|
+
db: Database,
|
|
146
|
+
slug: string,
|
|
147
|
+
): Promise<{
|
|
148
|
+
referralId: string;
|
|
149
|
+
ownerContactId: string;
|
|
150
|
+
linkId: string;
|
|
151
|
+
} | null> {
|
|
152
|
+
const [row] = await db
|
|
153
|
+
.select({
|
|
154
|
+
id: links.id,
|
|
155
|
+
referralId: links.referralId,
|
|
156
|
+
ownerContactId: links.ownerContactId,
|
|
157
|
+
})
|
|
158
|
+
.from(links)
|
|
159
|
+
.where(and(eq(links.slug, slug.toLowerCase()), isNull(links.archivedAt)))
|
|
160
|
+
.limit(1);
|
|
161
|
+
if (!row?.ownerContactId) return null;
|
|
162
|
+
return {
|
|
163
|
+
referralId: row.referralId ?? DEFAULT_REFERRAL_ID,
|
|
164
|
+
ownerContactId: row.ownerContactId,
|
|
165
|
+
linkId: row.id,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function registerReferralTouchRoute(router: OpenAPIHono<AppEnv>) {
|
|
170
|
+
router.openapi(touchRoute, async (c) => {
|
|
171
|
+
const container = c.get("container");
|
|
172
|
+
const { db, referrals } = container;
|
|
173
|
+
const body = c.req.valid("json");
|
|
174
|
+
|
|
175
|
+
let referralId = resolveReferralId(body.referral);
|
|
176
|
+
let referrerContactId: string | null = null;
|
|
177
|
+
let linkId: string | null = null;
|
|
178
|
+
|
|
179
|
+
if (body.slug) {
|
|
180
|
+
const link = await resolveSlug(db, body.slug);
|
|
181
|
+
if (!link) {
|
|
182
|
+
return c.json(
|
|
183
|
+
{ error: `no shared link with slug "${body.slug}"` },
|
|
184
|
+
404,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
// The slug carries BOTH ends of the selection: an explicit `referral`
|
|
188
|
+
// that disagrees with the link's own would credit the wrong program, so
|
|
189
|
+
// the link always wins and the body's value is ignored.
|
|
190
|
+
referralId = link.referralId;
|
|
191
|
+
referrerContactId = link.ownerContactId;
|
|
192
|
+
linkId = link.linkId;
|
|
193
|
+
} else {
|
|
194
|
+
referrerContactId = await resolveNamedContactId(
|
|
195
|
+
db,
|
|
196
|
+
body.referrerContactId ?? body.referrerKey,
|
|
197
|
+
);
|
|
198
|
+
if (!referrerContactId) {
|
|
199
|
+
return c.json({ error: "no such referrer" }, 404);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const referral = referrals.get(referralId);
|
|
204
|
+
if (!referral) {
|
|
205
|
+
return c.json(
|
|
206
|
+
{ error: `no referral "${referralId}" is registered` },
|
|
207
|
+
404,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const refereeContactId = await resolveNamedContactId(
|
|
212
|
+
db,
|
|
213
|
+
body.refereeContactId ?? body.refereeKey,
|
|
214
|
+
);
|
|
215
|
+
// The referee KEY is what `adoptOrphanHistory` scans for later, so a cold
|
|
216
|
+
// touch must keep the caller's raw key verbatim.
|
|
217
|
+
const refereeKey = body.refereeKey ?? refereeContactId ?? "";
|
|
218
|
+
if (!refereeKey) {
|
|
219
|
+
return c.json({ error: "no such referee" }, 404);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const result = await touchReferral({
|
|
223
|
+
db,
|
|
224
|
+
hatchet: container.hatchet,
|
|
225
|
+
registry: container.registry,
|
|
226
|
+
logger: container.logger,
|
|
227
|
+
...(container.analytics ? { analytics: container.analytics } : {}),
|
|
228
|
+
referrals,
|
|
229
|
+
referral,
|
|
230
|
+
referrerContactId,
|
|
231
|
+
refereeKey,
|
|
232
|
+
refereeContactId,
|
|
233
|
+
linkId,
|
|
234
|
+
source: body.source,
|
|
235
|
+
...(body.properties ? { properties: body.properties } : {}),
|
|
236
|
+
...(body.idempotencyKey ? { idempotencyKey: body.idempotencyKey } : {}),
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
return c.json(
|
|
240
|
+
{
|
|
241
|
+
touchId: result.touch?.id ?? null,
|
|
242
|
+
referral: referralId,
|
|
243
|
+
referrerContactId,
|
|
244
|
+
refereeContactId: result.touch?.refereeContactId ?? null,
|
|
245
|
+
status: result.touch?.status ?? "skipped",
|
|
246
|
+
created: result.created,
|
|
247
|
+
rejected: result.rejected,
|
|
248
|
+
},
|
|
249
|
+
200,
|
|
250
|
+
);
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function registerReferralImportRoute(router: OpenAPIHono<AppEnv>) {
|
|
255
|
+
router.openapi(importRoute, async (c) => {
|
|
256
|
+
const { db, referrals } = c.get("container");
|
|
257
|
+
const body = c.req.valid("json");
|
|
258
|
+
const referralId = resolveReferralId(body.referral);
|
|
259
|
+
// The definition is OPTIONAL here: importing history into a program whose
|
|
260
|
+
// code was deleted is legitimate, and `recordTouch` only needs it for
|
|
261
|
+
// `beforeTouch` (which an import deliberately does not run through the
|
|
262
|
+
// intent layer anyway).
|
|
263
|
+
const referral = referrals.get(referralId);
|
|
264
|
+
|
|
265
|
+
let inserted = 0;
|
|
266
|
+
let existing = 0;
|
|
267
|
+
let rejected = 0;
|
|
268
|
+
let skipped = 0;
|
|
269
|
+
|
|
270
|
+
for (const row of body.touches) {
|
|
271
|
+
const touchedAt = new Date(row.touchedAt);
|
|
272
|
+
const referrerContactId = await resolveNamedContactId(
|
|
273
|
+
db,
|
|
274
|
+
row.referrerContactId ?? row.referrerKey,
|
|
275
|
+
);
|
|
276
|
+
if (!referrerContactId || Number.isNaN(touchedAt.getTime())) {
|
|
277
|
+
skipped++;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const refereeContactId = await resolveNamedContactId(
|
|
281
|
+
db,
|
|
282
|
+
row.refereeContactId ?? row.refereeKey,
|
|
283
|
+
);
|
|
284
|
+
const refereeKey = row.refereeKey ?? refereeContactId;
|
|
285
|
+
if (!refereeKey) {
|
|
286
|
+
skipped++;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const result = await recordTouch({
|
|
291
|
+
db,
|
|
292
|
+
referralId,
|
|
293
|
+
...(referral ? { referral } : {}),
|
|
294
|
+
referrerContactId,
|
|
295
|
+
refereeKey,
|
|
296
|
+
refereeContactId,
|
|
297
|
+
source: "import",
|
|
298
|
+
touchedAt,
|
|
299
|
+
...(row.properties ? { properties: row.properties } : {}),
|
|
300
|
+
...(row.idempotencyKey ? { idempotencyKey: row.idempotencyKey } : {}),
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
if (result.rejected) rejected++;
|
|
304
|
+
else if (result.created) inserted++;
|
|
305
|
+
else existing++;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return c.json(
|
|
309
|
+
{ referral: referralId, inserted, existing, rejected, skipped },
|
|
310
|
+
200,
|
|
311
|
+
);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
7
|
+
import { secureHeaders } from "hono/secure-headers";
|
|
8
|
+
import { loadSnippet } from "../lib/snippet.js";
|
|
9
|
+
import {
|
|
10
|
+
createSnippetRouter,
|
|
11
|
+
SNIPPET_CACHE_CONTROL,
|
|
12
|
+
SNIPPET_PATH,
|
|
13
|
+
} from "./snippet.js";
|
|
14
|
+
|
|
15
|
+
// Mirrors app.ts: secureHeaders on everything EXCEPT the snippet path (it
|
|
16
|
+
// would force CORP same-origin after the handler and break the embed).
|
|
17
|
+
function appWith(path: string | null) {
|
|
18
|
+
const app = new OpenAPIHono();
|
|
19
|
+
const secure = secureHeaders();
|
|
20
|
+
app.use("*", (c, next) =>
|
|
21
|
+
c.req.path === SNIPPET_PATH ? next() : secure(c, next),
|
|
22
|
+
);
|
|
23
|
+
app.route("/", createSnippetRouter(loadSnippet(path)));
|
|
24
|
+
return app;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function tmpSnippet(body: string) {
|
|
28
|
+
const dir = mkdtempSync(join(tmpdir(), "hs-snippet-"));
|
|
29
|
+
const file = join(dir, "hogsend.js");
|
|
30
|
+
writeFileSync(file, body);
|
|
31
|
+
return file;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test("serves the snippet with cache + cross-origin headers", async () => {
|
|
35
|
+
const app = appWith(tmpSnippet("console.log('hi')"));
|
|
36
|
+
const res = await app.request("/hogsend.js");
|
|
37
|
+
assert.equal(res.status, 200);
|
|
38
|
+
assert.equal(await res.text(), "console.log('hi')");
|
|
39
|
+
assert.equal(
|
|
40
|
+
res.headers.get("content-type"),
|
|
41
|
+
"application/javascript; charset=utf-8",
|
|
42
|
+
);
|
|
43
|
+
assert.equal(res.headers.get("cache-control"), SNIPPET_CACHE_CONTROL);
|
|
44
|
+
assert.equal(res.headers.get("cross-origin-resource-policy"), "cross-origin");
|
|
45
|
+
assert.match(res.headers.get("etag") ?? "", /^"[a-f0-9]{32}"$/);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("revalidates to 304 on a matching If-None-Match", async () => {
|
|
49
|
+
const app = appWith(tmpSnippet("x"));
|
|
50
|
+
const first = await app.request("/hogsend.js");
|
|
51
|
+
const etag = first.headers.get("etag") ?? "";
|
|
52
|
+
const res = await app.request("/hogsend.js", {
|
|
53
|
+
headers: { "if-none-match": etag },
|
|
54
|
+
});
|
|
55
|
+
assert.equal(res.status, 304);
|
|
56
|
+
assert.equal(await res.text(), "");
|
|
57
|
+
assert.equal(res.headers.get("etag"), etag);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("etag tracks content", () => {
|
|
61
|
+
const a = loadSnippet(tmpSnippet("a"));
|
|
62
|
+
const b = loadSnippet(tmpSnippet("b"));
|
|
63
|
+
assert.notEqual(a?.etag, b?.etag);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("404s when no asset is installed", async () => {
|
|
67
|
+
const app = appWith(null);
|
|
68
|
+
const res = await app.request("/hogsend.js");
|
|
69
|
+
assert.equal(res.status, 404);
|
|
70
|
+
});
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../app.js";
|
|
3
|
+
import { type LoadedSnippet, loadSnippet } from "../lib/snippet.js";
|
|
4
|
+
|
|
5
|
+
// The drop-in browser snippet, root-mounted as `/hogsend.js` so the tag a
|
|
6
|
+
// non-bundler site pastes is just `${API_PUBLIC_URL}/hogsend.js`. Public and
|
|
7
|
+
// unauthenticated by construction (it is the SDK itself; the publishable key
|
|
8
|
+
// travels on the tag, not the request). Collides with nothing (`/v1`, `/l`,
|
|
9
|
+
// `/s`, `/studio`, `/docs`, `/api/auth`, `/connectors`, webhooks).
|
|
10
|
+
export const SNIPPET_PATH = "/hogsend.js";
|
|
11
|
+
|
|
12
|
+
const snippetRoute = createRoute({
|
|
13
|
+
method: "get",
|
|
14
|
+
path: SNIPPET_PATH,
|
|
15
|
+
tags: ["SDK"],
|
|
16
|
+
summary: "Drop-in browser SDK script",
|
|
17
|
+
responses: {
|
|
18
|
+
200: { description: "The @hogsend/js IIFE bundle" },
|
|
19
|
+
304: { description: "Not modified" },
|
|
20
|
+
404: { description: "Snippet asset not installed" },
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Cache policy: five minutes fresh, a day stale-while-revalidate, strong ETag.
|
|
26
|
+
* A deploy with a newer `@hogsend/js` is picked up within minutes by every
|
|
27
|
+
* page without a cache-busting URL, and a revalidation is a 304 with no body.
|
|
28
|
+
*/
|
|
29
|
+
export const SNIPPET_CACHE_CONTROL =
|
|
30
|
+
"public, max-age=300, stale-while-revalidate=86400";
|
|
31
|
+
|
|
32
|
+
export function createSnippetRouter(
|
|
33
|
+
snippet: LoadedSnippet | null = loadSnippet(),
|
|
34
|
+
): OpenAPIHono<AppEnv> {
|
|
35
|
+
return new OpenAPIHono<AppEnv>().openapi(snippetRoute, (c) => {
|
|
36
|
+
if (!snippet) {
|
|
37
|
+
return c.json(
|
|
38
|
+
{
|
|
39
|
+
error:
|
|
40
|
+
"hogsend.js is not installed on this engine. Add @hogsend/js as a dependency (or set HOGSEND_JS_PATH).",
|
|
41
|
+
},
|
|
42
|
+
404,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
// Explicit CORP so a cross-origin <script src> load is allowed (app.ts
|
|
46
|
+
// exempts this path from secureHeaders, which would force same-origin).
|
|
47
|
+
c.header("Cross-Origin-Resource-Policy", "cross-origin");
|
|
48
|
+
c.header("Cache-Control", SNIPPET_CACHE_CONTROL);
|
|
49
|
+
c.header("ETag", snippet.etag);
|
|
50
|
+
c.header("Vary", "Accept-Encoding");
|
|
51
|
+
|
|
52
|
+
if (c.req.header("if-none-match") === snippet.etag) {
|
|
53
|
+
return c.body(null, 304);
|
|
54
|
+
}
|
|
55
|
+
c.header("Content-Type", "application/javascript; charset=utf-8");
|
|
56
|
+
return c.body(snippet.body, 200);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_REFERRAL_ID } from "@hogsend/core";
|
|
1
2
|
import { linkClicks, links, trackedLinks } from "@hogsend/db";
|
|
2
3
|
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
4
|
import { and, eq, isNull } from "drizzle-orm";
|
|
@@ -5,9 +6,11 @@ import type { AppEnv } from "../../app.js";
|
|
|
5
6
|
import {
|
|
6
7
|
collidesWithIdentified,
|
|
7
8
|
PublishableAnonymousMergeError,
|
|
9
|
+
resolveContactNoCreate,
|
|
8
10
|
} from "../../lib/contacts.js";
|
|
9
11
|
import { ingestEvent } from "../../lib/ingestion.js";
|
|
10
12
|
import { emitOutbound } from "../../lib/outbound.js";
|
|
13
|
+
import { touchReferral } from "../../lib/referral-intent.js";
|
|
11
14
|
import { LINK_ARRIVED } from "../../lib/tracking-event-names.js";
|
|
12
15
|
import {
|
|
13
16
|
InvalidUserTokenError,
|
|
@@ -104,6 +107,11 @@ export const arriveRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
104
107
|
source: trackedLinks.source,
|
|
105
108
|
linkId: links.id,
|
|
106
109
|
campaign: links.campaign,
|
|
110
|
+
// Referral provenance: a `shared` link is owned by a person and
|
|
111
|
+
// clicked by someone else, so an arrival on one is a referral TOUCH.
|
|
112
|
+
linkType: links.type,
|
|
113
|
+
ownerContactId: links.ownerContactId,
|
|
114
|
+
referralId: links.referralId,
|
|
107
115
|
})
|
|
108
116
|
.from(linkClicks)
|
|
109
117
|
.innerJoin(trackedLinks, eq(linkClicks.trackedLinkId, trackedLinks.id))
|
|
@@ -294,6 +302,88 @@ export const arriveRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
294
302
|
});
|
|
295
303
|
}
|
|
296
304
|
|
|
305
|
+
// --- REFERRAL TOUCH -----------------------------------------------------
|
|
306
|
+
// ARRIVE, not the click, is where a cold referral touch can be recorded:
|
|
307
|
+
// a `shared` link carries no `distinct_id` (it stitches nobody), so the
|
|
308
|
+
// click itself knows the referrer but NOT the clicker. The `hs_ref` the
|
|
309
|
+
// redirect appended is what brings the two together here, which is why
|
|
310
|
+
// `getReferralLink` always mints with `appendRef: true`.
|
|
311
|
+
//
|
|
312
|
+
// The touch is written from the STAMPED identity, exactly like the ingest
|
|
313
|
+
// above, so a replayed ref cannot re-attribute; `clickId = ref` is the
|
|
314
|
+
// store's replay key, so a replay is a no-op rather than a second edge.
|
|
315
|
+
// No contact is minted on the anon leg: `refereeKey` is the raw anonymous
|
|
316
|
+
// id and the store writes it VERBATIM to `referral_touches.referee_key`,
|
|
317
|
+
// which is the value `adoptOrphanHistory` will bind against at identify.
|
|
318
|
+
await recordReferralArrival({
|
|
319
|
+
container: c.get("container"),
|
|
320
|
+
hit,
|
|
321
|
+
ref,
|
|
322
|
+
refereeKey: stamp.visitorDistinctId,
|
|
323
|
+
isToken,
|
|
324
|
+
}).catch((err: unknown) => {
|
|
325
|
+
logger.warn("arrive: referral touch failed", {
|
|
326
|
+
ref,
|
|
327
|
+
error: err instanceof Error ? err.message : String(err),
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
|
|
297
331
|
return ok();
|
|
298
332
|
},
|
|
299
333
|
);
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Record the referral touch for an arrival, when the link is a `shared` link
|
|
337
|
+
* belonging to a REGISTERED referral. Every other case is a silent no-op:
|
|
338
|
+
* a non-shared link, an owner-less link, an unregistered referral id (the
|
|
339
|
+
* program was deleted from code) and a self-arrival all leave no row.
|
|
340
|
+
*/
|
|
341
|
+
async function recordReferralArrival(opts: {
|
|
342
|
+
container: AppEnv["Variables"]["container"];
|
|
343
|
+
hit: {
|
|
344
|
+
linkId: string;
|
|
345
|
+
linkType: string | null;
|
|
346
|
+
ownerContactId: string | null;
|
|
347
|
+
referralId: string | null;
|
|
348
|
+
};
|
|
349
|
+
ref: string;
|
|
350
|
+
refereeKey: string;
|
|
351
|
+
isToken: boolean;
|
|
352
|
+
}): Promise<void> {
|
|
353
|
+
const { container, hit, ref, refereeKey, isToken } = opts;
|
|
354
|
+
if (hit.linkType !== "shared" || !hit.ownerContactId) return;
|
|
355
|
+
const referral = container.referrals.get(
|
|
356
|
+
hit.referralId ?? DEFAULT_REFERRAL_ID,
|
|
357
|
+
);
|
|
358
|
+
if (!referral) return;
|
|
359
|
+
|
|
360
|
+
// A TOKEN arrival is a server-minted identity assertion, so the toucher is a
|
|
361
|
+
// known person and the touch binds immediately (the store's self-check
|
|
362
|
+
// applies). An ANON arrival has no contact: it stays one-ended until the
|
|
363
|
+
// visitor identifies. Resolving the token leg's contact must never CREATE
|
|
364
|
+
// one, so it goes through the no-create resolver.
|
|
365
|
+
let refereeContactId: string | null = null;
|
|
366
|
+
if (isToken) {
|
|
367
|
+
const resolved = await resolveContactNoCreate({
|
|
368
|
+
db: container.db,
|
|
369
|
+
userId: refereeKey,
|
|
370
|
+
});
|
|
371
|
+
refereeContactId = resolved.id;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
await touchReferral({
|
|
375
|
+
db: container.db,
|
|
376
|
+
hatchet: container.hatchet,
|
|
377
|
+
registry: container.registry,
|
|
378
|
+
logger: container.logger,
|
|
379
|
+
...(container.analytics ? { analytics: container.analytics } : {}),
|
|
380
|
+
referrals: container.referrals,
|
|
381
|
+
referral,
|
|
382
|
+
referrerContactId: hit.ownerContactId,
|
|
383
|
+
refereeKey,
|
|
384
|
+
refereeContactId,
|
|
385
|
+
linkId: hit.linkId,
|
|
386
|
+
clickId: ref,
|
|
387
|
+
source: "link",
|
|
388
|
+
});
|
|
389
|
+
}
|
|
@@ -159,6 +159,14 @@ export async function handleTrackedClick(
|
|
|
159
159
|
: []),
|
|
160
160
|
]);
|
|
161
161
|
|
|
162
|
+
// REFERRAL LINKS (`type: "shared"`) record no touch HERE, deliberately. A
|
|
163
|
+
// shared link stitches nobody (it carries no `distinct_id`), so the click
|
|
164
|
+
// knows the referrer but has no key at all for the CLICKER — and inventing
|
|
165
|
+
// one from the click id would mint an edge to a person who never arrives.
|
|
166
|
+
// The referee's anonymous id first exists at `POST /v1/t/arrive`, reported
|
|
167
|
+
// back with the `hs_ref` the redirect appends, which is where the touch is
|
|
168
|
+
// written (`routes/tracking/arrive.ts`). `getReferralLink` therefore always
|
|
169
|
+
// mints with `appendRef: true`.
|
|
162
170
|
const { hatchet, registry, logger } = c.get("container");
|
|
163
171
|
|
|
164
172
|
// SEMANTIC link: the click is a PROVISIONAL answer. Confirmation is
|
|
@@ -140,6 +140,12 @@ export const importContactsTask = hatchet.task({
|
|
|
140
140
|
allowMerge: "any",
|
|
141
141
|
trustedKinds: ["external", "email"],
|
|
142
142
|
},
|
|
143
|
+
// A backfill is a statement about the PAST. If a row merges into a
|
|
144
|
+
// contact whose loser held a live linked account, the fold emits an
|
|
145
|
+
// `account.unlinked` — do NOT enrol journeys on it once per row
|
|
146
|
+
// (the outbound webhook still fires). Mirrors the
|
|
147
|
+
// `/v1/accounts/import` route's own `enrollJourneys` default-off.
|
|
148
|
+
enrollJourneys: false,
|
|
143
149
|
}).then(async (result) => {
|
|
144
150
|
await attachPhone(db, result.id, row.phone);
|
|
145
151
|
return { index: i + idx, ok: true };
|