@hogsend/engine 0.64.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.
Files changed (77) hide show
  1. package/package.json +12 -12
  2. package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
  3. package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
  4. package/src/account-links/__fixtures__/steam.json +21 -0
  5. package/src/account-links/__fixtures__/twitch.json +22 -0
  6. package/src/account-links/battlenet.ts +84 -0
  7. package/src/account-links/epic.ts +87 -0
  8. package/src/account-links/index.ts +15 -0
  9. package/src/account-links/riot.ts +82 -0
  10. package/src/account-links/steam.test.ts +243 -0
  11. package/src/account-links/steam.ts +48 -0
  12. package/src/account-links/twitch.test.ts +157 -0
  13. package/src/account-links/twitch.ts +99 -0
  14. package/src/account-links/xbox.ts +92 -0
  15. package/src/app.ts +9 -1
  16. package/src/container.account-links.env.test.ts +65 -0
  17. package/src/container.account-links.halfenv.test.ts +48 -0
  18. package/src/container.account-links.test.ts +185 -0
  19. package/src/container.ts +120 -0
  20. package/src/env.ts +53 -0
  21. package/src/index.ts +93 -1
  22. package/src/lib/account-link-emit.ts +126 -0
  23. package/src/lib/account-link-events.ts +180 -0
  24. package/src/lib/account-link-hooks.test.ts +158 -0
  25. package/src/lib/account-link-hooks.ts +73 -0
  26. package/src/lib/account-link-ingest.ts +364 -0
  27. package/src/lib/account-link-nonce.test.ts +52 -0
  28. package/src/lib/account-link-nonce.ts +57 -0
  29. package/src/lib/account-link-origins.test.ts +72 -0
  30. package/src/lib/account-link-origins.ts +87 -0
  31. package/src/lib/account-link-pkce.test.ts +91 -0
  32. package/src/lib/account-link-pkce.ts +106 -0
  33. package/src/lib/account-link-provider-registry.test.ts +52 -0
  34. package/src/lib/account-link-provider-registry.ts +61 -0
  35. package/src/lib/account-link-throttle.test.ts +178 -0
  36. package/src/lib/account-link-throttle.ts +130 -0
  37. package/src/lib/account-link-url.ts +85 -0
  38. package/src/lib/account-links-emit.test.ts +525 -0
  39. package/src/lib/account-links-env.test.ts +40 -0
  40. package/src/lib/account-links-from-env.test.ts +187 -0
  41. package/src/lib/account-links-from-env.ts +190 -0
  42. package/src/lib/account-links.ts +1300 -0
  43. package/src/lib/app-secret.ts +34 -0
  44. package/src/lib/connector-actions.test.ts +13 -4
  45. package/src/lib/connector-state.account-link.test.ts +114 -0
  46. package/src/lib/connector-state.ts +48 -3
  47. package/src/lib/contacts.ts +342 -6
  48. package/src/lib/outbound-account-payloads.test.ts +137 -0
  49. package/src/lib/outbound.ts +91 -0
  50. package/src/lib/provider-credentials.ts +19 -5
  51. package/src/lib/snippet.ts +76 -0
  52. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  53. package/src/lib/webhook-signing.ts +18 -1
  54. package/src/routes/accounts/callback.ts +597 -0
  55. package/src/routes/accounts/emit.ts +231 -0
  56. package/src/routes/accounts/import-links.ts +210 -0
  57. package/src/routes/accounts/index.ts +75 -0
  58. package/src/routes/accounts/lookup.ts +177 -0
  59. package/src/routes/accounts/me.ts +215 -0
  60. package/src/routes/accounts/mint.ts +279 -0
  61. package/src/routes/accounts/pages.ts +62 -0
  62. package/src/routes/accounts/resolve.ts +61 -0
  63. package/src/routes/accounts/serialize.ts +96 -0
  64. package/src/routes/accounts/shared.ts +107 -0
  65. package/src/routes/accounts/start.ts +229 -0
  66. package/src/routes/accounts/unlink.ts +98 -0
  67. package/src/routes/admin/agent.ts +2 -0
  68. package/src/routes/admin/api-keys.ts +7 -0
  69. package/src/routes/admin/contacts.ts +38 -2
  70. package/src/routes/connectors/index.ts +17 -0
  71. package/src/routes/contacts/index.ts +8 -0
  72. package/src/routes/index.ts +81 -0
  73. package/src/routes/snippet.test.ts +70 -0
  74. package/src/routes/snippet.ts +58 -0
  75. package/src/testing-barrel.test.ts +74 -0
  76. package/src/testing.ts +17 -0
  77. 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.64.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.64.0",
