@hogsend/engine 0.64.0 → 0.65.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 (68) 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/index.ts +8 -0
  7. package/src/account-links/steam.test.ts +243 -0
  8. package/src/account-links/steam.ts +48 -0
  9. package/src/account-links/twitch.test.ts +157 -0
  10. package/src/account-links/twitch.ts +99 -0
  11. package/src/container.account-links.env.test.ts +65 -0
  12. package/src/container.account-links.halfenv.test.ts +48 -0
  13. package/src/container.account-links.test.ts +185 -0
  14. package/src/container.ts +120 -0
  15. package/src/env.ts +37 -0
  16. package/src/index.ts +87 -1
  17. package/src/lib/account-link-emit.ts +126 -0
  18. package/src/lib/account-link-events.ts +180 -0
  19. package/src/lib/account-link-hooks.test.ts +158 -0
  20. package/src/lib/account-link-hooks.ts +73 -0
  21. package/src/lib/account-link-ingest.ts +364 -0
  22. package/src/lib/account-link-nonce.test.ts +52 -0
  23. package/src/lib/account-link-nonce.ts +57 -0
  24. package/src/lib/account-link-origins.test.ts +72 -0
  25. package/src/lib/account-link-origins.ts +87 -0
  26. package/src/lib/account-link-pkce.test.ts +91 -0
  27. package/src/lib/account-link-pkce.ts +106 -0
  28. package/src/lib/account-link-provider-registry.test.ts +52 -0
  29. package/src/lib/account-link-provider-registry.ts +61 -0
  30. package/src/lib/account-link-throttle.test.ts +178 -0
  31. package/src/lib/account-link-throttle.ts +130 -0
  32. package/src/lib/account-link-url.ts +85 -0
  33. package/src/lib/account-links-emit.test.ts +525 -0
  34. package/src/lib/account-links-env.test.ts +40 -0
  35. package/src/lib/account-links-from-env.test.ts +187 -0
  36. package/src/lib/account-links-from-env.ts +126 -0
  37. package/src/lib/account-links.ts +1300 -0
  38. package/src/lib/app-secret.ts +34 -0
  39. package/src/lib/connector-actions.test.ts +13 -4
  40. package/src/lib/connector-state.account-link.test.ts +114 -0
  41. package/src/lib/connector-state.ts +48 -3
  42. package/src/lib/contacts.ts +320 -6
  43. package/src/lib/outbound-account-payloads.test.ts +137 -0
  44. package/src/lib/outbound.ts +91 -0
  45. package/src/lib/provider-credentials.ts +19 -5
  46. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  47. package/src/lib/webhook-signing.ts +18 -1
  48. package/src/routes/accounts/callback.ts +597 -0
  49. package/src/routes/accounts/emit.ts +231 -0
  50. package/src/routes/accounts/import-links.ts +210 -0
  51. package/src/routes/accounts/index.ts +75 -0
  52. package/src/routes/accounts/lookup.ts +177 -0
  53. package/src/routes/accounts/me.ts +215 -0
  54. package/src/routes/accounts/mint.ts +279 -0
  55. package/src/routes/accounts/pages.ts +62 -0
  56. package/src/routes/accounts/resolve.ts +61 -0
  57. package/src/routes/accounts/serialize.ts +96 -0
  58. package/src/routes/accounts/shared.ts +107 -0
  59. package/src/routes/accounts/start.ts +229 -0
  60. package/src/routes/accounts/unlink.ts +98 -0
  61. package/src/routes/admin/agent.ts +2 -0
  62. package/src/routes/admin/api-keys.ts +7 -0
  63. package/src/routes/admin/contacts.ts +38 -2
  64. package/src/routes/connectors/index.ts +17 -0
  65. package/src/routes/contacts/index.ts +8 -0
  66. package/src/routes/index.ts +75 -0
  67. package/src/testing-barrel.test.ts +74 -0
  68. package/src/testing.ts +17 -0
