@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.
Files changed (40) hide show
  1. package/package.json +12 -12
  2. package/src/account-links/battlenet.ts +84 -0
  3. package/src/account-links/epic.ts +87 -0
  4. package/src/account-links/index.ts +12 -5
  5. package/src/account-links/riot.ts +82 -0
  6. package/src/account-links/xbox.ts +92 -0
  7. package/src/app.ts +9 -1
  8. package/src/container.ts +77 -0
  9. package/src/env.ts +18 -2
  10. package/src/index.ts +84 -0
  11. package/src/lib/account-links-from-env.ts +94 -30
  12. package/src/lib/contacts.ts +94 -2
  13. package/src/lib/ingestion.ts +61 -0
  14. package/src/lib/links.ts +94 -11
  15. package/src/lib/outbound.ts +94 -0
  16. package/src/lib/referral-intent.ts +723 -0
  17. package/src/lib/referral-link.ts +200 -0
  18. package/src/lib/referral-registry.ts +83 -0
  19. package/src/lib/referral-report.ts +739 -0
  20. package/src/lib/referral-runtime.ts +49 -0
  21. package/src/lib/referrals-no-emit.test.ts +109 -0
  22. package/src/lib/referrals.ts +712 -0
  23. package/src/lib/snippet.ts +76 -0
  24. package/src/lib/webhook-signing.ts +10 -0
  25. package/src/routes/admin/api-keys.ts +5 -0
  26. package/src/routes/admin/index.ts +2 -0
  27. package/src/routes/admin/links.ts +14 -5
  28. package/src/routes/admin/referrals.ts +565 -0
  29. package/src/routes/contacts/index.ts +78 -0
  30. package/src/routes/index.ts +45 -0
  31. package/src/routes/referrals/index.ts +41 -0
  32. package/src/routes/referrals/me.ts +123 -0
  33. package/src/routes/referrals/report.ts +285 -0
  34. package/src/routes/referrals/shared.ts +34 -0
  35. package/src/routes/referrals/touch.ts +313 -0
  36. package/src/routes/snippet.test.ts +70 -0
  37. package/src/routes/snippet.ts +58 -0
  38. package/src/routes/tracking/arrive.ts +90 -0
  39. package/src/routes/tracking/click-pipeline.ts +8 -0
  40. package/src/workflows/import-contacts.ts +6 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.65.0",
3
+ "version": "0.67.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,19 +53,19 @@
53
53
  "svix": "^1.95.1",
54
54
  "winston": "^3.19.0",
55
55
  "zod": "^4.4.3",
56
- "@hogsend/attribution": "^0.65.0",
57
- "@hogsend/core": "^0.65.0",
58
- "@hogsend/db": "^0.65.0",
59
- "@hogsend/email": "^0.65.0",
60
- "@hogsend/plugin-posthog": "^0.65.0",
61
- "@hogsend/plugin-resend": "^0.65.0",
62
- "@hogsend/sms": "^0.65.0"
56
+ "@hogsend/attribution": "^0.67.0",
57
+ "@hogsend/core": "^0.67.0",
58
+ "@hogsend/db": "^0.67.0",
59
+ "@hogsend/email": "^0.67.0",
60
+ "@hogsend/plugin-posthog": "^0.67.0",
61
+ "@hogsend/plugin-resend": "^0.67.0",
62
+ "@hogsend/sms": "^0.67.0"
63
63
  },