57
- "@hogsend/core": "^0.64.0",
58
- "@hogsend/db": "^0.64.0",
59
- "@hogsend/email": "^0.64.0",
60
- "@hogsend/plugin-posthog": "^0.64.0",
61
- "@hogsend/plugin-resend": "^0.64.0",
62
- "@hogsend/sms": "^0.64.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.64.0",
66
- "@hogsend/plugin-hogsend": "^0.64.0",
67
- "@hogsend/plugin-postmark": "^0.64.0",
68
- "@hogsend/plugin-twilio": "^0.64.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,57 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { fakeFetch } from "./fake-fetch.js";
4
+ import steamFixtures from "./steam.json" with { type: "json" };
5
+
6
+ test("records calls with method, headers and body", async () => {
7
+ const { fetchImpl, calls } = fakeFetch({
8
+ "POST https://id.twitch.tv/oauth2/token": {
9
+ body: { access_token: "fixture-token" },
10
+ },
11
+ });
12
+
13
+ const response = await fetchImpl("https://id.twitch.tv/oauth2/token?x=1", {
14
+ method: "POST",
15
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
16
+ body: new URLSearchParams({ grant_type: "authorization_code" }).toString(),
17
+ });
18
+
19
+ assert.equal(response.status, 200);
20
+ assert.deepEqual(await response.json(), { access_token: "fixture-token" });
21
+ assert.equal(calls.length, 1);
22
+ assert.equal(calls[0]?.method, "POST");
23
+ // The full URL (query included) is recorded even though the route key
24
+ // strips the query — tests assert params off `calls`.
25
+ assert.equal(calls[0]?.url, "https://id.twitch.tv/oauth2/token?x=1");
26
+ assert.equal(
27
+ calls[0]?.headers["content-type"],
28
+ "application/x-www-form-urlencoded",
29
+ );
30
+ assert.equal(calls[0]?.body, "grant_type=authorization_code");
31
+ });
32
+
33
+ test("throws on an unmatched route", async () => {
34
+ const { fetchImpl, calls } = fakeFetch({});
35
+ await assert.rejects(
36
+ () =>
37
+ fetchImpl("https://evil.example.com/openid/login", { method: "POST" }),
38
+ /no route registered for "POST https:\/\/evil\.example\.com\/openid\/login"/,
39
+ );
40
+ // The call is still recorded, so a test can see WHAT reached out.
41
+ assert.equal(calls.length, 1);
42
+ });
43
+
44
+ test("serves a text body for the steam check_authentication route", async () => {
45
+ const { fetchImpl } = fakeFetch({
46
+ "POST https://steamcommunity.com/openid/login": {
47
+ text: steamFixtures.checkAuthenticationValid,
48
+ },
49
+ });
50
+ const response = await fetchImpl("https://steamcommunity.com/openid/login", {
51
+ method: "POST",
52
+ body: "openid.mode=check_authentication",
53
+ });
54
+ assert.equal(response.status, 200);
55
+ assert.match(response.headers.get("content-type") ?? "", /text\/plain/);
56
+ assert.match(await response.text(), /^is_valid:true$/m);
57
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Deterministic in-process `fetch` for the account-link test suites.
3
+ *
4
+ * The injection point is PRD 01's `HandleCallbackArgs.fetchImpl` (resolved as
5
+ * `fetchImpl ?? globalThis.fetch` inside the presets) — the same pattern
6
+ * `plugin-apollo` proved (`packages/plugin-apollo/src/index.ts:46-47`, "the
7
+ * whole suite runs offline through this"). The engine providers therefore need
8
+ * no `fetch` field of their own, and PRD 07's route tests thread the same
9
+ * `fetchImpl` through.
10
+ *
11
+ * Routes key on `method + " " + url-without-query`, so a test asserts query
12
+ * params off `calls` rather than baking them into the key. An unmatched call
13
+ * THROWS with the full URL, so a provider that quietly reaches an unexpected
14
+ * endpoint fails loudly instead of hanging on a real network call.
15
+ */
16
+
17
+ export interface FakeFetchRoute {
18
+ /** Response status. Default 200. */
19
+ status?: number;
20
+ /** JSON body — serialized with `JSON.stringify`, `content-type: application/json`. */
21
+ body?: unknown;
22
+ /**
23
+ * Plain-text body (`content-type: text/plain`) — Steam's
24
+ * `check_authentication` answers key-value text, not JSON. Wins over `body`
25
+ * when both are set.
26
+ */
27
+ text?: string;
28
+ }
29
+
30
+ export interface FakeFetchCall {
31
+ url: string;
32
+ method: string;
33
+ headers: Record<string, string>;
34
+ body: string | null;
35
+ }
36
+
37
+ function normalizeHeaders(
38
+ headers: HeadersInit | undefined,
39
+ ): Record<string, string> {
40
+ const out: Record<string, string> = {};
41
+ if (!headers) return out;
42
+ // Headers lower-cases names on iteration; mirror that for the other shapes
43
+ // so a test never has to guess the casing.
44
+ if (headers instanceof Headers) {
45
+ headers.forEach((value, key) => {
46
+ out[key.toLowerCase()] = value;
47
+ });
48
+ return out;
49
+ }
50
+ if (Array.isArray(headers)) {
51
+ for (const [key, value] of headers) out[key.toLowerCase()] = value;
52
+ return out;
53
+ }
54
+ for (const [key, value] of Object.entries(headers)) {
55
+ out[key.toLowerCase()] = value;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ export function fakeFetch(routes: Record<string, FakeFetchRoute>): {
61
+ fetchImpl: typeof fetch;
62
+ calls: FakeFetchCall[];
63
+ } {
64
+ const calls: FakeFetchCall[] = [];
65
+
66
+ const fetchImpl = (async (
67
+ input: RequestInfo | URL,
68
+ init?: RequestInit,
69
+ ): Promise<Response> => {
70
+ const url =
71
+ typeof input === "string"
72
+ ? input
73
+ : input instanceof URL
74
+ ? input.toString()
75
+ : input.url;
76
+ const method = (init?.method ?? "GET").toUpperCase();
77
+ const parsed = new URL(url);
78
+ const key = `${method} ${parsed.origin}${parsed.pathname}`;
79
+
80
+ const rawBody = init?.body;
81
+ calls.push({
82
+ url,
83
+ method,
84
+ headers: normalizeHeaders(init?.headers),
85
+ body: rawBody === undefined || rawBody === null ? null : String(rawBody),
86
+ });
87
+
88
+ const route = routes[key];
89
+ if (!route) {
90
+ throw new Error(
91
+ `fakeFetch: no route registered for "${key}" (full url: ${url}). ` +
92
+ `Registered: ${Object.keys(routes).join(", ") || "<none>"}`,
93
+ );
94
+ }
95
+
96
+ const status = route.status ?? 200;
97
+ const isText = route.text !== undefined;
98
+ const bodyText = isText
99
+ ? (route.text as string)
100
+ : route.body !== undefined
101
+ ? JSON.stringify(route.body)
102
+ : "";
103
+ return new Response(bodyText, {
104
+ status,
105
+ headers: {
106
+ "content-type": isText
107
+ ? "text/plain; charset=utf-8"
108
+ : "application/json",
109
+ },
110
+ });
111
+ }) as typeof fetch;
112
+
113
+ return { fetchImpl, calls };
114
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "checkAuthenticationValid": "ns:http://specs.openid.net/auth/2.0\nis_valid:true\n",
3
+ "checkAuthenticationInvalid": "ns:http://specs.openid.net/auth/2.0\nis_valid:false\n",
4
+ "playerSummaries": {
5
+ "response": {
6
+ "players": [
7
+ {
8
+ "steamid": "76561197960435530",
9
+ "communityvisibilitystate": 3,
10
+ "profilestate": 1,
11
+ "personaname": "Robin",
12
+ "profileurl": "https://steamcommunity.com/id/robinwalker/",
13
+ "avatar": "https://avatars.steamstatic.com/small.jpg",
14
+ "avatarmedium": "https://avatars.steamstatic.com/medium.jpg",
15
+ "avatarfull": "https://avatars.steamstatic.com/full.jpg",
16
+ "personastate": 0
17
+ }
18
+ ]
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "users": {
3
+ "data": [
4
+ {
5
+ "id": "141981764",
6
+ "login": "twitchdev",
7
+ "display_name": "TwitchDev",
8
+ "type": "",
9
+ "broadcaster_type": "partner",
10
+ "description": "Supporting third-party developers building Twitch integrations.",
11
+ "profile_image_url": "https://static-cdn.jtvnw.net/jtv_user_pictures/8a6381c7-d0c0-4576-b179-38bd5ce1d6af-profile_image-300x300.png",
12
+ "offline_image_url": "",
13
+ "view_count": 5980557,
14
+ "email": "not-real@email.com",
15
+ "created_at": "2016-12-14T20:32:28Z"
16
+ }
17
+ ]
18
+ },
19
+ "usersEmpty": {
20
+ "data": []
21
+ }
22
+ }
@@ -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
+ }
@@ -0,0 +1,15 @@
1
+ // The six built-in account-link providers. Config over the `@hogsend/core`
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. 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";
13
+ export { type SteamAccountLinkConfig, steamAccountLink } from "./steam.js";
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
+ }