@hogsend/engine 0.64.0 → 0.66.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/battlenet.ts +84 -0
- package/src/account-links/epic.ts +87 -0
- package/src/account-links/index.ts +15 -0
- package/src/account-links/riot.ts +82 -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/account-links/xbox.ts +92 -0
- package/src/app.ts +9 -1
- 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 +53 -0
- package/src/index.ts +93 -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 +190 -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 +342 -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/snippet.ts +76 -0
- 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 +81 -0
- package/src/routes/snippet.test.ts +70 -0
- package/src/routes/snippet.ts +58 -0
- package/src/testing-barrel.test.ts +74 -0
- package/src/testing.ts +17 -0
- package/src/workflows/import-contacts.ts +6 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import {
|
|
4
|
+
type AccountLinkThrottleRedis,
|
|
5
|
+
checkAccountLinkThrottle,
|
|
6
|
+
} from "./account-link-throttle.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* PRD 07 T3. The fake redis is the whole point: this throttle is FAIL-CLOSED
|
|
10
|
+
* (DECISIONS §6.8), which is the opposite of the connector callback's
|
|
11
|
+
* degrade-to-TTL posture, so the "no redis" arm must be exercised directly.
|
|
12
|
+
*/
|
|
13
|
+
function fakeRedis(opts: { throwOnIncr?: boolean } = {}): {
|
|
14
|
+
redis: AccountLinkThrottleRedis;
|
|
15
|
+
counts: Map<string, number>;
|
|
16
|
+
expires: Array<{ key: string; seconds: number }>;
|
|
17
|
+
} {
|
|
18
|
+
const counts = new Map<string, number>();
|
|
19
|
+
const expires: Array<{ key: string; seconds: number }> = [];
|
|
20
|
+
return {
|
|
21
|
+
counts,
|
|
22
|
+
expires,
|
|
23
|
+
redis: {
|
|
24
|
+
async incr(key) {
|
|
25
|
+
if (opts.throwOnIncr) throw new Error("connection lost");
|
|
26
|
+
const next = (counts.get(key) ?? 0) + 1;
|
|
27
|
+
counts.set(key, next);
|
|
28
|
+
return next;
|
|
29
|
+
},
|
|
30
|
+
async expire(key, seconds) {
|
|
31
|
+
expires.push({ key, seconds });
|
|
32
|
+
return 1;
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("allows under the cap", async () => {
|
|
39
|
+
const { redis } = fakeRedis();
|
|
40
|
+
for (let i = 0; i < 20; i++) {
|
|
41
|
+
const result = await checkAccountLinkThrottle({
|
|
42
|
+
surface: "start",
|
|
43
|
+
ip: "203.0.113.7",
|
|
44
|
+
redis,
|
|
45
|
+
});
|
|
46
|
+
assert.deepEqual(result, { ok: true }, `attempt ${i + 1} should pass`);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("rejects over the cap with rate_limited", async () => {
|
|
51
|
+
const { redis } = fakeRedis();
|
|
52
|
+
for (let i = 0; i < 20; i++) {
|
|
53
|
+
await checkAccountLinkThrottle({
|
|
54
|
+
surface: "callback",
|
|
55
|
+
ip: "203.0.113.8",
|
|
56
|
+
redis,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const result = await checkAccountLinkThrottle({
|
|
60
|
+
surface: "callback",
|
|
61
|
+
ip: "203.0.113.8",
|
|
62
|
+
redis,
|
|
63
|
+
});
|
|
64
|
+
assert.deepEqual(result, { ok: false, reason: "rate_limited" });
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("rejects with redis_unavailable when redis is null", async () => {
|
|
68
|
+
// FAIL-CLOSED. A replayed account link can MOVE a platform account between
|
|
69
|
+
// contacts, so a cache miss must never wave one through.
|
|
70
|
+
const result = await checkAccountLinkThrottle({
|
|
71
|
+
surface: "start",
|
|
72
|
+
ip: "203.0.113.9",
|
|
73
|
+
redis: null,
|
|
74
|
+
});
|
|
75
|
+
assert.deepEqual(result, { ok: false, reason: "redis_unavailable" });
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("rejects with redis_unavailable when redis throws", async () => {
|
|
79
|
+
const { redis } = fakeRedis({ throwOnIncr: true });
|
|
80
|
+
const result = await checkAccountLinkThrottle({
|
|
81
|
+
surface: "start",
|
|
82
|
+
ip: "203.0.113.10",
|
|
83
|
+
redis,
|
|
84
|
+
});
|
|
85
|
+
assert.deepEqual(result, { ok: false, reason: "redis_unavailable" });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("sets the TTL exactly once, on the first increment", async () => {
|
|
89
|
+
const { redis, expires } = fakeRedis();
|
|
90
|
+
for (let i = 0; i < 5; i++) {
|
|
91
|
+
await checkAccountLinkThrottle({
|
|
92
|
+
surface: "start",
|
|
93
|
+
ip: "203.0.113.11",
|
|
94
|
+
redis,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
assert.deepEqual(expires, [
|
|
98
|
+
{ key: "hogsend:al:throttle:start:203.0.113.11", seconds: 900 },
|
|
99
|
+
]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("the warm path adds a per-contact budget on its own key", async () => {
|
|
103
|
+
const { redis, counts } = fakeRedis();
|
|
104
|
+
await checkAccountLinkThrottle({
|
|
105
|
+
surface: "start",
|
|
106
|
+
ip: "203.0.113.12",
|
|
107
|
+
contactId: "c-1",
|
|
108
|
+
redis,
|
|
109
|
+
});
|
|
110
|
+
assert.equal(counts.get("hogsend:al:throttle:start:203.0.113.12"), 1);
|
|
111
|
+
assert.equal(counts.get("hogsend:al:throttle:contact:c-1"), 1);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("a per-contact budget over the cap rejects even from a fresh IP", async () => {
|
|
115
|
+
const { redis } = fakeRedis();
|
|
116
|
+
for (let i = 0; i < 20; i++) {
|
|
117
|
+
await checkAccountLinkThrottle({
|
|
118
|
+
surface: "start",
|
|
119
|
+
ip: `198.51.100.${i}`,
|
|
120
|
+
contactId: "c-hot",
|
|
121
|
+
redis,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const result = await checkAccountLinkThrottle({
|
|
125
|
+
surface: "start",
|
|
126
|
+
ip: "198.51.100.200",
|
|
127
|
+
contactId: "c-hot",
|
|
128
|
+
redis,
|
|
129
|
+
});
|
|
130
|
+
assert.deepEqual(result, { ok: false, reason: "rate_limited" });
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("a contact-only call bumps the contact budget and no IP budget", async () => {
|
|
134
|
+
// `/start` calls this shape for the WARM leg, after the binding is known —
|
|
135
|
+
// re-passing the IP would double-count it against its own budget.
|
|
136
|
+
const { redis, counts } = fakeRedis();
|
|
137
|
+
const result = await checkAccountLinkThrottle({
|
|
138
|
+
surface: "start",
|
|
139
|
+
contactId: "c-2",
|
|
140
|
+
redis,
|
|
141
|
+
});
|
|
142
|
+
assert.deepEqual(result, { ok: true });
|
|
143
|
+
assert.deepEqual([...counts.keys()], ["hogsend:al:throttle:contact:c-2"]);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("start and callback hold separate budgets", async () => {
|
|
147
|
+
const { redis, counts } = fakeRedis();
|
|
148
|
+
await checkAccountLinkThrottle({ surface: "start", ip: "1.2.3.4", redis });
|
|
149
|
+
await checkAccountLinkThrottle({ surface: "callback", ip: "1.2.3.4", redis });
|
|
150
|
+
assert.equal(counts.get("hogsend:al:throttle:start:1.2.3.4"), 1);
|
|
151
|
+
assert.equal(counts.get("hogsend:al:throttle:cb:1.2.3.4"), 1);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("config overrides the window and the cap", async () => {
|
|
155
|
+
const { redis, expires } = fakeRedis();
|
|
156
|
+
const config = { windowSeconds: 60, max: 1 };
|
|
157
|
+
assert.deepEqual(
|
|
158
|
+
await checkAccountLinkThrottle({
|
|
159
|
+
surface: "start",
|
|
160
|
+
ip: "5.6.7.8",
|
|
161
|
+
config,
|
|
162
|
+
redis,
|
|
163
|
+
}),
|
|
164
|
+
{ ok: true },
|
|
165
|
+
);
|
|
166
|
+
assert.deepEqual(
|
|
167
|
+
await checkAccountLinkThrottle({
|
|
168
|
+
surface: "start",
|
|
169
|
+
ip: "5.6.7.8",
|
|
170
|
+
config,
|
|
171
|
+
redis,
|
|
172
|
+
}),
|
|
173
|
+
{ ok: false, reason: "rate_limited" },
|
|
174
|
+
);
|
|
175
|
+
assert.deepEqual(expires, [
|
|
176
|
+
{ key: "hogsend:al:throttle:start:5.6.7.8", seconds: 60 },
|
|
177
|
+
]);
|
|
178
|
+
});
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { getRedisIfConnected } from "./redis.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The public account-link surfaces (`/v1/accounts/:provider/start` and
|
|
5
|
+
* `/callback`) are UNAUTHENTICATED by construction — a browser redirect target
|
|
6
|
+
* carries no `Authorization` header — so they are throttled per IP, and the
|
|
7
|
+
* warm mint is additionally throttled per contact.
|
|
8
|
+
*
|
|
9
|
+
* FAIL-CLOSED (DECISIONS §6.8), which is a DELIBERATE divergence from the
|
|
10
|
+
* connector callback next door: that one degrades to TTL-only validity when
|
|
11
|
+
* Redis is absent on the stated principle that it will "never block a callback
|
|
12
|
+
* on a cache miss" (`routes/connectors/index.ts:134-136`). The threat is not
|
|
13
|
+
* the same. A replayed connector install re-captures a guild id; a replayed
|
|
14
|
+
* account-link callback can MOVE a platform account between contacts
|
|
15
|
+
* (DECISIONS §6.1). PKCE verifier custody also lives in Redis, so for the
|
|
16
|
+
* OAuth2 providers Redis is structurally required regardless. Do not "fix" this
|
|
17
|
+
* into the connector posture.
|
|
18
|
+
*
|
|
19
|
+
* Modelled on `cold-connect/throttle.ts` — the same fixed-window `INCR` + set
|
|
20
|
+
* the TTL on the FIRST increment idiom.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The slice of ioredis this module uses. Narrowed so a test can inject a fake
|
|
25
|
+
* (and so `null` — the fail-closed arm — is expressible), the same seam
|
|
26
|
+
* `lib/leader-lease.ts` uses for its `redis` argument.
|
|
27
|
+
*/
|
|
28
|
+
export interface AccountLinkThrottleRedis {
|
|
29
|
+
incr(key: string): Promise<number>;
|
|
30
|
+
expire(key: string, seconds: number): Promise<unknown>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ThrottleResult =
|
|
34
|
+
| { ok: true }
|
|
35
|
+
| { ok: false; reason: "rate_limited" | "redis_unavailable" };
|
|
36
|
+
|
|
37
|
+
const DEFAULT_WINDOW_SECONDS = 900;
|
|
38
|
+
const DEFAULT_MAX = 20;
|
|
39
|
+
|
|
40
|
+
/** The key namespaces, one per budget. `cb` keeps the key short and readable. */
|
|
41
|
+
const SURFACE_KEY = { start: "start", callback: "cb" } as const;
|
|
42
|
+
|
|
43
|
+
interface AccountLinkThrottleBase {
|
|
44
|
+
surface: "start" | "callback";
|
|
45
|
+
config?: { windowSeconds?: number; max?: number };
|
|
46
|
+
/**
|
|
47
|
+
* TEST SEAM (and the fail-closed arm). Defaults to
|
|
48
|
+
* {@link getRedisIfConnected}, NOT `getRedis()`: the account-link routes
|
|
49
|
+
* refuse to serve at all without a connected Redis, so this must never be the
|
|
50
|
+
* thing that lazily opens a connection and papers over that.
|
|
51
|
+
*/
|
|
52
|
+
redis?: AccountLinkThrottleRedis | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* At least ONE budget must be named, enforced by the union rather than by a
|
|
57
|
+
* runtime check — a call that names no budget would silently allow everything.
|
|
58
|
+
*
|
|
59
|
+
* `/start` calls this TWICE and that is deliberate: once on the IP alone,
|
|
60
|
+
* BEFORE anything is minted (the order of operations puts the throttle ahead of
|
|
61
|
+
* the binding resolution), and once on the sealed `contactId` alone once the
|
|
62
|
+
* WARM binding is known. One call cannot do both, because the contact is not
|
|
63
|
+
* known at the point the IP budget has to bite, and re-passing the IP on the
|
|
64
|
+
* second call would double-count every warm request against its own budget.
|
|
65
|
+
*/
|
|
66
|
+
export type AccountLinkThrottleArgs = AccountLinkThrottleBase &
|
|
67
|
+
(
|
|
68
|
+
| {
|
|
69
|
+
/** Best-effort client IP; `"unknown"` shares ONE bounded bucket, never bypasses. */
|
|
70
|
+
ip: string;
|
|
71
|
+
contactId?: string;
|
|
72
|
+
}
|
|
73
|
+
| {
|
|
74
|
+
ip?: undefined;
|
|
75
|
+
/** WARM only — the sealed contact gets its own budget across IPs. */
|
|
76
|
+
contactId: string;
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* One fixed-window counter. `INCR`, then set the TTL on the FIRST increment
|
|
82
|
+
* only so the window slides forward rather than being extended by traffic. A
|
|
83
|
+
* missing client throws so the caller fails CLOSED.
|
|
84
|
+
*/
|
|
85
|
+
async function bump(
|
|
86
|
+
redis: AccountLinkThrottleRedis | null | undefined,
|
|
87
|
+
key: string,
|
|
88
|
+
windowSeconds: number,
|
|
89
|
+
): Promise<number> {
|
|
90
|
+
if (!redis) throw new Error("redis_unavailable");
|
|
91
|
+
const count = await redis.incr(key);
|
|
92
|
+
if (count === 1) await redis.expire(key, windowSeconds);
|
|
93
|
+
return count;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Bump every budget this call owns and reject when ANY is over its cap. Both
|
|
98
|
+
* budgets are bumped even when the first is already over: a fixed-window
|
|
99
|
+
* counter that stops counting under attack is a counter that reopens early.
|
|
100
|
+
*/
|
|
101
|
+
export async function checkAccountLinkThrottle(
|
|
102
|
+
args: AccountLinkThrottleArgs,
|
|
103
|
+
): Promise<ThrottleResult> {
|
|
104
|
+
const windowSeconds = args.config?.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
|
|
105
|
+
const max = args.config?.max ?? DEFAULT_MAX;
|
|
106
|
+
const redis = args.redis === undefined ? getRedisIfConnected() : args.redis;
|
|
107
|
+
|
|
108
|
+
const keys = [
|
|
109
|
+
...(args.ip
|
|
110
|
+
? [`hogsend:al:throttle:${SURFACE_KEY[args.surface]}:${args.ip}`]
|
|
111
|
+
: []),
|
|
112
|
+
...(args.contactId
|
|
113
|
+
? [`hogsend:al:throttle:contact:${args.contactId}`]
|
|
114
|
+
: []),
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const counts = await Promise.all(
|
|
119
|
+
keys.map((key) => bump(redis, key, windowSeconds)),
|
|
120
|
+
);
|
|
121
|
+
if (counts.some((count) => count > max)) {
|
|
122
|
+
return { ok: false, reason: "rate_limited" };
|
|
123
|
+
}
|
|
124
|
+
return { ok: true };
|
|
125
|
+
} catch {
|
|
126
|
+
// Any Redis fault — absent client, connection loss, command error — is a
|
|
127
|
+
// refusal, never a bypass.
|
|
128
|
+
return { ok: false, reason: "redis_unavailable" };
|
|
129
|
+
}
|
|
130
|
+
}
|