@hogsend/engine 0.63.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 (92) hide show
  1. package/package.json +13 -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 +60 -0
  16. package/src/index.ts +104 -1
  17. package/src/journeys/journey-boundary.ts +8 -0
  18. package/src/lib/account-link-emit.ts +126 -0
  19. package/src/lib/account-link-events.ts +180 -0
  20. package/src/lib/account-link-hooks.test.ts +158 -0
  21. package/src/lib/account-link-hooks.ts +73 -0
  22. package/src/lib/account-link-ingest.ts +364 -0
  23. package/src/lib/account-link-nonce.test.ts +52 -0
  24. package/src/lib/account-link-nonce.ts +57 -0
  25. package/src/lib/account-link-origins.test.ts +72 -0
  26. package/src/lib/account-link-origins.ts +87 -0
  27. package/src/lib/account-link-pkce.test.ts +91 -0
  28. package/src/lib/account-link-pkce.ts +106 -0
  29. package/src/lib/account-link-provider-registry.test.ts +52 -0
  30. package/src/lib/account-link-provider-registry.ts +61 -0
  31. package/src/lib/account-link-throttle.test.ts +178 -0
  32. package/src/lib/account-link-throttle.ts +130 -0
  33. package/src/lib/account-link-url.ts +85 -0
  34. package/src/lib/account-links-emit.test.ts +525 -0
  35. package/src/lib/account-links-env.test.ts +40 -0
  36. package/src/lib/account-links-from-env.test.ts +187 -0
  37. package/src/lib/account-links-from-env.ts +126 -0
  38. package/src/lib/account-links.ts +1300 -0
  39. package/src/lib/app-secret.ts +34 -0
  40. package/src/lib/attachments.ts +81 -0
  41. package/src/lib/connector-actions.test.ts +13 -4
  42. package/src/lib/connector-state.account-link.test.ts +114 -0
  43. package/src/lib/connector-state.ts +48 -3
  44. package/src/lib/contacts.ts +320 -6
  45. package/src/lib/domain-status.return-path.test.ts +68 -0
  46. package/src/lib/domain-status.ts +19 -0
  47. package/src/lib/email-provider-boot.hogsend.test.ts +48 -0
  48. package/src/lib/email-provider-boot.test.ts +33 -0
  49. package/src/lib/email-providers-from-env.hogsend.test.ts +110 -0
  50. package/src/lib/email-providers-from-env.test.ts +52 -0
  51. package/src/lib/email-providers-from-env.ts +67 -0
  52. package/src/lib/email-service-types.ts +11 -0
  53. package/src/lib/email.ts +17 -0
  54. package/src/lib/mailer-bounce-idempotency.test.ts +469 -0
  55. package/src/lib/mailer-rejected.test.ts +229 -0
  56. package/src/lib/mailer-replied.test.ts +379 -0
  57. package/src/lib/mailer.ts +359 -24
  58. package/src/lib/outbound-account-payloads.test.ts +137 -0
  59. package/src/lib/outbound.ts +126 -0
  60. package/src/lib/provider-credentials.ts +19 -5
  61. package/src/lib/sending-domain-guidance.test.ts +99 -0
  62. package/src/lib/sending-domain-guidance.ts +84 -0
  63. package/src/lib/tracked-attachments.test.ts +376 -0
  64. package/src/lib/tracked-idempotency-header.test.ts +437 -0
  65. package/src/lib/tracked.ts +116 -4
  66. package/src/lib/tracking-event-names.ts +9 -0
  67. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  68. package/src/lib/webhook-signing.ts +25 -1
  69. package/src/routes/accounts/callback.ts +597 -0
  70. package/src/routes/accounts/emit.ts +231 -0
  71. package/src/routes/accounts/import-links.ts +210 -0
  72. package/src/routes/accounts/index.ts +75 -0
  73. package/src/routes/accounts/lookup.ts +177 -0
  74. package/src/routes/accounts/me.ts +215 -0
  75. package/src/routes/accounts/mint.ts +279 -0
  76. package/src/routes/accounts/pages.ts +62 -0
  77. package/src/routes/accounts/resolve.ts +61 -0
  78. package/src/routes/accounts/serialize.ts +96 -0
  79. package/src/routes/accounts/shared.ts +107 -0
  80. package/src/routes/accounts/start.ts +229 -0
  81. package/src/routes/accounts/unlink.ts +98 -0
  82. package/src/routes/admin/agent.ts +2 -0
  83. package/src/routes/admin/api-keys.ts +7 -0
  84. package/src/routes/admin/contacts.ts +38 -2
  85. package/src/routes/admin/domain-conflict.test.ts +188 -0
  86. package/src/routes/admin/domain-return-path.test.ts +274 -0
  87. package/src/routes/admin/domain.ts +214 -1
  88. package/src/routes/connectors/index.ts +17 -0
  89. package/src/routes/contacts/index.ts +8 -0
  90. package/src/routes/index.ts +75 -0
  91. package/src/testing-barrel.test.ts +74 -0
  92. package/src/testing.ts +17 -0
