@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.
- package/package.json +12 -12
- package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
- package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
- package/src/account-links/__fixtures__/steam.json +21 -0
- package/src/account-links/__fixtures__/twitch.json +22 -0
- package/src/account-links/index.ts +8 -0
- package/src/account-links/steam.test.ts +243 -0
- package/src/account-links/steam.ts +48 -0
- package/src/account-links/twitch.test.ts +157 -0
- package/src/account-links/twitch.ts +99 -0
- package/src/container.account-links.env.test.ts +65 -0
- package/src/container.account-links.halfenv.test.ts +48 -0
- package/src/container.account-links.test.ts +185 -0
- package/src/container.ts +120 -0
- package/src/env.ts +37 -0
- package/src/index.ts +87 -1
- package/src/lib/account-link-emit.ts +126 -0
- package/src/lib/account-link-events.ts +180 -0
- package/src/lib/account-link-hooks.test.ts +158 -0
- package/src/lib/account-link-hooks.ts +73 -0
- package/src/lib/account-link-ingest.ts +364 -0
- package/src/lib/account-link-nonce.test.ts +52 -0
- package/src/lib/account-link-nonce.ts +57 -0
- package/src/lib/account-link-origins.test.ts +72 -0
- package/src/lib/account-link-origins.ts +87 -0
- package/src/lib/account-link-pkce.test.ts +91 -0
- package/src/lib/account-link-pkce.ts +106 -0
- package/src/lib/account-link-provider-registry.test.ts +52 -0
- package/src/lib/account-link-provider-registry.ts +61 -0
- package/src/lib/account-link-throttle.test.ts +178 -0
- package/src/lib/account-link-throttle.ts +130 -0
- package/src/lib/account-link-url.ts +85 -0
- package/src/lib/account-links-emit.test.ts +525 -0
- package/src/lib/account-links-env.test.ts +40 -0
- package/src/lib/account-links-from-env.test.ts +187 -0
- package/src/lib/account-links-from-env.ts +126 -0
- package/src/lib/account-links.ts +1300 -0
- package/src/lib/app-secret.ts +34 -0
- package/src/lib/connector-actions.test.ts +13 -4
- package/src/lib/connector-state.account-link.test.ts +114 -0
- package/src/lib/connector-state.ts +48 -3
- package/src/lib/contacts.ts +320 -6
- package/src/lib/outbound-account-payloads.test.ts +137 -0
- package/src/lib/outbound.ts +91 -0
- package/src/lib/provider-credentials.ts +19 -5
- package/src/lib/webhook-catalog-sync.test.ts +24 -0
- package/src/lib/webhook-signing.ts +18 -1
- package/src/routes/accounts/callback.ts +597 -0
- package/src/routes/accounts/emit.ts +231 -0
- package/src/routes/accounts/import-links.ts +210 -0
- package/src/routes/accounts/index.ts +75 -0
- package/src/routes/accounts/lookup.ts +177 -0
- package/src/routes/accounts/me.ts +215 -0
- package/src/routes/accounts/mint.ts +279 -0
- package/src/routes/accounts/pages.ts +62 -0
- package/src/routes/accounts/resolve.ts +61 -0
- package/src/routes/accounts/serialize.ts +96 -0
- package/src/routes/accounts/shared.ts +107 -0
- package/src/routes/accounts/start.ts +229 -0
- package/src/routes/accounts/unlink.ts +98 -0
- package/src/routes/admin/agent.ts +2 -0
- package/src/routes/admin/api-keys.ts +7 -0
- package/src/routes/admin/contacts.ts +38 -2
- package/src/routes/connectors/index.ts +17 -0
- package/src/routes/contacts/index.ts +8 -0
- package/src/routes/index.ts +75 -0
- package/src/testing-barrel.test.ts +74 -0
- package/src/testing.ts +17 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import type { Database } from "@hogsend/db";
|
|
2
|
+
import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
|
+
import type { AppEnv } from "../../app.js";
|
|
4
|
+
import { listLiveLinks } from "../../lib/account-links.js";
|
|
5
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
6
|
+
import {
|
|
7
|
+
InvalidUserTokenError,
|
|
8
|
+
verifyUserToken,
|
|
9
|
+
} from "../../lib/user-token.js";
|
|
10
|
+
import { resolveTokenContactId } from "./resolve.js";
|
|
11
|
+
import {
|
|
12
|
+
publicLinkedAccountSchema,
|
|
13
|
+
serializePublicLinkedAccount,
|
|
14
|
+
} from "./serialize.js";
|
|
15
|
+
import { unlinkFromRoute } from "./unlink.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* THE PLAYER'S OWN TWO ROUTES (PRD 09 T8/T8b), both `userToken`-gated and both
|
|
19
|
+
* NON-CONFIRMING (DECISIONS §6.9/§14).
|
|
20
|
+
*
|
|
21
|
+
* A player signed in on the publisher's site already has a server-minted
|
|
22
|
+
* `userToken` for the rest of the SDK, so the in-app path needs no email, no
|
|
23
|
+
* hosted page and no token in a URL. PRD 11's hosted manage page is the
|
|
24
|
+
* FALLBACK for a player with no session; the secret-key `DELETE` is the
|
|
25
|
+
* operator path and is neither.
|
|
26
|
+
*
|
|
27
|
+
* **Non-confirmation is the whole design.** An absent, malformed, expired,
|
|
28
|
+
* forged or unknown-user token takes the SAME code path as "you exist and hold
|
|
29
|
+
* nothing": one `return` shape per handler, no `401`, no `403`, no `404` and no
|
|
30
|
+
* varying error body. Anything else lets a caller enumerate which players a
|
|
31
|
+
* publisher has and which platform accounts they hold.
|
|
32
|
+
*
|
|
33
|
+
* The one `403` here is a different case entirely: a body that tries to NAME an
|
|
34
|
+
* identity is a malformed REQUEST, not a question about whether a contact
|
|
35
|
+
* exists (the same rule as `POST /v1/accounts/link-url`).
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A `multiple: true` provider can hold many links per contact; both routes are
|
|
40
|
+
* bounded so a read and a revoke are finite.
|
|
41
|
+
*/
|
|
42
|
+
const MAX_ROWS = 500;
|
|
43
|
+
|
|
44
|
+
const meRoute = createRoute({
|
|
45
|
+
method: "get",
|
|
46
|
+
path: "/me",
|
|
47
|
+
tags: ["Accounts"],
|
|
48
|
+
summary: "List the signed-in player's linked accounts",
|
|
49
|
+
description:
|
|
50
|
+
"Publishable OR secret key, plus a server-minted `userToken` in the query string. Returns DISPLAY FIELDS ONLY (`provider`, `username`, `avatarUrl`, `linkedAt`) — never `providerUserId`, `contactId`, `version` or `method`. NON-CONFIRMING: an absent, forged, expired or unknown-user token returns `200 { accounts: [] }`, byte-identical to a real user with no links.",
|
|
51
|
+
request: {
|
|
52
|
+
query: z.object({ userToken: z.string().optional() }),
|
|
53
|
+
},
|
|
54
|
+
responses: {
|
|
55
|
+
200: {
|
|
56
|
+
content: {
|
|
57
|
+
"application/json": {
|
|
58
|
+
schema: z.object({
|
|
59
|
+
accounts: z.array(publicLinkedAccountSchema),
|
|
60
|
+
}),
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
description: "The player's live links (possibly empty)",
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const revokeRoute = createRoute({
|
|
69
|
+
method: "post",
|
|
70
|
+
path: "/me/revoke",
|
|
71
|
+
tags: ["Accounts"],
|
|
72
|
+
summary: "Unlink the signed-in player's accounts for one provider",
|
|
73
|
+
description:
|
|
74
|
+
'Publishable OR secret key, plus a server-minted `userToken`. THE PRIMARY player unlink. Unlinks every live link the token\'s contact holds for `provider` with `reason: "player"`, each at its own new version under its own advisory lock, each emitting one `account.unlinked`. Keyed on `provider`, not `providerUserId`, because `GET /v1/accounts/me` deliberately returns no id. NON-CONFIRMING: a token problem returns `200 { revoked: 0 }`. A body naming an identity (`contactId`/`email`/a foreign `userId`) is a 403 — ownership comes from the token, never the body.',
|
|
75
|
+
request: {
|
|
76
|
+
body: {
|
|
77
|
+
content: {
|
|
78
|
+
"application/json": {
|
|
79
|
+
schema: z.object({
|
|
80
|
+
provider: z.string().min(1),
|
|
81
|
+
userToken: z.string().optional(),
|
|
82
|
+
// Declared so they can be REFUSED. A zod object strips unknown
|
|
83
|
+
// keys, so an undeclared `contactId` would be silently dropped and
|
|
84
|
+
// the 403 below could never fire.
|
|
85
|
+
contactId: z.string().optional(),
|
|
86
|
+
email: z.string().optional(),
|
|
87
|
+
userId: z.string().optional(),
|
|
88
|
+
}),
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
responses: {
|
|
94
|
+
200: {
|
|
95
|
+
content: {
|
|
96
|
+
"application/json": {
|
|
97
|
+
schema: z.object({ revoked: z.number() }),
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
description: "How many live links were unlinked (possibly zero)",
|
|
101
|
+
},
|
|
102
|
+
403: {
|
|
103
|
+
content: { "application/json": { schema: errorSchema } },
|
|
104
|
+
description: "The body tried to name an identity",
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The token's contact, or `null` for EVERY failure mode. Deliberately
|
|
111
|
+
* indistinguishable: a bad signature, an expired token and a userId nobody
|
|
112
|
+
* owns all answer the same way.
|
|
113
|
+
*/
|
|
114
|
+
async function contactFromToken(
|
|
115
|
+
db: Database,
|
|
116
|
+
secret: string,
|
|
117
|
+
token: string | undefined,
|
|
118
|
+
): Promise<string | null> {
|
|
119
|
+
if (!token) return null;
|
|
120
|
+
try {
|
|
121
|
+
const { userId } = verifyUserToken({ token, secret });
|
|
122
|
+
return await resolveTokenContactId(db, userId);
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (err instanceof InvalidUserTokenError) return null;
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function registerAccountsMeRoute(router: OpenAPIHono<AppEnv>) {
|
|
130
|
+
router.openapi(meRoute, async (c) => {
|
|
131
|
+
const { db, env } = c.get("container");
|
|
132
|
+
// A GET has no body; the feed routes read the token from the query the same
|
|
133
|
+
// way (`routes/feed/recipient.ts:44-49`).
|
|
134
|
+
const { userToken } = c.req.valid("query");
|
|
135
|
+
|
|
136
|
+
const contactId = await contactFromToken(
|
|
137
|
+
db,
|
|
138
|
+
env.BETTER_AUTH_SECRET,
|
|
139
|
+
userToken,
|
|
140
|
+
);
|
|
141
|
+
const rows = contactId
|
|
142
|
+
? await listLiveLinks({ db, contactId, limit: MAX_ROWS })
|
|
143
|
+
: [];
|
|
144
|
+
|
|
145
|
+
// ONE return shape in this handler. Verification failure and "no such
|
|
146
|
+
// contact" reach it having built an empty array, so the response is
|
|
147
|
+
// byte-identical to a real user with no links.
|
|
148
|
+
return c.json({ accounts: rows.map(serializePublicLinkedAccount) }, 200);
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function registerAccountsMeRevokeRoute(router: OpenAPIHono<AppEnv>) {
|
|
153
|
+
router.openapi(revokeRoute, async (c) => {
|
|
154
|
+
const { db, env } = c.get("container");
|
|
155
|
+
const body = c.req.valid("json");
|
|
156
|
+
|
|
157
|
+
// A body that names an identity is REFUSED before anything else. This is
|
|
158
|
+
// about the request being malformed, not about whether a contact exists,
|
|
159
|
+
// so it is the one non-200 on this route.
|
|
160
|
+
if (body.contactId || body.email) {
|
|
161
|
+
return c.json(
|
|
162
|
+
{ error: "userToken does not authorize this identity" },
|
|
163
|
+
403,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const contactId = await contactFromToken(
|
|
168
|
+
db,
|
|
169
|
+
env.BETTER_AUTH_SECRET,
|
|
170
|
+
body.userToken,
|
|
171
|
+
);
|
|
172
|
+
if (contactId && body.userId) {
|
|
173
|
+
// A `userId` is only tolerable when it is the token's own subject; the
|
|
174
|
+
// token is still what decides, and a mismatch is the same refusal.
|
|
175
|
+
const claimed = await resolveTokenContactId(db, body.userId);
|
|
176
|
+
if (claimed !== contactId) {
|
|
177
|
+
return c.json(
|
|
178
|
+
{ error: "userToken does not authorize this identity" },
|
|
179
|
+
403,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (!contactId) {
|
|
184
|
+
// Non-confirming: no token, a forged one, or a user nobody owns — all
|
|
185
|
+
// answer exactly as "you hold nothing for this provider".
|
|
186
|
+
return c.json({ revoked: 0 }, 200);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const rows = await listLiveLinks({
|
|
190
|
+
db,
|
|
191
|
+
contactId,
|
|
192
|
+
provider: body.provider,
|
|
193
|
+
limit: MAX_ROWS,
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
let revoked = 0;
|
|
197
|
+
for (const row of rows) {
|
|
198
|
+
// `expectContactId` is NOT a duplicate of the enumeration above: that
|
|
199
|
+
// ran outside the pair lock, and a hosted callback can relink the pair
|
|
200
|
+
// between the read and the write. The store re-checks ownership INSIDE
|
|
201
|
+
// the lock and returns `rejected: not_owner` instead of destroying the
|
|
202
|
+
// new owner's just-proven link. A rejection is simply not counted —
|
|
203
|
+
// never a 403, never a 404.
|
|
204
|
+
const result = await unlinkFromRoute(c, {
|
|
205
|
+
provider: row.provider,
|
|
206
|
+
providerUserId: row.providerUserId,
|
|
207
|
+
reason: "player",
|
|
208
|
+
expectContactId: contactId,
|
|
209
|
+
});
|
|
210
|
+
if (result.status === "unlinked") revoked++;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return c.json({ revoked }, 200);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../../app.js";
|
|
3
|
+
import { checkAccountLinkThrottle } from "../../lib/account-link-throttle.js";
|
|
4
|
+
import {
|
|
5
|
+
AccountLinkReturnToError,
|
|
6
|
+
mintAccountLinkUrl,
|
|
7
|
+
} from "../../lib/account-link-url.js";
|
|
8
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
9
|
+
import {
|
|
10
|
+
InvalidUserTokenError,
|
|
11
|
+
verifyUserToken,
|
|
12
|
+
} from "../../lib/user-token.js";
|
|
13
|
+
import { resolveAccountsContactId, resolveTokenContactId } from "./resolve.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* THE TWO MINTS (PRD 09 T6/T7). Both return the SAME thing: an ENGINE-ORIGIN
|
|
17
|
+
* `<API_PUBLIC_URL>/v1/accounts/<provider>/start?t=<state>` URL, never a
|
|
18
|
+
* provider authorize URL (DECISIONS §15.2). PRD 13's embed derives its
|
|
19
|
+
* `postMessage` `expectedOrigin` from this value, so a provider-origin URL here
|
|
20
|
+
* would make every embedded link TIME OUT while the link had committed
|
|
21
|
+
* server-side — and a fake-`Window` test cannot see that.
|
|
22
|
+
*
|
|
23
|
+
* They differ in ONE thing, which is the whole security boundary:
|
|
24
|
+
*
|
|
25
|
+
* - `POST /mint-link` is SECRET-key + `accounts` scope, and may seal ANY
|
|
26
|
+
* contact. Server-trusted, exactly like `resolveFeedRecipient`'s secret arm.
|
|
27
|
+
* - `POST /link-url` is browser-reachable, and seals ONLY the contact the
|
|
28
|
+
* verified `userToken` names (DECISIONS §6.5). A `contactId`, `email` or
|
|
29
|
+
* differing `userId` in the body is a 403 with NO MINT — browsers can never
|
|
30
|
+
* mint for an arbitrary contact, whatever key tier they hold.
|
|
31
|
+
*
|
|
32
|
+
* Both are throttled through the Redis INCR helper and both FAIL CLOSED: a
|
|
33
|
+
* rejected budget AND an unavailable Redis are a `429` with no URL
|
|
34
|
+
* (DECISIONS §6.8). A mint that succeeded while Redis was down would hand out a
|
|
35
|
+
* state the hosted `/start` and `/callback` will then refuse anyway — those
|
|
36
|
+
* routes need Redis for PKCE custody and the single-use nonce burn.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
const mintResponse = z.object({
|
|
40
|
+
url: z.string(),
|
|
41
|
+
/** When the sealed state stops being accepted by `/start`. */
|
|
42
|
+
expiresAt: z.string(),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const mintLinkRoute = createRoute({
|
|
46
|
+
method: "post",
|
|
47
|
+
path: "/mint-link",
|
|
48
|
+
tags: ["Accounts"],
|
|
49
|
+
summary: "Mint a hosted link URL for a contact (operator)",
|
|
50
|
+
description:
|
|
51
|
+
"SECRET API KEY + `accounts` scope. Seals the named contact into an `account_link` state and returns the ENGINE-origin `/v1/accounts/<provider>/start?t=<state>` URL — never the provider's authorize URL. Use this to put a link button in an email or a DM. The browser equivalent is `POST /v1/accounts/link-url`, which can only ever mint for the `userToken`'s own user.",
|
|
52
|
+
request: {
|
|
53
|
+
body: {
|
|
54
|
+
content: {
|
|
55
|
+
"application/json": {
|
|
56
|
+
schema: z.object({
|
|
57
|
+
provider: z.string().min(1),
|
|
58
|
+
contactId: z.string().optional(),
|
|
59
|
+
email: z.string().optional(),
|
|
60
|
+
returnTo: z.string().optional(),
|
|
61
|
+
}),
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
responses: {
|
|
67
|
+
200: {
|
|
68
|
+
content: { "application/json": { schema: mintResponse } },
|
|
69
|
+
description: "The hosted link URL",
|
|
70
|
+
},
|
|
71
|
+
400: {
|
|
72
|
+
content: { "application/json": { schema: errorSchema } },
|
|
73
|
+
description: "No contact key, or an off-allowlist returnTo",
|
|
74
|
+
},
|
|
75
|
+
404: {
|
|
76
|
+
content: { "application/json": { schema: errorSchema } },
|
|
77
|
+
description: "Unknown provider or unknown contact",
|
|
78
|
+
},
|
|
79
|
+
429: {
|
|
80
|
+
content: { "application/json": { schema: errorSchema } },
|
|
81
|
+
description: "Throttled, or Redis unavailable (fail closed)",
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const linkUrlRoute = createRoute({
|
|
87
|
+
method: "post",
|
|
88
|
+
path: "/link-url",
|
|
89
|
+
tags: ["Accounts"],
|
|
90
|
+
summary: "Mint a hosted link URL for the signed-in player",
|
|
91
|
+
description:
|
|
92
|
+
"Publishable OR secret key, plus a server-minted `userToken`. THE DX UNLOCK: the customer's browser calls this directly, so they ship no backend endpoint of their own. Mints ONLY for the token's `userId`; a `contactId`, `email` or differing `userId` in the body is a 403 and nothing is minted. Returns the same ENGINE-origin `/start?t=` URL as `mint-link`.",
|
|
93
|
+
request: {
|
|
94
|
+
body: {
|
|
95
|
+
content: {
|
|
96
|
+
"application/json": {
|
|
97
|
+
schema: z.object({
|
|
98
|
+
provider: z.string().min(1),
|
|
99
|
+
userToken: z.string().optional(),
|
|
100
|
+
returnTo: z.string().optional(),
|
|
101
|
+
// Declared so they can be REFUSED — a zod object strips unknown
|
|
102
|
+
// keys, so an undeclared `contactId` would be silently dropped and
|
|
103
|
+
// the 403 could never fire.
|
|
104
|
+
contactId: z.string().optional(),
|
|
105
|
+
email: z.string().optional(),
|
|
106
|
+
userId: z.string().optional(),
|
|
107
|
+
}),
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
responses: {
|
|
113
|
+
200: {
|
|
114
|
+
content: { "application/json": { schema: mintResponse } },
|
|
115
|
+
description: "The hosted link URL",
|
|
116
|
+
},
|
|
117
|
+
400: {
|
|
118
|
+
content: { "application/json": { schema: errorSchema } },
|
|
119
|
+
description: "An off-allowlist returnTo",
|
|
120
|
+
},
|
|
121
|
+
403: {
|
|
122
|
+
content: { "application/json": { schema: errorSchema } },
|
|
123
|
+
description: "Missing/invalid userToken, or a body naming an identity",
|
|
124
|
+
},
|
|
125
|
+
404: {
|
|
126
|
+
content: { "application/json": { schema: errorSchema } },
|
|
127
|
+
description: "Unknown provider, or the token names no contact",
|
|
128
|
+
},
|
|
129
|
+
429: {
|
|
130
|
+
content: { "application/json": { schema: errorSchema } },
|
|
131
|
+
description: "Throttled, or Redis unavailable (fail closed)",
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
export function registerAccountsMintLinkRoute(router: OpenAPIHono<AppEnv>) {
|
|
137
|
+
router.openapi(mintLinkRoute, async (c) => {
|
|
138
|
+
const { accountLinkAllowedOrigins, accountLinkProviders, db, env } =
|
|
139
|
+
c.get("container");
|
|
140
|
+
const body = c.req.valid("json");
|
|
141
|
+
|
|
142
|
+
if (!accountLinkProviders.get(body.provider)) {
|
|
143
|
+
return c.json({ error: "unknown_provider" }, 404);
|
|
144
|
+
}
|
|
145
|
+
if (!body.contactId && !body.email) {
|
|
146
|
+
return c.json({ error: "contactId or email is required" }, 400);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const contactId = await resolveAccountsContactId(db, {
|
|
150
|
+
contactId: body.contactId,
|
|
151
|
+
email: body.email,
|
|
152
|
+
});
|
|
153
|
+
// No contact ⇒ no mint. Minting for a contact that does not exist would
|
|
154
|
+
// seal an id the callback then refuses (the FK is NOT NULL), so the player
|
|
155
|
+
// would walk the whole provider flow to reach an error page.
|
|
156
|
+
if (!contactId) return c.json({ error: "unknown_contact" }, 404);
|
|
157
|
+
|
|
158
|
+
const budget = await checkAccountLinkThrottle({
|
|
159
|
+
surface: "start",
|
|
160
|
+
contactId,
|
|
161
|
+
});
|
|
162
|
+
if (!budget.ok) return c.json({ error: budget.reason }, 429);
|
|
163
|
+
|
|
164
|
+
const minted = buildMintedUrl({
|
|
165
|
+
provider: body.provider,
|
|
166
|
+
contactId,
|
|
167
|
+
returnTo: body.returnTo,
|
|
168
|
+
allowedOrigins: accountLinkAllowedOrigins,
|
|
169
|
+
apiPublicUrl: env.API_PUBLIC_URL,
|
|
170
|
+
ttlSeconds: env.ACCOUNT_LINK_STATE_TTL_SECONDS,
|
|
171
|
+
});
|
|
172
|
+
if (!minted) return c.json({ error: "return_to_not_allowed" }, 400);
|
|
173
|
+
return c.json(minted, 200);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function registerAccountsLinkUrlRoute(router: OpenAPIHono<AppEnv>) {
|
|
178
|
+
router.openapi(linkUrlRoute, async (c) => {
|
|
179
|
+
const { accountLinkAllowedOrigins, accountLinkProviders, db, env } =
|
|
180
|
+
c.get("container");
|
|
181
|
+
const body = c.req.valid("json");
|
|
182
|
+
|
|
183
|
+
// (1) A body that names an identity is refused BEFORE the token is even
|
|
184
|
+
// read. The contact sealed into the state comes from the token, never from
|
|
185
|
+
// the request (DECISIONS §6.3/§6.5), so a request that argues otherwise is
|
|
186
|
+
// malformed regardless of whether its token is valid.
|
|
187
|
+
if (body.contactId || body.email) {
|
|
188
|
+
return c.json(
|
|
189
|
+
{ error: "userToken does not authorize this identity" },
|
|
190
|
+
403,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// (2) The token. Absent, malformed, expired or badly signed are ONE answer:
|
|
195
|
+
// 403, no mint. (Unlike `/me`, this route is not an existence oracle — it
|
|
196
|
+
// performs an action, so it may refuse out loud.)
|
|
197
|
+
if (!body.userToken) {
|
|
198
|
+
return c.json({ error: "Invalid userToken" }, 403);
|
|
199
|
+
}
|
|
200
|
+
let tokenUserId: string;
|
|
201
|
+
try {
|
|
202
|
+
tokenUserId = verifyUserToken({
|
|
203
|
+
token: body.userToken,
|
|
204
|
+
secret: env.BETTER_AUTH_SECRET,
|
|
205
|
+
}).userId;
|
|
206
|
+
} catch (err) {
|
|
207
|
+
if (err instanceof InvalidUserTokenError) {
|
|
208
|
+
return c.json({ error: "Invalid userToken" }, 403);
|
|
209
|
+
}
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
if (body.userId && body.userId !== tokenUserId) {
|
|
213
|
+
return c.json(
|
|
214
|
+
{ error: "userToken does not authorize this identity" },
|
|
215
|
+
403,
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (!accountLinkProviders.get(body.provider)) {
|
|
220
|
+
return c.json({ error: "unknown_provider" }, 404);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const contactId = await resolveTokenContactId(db, tokenUserId);
|
|
224
|
+
if (!contactId) return c.json({ error: "unknown_contact" }, 404);
|
|
225
|
+
|
|
226
|
+
const budget = await checkAccountLinkThrottle({
|
|
227
|
+
surface: "start",
|
|
228
|
+
contactId,
|
|
229
|
+
});
|
|
230
|
+
if (!budget.ok) return c.json({ error: budget.reason }, 429);
|
|
231
|
+
|
|
232
|
+
const minted = buildMintedUrl({
|
|
233
|
+
provider: body.provider,
|
|
234
|
+
contactId,
|
|
235
|
+
returnTo: body.returnTo,
|
|
236
|
+
allowedOrigins: accountLinkAllowedOrigins,
|
|
237
|
+
apiPublicUrl: env.API_PUBLIC_URL,
|
|
238
|
+
ttlSeconds: env.ACCOUNT_LINK_STATE_TTL_SECONDS,
|
|
239
|
+
});
|
|
240
|
+
if (!minted) return c.json({ error: "return_to_not_allowed" }, 400);
|
|
241
|
+
return c.json(minted, 200);
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The one place either route builds its URL, so the two cannot drift on the
|
|
247
|
+
* shape or on the `returnTo` refusal.
|
|
248
|
+
*
|
|
249
|
+
* `null` means the `returnTo` was off the allowlist — a 400 at both call sites,
|
|
250
|
+
* NEVER a silent fallback to the hosted page: an open redirect on a link flow
|
|
251
|
+
* is a phishing primitive, and one we would have SIGNED.
|
|
252
|
+
*/
|
|
253
|
+
function buildMintedUrl(args: {
|
|
254
|
+
provider: string;
|
|
255
|
+
contactId: string;
|
|
256
|
+
returnTo?: string;
|
|
257
|
+
allowedOrigins: string[];
|
|
258
|
+
apiPublicUrl: string;
|
|
259
|
+
ttlSeconds: number;
|
|
260
|
+
}): { url: string; expiresAt: string } | null {
|
|
261
|
+
let url: string;
|
|
262
|
+
try {
|
|
263
|
+
url = mintAccountLinkUrl({
|
|
264
|
+
provider: args.provider,
|
|
265
|
+
contactId: args.contactId,
|
|
266
|
+
...(args.returnTo ? { returnTo: args.returnTo } : {}),
|
|
267
|
+
allowedOrigins: args.allowedOrigins,
|
|
268
|
+
apiPublicUrl: args.apiPublicUrl,
|
|
269
|
+
ttlSeconds: args.ttlSeconds,
|
|
270
|
+
});
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if (err instanceof AccountLinkReturnToError) return null;
|
|
273
|
+
throw err;
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
url,
|
|
277
|
+
expiresAt: new Date(Date.now() + args.ttlSeconds * 1000).toISOString(),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PLACEHOLDER result pages for the hosted account-link flow.
|
|
3
|
+
*
|
|
4
|
+
* **PRD 10 owns the real pages** (shared branding module, `postMessage` to the
|
|
5
|
+
* configured origin allowlist, the headless `resultRedirect` escape hatch, the
|
|
6
|
+
* cold-connect XSS posture). PRD 07 ships this minimum so the callback has
|
|
7
|
+
* somewhere to land, and PRD 10 REPLACES it — do not grow features here.
|
|
8
|
+
*
|
|
9
|
+
* What is NOT placeholder, and must survive the replacement:
|
|
10
|
+
*
|
|
11
|
+
* - Nothing player-supplied is interpolated. The only dynamic value is the
|
|
12
|
+
* provider's display name, which comes from the registry (our own config),
|
|
13
|
+
* and it is escaped anyway.
|
|
14
|
+
* - The failure page never says WHICH of the four reasons occurred. `denied`,
|
|
15
|
+
* `vetoed`, `exchange_failed` and `state_invalid` are operator facts on the
|
|
16
|
+
* `account.link_failed` event, not player-facing copy: telling an attacker
|
|
17
|
+
* "that state was already used" vs "that signature was wrong" is a probing
|
|
18
|
+
* oracle.
|
|
19
|
+
* - `noindex`, because these URLs land in browser history and chat unfurls.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
function escapeHtml(value: string): string {
|
|
23
|
+
return value
|
|
24
|
+
.replace(/&/g, "&")
|
|
25
|
+
.replace(/</g, "<")
|
|
26
|
+
.replace(/>/g, ">")
|
|
27
|
+
.replace(/"/g, """);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function page(heading: string, body: string): string {
|
|
31
|
+
return `<!doctype html>
|
|
32
|
+
<html lang="en">
|
|
33
|
+
<head>
|
|
34
|
+
<meta charset="utf-8">
|
|
35
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
36
|
+
<meta name="robots" content="noindex">
|
|
37
|
+
<title>${escapeHtml(heading)}</title>
|
|
38
|
+
<style>
|
|
39
|
+
body { font: 16px/1.5 system-ui, sans-serif; margin: 0; display: grid;
|
|
40
|
+
place-items: center; min-height: 100vh; color: #111; }
|
|
41
|
+
main { max-width: 32rem; padding: 2rem; text-align: center; }
|
|
42
|
+
h1 { font-size: 1.25rem; margin: 0 0 .5rem; }
|
|
43
|
+
p { margin: 0; color: #444; }
|
|
44
|
+
</style>
|
|
45
|
+
</head>
|
|
46
|
+
<body><main><h1>${escapeHtml(heading)}</h1><p>${escapeHtml(body)}</p></main></body>
|
|
47
|
+
</html>`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function accountLinkSuccessPage(providerName: string): string {
|
|
51
|
+
return page(
|
|
52
|
+
`${providerName} account linked`,
|
|
53
|
+
"You can close this window and go back to where you started.",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function accountLinkErrorPage(providerName: string): string {
|
|
58
|
+
return page(
|
|
59
|
+
`We couldn't link your ${providerName} account`,
|
|
60
|
+
"Nothing was changed. You can close this window and try again.",
|
|
61
|
+
);
|
|
62
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { contacts, type Database } from "@hogsend/db";
|
|
2
|
+
import { and, eq, isNull } from "drizzle-orm";
|
|
3
|
+
import { normalizeEmail, resolveContact } from "../../lib/contacts.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the contact an OPERATOR named, by id or by email. Secret keys are
|
|
7
|
+
* server-trusted, so both keys are honoured directly — the same posture as
|
|
8
|
+
* `resolveFeedRecipient`'s secret arm (`routes/feed/recipient.ts:104-111`).
|
|
9
|
+
*
|
|
10
|
+
* It NEVER creates. A `/v1/accounts` route naming an unknown contact is a
|
|
11
|
+
* question, not an identity assertion, so minting one here would be exactly
|
|
12
|
+
* the ghost-contact case `resolveContactNoCreate` exists to prevent (and the
|
|
13
|
+
* import path reports it as a conflict rather than inventing an owner).
|
|
14
|
+
*
|
|
15
|
+
* `contactId` goes through `resolveContact`, so a uuid, an `external_id` and a
|
|
16
|
+
* merged-away external alias all resolve to the live survivor.
|
|
17
|
+
*/
|
|
18
|
+
export async function resolveAccountsContactId(
|
|
19
|
+
db: Database,
|
|
20
|
+
key: { contactId?: string; email?: string },
|
|
21
|
+
): Promise<string | null> {
|
|
22
|
+
if (key.contactId) {
|
|
23
|
+
const row = await resolveContact({ db, id: key.contactId });
|
|
24
|
+
return row?.id ?? null;
|
|
25
|
+
}
|
|
26
|
+
if (key.email) {
|
|
27
|
+
const [row] = await db
|
|
28
|
+
.select({ id: contacts.id })
|
|
29
|
+
.from(contacts)
|
|
30
|
+
.where(
|
|
31
|
+
and(
|
|
32
|
+
eq(contacts.email, normalizeEmail(key.email)),
|
|
33
|
+
isNull(contacts.deletedAt),
|
|
34
|
+
),
|
|
35
|
+
)
|
|
36
|
+
.limit(1);
|
|
37
|
+
return row?.id ?? null;
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Resolve the contact a VERIFIED `userToken` names, and nothing else.
|
|
44
|
+
*
|
|
45
|
+
* The token's `userId` is the ONLY input — never a `contactId`, an `email` or a
|
|
46
|
+
* `userId` from the request body (DECISIONS §6.3/§6.5). `resolveContact`
|
|
47
|
+
* matches a uuid or an `external_id` (including a merged-away alias), which is
|
|
48
|
+
* the same key `contactKey()` hands back on the outbound plane, so the SDK's
|
|
49
|
+
* "the userId I minted a token for" and the engine's answer are one value.
|
|
50
|
+
*
|
|
51
|
+
* Returns `null` for "no such contact". Every caller turns that into its
|
|
52
|
+
* ordinary EMPTY answer, never a 404 — a player-facing route must not confirm
|
|
53
|
+
* whether a person exists.
|
|
54
|
+
*/
|
|
55
|
+
export async function resolveTokenContactId(
|
|
56
|
+
db: Database,
|
|
57
|
+
userId: string,
|
|
58
|
+
): Promise<string | null> {
|
|
59
|
+
const row = await resolveContact({ db, id: userId });
|
|
60
|
+
return row?.id ?? null;
|
|
61
|
+
}
|