@hogsend/engine 0.65.0 → 0.66.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.65.0",
3
+ "version": "0.66.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.66.0",
57
+ "@hogsend/core": "^0.66.0",
58
+ "@hogsend/db": "^0.66.0",
59
+ "@hogsend/email": "^0.66.0",
60
+ "@hogsend/plugin-posthog": "^0.66.0",
61
+ "@hogsend/plugin-resend": "^0.66.0",
62
+ "@hogsend/sms": "^0.66.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.66.0",
66
+ "@hogsend/plugin-hogsend": "^0.66.0",
67
+ "@hogsend/plugin-postmark": "^0.66.0",
68
+ "@hogsend/plugin-twilio": "^0.66.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/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`
package/src/index.ts CHANGED
@@ -833,6 +833,11 @@ export type {
833
833
  SmsTrackedSendResult,
834
834
  } from "./lib/sms-service-types.js";
835
835
  export { SMS_CHANNEL_ID } from "./lib/sms-tracked.js";
836
+ export {
837
+ type LoadedSnippet,
838
+ loadSnippet,
839
+ resolveSnippetPath,
840
+ } from "./lib/snippet.js";
836
841
  export { type MountStudioResult, mountStudio } from "./lib/studio.js";
837
842
  // --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
838
843
  export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
@@ -971,6 +976,7 @@ export {
971
976
  serializeLinkedAccount,
972
977
  serializePublicLinkedAccount,
973
978
  } from "./routes/accounts/serialize.js";
979
+ export { createSnippetRouter } from "./routes/snippet.js";
974
980
  // --- Contact sources (Clay/Attio/generic-webhook → cold prospects) ---
