@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,57 @@
|
|
|
1
|
+
import { getRedisIfConnected } from "./redis.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The single-use nonce burn for the hosted account-link callback.
|
|
5
|
+
*
|
|
6
|
+
* Shape-identical to the connector callback's burn
|
|
7
|
+
* (`routes/connectors/index.ts:136-146`), down to the 900s TTL and the
|
|
8
|
+
* `"OK"`-comparison on the `SET NX` result: the signed state is otherwise
|
|
9
|
+
* TTL-replayable, so a captured callback URL works until `exp` unless the first
|
|
10
|
+
* use burns the per-mint nonce.
|
|
11
|
+
*
|
|
12
|
+
* ONE DELIBERATE DIVERGENCE, and it must stay: when Redis is absent the
|
|
13
|
+
* connector callback degrades to TTL-only validity ("we never block a callback
|
|
14
|
+
* on a cache miss"), and this one REFUSES. DECISIONS §6.8 says fail closed, and
|
|
15
|
+
* the threat differs — a replayed connector install re-captures a guild id,
|
|
16
|
+
* whereas a replayed account-link callback can MOVE a platform account between
|
|
17
|
+
* contacts (DECISIONS §6.1). It is a named function rather than four inline
|
|
18
|
+
* lines so the null-Redis arm is directly testable; a guard whose fail-closed
|
|
19
|
+
* branch no test can reach is a guard nobody will notice losing.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface AccountLinkNonceRedis {
|
|
23
|
+
set(
|
|
24
|
+
key: string,
|
|
25
|
+
value: string,
|
|
26
|
+
ex: "EX",
|
|
27
|
+
ttlSeconds: number,
|
|
28
|
+
nx: "NX",
|
|
29
|
+
): Promise<string | null>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Matches `connector:state:used:<nonce>`'s window so the marker outlives any valid state. */
|
|
33
|
+
export const NONCE_BURN_TTL_SECONDS = 900;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Claim a nonce. TRUE exactly once per nonce; FALSE on a replay, on a missing
|
|
37
|
+
* Redis, and on any Redis fault.
|
|
38
|
+
*/
|
|
39
|
+
export async function burnAccountLinkNonce(
|
|
40
|
+
nonce: string,
|
|
41
|
+
redis?: AccountLinkNonceRedis | null,
|
|
42
|
+
): Promise<boolean> {
|
|
43
|
+
const client = redis === undefined ? (getRedisIfConnected() ?? null) : redis;
|
|
44
|
+
if (!client) return false;
|
|
45
|
+
try {
|
|
46
|
+
const claimed = await client.set(
|
|
47
|
+
`account_link:state:used:${nonce}`,
|
|
48
|
+
"1",
|
|
49
|
+
"EX",
|
|
50
|
+
NONCE_BURN_TTL_SECONDS,
|
|
51
|
+
"NX",
|
|
52
|
+
);
|
|
53
|
+
return claimed === "OK";
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { parseAllowedOrigins } from "./account-link-origins.js";
|
|
4
|
+
|
|
5
|
+
test("parses a csv of origins", () => {
|
|
6
|
+
assert.deepEqual(
|
|
7
|
+
parseAllowedOrigins(
|
|
8
|
+
"https://play.example.com, https://www.example.com ,http://localhost:3000",
|
|
9
|
+
),
|
|
10
|
+
[
|
|
11
|
+
"https://play.example.com",
|
|
12
|
+
"https://www.example.com",
|
|
13
|
+
"http://localhost:3000",
|
|
14
|
+
],
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test("throws on a path", () => {
|
|
19
|
+
assert.throws(
|
|
20
|
+
() => parseAllowedOrigins("https://x.example.com/cb"),
|
|
21
|
+
/not an absolute origin/,
|
|
22
|
+
);
|
|
23
|
+
assert.throws(
|
|
24
|
+
() => parseAllowedOrigins(["https://x.example.com/cb"]),
|
|
25
|
+
/not an absolute origin/,
|
|
26
|
+
);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("throws on a bare *", () => {
|
|
30
|
+
assert.throws(() => parseAllowedOrigins("*"), /not an absolute origin/);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("throws on a wildcard host", () => {
|
|
34
|
+
assert.throws(
|
|
35
|
+
() => parseAllowedOrigins("https://*.example.com"),
|
|
36
|
+
/not an absolute origin/,
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("throws naming the offending entry", () => {
|
|
41
|
+
assert.throws(
|
|
42
|
+
() =>
|
|
43
|
+
parseAllowedOrigins("https://good.example.com,https://bad.example.com/x"),
|
|
44
|
+
/"https:\/\/bad\.example\.com\/x"/,
|
|
45
|
+
);
|
|
46
|
+
// The source label rides along so the operator knows which knob to fix.
|
|
47
|
+
assert.throws(
|
|
48
|
+
() => parseAllowedOrigins(["*"], "accountLinks.allowedOrigins"),
|
|
49
|
+
/accountLinks\.allowedOrigins/,
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("returns an empty array for undefined and for an empty string", () => {
|
|
54
|
+
assert.deepEqual(parseAllowedOrigins(undefined), []);
|
|
55
|
+
assert.deepEqual(parseAllowedOrigins(""), []);
|
|
56
|
+
assert.deepEqual(parseAllowedOrigins([]), []);
|
|
57
|
+
// Empty csv slots are dropped, not treated as malformed entries.
|
|
58
|
+
assert.deepEqual(parseAllowedOrigins(",https://a.example.com,,"), [
|
|
59
|
+
"https://a.example.com",
|
|
60
|
+
]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("dedupes", () => {
|
|
64
|
+
assert.deepEqual(
|
|
65
|
+
parseAllowedOrigins([
|
|
66
|
+
"https://a.example.com",
|
|
67
|
+
"https://b.example.com",
|
|
68
|
+
"https://a.example.com",
|
|
69
|
+
]),
|
|
70
|
+
["https://a.example.com", "https://b.example.com"],
|
|
71
|
+
);
|
|
72
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse the ONE origin allowlist governing `returnTo` (PRD 07) and the
|
|
3
|
+
* `postMessage` targetOrigin (PRD 10). THROWS on a malformed entry rather than
|
|
4
|
+
* dropping it: an allowlist is a security control, and a silently shortened one
|
|
5
|
+
* produces a link button that spins to a timeout while the link has already
|
|
6
|
+
* committed server-side — the single most likely first-run misconfiguration
|
|
7
|
+
* (PRD 13). Precedent: FX_RATES is parsed outside the env schema for exactly
|
|
8
|
+
* this reason (env.ts, lib/fx.ts).
|
|
9
|
+
*
|
|
10
|
+
* Accepts the csv env var (`ACCOUNT_LINK_ALLOWED_ORIGINS`) as a string, or the
|
|
11
|
+
* consumer option (`accountLinks.allowedOrigins`) as an array — the container
|
|
12
|
+
* concatenates env-first and parses both as ONE list, so the same rule applies
|
|
13
|
+
* to each. Entries are trimmed, empties dropped, and each remaining entry must
|
|
14
|
+
* be a parseable ABSOLUTE origin that round-trips (`new URL(e).origin === e`):
|
|
15
|
+
* a path suffix, a bare `*`, or a wildcard host all throw naming the entry.
|
|
16
|
+
* Returns the deduped list, order preserved.
|
|
17
|
+
*
|
|
18
|
+
* `source` names where the offending entry came from in the throw message;
|
|
19
|
+
* the container's single merged call keeps the default naming both.
|
|
20
|
+
*/
|
|
21
|
+
export function parseAllowedOrigins(
|
|
22
|
+
entries: string | string[] | undefined,
|
|
23
|
+
source = "ACCOUNT_LINK_ALLOWED_ORIGINS / accountLinks.allowedOrigins",
|
|
24
|
+
): string[] {
|
|
25
|
+
if (entries === undefined) return [];
|
|
26
|
+
const raw = typeof entries === "string" ? entries.split(",") : entries;
|
|
27
|
+
const origins: string[] = [];
|
|
28
|
+
for (const entry of raw) {
|
|
29
|
+
const trimmed = entry.trim();
|
|
30
|
+
if (trimmed === "") continue;
|
|
31
|
+
let origin: string | undefined;
|
|
32
|
+
// Explicit, BEFORE the URL parse: `*` is not a forbidden host code point
|
|
33
|
+
// in the WHATWG URL Standard, so `new URL("https://*.example.com")`
|
|
34
|
+
// parses and its origin round-trips — the round-trip check alone would
|
|
35
|
+
// wave a wildcard host (or a bare "*", on some runtimes) straight into a
|
|
36
|
+
// postMessage targetOrigin. An allowlist entry is one literal origin.
|
|
37
|
+
if (trimmed.includes("*")) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`allowed origin "${trimmed}" (from ${source}) is not an absolute ` +
|
|
40
|
+
"origin — wildcards are never allowed. Each entry must be one " +
|
|
41
|
+
'literal origin, e.g. "https://play.example.com"',
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
origin = new URL(trimmed).origin;
|
|
46
|
+
} catch {
|
|
47
|
+
// fall through to the throw below with origin undefined
|
|
48
|
+
}
|
|
49
|
+
if (origin !== trimmed) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`allowed origin "${trimmed}" (from ${source}) is not an absolute ` +
|
|
52
|
+
"origin. Each entry must be scheme + host [+ port] exactly — e.g. " +
|
|
53
|
+
'"https://play.example.com" — with no path, no trailing slash, and ' +
|
|
54
|
+
'never a wildcard or "*". A malformed allowlist entry is a security ' +
|
|
55
|
+
"control failure, so it stops boot rather than being dropped",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
if (!origins.includes(origin)) origins.push(origin);
|
|
59
|
+
}
|
|
60
|
+
return origins;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Is this `returnTo` allowed to be a redirect target?
|
|
65
|
+
*
|
|
66
|
+
* The ONE rule, applied at BOTH ends of the flow: `/start` checks it before it
|
|
67
|
+
* mints a state, and `/callback` re-checks it before it redirects, because the
|
|
68
|
+
* allowlist can be edited while a signed state is in flight and the signature
|
|
69
|
+
* proves only that WE minted the value, never that it is still permitted.
|
|
70
|
+
*
|
|
71
|
+
* Fail-closed by construction: an empty allowlist allows nothing (the container
|
|
72
|
+
* warns once at boot when providers are registered with no origins), an
|
|
73
|
+
* unparseable `returnTo` is refused, and the comparison is on the parsed
|
|
74
|
+
* `origin` — never a `startsWith`, which `https://play.example.com.evil.test`
|
|
75
|
+
* walks straight through.
|
|
76
|
+
*/
|
|
77
|
+
export function isAllowedReturnTo(
|
|
78
|
+
returnTo: string,
|
|
79
|
+
allowedOrigins: readonly string[],
|
|
80
|
+
): boolean {
|
|
81
|
+
if (allowedOrigins.length === 0) return false;
|
|
82
|
+
try {
|
|
83
|
+
return allowedOrigins.includes(new URL(returnTo).origin);
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import test from "node:test";
|
|
4
|
+
import {
|
|
5
|
+
type AccountLinkPkceRedis,
|
|
6
|
+
generatePkcePair,
|
|
7
|
+
storePkceVerifier,
|
|
8
|
+
takePkceVerifier,
|
|
9
|
+
} from "./account-link-pkce.js";
|
|
10
|
+
|
|
11
|
+
/** A fake with real `SET NX EX` / `GETDEL` semantics — the two that matter. */
|
|
12
|
+
function fakeRedis(): AccountLinkPkceRedis & { store: Map<string, string> } {
|
|
13
|
+
const store = new Map<string, string>();
|
|
14
|
+
return {
|
|
15
|
+
store,
|
|
16
|
+
async set(key, value, _ex, _ttl, _nx) {
|
|
17
|
+
if (store.has(key)) return null;
|
|
18
|
+
store.set(key, value);
|
|
19
|
+
return "OK";
|
|
20
|
+
},
|
|
21
|
+
async getdel(key) {
|
|
22
|
+
const value = store.get(key) ?? null;
|
|
23
|
+
store.delete(key);
|
|
24
|
+
return value;
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
test("the challenge is the base64url SHA-256 of the verifier", () => {
|
|
30
|
+
const { verifier, challenge } = generatePkcePair();
|
|
31
|
+
assert.equal(
|
|
32
|
+
challenge,
|
|
33
|
+
createHash("sha256").update(verifier).digest("base64url"),
|
|
34
|
+
);
|
|
35
|
+
// base64url only — a `+`, `/` or `=` breaks the authorize URL.
|
|
36
|
+
assert.match(challenge, /^[A-Za-z0-9_-]+$/);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("the verifier length is within RFC 7636 bounds", () => {
|
|
40
|
+
for (let i = 0; i < 25; i++) {
|
|
41
|
+
const { verifier } = generatePkcePair();
|
|
42
|
+
assert.ok(
|
|
43
|
+
verifier.length >= 43 && verifier.length <= 128,
|
|
44
|
+
`verifier length ${verifier.length} is outside RFC 7636's 43..128`,
|
|
45
|
+
);
|
|
46
|
+
// RFC 7636 unreserved charset.
|
|
47
|
+
assert.match(verifier, /^[A-Za-z0-9._~-]+$/);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("two pairs are never the same", () => {
|
|
52
|
+
const seen = new Set<string>();
|
|
53
|
+
for (let i = 0; i < 50; i++) seen.add(generatePkcePair().verifier);
|
|
54
|
+
assert.equal(seen.size, 50);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("takePkceVerifier returns the verifier once and null thereafter", async () => {
|
|
58
|
+
const redis = fakeRedis();
|
|
59
|
+
assert.equal(
|
|
60
|
+
await storePkceVerifier("nonce-1", "verifier-1", 900, redis),
|
|
61
|
+
true,
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
assert.equal(await takePkceVerifier("nonce-1", redis), "verifier-1");
|
|
65
|
+
// GETDEL, not GET: single-use even if the nonce burn were somehow bypassed.
|
|
66
|
+
assert.equal(await takePkceVerifier("nonce-1", redis), null);
|
|
67
|
+
assert.equal(redis.store.size, 0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("takePkceVerifier returns null for an unknown nonce", async () => {
|
|
71
|
+
assert.equal(await takePkceVerifier("never-stored", fakeRedis()), null);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("storePkceVerifier refuses to overwrite an existing nonce", async () => {
|
|
75
|
+
const redis = fakeRedis();
|
|
76
|
+
assert.equal(await storePkceVerifier("nonce-2", "first", 900, redis), true);
|
|
77
|
+
assert.equal(await storePkceVerifier("nonce-2", "second", 900, redis), false);
|
|
78
|
+
// The original custody is intact — a collision never silently rebinds it.
|
|
79
|
+
assert.equal(await takePkceVerifier("nonce-2", redis), "first");
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("a null redis stores nothing and takes nothing (fail closed)", async () => {
|
|
83
|
+
assert.equal(await storePkceVerifier("nonce-3", "v", 900, null), false);
|
|
84
|
+
assert.equal(await takePkceVerifier("nonce-3", null), null);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("the key is namespaced per nonce", async () => {
|
|
88
|
+
const redis = fakeRedis();
|
|
89
|
+
await storePkceVerifier("abc", "v", 900, redis);
|
|
90
|
+
assert.deepEqual([...redis.store.keys()], ["account_link:pkce:abc"]);
|
|
91
|
+
});
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { getRedisIfConnected } from "./redis.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* PKCE custody for the hosted account-link flow (RFC 7636, S256 only).
|
|
6
|
+
*
|
|
7
|
+
* The verifier NEVER travels: not in the signed state, not in the redirect
|
|
8
|
+
* URL, not in a log line. It lives in Redis for the life of one attempt, keyed
|
|
9
|
+
* by that attempt's nonce, and is consumed with `GETDEL` so it is single-use
|
|
10
|
+
* even if the nonce burn were somehow bypassed. Only the S256 CHALLENGE goes
|
|
11
|
+
* out on the authorize URL, which is the entire point of PKCE: an intercepted
|
|
12
|
+
* authorization code is worthless without the verifier the interceptor never
|
|
13
|
+
* saw.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** The slice of ioredis this module uses; narrowed so a test can inject a fake. */
|
|
17
|
+
export interface AccountLinkPkceRedis {
|
|
18
|
+
set(
|
|
19
|
+
key: string,
|
|
20
|
+
value: string,
|
|
21
|
+
ex: "EX",
|
|
22
|
+
ttlSeconds: number,
|
|
23
|
+
nx: "NX",
|
|
24
|
+
): Promise<string | null>;
|
|
25
|
+
getdel(key: string): Promise<string | null>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const KEY_PREFIX = "account_link:pkce:";
|
|
29
|
+
|
|
30
|
+
function pkceKey(nonce: string): string {
|
|
31
|
+
return `${KEY_PREFIX}${nonce}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function resolveRedis(
|
|
35
|
+
redis: AccountLinkPkceRedis | null | undefined,
|
|
36
|
+
): AccountLinkPkceRedis | null {
|
|
37
|
+
// `undefined` = "not injected" → the process client. Explicit `null` is the
|
|
38
|
+
// fail-closed arm and must never fall through to a lazy connect.
|
|
39
|
+
return redis === undefined ? (getRedisIfConnected() ?? null) : redis;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A fresh verifier + its S256 challenge.
|
|
44
|
+
*
|
|
45
|
+
* 32 random bytes → 43 base64url chars, the RFC 7636 MINIMUM length, which is
|
|
46
|
+
* also the maximum entropy the spec's 43..128 range can carry from a 256-bit
|
|
47
|
+
* source. base64url's alphabet is a subset of the spec's `unreserved`
|
|
48
|
+
* production, so the value needs no further encoding anywhere it appears.
|
|
49
|
+
*/
|
|
50
|
+
export function generatePkcePair(): { verifier: string; challenge: string } {
|
|
51
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
52
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
53
|
+
return { verifier, challenge };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Take custody of a verifier for one attempt. `SET NX` — returns FALSE when the
|
|
58
|
+
* nonce is already claimed rather than rebinding it, so a nonce collision (or a
|
|
59
|
+
* replayed `/start`) can never silently swap the verifier out from under a live
|
|
60
|
+
* attempt. `/start` treats `false` as a 500.
|
|
61
|
+
*
|
|
62
|
+
* Returns false on a Redis fault too: fail closed, never a PKCE-less flow.
|
|
63
|
+
*/
|
|
64
|
+
export async function storePkceVerifier(
|
|
65
|
+
nonce: string,
|
|
66
|
+
verifier: string,
|
|
67
|
+
ttlSeconds: number,
|
|
68
|
+
redis?: AccountLinkPkceRedis | null,
|
|
69
|
+
): Promise<boolean> {
|
|
70
|
+
const client = resolveRedis(redis);
|
|
71
|
+
if (!client) return false;
|
|
72
|
+
try {
|
|
73
|
+
const claimed = await client.set(
|
|
74
|
+
pkceKey(nonce),
|
|
75
|
+
verifier,
|
|
76
|
+
"EX",
|
|
77
|
+
ttlSeconds,
|
|
78
|
+
"NX",
|
|
79
|
+
);
|
|
80
|
+
return claimed === "OK";
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Consume the verifier for one attempt. `GETDEL` (Redis >= 6.2) so the read and
|
|
88
|
+
* the delete are one atomic step — a `GET` then `DEL` leaves a window in which
|
|
89
|
+
* two concurrent callbacks both read the same verifier.
|
|
90
|
+
*
|
|
91
|
+
* `null` means "no verifier for this nonce", which the callback treats as a
|
|
92
|
+
* rejection: a PKCE provider whose verifier is gone cannot complete an exchange
|
|
93
|
+
* that proves anything.
|
|
94
|
+
*/
|
|
95
|
+
export async function takePkceVerifier(
|
|
96
|
+
nonce: string,
|
|
97
|
+
redis?: AccountLinkPkceRedis | null,
|
|
98
|
+
): Promise<string | null> {
|
|
99
|
+
const client = resolveRedis(redis);
|
|
100
|
+
if (!client) return null;
|
|
101
|
+
try {
|
|
102
|
+
return await client.getdel(pkceKey(nonce));
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import type { AccountLinkProvider } from "@hogsend/core";
|
|
4
|
+
import { AccountLinkProviderRegistry } from "./account-link-provider-registry.js";
|
|
5
|
+
|
|
6
|
+
// Hand-built stubs on purpose (the PRD 05 "Seams" note): the registry cares
|
|
7
|
+
// only about `meta.id`, so a minimal object exercises it end to end without
|
|
8
|
+
// touching defineAccountLink's authoring guards (tested in @hogsend/core).
|
|
9
|
+
function stubProvider(id: string, name = id): AccountLinkProvider {
|
|
10
|
+
return {
|
|
11
|
+
meta: { id, name },
|
|
12
|
+
authorizeUrl: () => `https://example.com/authorize?provider=${id}`,
|
|
13
|
+
handleCallback: async () => ({ providerUserId: `${id}-user` }),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
test("register replaces a provider of the same id (last-writer-wins)", () => {
|
|
18
|
+
const first = stubProvider("steam", "first");
|
|
19
|
+
const second = stubProvider("steam", "second");
|
|
20
|
+
const registry = new AccountLinkProviderRegistry([first, second]);
|
|
21
|
+
assert.equal(registry.count(), 1);
|
|
22
|
+
assert.equal(registry.get("steam"), second);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("get returns undefined for an unknown id", () => {
|
|
26
|
+
const registry = new AccountLinkProviderRegistry([stubProvider("steam")]);
|
|
27
|
+
assert.equal(registry.get("twitch"), undefined);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test("register throws on a provider with no meta.id", () => {
|
|
31
|
+
const registry = new AccountLinkProviderRegistry();
|
|
32
|
+
const noMeta = { ...stubProvider("x"), meta: undefined };
|
|
33
|
+
const emptyId = stubProvider("");
|
|
34
|
+
assert.throws(
|
|
35
|
+
() => registry.register(noMeta as unknown as AccountLinkProvider),
|
|
36
|
+
TypeError,
|
|
37
|
+
);
|
|
38
|
+
assert.throws(() => registry.register(emptyId), TypeError);
|
|
39
|
+
assert.equal(registry.count(), 0);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("getAll preserves insertion order of distinct ids", () => {
|
|
43
|
+
const steam = stubProvider("steam");
|
|
44
|
+
const twitch = stubProvider("twitch");
|
|
45
|
+
const custom = stubProvider("battlenet");
|
|
46
|
+
const registry = new AccountLinkProviderRegistry([steam, twitch, custom]);
|
|
47
|
+
assert.deepEqual(
|
|
48
|
+
registry.getAll().map((p) => p.meta.id),
|
|
49
|
+
["steam", "twitch", "battlenet"],
|
|
50
|
+
);
|
|
51
|
+
assert.deepEqual(registry.ids(), ["steam", "twitch", "battlenet"]);
|
|
52
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { AccountLinkProvider } from "@hogsend/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Container-held registry of account-link providers, keyed by
|
|
5
|
+
* `provider.meta.id` — a direct structural mirror of the
|
|
6
|
+
* {@link EmailProviderRegistry} (`lib/email-provider-registry.ts`). The hosted
|
|
7
|
+
* flow routes (`/v1/accounts/:provider/start` + `/callback`, PRD 07), the data
|
|
8
|
+
* plane (PRD 09) and the property-sync cron (PRD 14) all resolve providers out
|
|
9
|
+
* of this via the container.
|
|
10
|
+
*
|
|
11
|
+
* Deliberately NOT a process singleton, for the same reason spelled out on the
|
|
12
|
+
* email registry: every reader holds a container reference, so a singleton +
|
|
13
|
+
* lazy-preset fallback would be dead weight.
|
|
14
|
+
*
|
|
15
|
+
* Divergence from the email registry: `meta.id` is REQUIRED here. The email
|
|
16
|
+
* registry falls back to `"resend"` for providers built before `meta` existed;
|
|
17
|
+
* this contract is new and has no pre-`meta` era, so an empty/absent id is a
|
|
18
|
+
* `TypeError` rather than a silent default. It does NOT re-validate
|
|
19
|
+
* `ACCOUNT_LINK_ID_RE` / `RESERVED_ACCOUNT_LINK_IDS` — `defineAccountLink()`
|
|
20
|
+
* already throws on both at definition time, and a second copy of that rule is
|
|
21
|
+
* a second place to update.
|
|
22
|
+
*
|
|
23
|
+
* Last-writer-wins on `meta.id`, so a consumer-supplied provider of the same id
|
|
24
|
+
* overrides an env preset of that id (env presets are constructed first).
|
|
25
|
+
*/
|
|
26
|
+
export class AccountLinkProviderRegistry {
|
|
27
|
+
private byId = new Map<string, AccountLinkProvider>();
|
|
28
|
+
|
|
29
|
+
constructor(providers: AccountLinkProvider[] = []) {
|
|
30
|
+
for (const provider of providers) this.register(provider);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Register (or replace) a provider. Last-writer-wins on `meta.id`. */
|
|
34
|
+
register(provider: AccountLinkProvider): void {
|
|
35
|
+
const id = provider.meta?.id;
|
|
36
|
+
if (!id) {
|
|
37
|
+
throw new TypeError(
|
|
38
|
+
"account link provider has no meta.id — the id keys the registry " +
|
|
39
|
+
"and is the `:provider` route segment, so it is required " +
|
|
40
|
+
"(author providers with defineAccountLink, which enforces it)",
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
this.byId.set(id, provider);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
get(id: string): AccountLinkProvider | undefined {
|
|
47
|
+
return this.byId.get(id);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
getAll(): AccountLinkProvider[] {
|
|
51
|
+
return [...this.byId.values()];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
ids(): string[] {
|
|
55
|
+
return [...this.byId.keys()];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
count(): number {
|
|
59
|
+
return this.byId.size;
|
|
60
|
+
}
|
|
61
|
+
}
|