@@ -0,0 +1,96 @@
1
+ import { z } from "@hono/zod-openapi";
2
+ import type { LinkedAccountRecord } from "../../lib/account-links.js";
3
+
4
+ /**
5
+ * TWO SHAPES, ONE ROW (PRD 09 T2). The `linked_accounts` row leaves the engine
6
+ * through exactly one of these, and which one is decided by the AUTH TIER of
7
+ * the route, never by a query parameter.
8
+ *
9
+ * Both mirror `serializeGroup` (`routes/groups/index.ts:31-43`): a fresh object
10
+ * literal, timestamps as ISO strings, internal columns dropped.
11
+ */
12
+
13
+ /**
14
+ * The OPERATOR shape — secret-key routes only (`GET /v1/accounts`, the reverse
15
+ * lookup, the import conflicts). Carries the reconciliation facts a customer's
16
+ * own store needs: the owning `contactId`, the monotonic `version`, and
17
+ * `tokensRevokedAt` (DECISIONS §10).
18
+ *
19
+ * The sealed `tokens` blob is NOT here and cannot be: `LinkedAccountRecord`
20
+ * already collapsed it to `hasTokens` inside the store, which is the one place
21
+ * the column is ever selected.
22
+ */
23
+ export const linkedAccountSchema = z.object({
24
+ provider: z.string(),
25
+ providerUserId: z.string(),
26
+ contactId: z.string(),
27
+ username: z.string().nullable(),
28
+ avatarUrl: z.string().nullable(),
29
+ method: z.enum(["oauth", "import"]),
30
+ /**
31
+ * A Postgres `bigint` as a decimal STRING (DECISIONS §5.1), never a JSON
32
+ * number. The customer's whole contract is an exact
33
+ * `incoming.version > stored.version` comparison, and a version above
34
+ * `Number.MAX_SAFE_INTEGER` rounded through float64 breaks that guard
35
+ * INVISIBLY — the wrong owner is recorded and nothing errors.
36
+ */
37
+ version: z.string(),
38
+ linkedAt: z.string(),
39
+ tokensRevokedAt: z.string().nullable(),
40
+ });
41
+
42
+ export type SerializedLinkedAccount = z.infer<typeof linkedAccountSchema>;
43
+
44
+ /**
45
+ * The ONLY shape `GET /v1/accounts/me` may return (DECISIONS §6.9). Four
46
+ * display keys. It structurally cannot carry an id, a version or an email, so
47
+ * a browser response can neither confirm which platform account a person holds
48
+ * nor be replayed into the operator plane.
49
+ */
50
+ export const publicLinkedAccountSchema = z.object({
51
+ provider: z.string(),
52
+ username: z.string().nullable(),
53
+ avatarUrl: z.string().nullable(),
54
+ linkedAt: z.string(),
55
+ });
56
+
57
+ export type SerializedPublicLinkedAccount = z.infer<
58
+ typeof publicLinkedAccountSchema
59
+ >;
60
+
61
+ export function serializeLinkedAccount(
62
+ row: LinkedAccountRecord,
63
+ ): SerializedLinkedAccount {
64
+ return {
65
+ provider: row.provider,
66
+ providerUserId: row.providerUserId,
67
+ contactId: row.contactId,
68
+ username: row.username,
69
+ avatarUrl: row.avatarUrl,
70
+ method: row.method,
71
+ // ALREADY a string off the store (`String(row.version)`), forwarded
72
+ // verbatim. Nothing on this plane parses it.
73
+ version: row.version,
74
+ linkedAt: row.linkedAt.toISOString(),
75
+ tokensRevokedAt: row.tokensRevokedAt
76
+ ? row.tokensRevokedAt.toISOString()
77
+ : null,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Builds a FRESH OBJECT LITERAL with four keys. It never spreads the row and
83
+ * must never start to: a spread is how `providerUserId` leaks the day someone
84
+ * adds a column, and the test that pins this asserts the KEY SET rather than a
85
+ * sample row, so the leak fails a test instead of shipping.
86
+ */
87
+ export function serializePublicLinkedAccount(
88
+ row: LinkedAccountRecord,
89
+ ): SerializedPublicLinkedAccount {
90
+ return {
91
+ provider: row.provider,
92
+ username: row.username,
93
+ avatarUrl: row.avatarUrl,
94
+ linkedAt: row.linkedAt.toISOString(),
95
+ };
96
+ }
@@ -0,0 +1,107 @@
1
+ import { steamReturnTo } from "@hogsend/core";
2
+ import type { Context } from "hono";
3
+ import type { AppEnv } from "../../app.js";
4
+
5
+ /**
6
+ * Pieces both hosted account-link routes need. Kept here rather than duplicated
7
+ * so `/start` and `/callback` cannot drift on the two things that MUST agree
8
+ * byte-for-byte: the callback URL they present, and the anon-id cookie.
9
+ */
10
+
11
+ /**
12
+ * The redirect URI this deployment presents for a provider, byte-exact.
13
+ *
14
+ * `/start` hands it to `authorizeUrl` and `/callback` hands it to
15
+ * `handleCallback`, where OAuth2 providers compare it verbatim against the
16
+ * authorize leg and Steam compares its `openid.return_to` echo against it. The
17
+ * trailing slash on `API_PUBLIC_URL` is the one operator-controlled degree of
18
+ * freedom, so it is stripped in exactly one place (the same normalization
19
+ * `lib/account-links-from-env.ts` applies to the Steam realm).
20
+ */
21
+ export function accountLinkCallbackUrl(
22
+ apiPublicUrl: string,
23
+ providerId: string,
24
+ ): string {
25
+ return `${apiPublicUrl.replace(/\/+$/, "")}/v1/accounts/${encodeURIComponent(providerId)}/callback`;
26
+ }
27
+
28
+ /**
29
+ * The redirect URI to present on the CALLBACK leg, which is not always the one
30
+ * the authorize leg presented.
31
+ *
32
+ * OAuth2 carries the state in its own `state` parameter, so its `redirect_uri`
33
+ * is the bare callback URL on BOTH legs and the token exchange compares it
34
+ * verbatim. OpenID 2.0 has no state parameter at all, so `steamOpenIdLink`
35
+ * folds our signed state into `openid.return_to` and its callback guard
36
+ * compares the echoed value BYTE-FOR-BYTE against the `redirectUri` we pass —
37
+ * which therefore has to carry the state.
38
+ *
39
+ * The discriminator is the presence of an `openid.*` parameter, because PRD 01
40
+ * froze the provider contract with no protocol flag and a hardcoded
41
+ * `providerId === "steam"` would break the moment a consumer registers their
42
+ * own OpenID 2.0 provider under another id.
43
+ *
44
+ * It is SAFE for the discriminator to be attacker-influenced. The state folded
45
+ * in is the one this route ALREADY signature-verified and nonce-burned, never
46
+ * the attacker's echoed `openid.return_to` — so the comparison stays a real
47
+ * channel binding, and the worst a stray `openid.*` param on an OAuth2 callback
48
+ * achieves is a `redirect_uri` that provider's own exchange then rejects.
49
+ */
50
+ export function accountLinkCallbackRedirectUri(args: {
51
+ apiPublicUrl: string;
52
+ providerId: string;
53
+ /** The VERIFIED state token, exactly as it was minted. */
54
+ state: string;
55
+ query: Record<string, string>;
56
+ }): string {
57
+ const base = accountLinkCallbackUrl(args.apiPublicUrl, args.providerId);
58
+ const isOpenId = Object.keys(args.query).some((key) =>
59
+ key.startsWith("openid."),
60
+ );
61
+ if (!isOpenId) return base;
62
+ // `steamReturnTo` is the preset's OWN builder, exported so this route
63
+ // constructs the same string it presented rather than a lookalike. Calling it
64
+ // is what makes "byte-for-byte" true instead of aspirational.
65
+ return steamReturnTo(base, args.state);
66
+ }
67
+
68
+ /**
69
+ * Best-effort client IP for the throttle buckets — the same header order the
70
+ * rate-limit middleware and the tracking routes use. `"unknown"` shares ONE
71
+ * bounded bucket rather than bypassing the budget.
72
+ */
73
+ export function accountLinkClientIp(c: Context<AppEnv>): string {
74
+ return (
75
+ c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ||
76
+ c.req.header("x-real-ip") ||
77
+ "unknown"
78
+ );
79
+ }
80
+
81
+ /**
82
+ * The cookie `/start` sets when it MINTS a cold anonymous key, so the browser
83
+ * carries the same key afterwards. Same name the browser SDK persists under
84
+ * (`packages/js/src/identity/identity-store.ts`), so a page that wants to adopt
85
+ * the key into the SDK reads one name.
86
+ *
87
+ * Deliberately NOT `HttpOnly`: an anonymous id is browser-readable BY DESIGN
88
+ * (`get_distinct_id()` returns it), which is exactly why a cold link may attach
89
+ * only to an anonymous-only contact (DECISIONS §6.10). Marking it HttpOnly
90
+ * would imply a secrecy the value does not have, and would stop the SDK
91
+ * adopting it, which is the whole point of setting it.
92
+ */
93
+ export const ANON_ID_COOKIE = "hs_anon_id";
94
+
95
+ /** One year, matching the SDK's own persistence horizon for the anon key. */
96
+ const ANON_ID_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
97
+
98
+ export function anonIdCookie(value: string, apiPublicUrl: string): string {
99
+ const secure = apiPublicUrl.startsWith("https://") ? "; Secure" : "";
100
+ // `SameSite=Lax` survives the top-level GET redirect back from the provider,
101
+ // which `Strict` would drop — the cookie would then be set and immediately
102
+ // invisible on the leg that needs it.
103
+ return (
104
+ `${ANON_ID_COOKIE}=${encodeURIComponent(value)}; Path=/; Max-Age=` +
105
+ `${ANON_ID_COOKIE_MAX_AGE}; SameSite=Lax${secure}`
106
+ );
107
+ }
@@ -0,0 +1,229 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
3
+ import type { AppEnv } from "../../app.js";
4
+ import { isAllowedReturnTo } from "../../lib/account-link-origins.js";
5
+ import {
6
+ generatePkcePair,
7
+ storePkceVerifier,
8
+ } from "../../lib/account-link-pkce.js";
9
+ import { checkAccountLinkThrottle } from "../../lib/account-link-throttle.js";
10
+ import {
11
+ signConnectorState,
12
+ verifyConnectorState,
13
+ } from "../../lib/connector-state.js";
14
+ import { getRedisIfConnected } from "../../lib/redis.js";
15
+ import {
16
+ accountLinkCallbackUrl,
17
+ accountLinkClientIp,
18
+ anonIdCookie,
19
+ } from "./shared.js";
20
+
21
+ /**
22
+ * `GET /v1/accounts/:provider/start` — the public entry point of the hosted
23
+ * flow. Unauthenticated BY CONSTRUCTION: it is a link a player clicks, in an
24
+ * email, a DM or a page, and it carries no `Authorization` header. Anything it
25
+ * trusts, it trusts because we SIGNED it.
26
+ *
27
+ * It resolves the binding (WARM: a sealed `contactId`; COLD: a browser
28
+ * anonymous key), mints the one-attempt state and PKCE material, and 302s to
29
+ * the provider's authorize URL. It writes nothing to the database — a link that
30
+ * is never completed leaves no trace, which is also why `account.link_started`
31
+ * was rejected (DECISIONS §8).
32
+ */
33
+ export function registerAccountLinkStartRoute(router: OpenAPIHono<AppEnv>) {
34
+ router.openapi(
35
+ createRoute({
36
+ method: "get",
37
+ path: "/{provider}/start",
38
+ tags: ["Account links"],
39
+ summary: "Begin a hosted account link",
40
+ request: {
41
+ params: z.object({ provider: z.string() }),
42
+ query: z.object({
43
+ /** A pre-sealed WARM state from `mintAccountLinkUrl` (DECISIONS §15.2). */
44
+ t: z.string().optional(),
45
+ /** COLD binding. Minted here when absent. */
46
+ anonymous_id: z.string().optional(),
47
+ return_to: z.string().optional(),
48
+ }),
49
+ },
50
+ responses: {
51
+ 302: { description: "Redirect to the provider's authorize URL" },
52
+ 400: { description: "Bad return_to / bad warm token" },
53
+ 404: { description: "Unknown provider" },
54
+ 429: { description: "Throttled" },
55
+ 500: { description: "Nonce collision" },
56
+ 503: { description: "Redis unavailable (fail closed)" },
57
+ },
58
+ }),
59
+ async (c) => {
60
+ const { provider: providerId } = c.req.valid("param");
61
+ const query = c.req.valid("query");
62
+ const container = c.get("container");
63
+ const { accountLinkProviders, accountLinkAllowedOrigins, env, logger } =
64
+ container;
65
+
66
+ // (1) The provider must be REGISTERED. An unconfigured provider is
67
+ // ABSENT, never present-but-disabled, so this is a plain 404.
68
+ const provider = accountLinkProviders.get(providerId);
69
+ if (!provider) return c.json({ error: "unknown_provider" }, 404);
70
+
71
+ // (2) Redis, FAIL-CLOSED (DECISIONS §6.8). PKCE custody and the callback's
72
+ // nonce burn both live in Redis, so serving this route without one would
73
+ // hand out states that cannot be safely completed.
74
+ if (!getRedisIfConnected()) {
75
+ logger.error(
76
+ "account link start refused: redis is not connected. The hosted " +
77
+ "flow fails closed because the state nonce burn and PKCE custody " +
78
+ "both live in redis. Set REDIS_URL",
79
+ { provider: providerId },
80
+ );
81
+ return c.json({ error: "unavailable" }, 503);
82
+ }
83
+
84
+ // (3) Throttle, per IP, BEFORE anything is minted.
85
+ const ip = accountLinkClientIp(c);
86
+ const ipBudget = await checkAccountLinkThrottle({ surface: "start", ip });
87
+ if (!ipBudget.ok) {
88
+ return ipBudget.reason === "rate_limited"
89
+ ? c.json({ error: "rate_limited" }, 429)
90
+ : c.json({ error: "unavailable" }, 503);
91
+ }
92
+
93
+ // (4) `return_to`, against the ONE allowlist. Never `*`.
94
+ let returnTo = query.return_to;
95
+ if (returnTo !== undefined) {
96
+ if (!isAllowedReturnTo(returnTo, accountLinkAllowedOrigins)) {
97
+ logger.warn("account link start: return_to not allowed", {
98
+ provider: providerId,
99
+ });
100
+ return c.json({ error: "return_to_not_allowed" }, 400);
101
+ }
102
+ }
103
+
104
+ // (5) The binding. WARM = a sealed `contactId` we minted; COLD = a
105
+ // browser anonymous key. A `?t=` that fails verification is a 400 and is
106
+ // NEVER silently downgraded to a cold link — a downgrade would turn a
107
+ // tampered warm token into an anonymous link that looks like it worked.
108
+ let contactId: string | undefined;
109
+ let anonymousId: string | undefined;
110
+ let mintedAnonymousId = false;
111
+
112
+ if (query.t !== undefined) {
113
+ const check = verifyConnectorState(query.t, env.BETTER_AUTH_SECRET);
114
+ const intent = check.valid ? check.intent : undefined;
115
+ if (
116
+ !intent ||
117
+ intent.purpose !== "account_link" ||
118
+ intent.providerId !== providerId ||
119
+ !intent.contactId
120
+ ) {
121
+ logger.warn("account link start: invalid warm token", {
122
+ provider: providerId,
123
+ reason: check.reason ?? "wrong_purpose_or_provider",
124
+ });
125
+ return c.json({ error: "invalid_token" }, 400);
126
+ }
127
+ contactId = intent.contactId;
128
+
129
+ // A `returnTo` that rode the warm token is re-checked, not trusted: the
130
+ // allowlist can have been edited since the mint, and our signature
131
+ // proves only that WE minted the value.
132
+ if (returnTo === undefined && intent.returnTo !== undefined) {
133
+ if (isAllowedReturnTo(intent.returnTo, accountLinkAllowedOrigins)) {
134
+ returnTo = intent.returnTo;
135
+ } else {
136
+ logger.warn(
137
+ "account link start: sealed return_to is no longer allowed — dropping it",
138
+ { provider: providerId },
139
+ );
140
+ }
141
+ }
142
+
143
+ // The WARM per-contact budget, now that the contact is known. A
144
+ // separate call on purpose: re-passing the IP would double-count it.
145
+ const contactBudget = await checkAccountLinkThrottle({
146
+ surface: "start",
147
+ contactId,
148
+ });
149
+ if (!contactBudget.ok) {
150
+ return contactBudget.reason === "rate_limited"
151
+ ? c.json({ error: "rate_limited" }, 429)
152
+ : c.json({ error: "unavailable" }, 503);
153
+ }
154
+ } else {
155
+ const supplied = query.anonymous_id?.trim();
156
+ if (supplied) {
157
+ anonymousId = supplied;
158
+ } else {
159
+ // NOT a 400. Steam yields no email, ever, and DECISIONS §7 forbids
160
+ // widening `IdentityKind` with a `steam` kind, so a browser anonymous
161
+ // key is the ONLY thing a cold Steam link can key its contact on —
162
+ // without this mint a cold link is keyless and cannot complete at
163
+ // all. Minting server-side also keeps the key out of an attacker's
164
+ // hands in the common (no-key) case. Same shape the browser SDK
165
+ // generates, and set as a cookie below so the browser carries it.
166
+ anonymousId = randomBytes(16).toString("base64url");
167
+ mintedAnonymousId = true;
168
+ }
169
+ }
170
+
171
+ // (6) The one-attempt nonce: the callback burns it, and PKCE custody is
172
+ // keyed by it.
173
+ const nonce = randomBytes(16).toString("base64url");
174
+
175
+ // (7) PKCE, only for providers that declare it. Steam is OpenID 2.0 and
176
+ // has no code to protect, so nothing is written for it — asserted by
177
+ // test, because a stray key here would be a silent Redis leak per link.
178
+ let codeChallenge: string | undefined;
179
+ if (provider.capabilities?.pkce) {
180
+ const pair = generatePkcePair();
181
+ const stored = await storePkceVerifier(
182
+ nonce,
183
+ pair.verifier,
184
+ env.ACCOUNT_LINK_STATE_TTL_SECONDS,
185
+ );
186
+ if (!stored) {
187
+ // `SET NX` refused: either a nonce collision (astronomically
188
+ // unlikely, and never silently overwritten) or Redis is gone. Both
189
+ // are refusals — a PKCE provider without a stored verifier can only
190
+ // complete an exchange that proves less than it claims to.
191
+ logger.error("account link start: could not take PKCE custody", {
192
+ provider: providerId,
193
+ });
194
+ return c.json({ error: "unavailable" }, 500);
195
+ }
196
+ codeChallenge = pair.challenge;
197
+ // The VERIFIER is deliberately not logged, not sealed into the state,
198
+ // and not put on the redirect. Only the challenge leaves this process.
199
+ }
200
+
201
+ // (8) Seal the attempt.
202
+ const state = signConnectorState(
203
+ {
204
+ purpose: "account_link",
205
+ providerId,
206
+ ...(contactId ? { contactId } : {}),
207
+ ...(anonymousId ? { anonymousId } : {}),
208
+ ...(returnTo ? { returnTo } : {}),
209
+ nonce,
210
+ },
211
+ env.BETTER_AUTH_SECRET,
212
+ env.ACCOUNT_LINK_STATE_TTL_SECONDS,
213
+ );
214
+
215
+ // (9) Off to the provider. `authorizeUrl` may be async (PRD 01 types it
216
+ // `string | Promise<string>`), so it is awaited.
217
+ const location = await provider.authorizeUrl({
218
+ state,
219
+ redirectUri: accountLinkCallbackUrl(env.API_PUBLIC_URL, providerId),
220
+ ...(codeChallenge ? { codeChallenge } : {}),
221
+ });
222
+
223
+ if (mintedAnonymousId && anonymousId) {
224
+ c.header("set-cookie", anonIdCookie(anonymousId, env.API_PUBLIC_URL));
225
+ }
226
+ return c.redirect(location, 302);
227
+ },
228
+ );
229
+ }
@@ -0,0 +1,98 @@
1
+ import type { Context } from "hono";
2
+ import type { AppEnv } from "../../app.js";
3
+ import {
4
+ type UnlinkAccountResult,
5
+ unlinkAccount,
6
+ } from "../../lib/account-links.js";
7
+ import { noteUnlinked } from "./emit.js";
8
+
9
+ /**
10
+ * ONE unlink, the way every `/v1/accounts/*` route must do it (PRD 09 T4/T8b).
11
+ *
12
+ * Three things are bundled here precisely because a second copy would drift on
13
+ * one of them:
14
+ *
15
+ * 1. The store call carries `hooks: container.accountLinkHooks`. The STORE is
16
+ * the sole invoker of the post-commit after-unlink hook (DECISIONS §15.4)
17
+ * — a route that also invoked it would fire every customer hook twice, and
18
+ * the hooks being documented at-least-once means nothing would fail
19
+ * loudly. The hook's NAME is deliberately not spelled out anywhere under
20
+ * `routes/accounts/`, so a grep for the identifier stays a reviewable
21
+ * invariant rather than a convention.
22
+ * 2. The provider's best-effort `revoke` wire is handed in, so a token grant
23
+ * is released at the platform when a link ends (DECISIONS §10). The store
24
+ * unseals the blob post-commit and never returns or logs it.
25
+ * 3. Exactly ONE `account.unlinked` is emitted, from the INTENT layer, off the
26
+ * facts the store returned inside its advisory-locked transaction, keyed
27
+ * `al:<provider>:<uid>:v<version>` (DECISIONS §5.5/§8). A `not_found` or a
28
+ * `not_owner` rejection emits NOTHING: nothing transitioned.
29
+ *
30
+ * `expectContactId` is the caller's business. It is REQUIRED on every
31
+ * player-facing revoke and evaluated INSIDE the pair lock, after the live-owner
32
+ * probe — the enumeration that found the rows happened outside the lock, and a
33
+ * hosted callback can relink the pair in between.
34
+ */
35
+ export async function unlinkFromRoute(
36
+ c: Context<AppEnv>,
37
+ opts: {
38
+ provider: string;
39
+ providerUserId: string;
40
+ reason: "player" | "api";
41
+ expectContactId?: string;
42
+ },
43
+ ): Promise<UnlinkAccountResult> {
44
+ const {
45
+ accountLinkHooks,
46
+ accountLinkProviders,
47
+ analytics,
48
+ db,
49
+ hatchet,
50
+ logger,
51
+ registry,
52
+ } = c.get("container");
53
+
54
+ const provider = accountLinkProviders.get(opts.provider);
55
+ const revoke = provider?.revoke?.bind(provider);
56
+
57
+ const result = await unlinkAccount({
58
+ db,
59
+ provider: opts.provider,
60
+ providerUserId: opts.providerUserId,
61
+ reason: opts.reason,
62
+ ...(opts.expectContactId ? { expectContactId: opts.expectContactId } : {}),
63
+ ...(revoke ? { revoke: (tokens) => revoke(tokens) } : {}),
64
+ hooks: accountLinkHooks,
65
+ logger,
66
+ });
67
+
68
+ if (result.status !== "unlinked") return result;
69
+
70
+ logger.info("account unlinked", {
71
+ provider: opts.provider,
72
+ reason: opts.reason,
73
+ version: result.version,
74
+ contactId: result.owner.contactId,
75
+ });
76
+
77
+ // `void … .catch` per `emitOutbound`'s contract: it never throws, and an
78
+ // emit must never fail a mutation the customer already committed.
79
+ void noteUnlinked(
80
+ {
81
+ providerId: opts.provider,
82
+ db,
83
+ hatchet,
84
+ logger,
85
+ registry,
86
+ ...(analytics ? { analytics } : {}),
87
+ },
88
+ {
89
+ provider: opts.provider,
90
+ providerUserId: opts.providerUserId,
91
+ version: result.version,
92
+ reason: opts.reason,
93
+ owner: result.owner,
94
+ },
95
+ ).catch(logger.warn);
96
+
97
+ return result;
98
+ }
@@ -369,6 +369,8 @@ agentRouter.post("/confirm", async (c) => {
369
369
  break;
370
370
  }
371
371
 
372
+ // NOT an `account.unlinked` emit point: `softDeleteContact` fans those
373
+ // out itself, post-commit, for every caller (PRD 08 T3).
372
374
  case "delete_contact":
373
375
  result = await softDeleteContact({
374
376
  db,
@@ -113,6 +113,13 @@ const createKeyRoute = createRoute({
113
113
  "full-admin",
114
114
  "ingest",
115
115
  "ingest-public",
116
+ // The account-link data plane (`/v1/accounts`, the reverse
117
+ // lookup + unlink, import, mint-link). ORTHOGONAL, like
118
+ // `ingest`: `hasScope` treats an unrecognised required
119
+ // scope as "explicit grant or full-admin", so this needs no
120
+ // SCOPE_HIERARCHY edit and no migration (`api_keys.scopes`
121
+ // is a jsonb string array).
122
+ "accounts",
116
123
  ]),
117
124
  )
118
125
  .min(1)
@@ -7,6 +7,8 @@ import {
7
7
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
8
8
  import { and, asc, count, desc, eq, isNull, not, sql } from "drizzle-orm";
9
9
  import type { AppEnv } from "../../app.js";
10
+ import { emitAccountUnlinked } from "../../lib/account-link-emit.js";
11
+ import { unlinkAccountsForContactInTx } from "../../lib/account-links.js";
10
12
  import {
11
13
  ALL_IDENTITY_KINDS,
12
14
  contactKeySql,
@@ -650,7 +652,7 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
650
652
  return c.json({ contact: serializeContact(updated) }, 200);
651
653
  })
652
654
  .openapi(deleteRoute, async (c) => {
653
- const { db } = c.get("container");
655
+ const { db, hatchet, logger } = c.get("container");
654
656
  const { id } = c.req.valid("param");
655
657
 
656
658
  const contact = await resolveContact({ db, id });
@@ -661,13 +663,47 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
661
663
  // Soft-delete + erasure hook in ONE transaction (PRD 02 T1): every
662
664
  // contact_aliases row keyed to the erased contact is that person's own
663
665
  // identity data, whatever `reason`/`from_contact_id` it carries.
664
- await db.transaction(async (tx) => {
666
+ //
667
+ // PRD 04 T5 (DECISIONS §15.3): this route is the ERASURE hook, so it also
668
+ // soft-unlinks every live account link at that pair's own next version
669
+ // (tokens hard-deleted) AND, via `erase: true`, nulls the personal display
670
+ // fields (verified_email/username/avatar_url) on every historical row —
671
+ // the version sequence survives erasure; the personal data does not. The
672
+ // transaction RETURNS the unlink facts; PRD 08 binds them and emits one
673
+ // `account.unlinked` per fact post-commit so mirrors converge.
674
+ const linkUnlinks = await db.transaction(async (tx) => {
675
+ const facts = await unlinkAccountsForContactInTx(tx, contact.id, {
676
+ reason: "api",
677
+ erase: true,
678
+ });
665
679
  await tx
666
680
  .update(contacts)
667
681
  .set({ deletedAt: new Date(), updatedAt: new Date() })
668
682
  .where(eq(contacts.id, contact.id));
669
683
  await deleteIdentityAliasesForContact(tx, contact.id);
684
+ return facts;
670
685
  });
671
686
 
687
+ // PRD 08 T3 — one `account.unlinked` per soft-unlinked row, `reason:
688
+ // "api"`, STRICTLY after the transaction resolved (a rolled-back erasure
689
+ // never reaches this line). This route runs its own transaction rather
690
+ // than going through `softDeleteContact`, so it owns this emit itself; the
691
+ // shared fan-out keeps the payload and dedupe key identical to the other
692
+ // legs.
693
+ //
694
+ // The CONTAINER's handles, like every other emit in this file: a
695
+ // deployment using `overrides.hatchet` must not have this one emit slip
696
+ // past onto the module singleton's live gRPC dial while `contact.updated`
697
+ // from the sibling route goes to the override.
698
+ emitAccountUnlinked(db, linkUnlinks, { hatchet, logger });
699
+
700
+ // NO journey-plane re-ingest here, deliberately (PRD 08 T5), for the same
701
+ // two reasons `softDeleteContact` states at its own emit: this route IS
702
+ // the erasure hook, so writing a fresh `user_events` row for the contact
703
+ // it just erased contradicts the erasure — and the only keys available are
704
+ // a pin at a soft-deleted row (dropped as provenance-lost) or a value key
705
+ // that would MINT the erased contact straight back. The customer's mirror
706
+ // still converges via the emit above.
707
+
672
708
  return c.json({ deleted: true }, 200);
673
709
  });
@@ -114,6 +114,23 @@ export function registerConnectorRoutes(app: OpenAPIHono<AppEnv>) {
114
114
  });
115
115
  return c.json({ error: "Invalid state" }, 400);
116
116
  }
117
+ // Bind the state to THIS SURFACE. One secret signs every state in the
118
+ // process, so an `account_link` state (PRD 07's hosted flow) is
119
+ // signature-valid here too. The `connectorId` check below rejects it
120
+ // incidentally — an account-link state carries none, and
121
+ // `undefined !== id` — but incidental is not a statement of the rule,
122
+ // and `plugin-discord`'s exhaustive `else` is a plugin's defence that a
123
+ // new plugin can drop. State the allowlist here, at the dispatcher.
124
+ if (
125
+ stateCheck.intent.purpose !== "install" &&
126
+ stateCheck.intent.purpose !== "member_link"
127
+ ) {
128
+ logger.warn("connector oauth callback: unsupported state purpose", {
129
+ connectorId: id,
130
+ purpose: stateCheck.intent.purpose,
131
+ });
132
+ return c.json({ error: "Invalid state" }, 400);
133
+ }
117
134
  // Bind the state to THIS connector: `BETTER_AUTH_SECRET` signs every
118
135
  // connector's state, so a state minted for connector A is
119
136
  // signature-valid here too. Reject a state whose `connectorId` does not
@@ -287,6 +287,14 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
287
287
  return c.json({ error: "Contact not found" }, 404);
288
288
  }
289
289
 
290
+ // NOT an `account.unlinked` emit point, though `result.linkUnlinks` is
291
+ // right there: `softDeleteContact` already fanned those out post-commit
292
+ // (PRD 08 T3), once for all three of its callers. Emitting again here
293
+ // would be silently swallowed by the `(endpointId, dedupeKey)` index, so
294
+ // the duplicate would cost a build cycle and hide which layer owns the
295
+ // fact rather than failing a test. The field stays on the result as the
296
+ // route's reporting channel.
297
+ //
290
298
  // The widened `softDeleteContact` returns the deleted row's identity so the
291
299
  // `contact.deleted` outbound webhook carries it without a second read-back.
292
300
  if (result.id) {