975
981
  export {
976
982
  type ColdChannelPosture,
@@ -1,6 +1,10 @@
1
1
  import type { AccountLinkProvider } from "@hogsend/core";
2
+ import { battlenetAccountLink } from "../account-links/battlenet.js";
3
+ import { epicAccountLink } from "../account-links/epic.js";
4
+ import { riotAccountLink } from "../account-links/riot.js";
2
5
  import { steamAccountLink } from "../account-links/steam.js";
3
6
  import { twitchAccountLink } from "../account-links/twitch.js";
7
+ import { xboxAccountLink } from "../account-links/xbox.js";
4
8
  import type { env as envSchema } from "../env.js";
5
9
 
6
10
  export interface AccountLinkEnvResult {
@@ -31,6 +35,14 @@ function hasEnvIntent(env: typeof envSchema): boolean {
31
35
  env.ACCOUNT_LINK_TWITCH_CLIENT_ID ||
32
36
  env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET ||
33
37
  env.STEAM_WEB_API_KEY ||
38
+ env.ACCOUNT_LINK_BATTLENET_CLIENT_ID ||
39
+ env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET ||
40
+ env.ACCOUNT_LINK_EPIC_CLIENT_ID ||
41
+ env.ACCOUNT_LINK_EPIC_CLIENT_SECRET ||
42
+ env.ACCOUNT_LINK_XBOX_CLIENT_ID ||
43
+ env.ACCOUNT_LINK_XBOX_CLIENT_SECRET ||
44
+ env.ACCOUNT_LINK_RIOT_CLIENT_ID ||
45
+ env.ACCOUNT_LINK_RIOT_CLIENT_SECRET ||
34
46
  env.ACCOUNT_LINK_ALLOWED_ORIGINS,
35
47
  );
36
48
  }
@@ -41,9 +53,9 @@ function hasEnvIntent(env: typeof envSchema): boolean {
41
53
  * deliberate divergences:
42
54
  *
43
55
  * 1. **Static imports.** No `loadOptionalPlugin`, no runtime-assembled
44
- * specifier, because Steam and Twitch are IN-PACKAGE config over the
45
- * `@hogsend/core` presets, not opt-in plugin packages (DECISIONS §3.1). No
46
- * top-level `await`, so `createHogsendClient` stays synchronous.
56
+ * specifier, because the six built-in providers are IN-PACKAGE config over
57
+ * the `@hogsend/core` presets, not opt-in plugin packages (DECISIONS §3.1).
58
+ * No top-level `await`, so `createHogsendClient` stays synchronous.
47
59
  * 2. **It returns warnings rather than calling `console.warn`.** The email
48
60
  * preset builder warns straight to `console.warn` because it runs before a
49
61
  * logger exists; here the container already has `logger`, so the strings
@@ -55,7 +67,7 @@ function hasEnvIntent(env: typeof envSchema): boolean {
55
67
  * preserving this repo's inert-when-unconfigured posture: a deploy that
56
68
  * never asked for account linking gets no public `/v1/accounts/*` surface
57
69
  * and no boot warning. Intent is EITHER env-side ({@link hasEnvIntent}: any
58
- * `ACCOUNT_LINK_TWITCH_*` var, `STEAM_WEB_API_KEY`, or
70
+ * `ACCOUNT_LINK_*` var, `STEAM_WEB_API_KEY`, or
59
71
  * `ACCOUNT_LINK_ALLOWED_ORIGINS` set) OR code-side
60
72
  * ({@link AccountLinksFromEnvOptions.consumerOptedIn}: any `accountLinks`
61
73
  * option passed, even `{}`). No intent ⇒ empty result.
@@ -70,13 +82,12 @@ function hasEnvIntent(env: typeof envSchema): boolean {
70
82
  * `API_PUBLIC_URL` (already required by the engine env), trailing slash
71
83
  * stripped — Steam rejects the assertion under a wrong realm. Steam
72
84
  * contributes no warning and cannot be half-configured.
73
- * - Twitch is registered iff BOTH `ACCOUNT_LINK_TWITCH_CLIENT_ID` and
74
- * `ACCOUNT_LINK_TWITCH_CLIENT_SECRET` are set. Exactly one set ⇒ no
75
- * registration (absent from the registry, not present-but-disabled) plus a
76
- * warning naming the MISSING var.
77
- * - Steam and twitch are the ONLY branches, by decision (DECISIONS §12): a
78
- * platform whose linking already ships elsewhere in this repo keeps its one
79
- * writer, so no third branch is added here.
85
+ * - OAuth providers (Twitch, Battle.net, Epic, Xbox, Riot) are registered iff
86
+ * BOTH `ACCOUNT_LINK_<ID>_CLIENT_ID` and `_CLIENT_SECRET` are set. Exactly
87
+ * one set ⇒ no registration (absent from the registry, not
88
+ * present-but-disabled) plus a warning naming the MISSING var.
89
+ * - Discord is the only excluded platform: it already ships via
90
+ * `plugin-discord`, and a second writer on `contacts.discordId` would drift.
80
91
  *
81
92
  * These presets come FIRST in the container's merge — a consumer-supplied
82
93
  * provider of the same id wins (last-writer-wins on the registry).
@@ -101,25 +112,78 @@ export function accountLinksFromEnv(
101
112
  }),
102
113
  );
103
114
 
104
- const twitchClientId = env.ACCOUNT_LINK_TWITCH_CLIENT_ID;
105
- const twitchClientSecret = env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET;
106
- if (twitchClientId && twitchClientSecret) {
107
- providers.push(
108
- twitchAccountLink({
109
- clientId: twitchClientId,
110
- clientSecret: twitchClientSecret,
111
- }),
112
- );
113
- } else if (twitchClientId || twitchClientSecret) {
114
- const missing = twitchClientId
115
- ? "ACCOUNT_LINK_TWITCH_CLIENT_SECRET"
116
- : "ACCOUNT_LINK_TWITCH_CLIENT_ID";
117
- warnings.push(
118
- `twitch account linking is half-configured: ${missing} is unset, so ` +
119
- "the twitch provider is NOT registered. Set both " +
120
- "ACCOUNT_LINK_TWITCH_CLIENT_ID and ACCOUNT_LINK_TWITCH_CLIENT_SECRET " +
121
- "(from https://dev.twitch.tv/console/apps), or unset both",
122
- );
115
+ const oauthPresets: Array<{
116
+ id: string;
117
+ clientId: string | undefined;
118
+ clientSecret: string | undefined;
119
+ idVar: string;
120
+ secretVar: string;
121
+ factory: (cfg: {
122
+ clientId: string;
123
+ clientSecret: string;
124
+ }) => AccountLinkProvider;
125
+ portal: string;
126
+ }> = [
127
+ {
128
+ id: "twitch",
129
+ clientId: env.ACCOUNT_LINK_TWITCH_CLIENT_ID,
130
+ clientSecret: env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET,
131
+ idVar: "ACCOUNT_LINK_TWITCH_CLIENT_ID",
132
+ secretVar: "ACCOUNT_LINK_TWITCH_CLIENT_SECRET",
133
+ factory: twitchAccountLink,
134
+ portal: "https://dev.twitch.tv/console/apps",
135
+ },
136
+ {
137
+ id: "battlenet",
138
+ clientId: env.ACCOUNT_LINK_BATTLENET_CLIENT_ID,
139
+ clientSecret: env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET,
140
+ idVar: "ACCOUNT_LINK_BATTLENET_CLIENT_ID",
141
+ secretVar: "ACCOUNT_LINK_BATTLENET_CLIENT_SECRET",
142
+ factory: battlenetAccountLink,
143
+ portal: "https://develop.battle.net/access",
144
+ },
145
+ {
146
+ id: "epic",
147
+ clientId: env.ACCOUNT_LINK_EPIC_CLIENT_ID,
148
+ clientSecret: env.ACCOUNT_LINK_EPIC_CLIENT_SECRET,
149
+ idVar: "ACCOUNT_LINK_EPIC_CLIENT_ID",
150
+ secretVar: "ACCOUNT_LINK_EPIC_CLIENT_SECRET",
151
+ factory: epicAccountLink,
152
+ portal: "https://dev.epicgames.com/portal",
153
+ },
154
+ {
155
+ id: "xbox",
156
+ clientId: env.ACCOUNT_LINK_XBOX_CLIENT_ID,
157
+ clientSecret: env.ACCOUNT_LINK_XBOX_CLIENT_SECRET,
158
+ idVar: "ACCOUNT_LINK_XBOX_CLIENT_ID",
159
+ secretVar: "ACCOUNT_LINK_XBOX_CLIENT_SECRET",
160
+ factory: xboxAccountLink,
161
+ portal: "https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps",
162
+ },
163
+ {
164
+ id: "riot",
165
+ clientId: env.ACCOUNT_LINK_RIOT_CLIENT_ID,
166
+ clientSecret: env.ACCOUNT_LINK_RIOT_CLIENT_SECRET,
167
+ idVar: "ACCOUNT_LINK_RIOT_CLIENT_ID",
168
+ secretVar: "ACCOUNT_LINK_RIOT_CLIENT_SECRET",
169
+ factory: riotAccountLink,
170
+ portal: "https://developer.riotgames.com",
171
+ },
172
+ ];
173
+
174
+ for (const p of oauthPresets) {
175
+ if (p.clientId && p.clientSecret) {
176
+ providers.push(
177
+ p.factory({ clientId: p.clientId, clientSecret: p.clientSecret }),
178
+ );
179
+ } else if (p.clientId || p.clientSecret) {
180
+ const missing = p.clientId ? p.secretVar : p.idVar;
181
+ warnings.push(
182
+ `${p.id} account linking is half-configured: ${missing} is unset, ` +
183
+ `so the ${p.id} provider is NOT registered. Set both ${p.idVar} ` +
184
+ `and ${p.secretVar} (from ${p.portal}), or unset both`,
185
+ );
186
+ }
123
187
  }
124
188
 
125
189
  return { providers, warnings };
@@ -1079,6 +1079,21 @@ interface ResolveContactOptions {
1079
1079
  source?: string;
1080
1080
  /** Timestamp paired with {@link source}; defaults to now() at create time. */
1081
1081
  sourcedAt?: Date;
1082
+ /**
1083
+ * JOURNEY-PLANE opt-out for the merge fold's `account.unlinked` re-ingest
1084
+ * (PRD 08 T5). Default `true`: an organic resolve (a live `/v1/events`
1085
+ * ingest that happens to fold two contacts) SHOULD enrol journeys on the
1086
+ * `account.unlinked` a merge produced, exactly as a direct unlink would.
1087
+ *
1088
+ * A BULK importer sets `false`. A CSV import is a statement about the PAST,
1089
+ * and one job can merge many rows whose losers each held a live linked
1090
+ * account — so left on, a single import would fan out one journey enrolment
1091
+ * per such row (the same amplification class the `/v1/accounts/import`
1092
+ * route gates with its own `enrollJourneys`). This suppresses ONLY the
1093
+ * journey plane; the outbound `account.unlinked` webhook still fires, so the
1094
+ * customer's mirror converges whether or not a journey ran.
1095
+ */
1096
+ enrollJourneys?: boolean;
1082
1097
  }
1083
1098
 
1084
1099
  /**
@@ -1500,8 +1515,15 @@ async function resolveContactShared(
1500
1515
  // and returns without probing value keys — so it can neither merge again
1501
1516
  // nor produce a second `linkUnlinks`. It is also fire-and-forget and
1502
1517
  // strictly post-commit, so it cannot slow or fail the resolve.
1503
- for (const fact of resolved.linkUnlinks) {
1504
- ingestAccountUnlinked(db, fact);
1518
+ //
1519
+ // A BULK importer opts OUT here (`enrollJourneys: false`): one job can fold
1520
+ // many rows, and left on it would fan out one enrolment per merged row that
1521
+ // dropped a live link. The outbound `emitAccountUnlinked` above is
1522
+ // deliberately NOT gated — the customer's mirror converges regardless.
1523
+ if (opts.enrollJourneys !== false) {
1524
+ for (const fact of resolved.linkUnlinks) {
1525
+ ingestAccountUnlinked(db, fact);
1526
+ }
1505
1527
  }
1506
1528
  }
1507
1529
 
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /**
8
+ * The drop-in browser snippet: `@hogsend/js` builds a single minified IIFE to
9
+ * `dist/hogsend.js`, and the engine serves it first-party at `GET /hogsend.js`
10
+ * so a site with no bundler can paste one `<script>` tag.
11
+ *
12
+ * Like the Studio SPA, `@hogsend/js` is NOT a code import of the engine — the
13
+ * asset is located on disk at boot (so consumer bundlers never inline it) and
14
+ * serving is best-effort: no file, no route (404), never a boot crash.
15
+ *
16
+ * Resolution order:
17
+ * 1. `HOGSEND_JS_PATH` env var (explicit file path; absolute or cwd-relative).
18
+ * 2. `require.resolve("@hogsend/js/package.json")` → sibling `dist/hogsend.js`
19
+ * (the package is installed alongside the engine).
20
+ * 3. Monorepo source layout: `packages/js/dist/hogsend.js` relative to here.
21
+ * 4. cwd-relative `packages/js/dist/hogsend.js`.
22
+ */
23
+ export function resolveSnippetPath(): string | null {
24
+ const candidates: string[] = [];
25
+
26
+ const envPath = process.env.HOGSEND_JS_PATH;
27
+ if (envPath && envPath.length > 0) {
28
+ candidates.push(resolve(process.cwd(), envPath));
29
+ }
30
+
31
+ const require = createRequire(import.meta.url);
32
+ try {
33
+ const pkgJson = require.resolve("@hogsend/js/package.json");
34
+ candidates.push(join(dirname(pkgJson), "dist", "hogsend.js"));
35
+ } catch {
36
+ // Not installed next to the engine — fall through to layout guesses.
37
+ }
38
+
39
+ const here = dirname(fileURLToPath(import.meta.url));
40
+ candidates.push(resolve(here, "../../../js/dist/hogsend.js"));
41
+ candidates.push(resolve(process.cwd(), "packages/js/dist/hogsend.js"));
42
+ candidates.push(resolve(process.cwd(), "../../packages/js/dist/hogsend.js"));
43
+
44
+ for (const file of candidates) {
45
+ if (existsSync(file)) return file;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ export interface LoadedSnippet {
51
+ /** The JS source, served verbatim. */
52
+ body: string;
53
+ /** Strong ETag: quoted sha256 prefix of the body. */
54
+ etag: string;
55
+ /** Where it was read from (logging). */
56
+ path: string;
57
+ }
58
+
59
+ /**
60
+ * Read the snippet ONCE. The body is small (tens of KB) and immutable for the
61
+ * life of the process, so it stays in memory; the ETag is content-derived so
62
+ * clients revalidate cheaply and a new build invalidates naturally.
63
+ */
64
+ export function loadSnippet(
65
+ path: string | null = resolveSnippetPath(),
66
+ ): LoadedSnippet | null {
67
+ if (!path) return null;
68
+ let body: string;
69
+ try {
70
+ body = readFileSync(path, "utf8");
71
+ } catch {
72
+ return null;
73
+ }
74
+ const hash = createHash("sha256").update(body).digest("hex").slice(0, 32);
75
+ return { body, etag: `"${hash}"`, path };
76
+ }
@@ -17,6 +17,7 @@ import { flagsRouter } from "./flags/index.js";
17
17
  import { groupsRouter } from "./groups/index.js";
18
18
  import { healthRouter } from "./health.js";
19
19
  import { listsRouter } from "./lists/index.js";
20
+ import { createSnippetRouter } from "./snippet.js";
20
21
  import { trackingRouter } from "./tracking/index.js";
21
22
  import { shortLinkRouter } from "./tracking/short.js";
22
23
  import { vanityRouter } from "./tracking/vanity.js";
@@ -244,6 +245,11 @@ export function registerRoutes(
244
245
  // against the GSM-7 segment budget. Unauthenticated like /l.
245
246
  app.route("/", shortLinkRouter);
246
247
 
248
+ // Drop-in browser SDK — root-mounted so the pasted tag is
249
+ // `${API_PUBLIC_URL}/hogsend.js`. Public; 404s when @hogsend/js is not
250
+ // installed next to the engine (best-effort, like the Studio SPA).
251
+ app.route("/", createSnippetRouter());
252
+
247
253
  // Generic connector dispatch (oauth/interactions/ingress) — the static
248
254
  // `connectors/` prefix is registered BEFORE the `:sourceId` webhook catch-all
249
255
  // so it wins path matching. These routes self-authenticate (oauth state +
@@ -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
+ }
@@ -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 };