64
64
  "optionalDependencies": {
65
- "@hogsend/plugin-apollo": "^0.65.0",
66
- "@hogsend/plugin-hogsend": "^0.65.0",
67
- "@hogsend/plugin-postmark": "^0.65.0",
68
- "@hogsend/plugin-twilio": "^0.65.0"
65
+ "@hogsend/plugin-apollo": "^0.67.0",
66
+ "@hogsend/plugin-hogsend": "^0.67.0",
67
+ "@hogsend/plugin-postmark": "^0.67.0",
68
+ "@hogsend/plugin-twilio": "^0.67.0"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@types/node": "^22.15.3",
@@ -0,0 +1,84 @@
1
+ import {
2
+ AccountLinkCallbackError,
3
+ type AccountLinkProvider,
4
+ type LinkedIdentity,
5
+ oauth2Link,
6
+ } from "@hogsend/core";
7
+
8
+ /**
9
+ * Battle.net app credentials, from an application registered at
10
+ * `https://develop.battle.net/access/clients` with OAuth redirect URL
11
+ * `<API_PUBLIC_URL>/v1/accounts/battlenet/callback`. Env spelling:
12
+ * `ACCOUNT_LINK_BATTLENET_CLIENT_ID` / `ACCOUNT_LINK_BATTLENET_CLIENT_SECRET`
13
+ * (see `lib/account-links-from-env.ts` — registered only when BOTH are set).
14
+ */
15
+ export interface BattlenetAccountLinkConfig {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ }
19
+
20
+ /** The slice of a Battle.net `/oauth/userinfo` response this mapping reads. */
21
+ interface BattlenetUserInfo {
22
+ sub?: string;
23
+ battletag?: string;
24
+ }
25
+
26
+ /**
27
+ * Map a Battle.net `/oauth/userinfo` response onto a {@link LinkedIdentity}.
28
+ * Exported for direct unit testing — it is the only real logic in this file.
29
+ *
30
+ * - `providerUserId` is the `sub` claim, the IMMUTABLE key. Never `battletag`:
31
+ * it is user-editable, so keying on it lets a player rename themselves onto
32
+ * another player's link row.
33
+ * - `battletag` is a display name and lands in `username`, NOT `verifiedEmail`:
34
+ * the userinfo endpoint exposes no email verification info.
35
+ */
36
+ export function mapBattlenetUser(
37
+ json: unknown,
38
+ ): Omit<LinkedIdentity, "tokens"> {
39
+ const user = json as BattlenetUserInfo | null | undefined;
40
+ if (!user?.sub) {
41
+ throw new AccountLinkCallbackError(
42
+ "exchange_failed",
43
+ "Battle.net /oauth/userinfo returned no sub for the presented token",
44
+ );
45
+ }
46
+ return {
47
+ providerUserId: user.sub,
48
+ ...(user.battletag ? { username: user.battletag } : {}),
49
+ };
50
+ }
51
+
52
+ /**
53
+ * The Battle.net account-link provider: pure CONFIG over the `oauth2Link()`
54
+ * preset (OAuth2 authorization code + PKCE, tokens sealed). All protocol
55
+ * mechanics — authorize URL, token exchange, `error=access_denied` mapping,
56
+ * the userinfo fetch — live in the preset
57
+ * (`@hogsend/core`, `providers/account-link-presets.ts`), not here.
58
+ *
59
+ * Battle.net has no standard token revocation endpoint, so `revokeEndpoint`
60
+ * is omitted — unlinking destroys the stored tokens without calling the
61
+ * provider.
62
+ */
63
+ export function battlenetAccountLink(
64
+ config: BattlenetAccountLinkConfig,
65
+ ): AccountLinkProvider {
66
+ return oauth2Link({
67
+ meta: {
68
+ id: "battlenet",
69
+ name: "Battle.net",
70
+ description: "Link a Battle.net account (OAuth2 + PKCE)",
71
+ },
72
+ authorizeEndpoint: "https://oauth.battle.net/authorize",
73
+ tokenEndpoint: "https://oauth.battle.net/token",
74
+ clientId: config.clientId,
75
+ clientSecret: config.clientSecret,
76
+ scopes: ["openid"],
77
+ usePkce: true,
78
+ storeTokens: true,
79
+ userInfo: {
80
+ url: "https://oauth.battle.net/oauth/userinfo",
81
+ map: mapBattlenetUser,
82
+ },
83
+ });
84
+ }
@@ -0,0 +1,87 @@
1
+ import {
2
+ AccountLinkCallbackError,
3
+ type AccountLinkProvider,
4
+ type LinkedIdentity,
5
+ oauth2Link,
6
+ } from "@hogsend/core";
7
+
8
+ /**
9
+ * Epic Games app credentials, from an application registered at
10
+ * `https://dev.epicgames.com/portal` with OAuth redirect URL
11
+ * `<API_PUBLIC_URL>/v1/accounts/epic/callback`. Env spelling:
12
+ * `ACCOUNT_LINK_EPIC_CLIENT_ID` / `ACCOUNT_LINK_EPIC_CLIENT_SECRET`
13
+ * (see `lib/account-links-from-env.ts` — registered only when BOTH are set).
14
+ */
15
+ export interface EpicAccountLinkConfig {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ }
19
+
20
+ /** The slice of an Epic `/oauth/verify` response this mapping reads. */
21
+ interface EpicVerifyUser {
22
+ accountId?: string;
23
+ account_id?: string;
24
+ displayName?: string;
25
+ display_name?: string;
26
+ }
27
+
28
+ /**
29
+ * Map an Epic `GET /oauth/verify` response onto a {@link LinkedIdentity}.
30
+ * Exported for direct unit testing — it is the only real logic in this file.
31
+ *
32
+ * - `providerUserId` is Epic's `accountId`, the IMMUTABLE key. Never
33
+ * `displayName`: it is user-editable, so keying on it lets a player rename
34
+ * themselves onto another player's link row.
35
+ * - Epic's verify endpoint returns camelCase (`accountId`, `displayName`) but
36
+ * we defensively check snake_case variants too.
37
+ */
38
+ export function mapEpicUser(json: unknown): Omit<LinkedIdentity, "tokens"> {
39
+ const user = json as EpicVerifyUser | null | undefined;
40
+ const id = user?.accountId ?? user?.account_id;
41
+ if (!id) {
42
+ throw new AccountLinkCallbackError(
43
+ "exchange_failed",
44
+ "Epic /oauth/verify returned no accountId for the presented token",
45
+ );
46
+ }
47
+ const username = user?.displayName ?? user?.display_name;
48
+ return {
49
+ providerUserId: id,
50
+ ...(username ? { username } : {}),
51
+ };
52
+ }
53
+
54
+ /**
55
+ * The Epic Games account-link provider: pure CONFIG over the `oauth2Link()`
56
+ * preset (OAuth2 authorization code, tokens sealed). All protocol mechanics
57
+ * — authorize URL, token exchange, `error=access_denied` mapping, the
58
+ * userinfo fetch — live in the preset
59
+ * (`@hogsend/core`, `providers/account-link-presets.ts`), not here.
60
+ *
61
+ * Epic does not support PKCE for confidential clients, so `usePkce` is false.
62
+ * The verify endpoint returns the authenticated user's identity from the
63
+ * bearer token alone — no extra headers needed.
64
+ */
65
+ export function epicAccountLink(
66
+ config: EpicAccountLinkConfig,
67
+ ): AccountLinkProvider {
68
+ return oauth2Link({
69
+ meta: {
70
+ id: "epic",
71
+ name: "Epic Games",
72
+ description: "Link an Epic Games account (OAuth2)",
73
+ },
74
+ authorizeEndpoint: "https://www.epicgames.com/id/authorize",
75
+ tokenEndpoint:
76
+ "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/token",
77
+ clientId: config.clientId,
78
+ clientSecret: config.clientSecret,
79
+ scopes: ["basic_profile"],
80
+ usePkce: false,
81
+ storeTokens: true,
82
+ userInfo: {
83
+ url: "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/verify",
84
+ map: mapEpicUser,
85
+ },
86
+ });
87
+ }
@@ -1,8 +1,15 @@
1
- // The two built-in account-link providers. Config over the `@hogsend/core`
1
+ // The six built-in account-link providers. Config over the `@hogsend/core`
2
2
  // presets, NOT plugin packages (DECISIONS §3.1): a provider here is a URL, one
3
- // `fetch` and a field mapping — zero dependencies, no runtime. Steam and
4
- // Twitch are deliberately the ONLY first-party providers here (DECISIONS
5
- // §12): a platform whose linking already ships elsewhere in this repo must
6
- // keep its single writer, so it gets no second definition in this directory.
3
+ // `fetch` and a field mapping — zero dependencies, no runtime. Discord is the
4
+ // only excluded platform: it already ships via `plugin-discord`, and a second
5
+ // writer on `contacts.discordId` would drift.
6
+
7
+ export {
8
+ type BattlenetAccountLinkConfig,
9
+ battlenetAccountLink,
10
+ } from "./battlenet.js";
11
+ export { type EpicAccountLinkConfig, epicAccountLink } from "./epic.js";
12
+ export { type RiotAccountLinkConfig, riotAccountLink } from "./riot.js";
7
13
  export { type SteamAccountLinkConfig, steamAccountLink } from "./steam.js";
8
14
  export { type TwitchAccountLinkConfig, twitchAccountLink } from "./twitch.js";
15
+ export { type XboxAccountLinkConfig, xboxAccountLink } from "./xbox.js";
@@ -0,0 +1,82 @@
1
+ import {
2
+ AccountLinkCallbackError,
3
+ type AccountLinkProvider,
4
+ type LinkedIdentity,
5
+ oauth2Link,
6
+ } from "@hogsend/core";
7
+
8
+ /**
9
+ * Riot Games app credentials, from an application registered at
10
+ * `https://developer.riotgames.com/` with OAuth redirect URL
11
+ * `<API_PUBLIC_URL>/v1/accounts/riot/callback`. Env spelling:
12
+ * `ACCOUNT_LINK_RIOT_CLIENT_ID` / `ACCOUNT_LINK_RIOT_CLIENT_SECRET`
13
+ * (see `lib/account-links-from-env.ts` — registered only when BOTH are set).
14
+ */
15
+ export interface RiotAccountLinkConfig {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ }
19
+
20
+ /** The slice of an RSO `/userinfo` response this mapping reads. */
21
+ interface RsoUserInfo {
22
+ sub?: string;
23
+ puuid?: string;
24
+ cpid?: string;
25
+ }
26
+
27
+ /**
28
+ * Map an RSO `GET /userinfo` response onto a {@link LinkedIdentity}.
29
+ * Exported for direct unit testing — it is the only real logic in this file.
30
+ *
31
+ * - `providerUserId` is the PUUID (`sub`), the IMMUTABLE key. Riot returns it
32
+ * as `sub` in the OpenID Connect userinfo response; some endpoint versions
33
+ * also surface it as `puuid`. Never `cpid`: that is a legacy id.
34
+ * - Riot's userinfo endpoint does NOT return a gameName or tagLine, so no
35
+ * `username` is set. The PUUID alone is sufficient for the link row.
36
+ */
37
+ export function mapRiotUser(json: unknown): Omit<LinkedIdentity, "tokens"> {
38
+ const info = json as RsoUserInfo | null | undefined;
39
+ const puuid = info?.sub || info?.puuid;
40
+ if (!puuid) {
41
+ throw new AccountLinkCallbackError(
42
+ "exchange_failed",
43
+ "RSO /userinfo returned no sub or puuid for the presented token",
44
+ );
45
+ }
46
+ return {
47
+ providerUserId: puuid,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * The Riot Games account-link provider: pure CONFIG over the `oauth2Link()`
53
+ * preset (OAuth2 authorization code + PKCE, tokens sealed). All protocol
54
+ * mechanics — authorize URL, token exchange, `error=access_denied` mapping,
55
+ * the userinfo fetch — live in the preset
56
+ * (`@hogsend/core`, `providers/account-link-presets.ts`), not here.
57
+ *
58
+ * RSO (Riot Sign On) is standard OAuth2 / OpenID Connect. The `openid` scope
59
+ * gives access to the `/userinfo` endpoint which returns the PUUID as `sub`.
60
+ */
61
+ export function riotAccountLink(
62
+ config: RiotAccountLinkConfig,
63
+ ): AccountLinkProvider {
64
+ return oauth2Link({
65
+ meta: {
66
+ id: "riot",
67
+ name: "Riot Games",
68
+ description: "Link a Riot Games account (RSO OAuth2)",
69
+ },
70
+ authorizeEndpoint: "https://auth.riotgames.com/authorize",
71
+ tokenEndpoint: "https://auth.riotgames.com/token",
72
+ clientId: config.clientId,
73
+ clientSecret: config.clientSecret,
74
+ scopes: ["openid"],
75
+ usePkce: true,
76
+ storeTokens: true,
77
+ userInfo: {
78
+ url: "https://auth.riotgames.com/userinfo",
79
+ map: mapRiotUser,
80
+ },
81
+ });
82
+ }
@@ -0,0 +1,92 @@
1
+ import {
2
+ AccountLinkCallbackError,
3
+ type AccountLinkProvider,
4
+ type LinkedIdentity,
5
+ oauth2Link,
6
+ } from "@hogsend/core";
7
+
8
+ /**
9
+ * Microsoft (Xbox) app credentials, from an application registered at
10
+ * `https://portal.azure.com` → App registrations with OAuth redirect URL
11
+ * `<API_PUBLIC_URL>/v1/accounts/xbox/callback`. The app MUST allow
12
+ * "personal Microsoft accounts" (consumers tenant). Env spelling:
13
+ * `ACCOUNT_LINK_XBOX_CLIENT_ID` / `ACCOUNT_LINK_XBOX_CLIENT_SECRET`
14
+ * (see `lib/account-links-from-env.ts` — registered only when BOTH are set).
15
+ */
16
+ export interface XboxAccountLinkConfig {
17
+ clientId: string;
18
+ clientSecret: string;
19
+ }
20
+
21
+ /** The slice of a Microsoft Graph `GET /v1.0/me` response this mapping reads. */
22
+ interface GraphUser {
23
+ id?: string;
24
+ displayName?: string;
25
+ userPrincipalName?: string;
26
+ }
27
+
28
+ /**
29
+ * Map a Microsoft Graph `GET /v1.0/me` response onto a {@link LinkedIdentity}.
30
+ * Exported for direct unit testing — it is the only real logic in this file.
31
+ *
32
+ * - `providerUserId` is Graph's `id` (the IMMUTABLE Azure AD object id). This
33
+ * is the same identity that owns the Xbox account — personal Microsoft
34
+ * accounts are the backing identity for Xbox Live.
35
+ * - `userPrincipalName` is a PROPERTY, never an identity key and never
36
+ * `verifiedEmail`: Graph returns the primary email but DECISIONS §6.4 makes
37
+ * a provider-reported email a property regardless. It lands in
38
+ * `properties.xbox_email`.
39
+ */
40
+ export function mapXboxUser(json: unknown): Omit<LinkedIdentity, "tokens"> {
41
+ const user = json as GraphUser | null | undefined;
42
+ if (!user?.id) {
43
+ throw new AccountLinkCallbackError(
44
+ "exchange_failed",
45
+ "Microsoft Graph /me returned no id for the presented token",
46
+ );
47
+ }
48
+ return {
49
+ providerUserId: user.id,
50
+ ...(user.displayName ? { username: user.displayName } : {}),
51
+ ...(user.userPrincipalName
52
+ ? { properties: { xbox_email: user.userPrincipalName } }
53
+ : {}),
54
+ };
55
+ }
56
+
57
+ /**
58
+ * The Xbox account-link provider: pure CONFIG over the `oauth2Link()` preset
59
+ * (OAuth2 authorization code + PKCE, tokens sealed). All protocol mechanics —
60
+ * authorize URL, token exchange, `error=access_denied` mapping, the userinfo
61
+ * fetch — live in the preset (`@hogsend/core`, `providers/account-link-presets.ts`),
62
+ * not here.
63
+ *
64
+ * Uses the Microsoft `/consumers` tenant so ONLY personal Microsoft accounts
65
+ * (which back Xbox Live) are accepted — work/school accounts are rejected at
66
+ * the authorize step by Microsoft itself.
67
+ */
68
+ export function xboxAccountLink(
69
+ config: XboxAccountLinkConfig,
70
+ ): AccountLinkProvider {
71
+ return oauth2Link({
72
+ meta: {
73
+ id: "xbox",
74
+ name: "Xbox",
75
+ description: "Link an Xbox account (OAuth2 via Microsoft)",
76
+ },
77
+ authorizeEndpoint:
78
+ "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize",
79
+ tokenEndpoint:
80
+ "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
81
+ clientId: config.clientId,
82
+ clientSecret: config.clientSecret,
83
+ scopes: ["User.Read", "offline_access"],
84
+ usePkce: true,
85
+ storeTokens: true,
86
+ authorizeParams: { prompt: "select_account" },
87
+ userInfo: {
88
+ url: "https://graph.microsoft.com/v1.0/me",
89
+ map: mapXboxUser,
90
+ },
91
+ });
92
+ }
package/src/app.ts CHANGED
@@ -16,6 +16,7 @@ import { errorHandler } from "./middleware/error-handler.js";
16
16
  import { clientIpKey, createRateLimit } from "./middleware/rate-limit.js";
17
17
  import { requestLogger } from "./middleware/request-logger.js";
18
18
  import { registerRoutes } from "./routes/index.js";
19
+ import { SNIPPET_PATH } from "./routes/snippet.js";
19
20
  import {
20
21
  type DefinedWebhookSource,
21
22
  webhookSourceToConnector,
@@ -81,7 +82,14 @@ export function createApp(
81
82
  await next();
82
83
  });
83
84
 
84
- app.use("*", secureHeaders());
85
+ // secureHeaders sets `Cross-Origin-Resource-Policy: same-origin` AFTER the
86
+ // handler runs (a route cannot override it), which would block a cross-origin
87
+ // `<script src>` load of the drop-in SDK. That one path is the SDK itself,
88
+ // meant to be embedded on other origins, so it skips the middleware.
89
+ const secure = secureHeaders();
90
+ app.use("*", (c, next) =>
91
+ c.req.path === SNIPPET_PATH ? next() : secure(c, next),
92
+ );
85
93
  app.use(
86
94
  "*",
87
95
  cors({
package/src/container.ts CHANGED
@@ -10,6 +10,7 @@ import type {
10
10
  DefinedConversion,
11
11
  DefinedFlag,
12
12
  DefinedFunnel,
13
+ DefinedReferral,
13
14
  EmailProvider,
14
15
  EnrichmentProvider,
15
16
  FunnelStageEntry,
@@ -125,6 +126,8 @@ import {
125
126
  getOperatorSetting,
126
127
  } from "./lib/operator-settings.js";
127
128
  import { createRedisSecondaryStorage, getRedis } from "./lib/redis.js";
129
+ import { ReferralRegistry } from "./lib/referral-registry.js";
130
+ import { setReferralRuntime } from "./lib/referral-runtime.js";
128
131
  import { sendResetPasswordEmail } from "./lib/reset-email.js";
129
132
  import { seedPostHogDestination } from "./lib/seed-posthog-destination.js";
130
133
  import { setSmsService } from "./lib/sms.js";
@@ -236,6 +239,16 @@ export interface HogsendClient {
236
239
  accountLinkHooks: AccountLinkHooks;
237
240
  /** Parsed + validated ACCOUNT_LINK_ALLOWED_ORIGINS. Empty array = none permitted. */
238
241
  accountLinkAllowedOrigins: string[];
242
+ /**
243
+ * The container-held registry of referral definitions (`defineReferral`),
244
+ * keyed by id. There is NO env preset and NO single active referral: a
245
+ * referral exists because it was authored in code, and a product may run
246
+ * several at once. EMPTY is the normal state of a deploy that never asked
247
+ * for referrals, and every wired site (the arrive touch, the bind at
248
+ * identity adoption, the qualify evaluation in `ingestEvent`, the conversion
249
+ * tree walk) is INERT while it stays empty.
250
+ */
251
+ referrals: ReferralRegistry;
239
252
  /**
240
253
  * The container-held registry of enrichment providers, keyed by `meta.id` —
241
254
  * the enrichment sibling of {@link smsProviders}. Empty when no enrichment
@@ -380,6 +393,13 @@ export interface HogsendClient {
380
393
  * (frequency cap).
381
394
  */
382
395
  defaults: HogsendDefaults;
396
+ /**
397
+ * Resolved browser-readable contact projection (`GET /v1/contacts/me`).
398
+ * `publicProperties` is an operator ALLOWLIST of exact `contacts.properties`
399
+ * keys; `exposeEmail` opts the address in. Both default to closed
400
+ * (`[]` / `false`), so a deploy that configures nothing exposes nothing.
401
+ */
402
+ contactsConfig: { publicProperties: string[]; exposeEmail: boolean };
383
403
  }
384
404
 
385
405
  export interface HogsendClientOptions {
@@ -486,6 +506,20 @@ export interface HogsendClientOptions {
486
506
  linkTracking?: boolean;
487
507
  linkHost?: string;
488
508
  };
509
+ /**
510
+ * What `GET /v1/contacts/me` may hand back to a browser.
511
+ *
512
+ * - `publicProperties` — EXACT `contacts.properties` keys the browser may
513
+ * read. No wildcard, no prefix match. Anything not listed is omitted.
514
+ * - `exposeEmail` — include the contact's email address in the response.
515
+ *
516
+ * Defaults are closed (`[]` / `false`): with no `contacts` option the route
517
+ * answers `{ identified: false, traits: {} }` for everyone.
518
+ */
519
+ contacts?: {
520
+ publicProperties?: string[];
521
+ exposeEmail?: boolean;
522
+ };
489
523
  /**
490
524
  * Account linking (Steam, Twitch, or your own `defineAccountLink` provider).
491
525
  * The engine owns the stateful flow (state tokens, the link store,
@@ -506,6 +540,14 @@ export interface HogsendClientOptions {
506
540
  */
507
541
  allowedOrigins?: string[];
508
542
  };
543
+ /**
544
+ * Referral programs, authored with `defineReferral` (PRD 05). Pass the SAME
545
+ * array in BOTH `index.ts` and `worker.ts`: the HTTP side runs the touch and
546
+ * the bind, the worker side runs `getReferralLink` inside journeys.
547
+ * Duplicate ids inside one array warn and last-writer-wins, like every other
548
+ * registry merge. Omitted ⇒ referrals are entirely inert.
549
+ */
550
+ referrals?: DefinedReferral[];
509
551
  /**
510
552
  * Enrichment (Refinement) is a first-class provider kind mirroring
511
553
  * {@link email}/{@link sms}. The engine owns the cohesive refinement
@@ -992,6 +1034,21 @@ export function createHogsendClient(
992
1034
  ...(opts.accountLinks?.allowedOrigins ?? []),
993
1035
  ]);
994
1036
  const accountLinkHooks: AccountLinkHooks = opts.accountLinks?.hooks ?? {};
1037
+ // Referrals: code-only, no env preset. Duplicate ids in one array are almost
1038
+ // certainly an authoring mistake, so warn (last-writer-wins, mirroring the
1039
+ // account-link providers merge just above).
1040
+ {
1041
+ const seenReferralIds = new Set<string>();
1042
+ for (const referral of opts.referrals ?? []) {
1043
+ if (seenReferralIds.has(referral.id)) {
1044
+ logger.warn(
1045
+ `referrals contains "${referral.id}" more than once — the last one wins (last-writer-wins on id)`,
1046
+ );
1047
+ }
1048
+ seenReferralIds.add(referral.id);
1049
+ }
1050
+ }
1051
+ const referrals = new ReferralRegistry(opts.referrals ?? []);
995
1052
  if (
996
1053
  accountLinkProviders.count() > 0 &&
997
1054
  accountLinkAllowedOrigins.length === 0
@@ -1753,6 +1810,21 @@ export function createHogsendClient(
1753
1810
  `Destination registry loaded: ${destinationRegistry.count()} destinations`,
1754
1811
  );
1755
1812
 
1813
+ // The referral runtime, for the sites that hold no container: the bind in
1814
+ // `lib/contacts.ts` (post-commit, library code), the qualify + conversion
1815
+ // walk in `lib/ingestion.ts`, and `getReferralLink` inside a durable journey
1816
+ // task. OPTIONAL by design — a deploy with no referrals installs an empty
1817
+ // registry and every one of those sites stays inert.
1818
+ setReferralRuntime({
1819
+ referrals,
1820
+ db,
1821
+ baseUrl: env.API_PUBLIC_URL,
1822
+ hatchet,
1823
+ registry,
1824
+ logger,
1825
+ ...(analytics ? { analytics } : {}),
1826
+ });
1827
+
1756
1828
  const client: HogsendClient = {
1757
1829
  env,
1758
1830
  logger,
@@ -1770,6 +1842,7 @@ export function createHogsendClient(
1770
1842
  accountLinkProviders,
1771
1843
  accountLinkHooks,
1772
1844
  accountLinkAllowedOrigins,
1845
+ referrals,
1773
1846
  enrichmentProviders,
1774
1847
  enrichmentProvider,
1775
1848
  crmProviders,
@@ -1795,6 +1868,10 @@ export function createHogsendClient(
1795
1868
  hatchet: opts.overrides?.hatchet ?? hatchet,
1796
1869
  clientJournal: opts.clientJournal ?? { entries: [] },
1797
1870
  defaults,
1871
+ contactsConfig: {
1872
+ publicProperties: opts.contacts?.publicProperties ?? [],
1873
+ exposeEmail: opts.contacts?.exposeEmail ?? false,
1874
+ },
1798
1875
  };
1799
1876
 
1800
1877
  // Boot-time reader for `hogsend connect posthog`'s persisted phc_: when no
package/src/env.ts CHANGED
@@ -230,10 +230,10 @@ export const env = createEnv({
230
230
  .int()
231
231
  .nonnegative()
232
232
  .default(0),
233
- // --- Account links (Steam / Twitch, opt-in) ---
233
+ // --- Account links (opt-in) ---
234
234
  // Declared here (PRD 05); READ by the env presets (PRD 06). Convention:
235
235
  // ACCOUNT_LINK_<PROVIDER_ID>_CLIENT_ID / _CLIENT_SECRET for OAuth pairs.
236
- // Only the two built-ins get declared vars — this schema is STATIC, so a
236
+ // The six built-ins get declared vars — this schema is STATIC, so a
237
237
  // consumer-authored provider configures in CODE via the closure it passes
238
238
  // to `accountLinks.providers`, never via a dynamically-named env key.
239
239
  //
@@ -251,6 +251,22 @@ export const env = createEnv({
251
251
  // uses; an ACCOUNT_LINK_STEAM_CLIENT_SECRET name would be a lie (Steam has
252
252
  // no OAuth client pair at all).
253
253
  STEAM_WEB_API_KEY: z.string().min(1).optional(),
254
+ // Battle.net: the preset is built only when BOTH id + secret are present
255
+ // (same rule as Twitch). Register at https://develop.battle.net/access.
256
+ ACCOUNT_LINK_BATTLENET_CLIENT_ID: z.string().min(1).optional(),
257
+ ACCOUNT_LINK_BATTLENET_CLIENT_SECRET: z.string().min(1).optional(),
258
+ // Epic Games: the preset is built only when BOTH id + secret are present.
259
+ // Register at https://dev.epicgames.com/portal.
260
+ ACCOUNT_LINK_EPIC_CLIENT_ID: z.string().min(1).optional(),
261
+ ACCOUNT_LINK_EPIC_CLIENT_SECRET: z.string().min(1).optional(),
262
+ // Xbox (Microsoft Entra): the preset is built only when BOTH id + secret
263
+ // are present. Register at https://portal.azure.com.
264
+ ACCOUNT_LINK_XBOX_CLIENT_ID: z.string().min(1).optional(),
265
+ ACCOUNT_LINK_XBOX_CLIENT_SECRET: z.string().min(1).optional(),
266
+ // Riot Games: the preset is built only when BOTH id + secret are present.
267
+ // Register at https://developer.riotgames.com.
268
+ ACCOUNT_LINK_RIOT_CLIENT_ID: z.string().min(1).optional(),
269
+ ACCOUNT_LINK_RIOT_CLIENT_SECRET: z.string().min(1).optional(),
254
270
  // CSV of absolute origins ("https://play.example.com,https://example.com")
255
271
  // — the ONE allowlist governing both `returnTo` (PRD 07) and the
256
272
  // `postMessage` targetOrigin (PRD 10). Unset ⇒ empty list ⇒ no `returnTo`