@@ -0,0 +1,231 @@
1
+ import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
+ import type { AnalyticsProvider } from "@hogsend/core";
3
+ import type { JourneyRegistry } from "@hogsend/core/registry";
4
+ import type { Database } from "@hogsend/db";
5
+ import {
6
+ type AccountUnlinkedFacts,
7
+ buildAccountLinkedPayload,
8
+ buildAccountUnlinkedPayload,
9
+ buildDedupeKey,
10
+ } from "../../lib/account-link-events.js";
11
+ import {
12
+ ingestAccountLinked,
13
+ ingestAccountUnlinked,
14
+ } from "../../lib/account-link-ingest.js";
15
+ import type { LinkAccountResult } from "../../lib/account-links.js";
16
+ import type { Logger } from "../../lib/logger.js";
17
+ import { emitOutbound } from "../../lib/outbound.js";
18
+
19
+ /**
20
+ * THE `/v1/accounts/*` EMIT SITES, in one module.
21
+ *
22
+ * DECISIONS §8/§15.7: the STORE returns facts and never emits; the INTENT
23
+ * layer (these routes) emits. Two intent layers now produce link endings — the
24
+ * hosted callback and the data plane's two revokes plus the import — and the
25
+ * shape has to be identical at all of them, so it lives here rather than being
26
+ * re-derived per route. A drifted key or a payload built from the wrong pair is
27
+ * invisible in production: `emitOutbound` de-dupes on
28
+ * `(endpointId, dedupeKey)` with `onConflictDoNothing`, so a wrong key silently
29
+ * stops de-duping and a colliding one silently swallows a real fact.
30
+ */
31
+
32
+ /**
33
+ * Everything an emit needs from the request.
34
+ *
35
+ * `hatchet` is carried ONLY to satisfy `emitOutbound`'s signature, and saying
36
+ * anything stronger would be false: `emitOutbound` destructures
37
+ * `const { db, logger, event, payload, dedupeKey } = opts` and never reads
38
+ * `opts.hatchet`; the enqueue runs through the MODULE-LEVEL
39
+ * `deliverWebhookTask` built from the `lib/hatchet.ts` singleton at import
40
+ * time.
41
+ */
42
+ export interface AccountLinkEmitContext {
43
+ providerId: string;
44
+ db: Database;
45
+ hatchet: HatchetClient;
46
+ logger: Logger;
47
+ /**
48
+ * The JOURNEY plane's handles (PRD 08 T5) — the container's, so a test or a
49
+ * consumer that swapped either one is honored instead of the process
50
+ * singleton silently winning. Both optional: `lib/account-link-ingest.ts`
51
+ * falls back to the singletons `createHogsendClient` installs at boot, which
52
+ * is what keeps the container-free `lib/contacts.ts` call site a two-arg
53
+ * call.
54
+ */
55
+ registry?: JourneyRegistry;
56
+ analytics?: AnalyticsProvider;
57
+ }
58
+
59
+ /**
60
+ * THE `account.linked` SITE, emitting off the facts the store returned.
61
+ *
62
+ * One mutation can END up to two links, and every ending is emitted BEFORE the
63
+ * `account.linked` that caused it. The ORDER IS LOAD-BEARING for the `previous`
64
+ * leg: `account.unlinked` for the displaced owner at the LOWER version (N+1)
65
+ * FIRST, then `account.linked` at the higher one (N+2). A consumer's guard is
66
+ * `incoming.version > stored.version`, so if the two deliveries arrive out of
67
+ * order the late unlink at N+1 is DISCARDED against a stored N+2 — rather than
68
+ * winning and permanently recording the wrong owner.
69
+ *
70
+ * The emits are therefore CHAINED, not fired side by side: independent
71
+ * `void emitOutbound(...)` calls race their own INSERTs, which is no ordering
72
+ * at all. Chaining keeps the handler non-blocking (nothing is awaited here)
73
+ * while making each unlink's delivery row — and its enqueue — strictly first.
74
+ *
75
+ * The two endings, which are NOT the same thing:
76
+ *
77
+ * - `previous` — the SAME platform account changing hands (a hosted callback
78
+ * only; every other caller passes `allowDisplaceLiveOwner: false`). Its
79
+ * unlink shares this pair's version sequence, which is why order matters.
80
+ * - `replacedSingleton` — this contact's OTHER pair on a `multiple: false`
81
+ * provider, soft-unlinked to make room. It is a DIFFERENT pair with its OWN
82
+ * version sequence, so its dedupe key is built from `r.provider` /
83
+ * `r.providerUserId`, never from `result.row`'s. A key built from the NEW
84
+ * pair would collide with the `account.linked` emit and be silently
85
+ * swallowed by `onConflictDoNothing`. **It is returned on the `linked` arm
86
+ * too, not only `relinked`** — which is exactly why this fan-out is shared
87
+ * rather than re-written per call site.
88
+ */
89
+ export function noteLinked(
90
+ ctx: AccountLinkEmitContext,
91
+ result: Extract<LinkAccountResult, { status: "linked" | "relinked" }>,
92
+ opts: { journeyPlane?: boolean } = {},
93
+ ): void {
94
+ ctx.logger.info("account linked", {
95
+ provider: ctx.providerId,
96
+ status: result.status,
97
+ version: result.version,
98
+ contactId: result.owner.contactId,
99
+ });
100
+
101
+ const { provider, providerUserId } = result.row;
102
+ const linked = () =>
103
+ emitOutbound({
104
+ db: ctx.db,
105
+ hatchet: ctx.hatchet,
106
+ logger: ctx.logger,
107
+ event: "account.linked",
108
+ payload: buildAccountLinkedPayload(result),
109
+ dedupeKey: buildDedupeKey(provider, providerUserId, result.version),
110
+ });
111
+
112
+ // Every ending this mutation produced, each with ITS OWN pair, version and
113
+ // owner — all read by the store inside the pair-locked transaction and never
114
+ // re-read here.
115
+ const ended: AccountUnlinkedFacts[] = [];
116
+ if (result.replacedSingleton) {
117
+ const r = result.replacedSingleton;
118
+ ended.push({
119
+ provider: r.provider,
120
+ providerUserId: r.providerUserId,
121
+ version: r.version,
122
+ reason: "relinked",
123
+ owner: r.owner,
124
+ });
125
+ }
126
+ if (result.status === "relinked") {
127
+ ended.push({
128
+ provider,
129
+ providerUserId,
130
+ version: result.previous.version,
131
+ reason: "relinked",
132
+ owner: result.previous.owner,
133
+ });
134
+ }
135
+
136
+ // THE JOURNEY PLANE, beside the outbound one. TWO DIFFERENT PLANES; neither
137
+ // may be collapsed into the other, and the ingest path must never emit
138
+ // (DECISIONS §8) — see the header of `lib/account-link-ingest.ts`.
139
+ //
140
+ // `journeyPlane: false` is the BULK opt-out: a backfill is a statement about
141
+ // the PAST, so `POST /v1/accounts/import` defaults it off. It suppresses only
142
+ // this plane — the outbound emits still fire, because the customer's mirror
143
+ // must converge whether or not a journey ran.
144
+ const ingestLinked = () => {
145
+ if (opts.journeyPlane === false) return;
146
+ ingestAccountLinked(ctx.db, result, {
147
+ hatchet: ctx.hatchet,
148
+ logger: ctx.logger,
149
+ ...(ctx.registry ? { registry: ctx.registry } : {}),
150
+ ...(ctx.analytics ? { analytics: ctx.analytics } : {}),
151
+ });
152
+ };
153
+
154
+ if (ended.length === 0) {
155
+ ingestLinked();
156
+ void linked().catch(ctx.logger.warn);
157
+ return;
158
+ }
159
+
160
+ // ORDERED, on BOTH planes, for the reason the docstring above gives: every
161
+ // ending is announced before the link that caused it. `noteUnlinked` ingests
162
+ // its own fact as the chain reaches it, and the link's ingest hangs off the
163
+ // same `.then` as the outbound `linked()` — so the journey plane cannot
164
+ // invert an order the outbound plane calls load-bearing. Ingesting the link
165
+ // eagerly (before `ended` was even walked) is exactly what did invert it: on
166
+ // a `replacedSingleton` both facts belong to the SAME contact, so a journey
167
+ // with `trigger: account.linked` and `exitOn: account.unlinked` enrolled on
168
+ // the new link and was then exited by the displacement it replaced.
169
+ void ended
170
+ .reduce<Promise<void>>(
171
+ (chain, facts) => chain.then(() => noteUnlinked(ctx, facts, opts)),
172
+ Promise.resolve(),
173
+ )
174
+ .then(() => {
175
+ ingestLinked();
176
+ return linked();
177
+ })
178
+ .catch(ctx.logger.warn);
179
+ }
180
+
181
+ /**
182
+ * One `account.unlinked`, keyed off the facts' OWN pair.
183
+ *
184
+ * The key is derived HERE rather than at the call site so the pair in the
185
+ * payload and the pair in the dedupe key cannot be different pairs — the exact
186
+ * mistake that would make a `replacedSingleton` emit collide with the
187
+ * `account.linked` it accompanies.
188
+ *
189
+ * Returns the promise (rather than firing and forgetting) so `noteLinked` can
190
+ * CHAIN the ordering; the fire-and-forget `void … .catch` belongs to the
191
+ * caller, exactly as `emitOutbound`'s own contract asks.
192
+ */
193
+ export function noteUnlinked(
194
+ ctx: AccountLinkEmitContext,
195
+ facts: AccountUnlinkedFacts,
196
+ opts: { journeyPlane?: boolean } = {},
197
+ ): Promise<void> {
198
+ // THE JOURNEY PLANE, beside the outbound one — see `noteLinked` above and
199
+ // the header of `lib/account-link-ingest.ts`. TWO DIFFERENT PLANES; neither
200
+ // may be collapsed into the other. Deliberately NOT part of the returned
201
+ // promise: `noteLinked` chains on that promise to order the outbound
202
+ // deliveries, and a re-ingest that rejected would then swallow the
203
+ // `account.linked` emit behind it.
204
+ //
205
+ // `journeyPlane: false` is the same BULK opt-out `noteLinked` carries, and
206
+ // it must exist on BOTH: one call can produce a link AND up to two unlinks,
207
+ // so gating only the link half would let a suppressed 1000-row backfill
208
+ // still fire 2000 unlink enrolments the moment the import is allowed to
209
+ // displace. The outbound emit below is unaffected either way.
210
+ if (opts.journeyPlane !== false) {
211
+ ingestAccountUnlinked(ctx.db, facts, {
212
+ hatchet: ctx.hatchet,
213
+ logger: ctx.logger,
214
+ ...(ctx.registry ? { registry: ctx.registry } : {}),
215
+ ...(ctx.analytics ? { analytics: ctx.analytics } : {}),
216
+ });
217
+ }
218
+
219
+ return emitOutbound({
220
+ db: ctx.db,
221
+ hatchet: ctx.hatchet,
222
+ logger: ctx.logger,
223
+ event: "account.unlinked",
224
+ payload: buildAccountUnlinkedPayload(facts),
225
+ dedupeKey: buildDedupeKey(
226
+ facts.provider,
227
+ facts.providerUserId,
228
+ facts.version,
229
+ ),
230
+ });
231
+ }
@@ -0,0 +1,210 @@
1
+ import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
2
+ import type { AppEnv } from "../../app.js";
3
+ import { linkAccount } from "../../lib/account-links.js";
4
+ import { noteLinked } from "./emit.js";
5
+ import { resolveAccountsContactId } from "./resolve.js";
6
+
7
+ /**
8
+ * `POST /v1/accounts/import` — THE ONE CARVE-OUT, AND IT IS INSERT-ONLY
9
+ * (DECISIONS §6.2).
10
+ *
11
+ * A customer arriving with years of existing Steam/Twitch links needs them in
12
+ * the store without asking every player to re-authorize. That is the whole
13
+ * scope of this route. It may NOT move a link: **only a completed hosted
14
+ * callback may displace a live owner** (DECISIONS §6.1), because only the
15
+ * callback carries proof of control of the platform account.
16
+ *
17
+ * The insert-only property is STRUCTURAL, not a policy this route enforces in
18
+ * application code: it passes `allowDisplaceLiveOwner: false`, and the store
19
+ * refuses inside its advisory-locked transaction, one statement after the
20
+ * live-owner probe. There is deliberately no read-then-write here — a check in
21
+ * this file would leave a window in which a concurrent hosted callback slips a
22
+ * live owner in between the check and the write.
23
+ *
24
+ * `onConflict` is pinned to `"reject"` and NEVER read from the provider
25
+ * definition. `replace` is a MOVE, and a `multiple: false` provider configured
26
+ * with it must not become an import-time takeover primitive: the same request
27
+ * that is refused for `steam` must be refused for a provider whose author
28
+ * happened to write `onConflict: "replace"`.
29
+ */
30
+
31
+ const conflictSchema = z.object({
32
+ provider: z.string(),
33
+ providerUserId: z.string(),
34
+ reason: z.enum(["already_linked", "singleton_conflict", "unknown_contact"]),
35
+ /** Present on `already_linked`: who holds the pair right now. */
36
+ ownerContactId: z.string().optional(),
37
+ });
38
+
39
+ const importRoute = createRoute({
40
+ method: "post",
41
+ path: "/import",
42
+ tags: ["Accounts"],
43
+ summary: "Import existing links (insert-only)",
44
+ description:
45
+ 'SECRET API KEY + `accounts` scope. Inserts links a customer already had, stamped `method: "import"`, preserving `linkedAt` when supplied. INSERT-ONLY: a pair that already has a live owner is reported under `conflicts` with the existing row left completely untouched — same contact, same version, same `linkedAt` — because only a completed hosted callback may move a link. Partial success: every non-conflicting row is applied and both counts are returned. Max 1000 rows. Journeys are NOT enrolled unless `enrollJourneys: true` — a backfill would otherwise run an `account.linked` journey once per row; the outbound webhook fires either way.',
46
+ request: {
47
+ body: {
48
+ content: {
49
+ "application/json": {
50
+ schema: z.object({
51
+ rows: z
52
+ .array(
53
+ z
54
+ .object({
55
+ provider: z.string().min(1),
56
+ providerUserId: z.string().min(1),
57
+ contactId: z.string().optional(),
58
+ email: z.string().optional(),
59
+ username: z.string().optional(),
60
+ avatarUrl: z.string().optional(),
61
+ /** ISO; preserves the customer's historical timestamp. */
62
+ linkedAt: z.string().datetime().optional(),
63
+ })
64
+ .refine((r) => Boolean(r.contactId) !== Boolean(r.email), {
65
+ message: "exactly one of contactId | email is required",
66
+ }),
67
+ )
68
+ .max(1000),
69
+ /**
70
+ * Enroll journeys for the imported links. DEFAULT FALSE, because a
71
+ * backfill is a statement about the PAST: leaving it on would run
72
+ * an `account.linked` journey once per row, so importing a
73
+ * publisher's existing Steam history would send its welcome email
74
+ * to the entire back catalogue. The outbound `account.linked`
75
+ * webhook fires either way — the customer's mirror must converge
76
+ * regardless of whether a journey ran.
77
+ */
78
+ enrollJourneys: z.boolean().optional().default(false),
79
+ }),
80
+ },
81
+ },
82
+ },
83
+ },
84
+ responses: {
85
+ 200: {
86
+ content: {
87
+ "application/json": {
88
+ schema: z.object({
89
+ inserted: z.number(),
90
+ conflicts: z.array(conflictSchema),
91
+ }),
92
+ },
93
+ },
94
+ description:
95
+ "Both counts — a conflicting batch still applies its clean rows",
96
+ },
97
+ },
98
+ });
99
+
100
+ export function registerAccountsImportRoute(router: OpenAPIHono<AppEnv>) {
101
+ router.openapi(importRoute, async (c) => {
102
+ const {
103
+ accountLinkHooks,
104
+ accountLinkProviders,
105
+ analytics,
106
+ db,
107
+ hatchet,
108
+ logger,
109
+ registry,
110
+ } = c.get("container");
111
+ const { rows, enrollJourneys } = c.req.valid("json");
112
+
113
+ let inserted = 0;
114
+ const conflicts: z.infer<typeof conflictSchema>[] = [];
115
+
116
+ for (const row of rows) {
117
+ const contactId = await resolveAccountsContactId(db, {
118
+ contactId: row.contactId,
119
+ email: row.email,
120
+ });
121
+ if (!contactId) {
122
+ // A referenced contact that does not exist is a CONFLICT, never a
123
+ // minted contact: an import row is a claim about a person the customer
124
+ // says they already have, and inventing one would be the ghost-contact
125
+ // case in its purest form.
126
+ conflicts.push({
127
+ provider: row.provider,
128
+ providerUserId: row.providerUserId,
129
+ reason: "unknown_contact",
130
+ });
131
+ continue;
132
+ }
133
+
134
+ // `multiple` comes from the provider definition when it is registered,
135
+ // and falls back to the contract default (`true`) when it is not — a
136
+ // customer may legitimately import history for a provider this deploy no
137
+ // longer has configured.
138
+ const provider = accountLinkProviders.get(row.provider);
139
+
140
+ const result = await linkAccount({
141
+ db,
142
+ provider: row.provider,
143
+ identity: {
144
+ providerUserId: row.providerUserId,
145
+ ...(row.username ? { username: row.username } : {}),
146
+ ...(row.avatarUrl ? { avatarUrl: row.avatarUrl } : {}),
147
+ },
148
+ contactId,
149
+ method: "import",
150
+ multiple: provider?.multiple ?? true,
151
+ // PINNED. See the module docstring: `replace` is a move.
152
+ onConflict: "reject",
153
+ // An import carries no proven grant, so there is nothing to seal.
154
+ storeTokens: false,
155
+ allowDisplaceLiveOwner: false,
156
+ ...(row.linkedAt ? { linkedAt: new Date(row.linkedAt) } : {}),
157
+ // The STORE invokes the post-commit after-link hook (DECISIONS
158
+ // §15.4); this route invokes nothing itself.
159
+ hooks: accountLinkHooks,
160
+ logger,
161
+ });
162
+
163
+ if (result.status === "rejected") {
164
+ conflicts.push({
165
+ provider: row.provider,
166
+ providerUserId: row.providerUserId,
167
+ reason:
168
+ result.reason === "singleton_conflict"
169
+ ? "singleton_conflict"
170
+ : "already_linked",
171
+ ...(result.currentOwnerContactId
172
+ ? { ownerContactId: result.currentOwnerContactId }
173
+ : {}),
174
+ });
175
+ continue;
176
+ }
177
+
178
+ if (result.status === "unchanged") {
179
+ // The pair is ALREADY owned by this very contact. A conflict-free
180
+ // no-op: nothing transitioned, no version was allocated, so it is
181
+ // neither an insert nor a conflict and nothing is emitted.
182
+ continue;
183
+ }
184
+
185
+ inserted++;
186
+ // `noteLinked` is the shared fan-out, so an import announces a link the
187
+ // same way the hosted callback does — including any `replacedSingleton`
188
+ // ending, which the `linked` arm can carry too. (This route cannot
189
+ // produce one today, since `onConflict` is pinned to `"reject"`; sharing
190
+ // the fan-out is what keeps that true if it ever changes.)
191
+ noteLinked(
192
+ {
193
+ providerId: row.provider,
194
+ db,
195
+ hatchet,
196
+ logger,
197
+ registry,
198
+ ...(analytics ? { analytics } : {}),
199
+ },
200
+ result,
201
+ // Off by default: a bulk backfill must not run a welcome journey once
202
+ // per imported row. The outbound emit inside `noteLinked` is
203
+ // unaffected.
204
+ { journeyPlane: enrollJourneys },
205
+ );
206
+ }
207
+
208
+ return c.json({ inserted, conflicts }, 200);
209
+ });
210
+ }
@@ -0,0 +1,75 @@
1
+ import { OpenAPIHono } from "@hono/zod-openapi";
2
+ import type { AppEnv } from "../../app.js";
3
+ import { registerAccountLinkCallbackRoute } from "./callback.js";
4
+ import { registerAccountsImportRoute } from "./import-links.js";
5
+ import {
6
+ registerAccountsListRoute,
7
+ registerAccountsLookupRoute,
8
+ registerAccountsUnlinkRoute,
9
+ } from "./lookup.js";
10
+ import {
11
+ registerAccountsMeRevokeRoute,
12
+ registerAccountsMeRoute,
13
+ } from "./me.js";
14
+ import {
15
+ registerAccountsLinkUrlRoute,
16
+ registerAccountsMintLinkRoute,
17
+ } from "./mint.js";
18
+ import { registerAccountLinkStartRoute } from "./start.js";
19
+
20
+ /**
21
+ * The `/v1/accounts/*` router: PRD 07's two PUBLIC hosted-flow routes and PRD
22
+ * 09's api-key data plane, in ONE router.
23
+ *
24
+ * **`/start` and `/callback` are unauthenticated BY CONSTRUCTION** — they are
25
+ * browser redirect targets and carry no `Authorization` header — and mounting
26
+ * them here does NOT put them outside the api-key data plane. Hono runs EVERY
27
+ * matching `use`, and `app.route("/v1", v1)` flattens the middleware into one
28
+ * router, so a guard registered on the two-segment param pattern
29
+ * `/accounts/:provider/:providerUserId` ALSO matches `/accounts/steam/start`
30
+ * and `/accounts/steam/callback`. As originally specified that made the entire
31
+ * hosted OAuth flow dead: 401 with no key, or 403 with a `pk_` one.
32
+ *
33
+ * DECISIONS §15.1 settles it — `routes/index.ts` registers ONE guard on that
34
+ * pattern that BRANCHES INTERNALLY, mirroring the method-branching `/contacts`
35
+ * guard. Moving these routes to a different mount point does not dodge it and
36
+ * must not be attempted. The tests that pin this assert NEITHER 401 NOR 403,
37
+ * not merely "not 401": a blanket guard 403s (from the scope check) rather than
38
+ * 401s, so a "not 401" assertion would ship the broken route green.
39
+ *
40
+ * ## Registration order is LITERALS FIRST, and it is load-bearing
41
+ *
42
+ * `/{provider}/{providerUserId}` matches `/steam/callback` (with
43
+ * `providerUserId = "callback"`) and `/me/revoke` (with `provider = "me"`), so
44
+ * a later registration would be captured by the earlier one — the hosted
45
+ * callback would 404, or worse be answered by the reverse lookup as an unknown
46
+ * pair, and the primary player revoke would never run. Every id that could
47
+ * collide (`me`, `import`, `link-url`, `manage`, `start`, `callback`) is in
48
+ * `RESERVED_ACCOUNT_LINK_IDS`, so no real provider can reach these branches by
49
+ * accident.
50
+ *
51
+ * The router itself re-applies NO auth — the prefix guards in
52
+ * `routes/index.ts` own that, exactly as `routes/groups/index.ts:250-255`
53
+ * documents for `/v1/groups`.
54
+ */
55
+ export function createAccountsRouter(): OpenAPIHono<AppEnv> {
56
+ const router = new OpenAPIHono<AppEnv>();
57
+
58
+ // (1) Literals, browser tier first.
59
+ registerAccountsMeRoute(router);
60
+ registerAccountsMeRevokeRoute(router);
61
+ registerAccountsLinkUrlRoute(router);
62
+ // (2) Literals, operator tier.
63
+ registerAccountsImportRoute(router);
64
+ registerAccountsMintLinkRoute(router);
65
+ // (3) The bare collection.
66
+ registerAccountsListRoute(router);
67
+ // (4) PRD 07's hosted flow — BEFORE the two-segment param pattern.
68
+ registerAccountLinkStartRoute(router);
69
+ registerAccountLinkCallbackRoute(router);
70
+ // (5) The parameterised operator routes, last.
71
+ registerAccountsLookupRoute(router);
72
+ registerAccountsUnlinkRoute(router);
73
+
74
+ return router;
75
+ }
@@ -0,0 +1,177 @@
1
+ import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
2
+ import type { AppEnv } from "../../app.js";
3
+ import { getLiveLink, listLiveLinks } from "../../lib/account-links.js";
4
+ import { errorSchema } from "../../lib/schemas.js";
5
+ import { resolveAccountsContactId } from "./resolve.js";
6
+ import { linkedAccountSchema, serializeLinkedAccount } from "./serialize.js";
7
+ import { unlinkFromRoute } from "./unlink.js";
8
+
9
+ /**
10
+ * The OPERATOR pull plane (PRD 09 T3/T4) — `GET /v1/accounts`,
11
+ * `GET /v1/accounts/{provider}/{providerUserId}` and the `DELETE` beside it.
12
+ *
13
+ * SECRET KEY ONLY, guarded in `routes/index.ts` (this router re-applies no auth
14
+ * of its own, exactly like `routes/groups/index.ts:250-255`). The reads are
15
+ * strongly consistent and always the live row: this plane is what a customer
16
+ * reconciles against, so it never serves a mirror (DECISIONS §3.2).
17
+ *
18
+ * Every read goes through the store's helpers; this module writes no SQL.
19
+ */
20
+
21
+ const LIMIT_DEFAULT = 50;
22
+ const LIMIT_MAX = 200;
23
+
24
+ const listRoute = createRoute({
25
+ method: "get",
26
+ path: "/",
27
+ tags: ["Accounts"],
28
+ summary: "List linked accounts",
29
+ description:
30
+ "SECRET API KEY + `accounts` scope. Live links only, newest first. Filter by `contactId`, `email` (the contact is resolved first) or `provider`; at least one is required. Paginate with `limit` (default 50, max 200) and `offset`. Never returns the sealed token blob.",
31
+ request: {
32
+ query: z.object({
33
+ contactId: z.string().optional(),
34
+ email: z.string().optional(),
35
+ provider: z.string().optional(),
36
+ limit: z.coerce.number().min(1).max(LIMIT_MAX).optional(),
37
+ offset: z.coerce.number().min(0).optional(),
38
+ }),
39
+ },
40
+ responses: {
41
+ 200: {
42
+ content: {
43
+ "application/json": {
44
+ schema: z.object({ accounts: z.array(linkedAccountSchema) }),
45
+ },
46
+ },
47
+ description: "Live links, newest first",
48
+ },
49
+ 400: {
50
+ content: { "application/json": { schema: errorSchema } },
51
+ description: "No filter supplied",
52
+ },
53
+ },
54
+ });
55
+
56
+ const lookupRoute = createRoute({
57
+ method: "get",
58
+ path: "/{provider}/{providerUserId}",
59
+ tags: ["Accounts"],
60
+ summary: "Reverse lookup a platform account",
61
+ description:
62
+ "SECRET API KEY + `accounts` scope. Answers 'who owns this platform account RIGHT NOW' with the full operator row (`contactId`, `version`, `linkedAt`, `method`, `tokensRevokedAt`). An unlinked pair is history, not a live owner, and 404s.",
63
+ request: {
64
+ params: z.object({
65
+ provider: z.string().min(1),
66
+ providerUserId: z.string().min(1),
67
+ }),
68
+ },
69
+ responses: {
70
+ 200: {
71
+ content: {
72
+ "application/json": {
73
+ schema: z.object({ account: linkedAccountSchema }),
74
+ },
75
+ },
76
+ description: "The live link",
77
+ },
78
+ 404: {
79
+ content: { "application/json": { schema: errorSchema } },
80
+ description: "No live link for this pair",
81
+ },
82
+ },
83
+ });
84
+
85
+ const unlinkRoute = createRoute({
86
+ method: "delete",
87
+ path: "/{provider}/{providerUserId}",
88
+ tags: ["Accounts"],
89
+ summary: "Unlink a platform account (operator)",
90
+ description:
91
+ 'SECRET API KEY + `accounts` scope. The operator / reconciliation unlink — stamps `reason: "api"`, allocates a new `version` inside the store\'s advisory-locked transaction and emits exactly one `account.unlinked`. The player-facing revokes are `POST /v1/accounts/me/revoke` (primary) and the hosted manage page. Unknown pair ⇒ `{ unlinked: false }` with 200 and no emission.',
92
+ request: {
93
+ params: z.object({
94
+ provider: z.string().min(1),
95
+ providerUserId: z.string().min(1),
96
+ }),
97
+ },
98
+ responses: {
99
+ 200: {
100
+ content: {
101
+ "application/json": {
102
+ schema: z.object({
103
+ unlinked: z.boolean(),
104
+ /** Decimal STRING (DECISIONS §5.1). Absent when nothing changed. */
105
+ version: z.string().optional(),
106
+ }),
107
+ },
108
+ },
109
+ description: "Unlink result",
110
+ },
111
+ },
112
+ });
113
+
114
+ export function registerAccountsListRoute(router: OpenAPIHono<AppEnv>) {
115
+ router.openapi(listRoute, async (c) => {
116
+ const { db } = c.get("container");
117
+ const { contactId, email, provider, limit, offset } = c.req.valid("query");
118
+
119
+ if (!contactId && !email && !provider) {
120
+ return c.json({ error: "contactId, email or provider is required" }, 400);
121
+ }
122
+
123
+ let filterContactId: string | undefined;
124
+ if (contactId || email) {
125
+ const resolved = await resolveAccountsContactId(db, { contactId, email });
126
+ // An unknown contact is an EMPTY answer, never an unfiltered one: falling
127
+ // through with no contact filter would list every live link in the
128
+ // deployment under a filter the caller believes narrowed it.
129
+ if (!resolved) return c.json({ accounts: [] }, 200);
130
+ filterContactId = resolved;
131
+ }
132
+
133
+ const rows = await listLiveLinks({
134
+ db,
135
+ ...(filterContactId ? { contactId: filterContactId } : {}),
136
+ ...(provider ? { provider } : {}),
137
+ limit: limit ?? LIMIT_DEFAULT,
138
+ offset: offset ?? 0,
139
+ });
140
+
141
+ return c.json({ accounts: rows.map(serializeLinkedAccount) }, 200);
142
+ });
143
+ }
144
+
145
+ export function registerAccountsLookupRoute(router: OpenAPIHono<AppEnv>) {
146
+ router.openapi(lookupRoute, async (c) => {
147
+ const { db } = c.get("container");
148
+ // Hono decodes a path segment ONCE, and the SDK encodes once — so the value
149
+ // here is byte-identical to the one the store wrote, reserved characters
150
+ // and all.
151
+ const { provider, providerUserId } = c.req.valid("param");
152
+
153
+ const row = await getLiveLink({ db, provider, providerUserId });
154
+ if (!row) {
155
+ return c.json(
156
+ { error: `No live link for ${provider}/${providerUserId}` },
157
+ 404,
158
+ );
159
+ }
160
+ return c.json({ account: serializeLinkedAccount(row) }, 200);
161
+ });
162
+ }
163
+
164
+ export function registerAccountsUnlinkRoute(router: OpenAPIHono<AppEnv>) {
165
+ router.openapi(unlinkRoute, async (c) => {
166
+ const { provider, providerUserId } = c.req.valid("param");
167
+
168
+ const result = await unlinkFromRoute(c, {
169
+ provider,
170
+ providerUserId,
171
+ reason: "api",
172
+ });
173
+
174
+ if (result.status !== "unlinked") return c.json({ unlinked: false }, 200);
175
+ return c.json({ unlinked: true, version: result.version }, 200);
176
+ });
177
+ }