create-ailk 0.35.1 → 0.37.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/README.md +1 -1
- package/component-catalog.json +51 -1
- package/component-catalog.md +8 -5
- package/dist/lib/env-catalog.js +8 -0
- package/dist/surfaces.js +66 -22
- package/dist/topology.d.ts +4 -4
- package/dist/topology.js +104 -60
- package/dist/update.d.ts +19 -1
- package/dist/update.js +293 -35
- package/package.json +3 -3
- package/templates/.env.example +38 -0
- package/templates/apps/api/.env.example +45 -0
- package/templates/apps/api/CLAUDE.md +12 -4
- package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -0
- package/templates/apps/mcp/CLAUDE.md +4 -2
- package/templates/apps/web/.env.example +16 -0
- package/templates/apps/web/CLAUDE.md +73 -5
- package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
- package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +179 -0
- package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +22 -2
- package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +9 -2
- package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
- package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
- package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
- package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
- package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
- package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
- package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
- package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +241 -66
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +242 -28
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +377 -151
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +26 -1
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +17 -6
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +51 -12
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +17 -2
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +153 -2
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +206 -23
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +150 -188
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +235 -177
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +63 -0
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -3
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +340 -0
- package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +7 -5
- package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +20 -4
- package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -4
- package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +161 -0
- package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +426 -0
- package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +76 -0
- package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +139 -0
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +92 -24
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +32 -1
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +76 -3
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +290 -41
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +109 -11
- package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +43 -44
- package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +99 -0
- package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +123 -0
- package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +323 -73
- package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +199 -43
- package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +52 -7
- package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
- package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
- package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +36 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +70 -2
- package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +42 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +97 -53
- package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +215 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +73 -0
- package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +12 -9
- package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +18 -4
- package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +20 -2
- package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +43 -0
- package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +125 -0
- package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +88 -0
- package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +31 -0
- package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
- package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
- package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
- package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
- package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
- package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +9 -6
- package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +33 -8
- package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +31 -52
- package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +44 -4
- package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +69 -49
- package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +173 -0
- package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +42 -4
- package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +102 -0
- package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +147 -137
- package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +258 -0
- package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +21 -22
- package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +34 -6
- package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +37 -7
- package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
- package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +8 -5
- package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
- package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +3 -2
- package/templates/apps/web/app/[locale]/layout.tsx +24 -75
- package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
- package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
- package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
- package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
- package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
- package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
- package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
- package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
- package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +86 -0
- package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +368 -0
- package/templates/apps/web/app/api/auth/hub/password/return.ts +86 -0
- package/templates/apps/web/app/api/auth/hub/password/route.ts +171 -0
- package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
- package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
- package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
- package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
- package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +738 -7
- package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
- package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
- package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
- package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
- package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
- package/templates/apps/web/app/api/hub-session/password/return/route.ts +69 -0
- package/templates/apps/web/app/api/hub-session/password/route.ts +106 -0
- package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
- package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
- package/templates/apps/web/auth.ts +133 -6
- package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
- package/templates/apps/web/lib/__tests__/account-config.test.ts +129 -1
- package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
- package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
- package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
- package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
- package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +33 -0
- package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
- package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
- package/templates/apps/web/lib/account-config.ts +132 -8
- package/templates/apps/web/lib/auth-email.ts +62 -6
- package/templates/apps/web/lib/auth-env.ts +13 -0
- package/templates/apps/web/lib/auth-routes.ts +11 -6
- package/templates/apps/web/lib/auth-sms.ts +180 -0
- package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
- package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
- package/templates/apps/web/lib/hub-session/config.ts +7 -1
- package/templates/apps/web/lib/hub-session/entry.ts +238 -0
- package/templates/apps/web/lib/hub-session/index.ts +1 -4
- package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
- package/templates/apps/web/lib/hub-session/session.ts +120 -2
- package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
- package/templates/apps/web/lib/offerings-pricing.ts +4 -1
- package/templates/apps/web/lib/site-header.ts +14 -1
- package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
- package/templates/apps/web/lib/topology.generated.ts +39 -0
- package/templates/apps/web/messages/en.json +264 -96
- package/templates/apps/web/middleware.ts +34 -2
- package/templates/apps/web/security-headers.config.ts +21 -0
- package/versions.json +48 -48
- package/templates/apps/web/app/[locale]/(authed)/account/components/schedule-service.tsx +0 -276
- package/templates/apps/web/app/[locale]/(authed)/account/components/send-message.tsx +0 -128
- package/templates/apps/web/app/[locale]/(authed)/account/settings/__tests__/theme-modes.test.ts +0 -42
- package/templates/apps/web/app/[locale]/(authed)/account/settings/theme-modes.ts +0 -40
- package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
- package/templates/apps/web/components/signed-in-nav.tsx +0 -79
- package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
- package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the hub web's spoke-facing entry routes share (#11096 D2, D9): the
|
|
3
|
+
* JSON answer, a bounded JSON body read, the spoke's forwarded client
|
|
4
|
+
* authentication, the refused-caller limit, and the mapping of a Better Auth
|
|
5
|
+
* refusal onto the wire.
|
|
6
|
+
*
|
|
7
|
+
* Nothing here logs. The forwarded `Authorization` and spoke key go only to
|
|
8
|
+
* the hub API's entry check — never to Better Auth, a log line or an error
|
|
9
|
+
* report (SEC-11096-12).
|
|
10
|
+
*/
|
|
11
|
+
import type { HubForwardedClientAuth } from "@working-theory/api-client";
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
clientIpFromHeaders,
|
|
15
|
+
UNKNOWN_VISITOR_FACTOR,
|
|
16
|
+
} from "../../../../src/lib/rate-limit";
|
|
17
|
+
|
|
18
|
+
/** A purchase claim's life: three days to open the account (#11096 D9). */
|
|
19
|
+
export const PURCHASE_CLAIM_TTL_SECONDS = 72 * 3600;
|
|
20
|
+
|
|
21
|
+
/** The name a purchase claim is sealed under — never `hub-continue`. */
|
|
22
|
+
export const PURCHASE_CLAIM_NAME = "hub-purchase";
|
|
23
|
+
|
|
24
|
+
/** The largest body an entry route reads. */
|
|
25
|
+
export const ENTRY_BODY_MAX_BYTES = 4096;
|
|
26
|
+
|
|
27
|
+
export function json(
|
|
28
|
+
status: number,
|
|
29
|
+
body: Record<string, unknown>,
|
|
30
|
+
headers: Record<string, string> = {},
|
|
31
|
+
): Response {
|
|
32
|
+
return new Response(JSON.stringify(body), {
|
|
33
|
+
status,
|
|
34
|
+
headers: {
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
"Cache-Control": "no-store",
|
|
37
|
+
...headers,
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const refuse = (status: number, error: string): Response =>
|
|
43
|
+
json(status, { error });
|
|
44
|
+
|
|
45
|
+
/** The raw body as text, or `null` past 4 KB or on a read failure. */
|
|
46
|
+
export async function readRawBody(request: Request): Promise<string | null> {
|
|
47
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
48
|
+
if (Number.isFinite(declared) && declared > ENTRY_BODY_MAX_BYTES) return null;
|
|
49
|
+
try {
|
|
50
|
+
const text = await request.text();
|
|
51
|
+
return Buffer.byteLength(text, "utf8") > ENTRY_BODY_MAX_BYTES ? null : text;
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The parsed JSON value of `raw`, or `undefined` when it does not parse. */
|
|
58
|
+
export function parseJson(raw: string): unknown {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(raw) as unknown;
|
|
61
|
+
} catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `Basic <base64>`: the only `Authorization` shape a spoke sends. */
|
|
67
|
+
const BASIC_AUTHORIZATION = /^Basic [A-Za-z0-9+/]{4,684}={0,2}$/;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The spoke's `Authorization` and `x-ailk-spoke-key`, as received, or `null`
|
|
71
|
+
* when either is missing or the `Authorization` is not `Basic <base64>`: the
|
|
72
|
+
* hub API decides whether they are good.
|
|
73
|
+
*/
|
|
74
|
+
export function forwardedClientAuth(
|
|
75
|
+
request: Request,
|
|
76
|
+
): HubForwardedClientAuth | null {
|
|
77
|
+
const authorization = request.headers.get("authorization");
|
|
78
|
+
const spokeKey = request.headers.get("x-ailk-spoke-key");
|
|
79
|
+
if (!authorization || !spokeKey) return null;
|
|
80
|
+
if (!BASIC_AUTHORIZATION.test(authorization) || spokeKey.length > 256) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
return { authorization, spokeKey };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ── The refused-caller limit (SEC review of #11096) ─────────────────────────
|
|
87
|
+
//
|
|
88
|
+
// These routes are public, and every call that reaches the hub API arrives
|
|
89
|
+
// from this app's own egress address, which the API's per-IP limiter counts
|
|
90
|
+
// as one caller. So a caller sending credentials the API refuses could spend
|
|
91
|
+
// that budget for every spoke. The caller here is a spoke's SERVER, not a
|
|
92
|
+
// person, so a plain request cap would also cap a busy spoke's real sign-ins;
|
|
93
|
+
// what is limited instead is REFUSALS: a caller whose credentials were
|
|
94
|
+
// missing, malformed or refused by the API (401/403) ten times in ten minutes
|
|
95
|
+
// is answered 429 before any API call until the window ends. A spoke whose
|
|
96
|
+
// credentials are good never accrues one. The address is the per-visitor
|
|
97
|
+
// limiter's (`clientIpFromHeaders`); an unreadable one shares one bucket
|
|
98
|
+
// `UNKNOWN_VISITOR_FACTOR` times as wide. Per instance and best-effort, like
|
|
99
|
+
// that limiter.
|
|
100
|
+
|
|
101
|
+
const REFUSALS_PER_WINDOW = 10;
|
|
102
|
+
const REFUSAL_WINDOW_MS = 10 * 60_000;
|
|
103
|
+
const MAX_TRACKED_CALLERS = 5000;
|
|
104
|
+
|
|
105
|
+
const refusals = new Map<string, { count: number; resetAt: number }>();
|
|
106
|
+
|
|
107
|
+
/** Test seam: forget every caller's refusals. */
|
|
108
|
+
export function __resetRefusedCallers(): void {
|
|
109
|
+
refusals.clear();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function callerKey(request: Request): { key: string; limit: number } {
|
|
113
|
+
const address = clientIpFromHeaders(request.headers);
|
|
114
|
+
return address === "unknown"
|
|
115
|
+
? { key: "unknown", limit: UNKNOWN_VISITOR_FACTOR * REFUSALS_PER_WINDOW }
|
|
116
|
+
: { key: address, limit: REFUSALS_PER_WINDOW };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A 429 when this caller has used up its refusals, else `null`. Counts nothing. */
|
|
120
|
+
export function refusedCallerLimit(request: Request): Response | null {
|
|
121
|
+
const { key, limit } = callerKey(request);
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
const entry = refusals.get(key);
|
|
124
|
+
if (!entry || entry.resetAt <= now || entry.count < limit) return null;
|
|
125
|
+
return json(
|
|
126
|
+
429,
|
|
127
|
+
{ error: "rate_limited" },
|
|
128
|
+
{ "Retry-After": String(Math.max(1, Math.ceil((entry.resetAt - now) / 1000))) },
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Count one refusal against this caller. */
|
|
133
|
+
export function noteRefusedCaller(request: Request): void {
|
|
134
|
+
const { key } = callerKey(request);
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const entry = refusals.get(key);
|
|
137
|
+
if (entry && entry.resetAt > now) {
|
|
138
|
+
entry.count += 1;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (refusals.size >= MAX_TRACKED_CALLERS) {
|
|
142
|
+
for (const [k, v] of refusals) if (v.resetAt <= now) refusals.delete(k);
|
|
143
|
+
const oldest = refusals.keys().next().value;
|
|
144
|
+
if (refusals.size >= MAX_TRACKED_CALLERS && oldest !== undefined) {
|
|
145
|
+
refusals.delete(oldest);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
refusals.set(key, { count: 1, resetAt: now + REFUSAL_WINDOW_MS });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The `error.code` of a refused api-client call, or `fallback`. */
|
|
152
|
+
export function apiErrorCode(body: unknown, fallback: string): string {
|
|
153
|
+
const code = (body as { error?: { code?: unknown } } | null)?.error?.code;
|
|
154
|
+
return typeof code === "string" && /^[a-z_]{1,64}$/.test(code)
|
|
155
|
+
? code
|
|
156
|
+
: fallback;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The `code` a Better Auth `APIError` carries, or `null`. */
|
|
160
|
+
export function betterAuthCode(err: unknown): string | null {
|
|
161
|
+
const code = (err as { body?: { code?: unknown } } | null)?.body?.code;
|
|
162
|
+
return typeof code === "string" ? code : null;
|
|
163
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @jest-environment node
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The sealed return a spoke's password link carries (#11162 AC-2): it opens
|
|
7
|
+
* only to the registered origin plus the Security path it was minted from,
|
|
8
|
+
* under its own name, within its life.
|
|
9
|
+
*/
|
|
10
|
+
import { mintContinuation } from "../../continuation";
|
|
11
|
+
import {
|
|
12
|
+
SECURITY_RETURN_NAME,
|
|
13
|
+
SECURITY_RETURN_TTL_SECONDS,
|
|
14
|
+
SPOKE_RETURN_PATH,
|
|
15
|
+
mintSecurityReturn,
|
|
16
|
+
openSecurityReturn,
|
|
17
|
+
} from "../return";
|
|
18
|
+
|
|
19
|
+
const SECRET = "k".repeat(43);
|
|
20
|
+
const SPOKE = "https://spoke.example";
|
|
21
|
+
|
|
22
|
+
/** Where a ref for `origin` + `path` lands: the spoke's return route, the tab as `next`. */
|
|
23
|
+
function landing(origin: string, path: string): string {
|
|
24
|
+
return `${origin}${SPOKE_RETURN_PATH}?next=${encodeURIComponent(path)}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("mintSecurityReturn / openSecurityReturn", () => {
|
|
28
|
+
it("round-trips the origin and the Security path as the spoke's return route with the tab as next", () => {
|
|
29
|
+
const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET);
|
|
30
|
+
expect(ref).toMatch(/^[A-Za-z0-9_-]+$/);
|
|
31
|
+
expect(openSecurityReturn(ref, SECRET)).toBe(landing(SPOKE, "/account/security"));
|
|
32
|
+
expect(SPOKE_RETURN_PATH).toBe("/api/hub-session/password/return");
|
|
33
|
+
expect(openSecurityReturn(mintSecurityReturn(SPOKE, "/fr/account/security", SECRET), SECRET)).toBe(
|
|
34
|
+
landing(SPOKE, "/fr/account/security"),
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("opens a loopback http origin, for a local spoke", () => {
|
|
39
|
+
const ref = mintSecurityReturn("http://127.0.0.1:3100", "/account/security", SECRET);
|
|
40
|
+
expect(openSecurityReturn(ref, SECRET)).toBe(landing("http://127.0.0.1:3100", "/account/security"));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("outlives the hour-long link, and no more than ten minutes past it", () => {
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET, now);
|
|
46
|
+
expect(SECURITY_RETURN_TTL_SECONDS).toBe(3600 + 600);
|
|
47
|
+
expect(openSecurityReturn(ref, SECRET, now + 3600_000)).toBe(landing(SPOKE, "/account/security"));
|
|
48
|
+
expect(openSecurityReturn(ref, SECRET, now + SECURITY_RETURN_TTL_SECONDS * 1000)).toBeNull();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("never opens under another secret, nor a continuation or a purchase claim sealed under their names", () => {
|
|
52
|
+
const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET);
|
|
53
|
+
expect(openSecurityReturn(ref, "x".repeat(43))).toBeNull();
|
|
54
|
+
const query = new URLSearchParams({ o: SPOKE, p: "/account/security" }).toString();
|
|
55
|
+
expect(openSecurityReturn(mintContinuation(query, SECRET), SECRET)).toBeNull();
|
|
56
|
+
expect(openSecurityReturn(mintContinuation(query, SECRET, Date.now(), "hub-purchase"), SECRET)).toBeNull();
|
|
57
|
+
expect(SECURITY_RETURN_NAME).not.toBe("hub-continue");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it.each([
|
|
61
|
+
["an http origin off loopback", { o: "http://spoke.example", p: "/account/security" }],
|
|
62
|
+
["an origin with a path", { o: `${SPOKE}/x`, p: "/account/security" }],
|
|
63
|
+
["an origin that is not a URL", { o: "spoke.example", p: "/account/security" }],
|
|
64
|
+
["a javascript: scheme", { o: "javascript:alert(1)", p: "/account/security" }],
|
|
65
|
+
["a path off the Security tab", { o: SPOKE, p: "/account" }],
|
|
66
|
+
["a path with a query", { o: SPOKE, p: "/account/security?x=1" }],
|
|
67
|
+
["a third key", { o: SPOKE, p: "/account/security", q: "1" }],
|
|
68
|
+
["a missing path", { o: SPOKE }],
|
|
69
|
+
] as Array<[string, Record<string, string>]>)("refuses a forged payload holding %s", (_label, payload) => {
|
|
70
|
+
const forged = mintContinuation(
|
|
71
|
+
new URLSearchParams(payload).toString(),
|
|
72
|
+
SECRET,
|
|
73
|
+
Date.now(),
|
|
74
|
+
SECURITY_RETURN_NAME,
|
|
75
|
+
SECURITY_RETURN_TTL_SECONDS,
|
|
76
|
+
);
|
|
77
|
+
expect(openSecurityReturn(forged, SECRET)).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it.each([["", ""], ["not base64url", "a.b/c"], ["too long", "a".repeat(5000)]])(
|
|
81
|
+
"refuses %s as a ref",
|
|
82
|
+
(_label, ref) => {
|
|
83
|
+
expect(openSecurityReturn(ref, SECRET)).toBeNull();
|
|
84
|
+
},
|
|
85
|
+
);
|
|
86
|
+
});
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @jest-environment node
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `POST /api/auth/hub/password` — the hub web's half of a spoke-hosted Set /
|
|
7
|
+
* Change password (#11162 AC-2).
|
|
8
|
+
*
|
|
9
|
+
* Better Auth's internal adapter (the `reset-password:<token>` row) and
|
|
10
|
+
* `@working-theory/api-client` (the hub API's client-and-credential check,
|
|
11
|
+
* the signed mail relay) are the external boundaries; both are doubles. The
|
|
12
|
+
* route's own decisions are under test: what it accepts, in what order it
|
|
13
|
+
* refuses, which person it mints for, where the mailed link lands, and what
|
|
14
|
+
* it never sends.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createHmac } from "node:crypto";
|
|
18
|
+
|
|
19
|
+
const mockSecret = "k".repeat(43);
|
|
20
|
+
const mockCreateVerificationValue = jest.fn();
|
|
21
|
+
const mockDeleteVerificationByIdentifier = jest.fn();
|
|
22
|
+
// eslint-disable-next-line no-restricted-syntax -- auth.ts is the Better Auth singleton (its adapter needs a live database); this stand-in for its internal adapter is the repo-standard double for that boundary (see ../../__tests__/entry-routes.test.ts).
|
|
23
|
+
jest.mock("../../../../../../auth", () => ({
|
|
24
|
+
__esModule: true,
|
|
25
|
+
auth: {
|
|
26
|
+
$context: Promise.resolve({
|
|
27
|
+
// The library's resolved base: the pinned origin plus `/api/auth`.
|
|
28
|
+
baseURL: "https://hub.example/api/auth",
|
|
29
|
+
internalAdapter: {
|
|
30
|
+
createVerificationValue: (...args: unknown[]) => mockCreateVerificationValue(...args),
|
|
31
|
+
deleteVerificationByIdentifier: (...args: unknown[]) =>
|
|
32
|
+
mockDeleteVerificationByIdentifier(...args),
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
},
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
// eslint-disable-next-line no-restricted-syntax -- #507: auth-secret.ts is a pure env read; pinned so the ref's seal is checkable here.
|
|
39
|
+
jest.mock("../../../../../../lib/auth-secret", () => ({
|
|
40
|
+
__esModule: true,
|
|
41
|
+
resolveSecret: () => mockSecret,
|
|
42
|
+
}));
|
|
43
|
+
|
|
44
|
+
const mockPassword = jest.fn();
|
|
45
|
+
const mockMailSend = jest.fn();
|
|
46
|
+
jest.mock("@working-theory/api-client", () => ({
|
|
47
|
+
__esModule: true,
|
|
48
|
+
hubSignIn: { password: (...args: unknown[]) => mockPassword(...args) },
|
|
49
|
+
authEmail: { send: (...args: unknown[]) => mockMailSend(...args) },
|
|
50
|
+
}));
|
|
51
|
+
|
|
52
|
+
const mockResetSendConfigured = jest.fn();
|
|
53
|
+
// eslint-disable-next-line no-restricted-syntax -- #507: auth-env.ts is a pure env-introspection module; the route reads one predicate of it.
|
|
54
|
+
jest.mock("../../../../../../lib/auth-env", () => ({
|
|
55
|
+
__esModule: true,
|
|
56
|
+
resetSendConfigured: () => mockResetSendConfigured(),
|
|
57
|
+
}));
|
|
58
|
+
|
|
59
|
+
import { __resetRefusedCallers } from "../../entry-shared";
|
|
60
|
+
import { SPOKE_RETURN_PATH, openSecurityReturn } from "../return";
|
|
61
|
+
import { POST } from "../route";
|
|
62
|
+
|
|
63
|
+
const HUB = "https://hub.example";
|
|
64
|
+
const SPOKE = "https://spoke.example";
|
|
65
|
+
const CALLBACK = `${SPOKE}/api/hub-session/callback`;
|
|
66
|
+
const BASIC = "Basic c3Bva2VfYWJjOnNlY3JldA==";
|
|
67
|
+
const SPOKE_KEY = "ailk_spk_spoke";
|
|
68
|
+
const CREDENTIAL = `ailk_hst_${"t".repeat(43)}`;
|
|
69
|
+
const RELAY_SECRET = "relay-secret";
|
|
70
|
+
const USER = {
|
|
71
|
+
id: "user_1",
|
|
72
|
+
name: "Pat",
|
|
73
|
+
email: "pat@example.com",
|
|
74
|
+
emailVerified: true,
|
|
75
|
+
createdAt: "2026-09-01T00:00:00.000Z",
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const BODY = {
|
|
79
|
+
client_id: "spoke_abc",
|
|
80
|
+
redirect_uri: CALLBACK,
|
|
81
|
+
access_token: CREDENTIAL,
|
|
82
|
+
locale: "en",
|
|
83
|
+
return_path: "/account/security",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const CLIENT_HEADERS = { authorization: BASIC, "x-ailk-spoke-key": SPOKE_KEY };
|
|
87
|
+
|
|
88
|
+
/** Where a completed reset lands: the spoke's return route, the tab as `next`. */
|
|
89
|
+
function landing(origin: string, path: string): string {
|
|
90
|
+
return `${origin}${SPOKE_RETURN_PATH}?next=${encodeURIComponent(path)}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function request(body: unknown, headers: Record<string, string> = CLIENT_HEADERS): Request {
|
|
94
|
+
return new Request(`${HUB}/api/auth/hub/password`, {
|
|
95
|
+
method: "POST",
|
|
96
|
+
headers: { "content-type": "application/json", ...headers },
|
|
97
|
+
body: typeof body === "string" ? body : JSON.stringify(body),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function apiAnswers(hasPassword: boolean): void {
|
|
102
|
+
mockPassword.mockResolvedValue({
|
|
103
|
+
ok: true,
|
|
104
|
+
status: 200,
|
|
105
|
+
body: { clientId: "spoke_abc", origin: SPOKE, user: USER, hasPassword },
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The one mail the relay double received, parsed. */
|
|
110
|
+
function sentMail(): { body: Record<string, unknown>; headers: Record<string, string> } {
|
|
111
|
+
expect(mockMailSend).toHaveBeenCalledTimes(1);
|
|
112
|
+
const [rawBody, headers] = mockMailSend.mock.calls[0] as [string, Record<string, string>];
|
|
113
|
+
return { body: JSON.parse(rawBody) as Record<string, unknown>, headers };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The token the one minted row carries. */
|
|
117
|
+
function mintedToken(): string {
|
|
118
|
+
expect(mockCreateVerificationValue).toHaveBeenCalledTimes(1);
|
|
119
|
+
const [row] = mockCreateVerificationValue.mock.calls[0] as [{ identifier: string }];
|
|
120
|
+
return row.identifier.replace(/^reset-password:/, "");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const ORIGINAL_ENV = process.env;
|
|
124
|
+
|
|
125
|
+
beforeEach(() => {
|
|
126
|
+
jest.resetAllMocks();
|
|
127
|
+
__resetRefusedCallers();
|
|
128
|
+
process.env = {
|
|
129
|
+
...ORIGINAL_ENV,
|
|
130
|
+
// The bare origin, as every deployment sets it (`apps/web/.env.example`).
|
|
131
|
+
BETTER_AUTH_URL: HUB,
|
|
132
|
+
AUTH_EMAIL_WEBHOOK_SECRET: RELAY_SECRET,
|
|
133
|
+
NEXT_PUBLIC_ENABLED_LOCALES: "en,fr",
|
|
134
|
+
};
|
|
135
|
+
mockResetSendConfigured.mockReturnValue(true);
|
|
136
|
+
apiAnswers(false);
|
|
137
|
+
mockCreateVerificationValue.mockResolvedValue({});
|
|
138
|
+
mockDeleteVerificationByIdentifier.mockResolvedValue(undefined);
|
|
139
|
+
mockMailSend.mockResolvedValue({ ok: true, status: 202 });
|
|
140
|
+
jest.spyOn(console, "info").mockImplementation(() => undefined);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
afterAll(() => {
|
|
144
|
+
process.env = ORIGINAL_ENV;
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
describe("the accepted request", () => {
|
|
148
|
+
it("asks the API's check with the spoke's two headers and the body's three keys, mints the person's reset row for an hour, and answers 202", async () => {
|
|
149
|
+
const before = Date.now();
|
|
150
|
+
const res = await POST(request(BODY));
|
|
151
|
+
|
|
152
|
+
expect(res.status).toBe(202);
|
|
153
|
+
expect(await res.json()).toEqual({ sent: true });
|
|
154
|
+
expect(res.headers.get("cache-control")).toBe("no-store");
|
|
155
|
+
expect(mockPassword).toHaveBeenCalledWith(
|
|
156
|
+
{ authorization: BASIC, spokeKey: SPOKE_KEY },
|
|
157
|
+
{ clientId: "spoke_abc", redirectUri: CALLBACK, accessToken: CREDENTIAL },
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
const [row] = mockCreateVerificationValue.mock.calls[0] as [
|
|
161
|
+
{ identifier: string; value: string; expiresAt: Date },
|
|
162
|
+
];
|
|
163
|
+
expect(row.identifier).toMatch(/^reset-password:[A-Za-z0-9_-]{32}$/);
|
|
164
|
+
expect(row.value).toBe(USER.id);
|
|
165
|
+
const ttl = row.expiresAt.getTime() - before;
|
|
166
|
+
expect(ttl).toBeGreaterThanOrEqual(3600_000 - 5_000);
|
|
167
|
+
expect(ttl).toBeLessThanOrEqual(3600_000 + 5_000);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("mails the API's person — never a body address — Better Auth's own link under its /api/auth base, whose callback is the hub's reset page carrying a return to the spoke's Security tab", async () => {
|
|
171
|
+
await POST(request(BODY));
|
|
172
|
+
const token = mintedToken();
|
|
173
|
+
const { body, headers } = sentMail();
|
|
174
|
+
|
|
175
|
+
expect(body).toEqual({
|
|
176
|
+
kind: "password-reset",
|
|
177
|
+
userId: USER.id,
|
|
178
|
+
to: USER.email,
|
|
179
|
+
url: expect.stringContaining(`${HUB}/api/auth/reset-password/${token}?callbackURL=`),
|
|
180
|
+
expiresInMinutes: 60,
|
|
181
|
+
});
|
|
182
|
+
// The library's own route, never a page path on the bare origin.
|
|
183
|
+
expect(String(body.url).startsWith(`${HUB}/api/auth/reset-password/`)).toBe(true);
|
|
184
|
+
expect(String(body.url).startsWith(`${HUB}/reset-password/`)).toBe(false);
|
|
185
|
+
const callbackURL = new URL(decodeURIComponent(String(body.url).split("callbackURL=")[1] ?? ""));
|
|
186
|
+
expect(callbackURL.origin).toBe(HUB);
|
|
187
|
+
expect(callbackURL.pathname).toBe("/reset-password");
|
|
188
|
+
expect([...callbackURL.searchParams.keys()]).toEqual(["ref"]);
|
|
189
|
+
expect(openSecurityReturn(callbackURL.searchParams.get("ref") ?? "", mockSecret)).toBe(
|
|
190
|
+
landing(SPOKE, "/account/security"),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
// Signed for the relay over the exact serialized body.
|
|
194
|
+
const expected = `sha256=${createHmac("sha256", RELAY_SECRET)
|
|
195
|
+
.update(`${headers["x-ailk-auth-email-timestamp"]}.${mockMailSend.mock.calls[0]?.[0]}`, "utf8")
|
|
196
|
+
.digest("hex")}`;
|
|
197
|
+
expect(headers["x-ailk-auth-email-signature"]).toBe(expected);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("the return is the client's REGISTERED origin from the API, never the body's callback", async () => {
|
|
201
|
+
mockPassword.mockResolvedValue({
|
|
202
|
+
ok: true,
|
|
203
|
+
status: 200,
|
|
204
|
+
body: { clientId: "spoke_abc", origin: "https://registered.example", user: USER, hasPassword: true },
|
|
205
|
+
});
|
|
206
|
+
await POST(request(BODY));
|
|
207
|
+
const callbackURL = new URL(
|
|
208
|
+
decodeURIComponent(String(sentMail().body.url).split("callbackURL=")[1] ?? ""),
|
|
209
|
+
);
|
|
210
|
+
expect(openSecurityReturn(callbackURL.searchParams.get("ref") ?? "", mockSecret)).toBe(
|
|
211
|
+
landing("https://registered.example", "/account/security"),
|
|
212
|
+
);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("renders the hub's page under the body's locale and returns to the locale's Security tab", async () => {
|
|
216
|
+
await POST(request({ ...BODY, locale: "fr", return_path: "/fr/account/security" }));
|
|
217
|
+
const callbackURL = new URL(
|
|
218
|
+
decodeURIComponent(String(sentMail().body.url).split("callbackURL=")[1] ?? ""),
|
|
219
|
+
);
|
|
220
|
+
expect(callbackURL.pathname).toBe("/fr/reset-password");
|
|
221
|
+
expect(openSecurityReturn(callbackURL.searchParams.get("ref") ?? "", mockSecret)).toBe(
|
|
222
|
+
landing(SPOKE, "/fr/account/security"),
|
|
223
|
+
);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("a locale this hub does not enable renders the default page", async () => {
|
|
227
|
+
await POST(request({ ...BODY, locale: "de" }));
|
|
228
|
+
const callbackURL = new URL(
|
|
229
|
+
decodeURIComponent(String(sentMail().body.url).split("callbackURL=")[1] ?? ""),
|
|
230
|
+
);
|
|
231
|
+
expect(callbackURL.pathname).toBe("/reset-password");
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
describe("the body", () => {
|
|
236
|
+
it.each([
|
|
237
|
+
["an email (the person is the credential's)", { ...BODY, email: "eve@example.com" }],
|
|
238
|
+
["a password", { ...BODY, password: "hunter22" }],
|
|
239
|
+
["no credential", { ...BODY, access_token: undefined }],
|
|
240
|
+
["a credential of another shape", { ...BODY, access_token: "Bearer something" }],
|
|
241
|
+
["a return path off the Security tab", { ...BODY, return_path: "/account" }],
|
|
242
|
+
["a return path with a query", { ...BODY, return_path: "/account/security?x=1" }],
|
|
243
|
+
["a return path that is a URL", { ...BODY, return_path: "https://evil.example/account/security" }],
|
|
244
|
+
["a malformed locale", { ...BODY, locale: "english" }],
|
|
245
|
+
["a body that is not JSON", "client_id=spoke_abc"],
|
|
246
|
+
] as Array<[string, unknown]>)("%s → 400 invalid_request, no API call, nothing minted or sent", async (_label, body) => {
|
|
247
|
+
const res = await POST(request(body));
|
|
248
|
+
expect(res.status).toBe(400);
|
|
249
|
+
expect(await res.json()).toEqual({ error: "invalid_request" });
|
|
250
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
251
|
+
expect(mockCreateVerificationValue).not.toHaveBeenCalled();
|
|
252
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it("a body past 4 KB → 400", async () => {
|
|
256
|
+
const res = await POST(request({ ...BODY, pad: "x".repeat(5000) }));
|
|
257
|
+
expect(res.status).toBe(400);
|
|
258
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
describe("the client", () => {
|
|
263
|
+
it.each([
|
|
264
|
+
["no Authorization", { "x-ailk-spoke-key": SPOKE_KEY }],
|
|
265
|
+
["no spoke key", { authorization: BASIC }],
|
|
266
|
+
["a Bearer Authorization", { authorization: `Bearer ${CREDENTIAL}`, "x-ailk-spoke-key": SPOKE_KEY }],
|
|
267
|
+
] as Array<[string, Record<string, string>]>)("%s → 401 invalid_client before any API call", async (_label, headers) => {
|
|
268
|
+
const res = await POST(request(BODY, headers));
|
|
269
|
+
expect(res.status).toBe(401);
|
|
270
|
+
expect(await res.json()).toEqual({ error: "invalid_client" });
|
|
271
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
272
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it.each([
|
|
276
|
+
[401, "invalid_client"],
|
|
277
|
+
[400, "invalid_grant"],
|
|
278
|
+
[400, "invalid_request"],
|
|
279
|
+
[429, "rate_limited"],
|
|
280
|
+
])("the API's %i %s is passed on, and nothing is minted or sent", async (status, code) => {
|
|
281
|
+
mockPassword.mockResolvedValue({
|
|
282
|
+
ok: false,
|
|
283
|
+
status,
|
|
284
|
+
body: { ok: false, error: { code, message: "refused" } },
|
|
285
|
+
});
|
|
286
|
+
const res = await POST(request(BODY));
|
|
287
|
+
expect(res.status).toBe(status);
|
|
288
|
+
expect(await res.json()).toEqual({ error: code });
|
|
289
|
+
expect(mockCreateVerificationValue).not.toHaveBeenCalled();
|
|
290
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it("an API that cannot be reached → 503", async () => {
|
|
294
|
+
mockPassword.mockRejectedValue(new Error("network"));
|
|
295
|
+
const res = await POST(request(BODY));
|
|
296
|
+
expect(res.status).toBe(503);
|
|
297
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
it("ten API refusals of a caller's credentials → 429 before the eleventh API call", async () => {
|
|
301
|
+
mockPassword.mockResolvedValue({
|
|
302
|
+
ok: false,
|
|
303
|
+
status: 401,
|
|
304
|
+
body: { ok: false, error: { code: "invalid_client", message: "refused" } },
|
|
305
|
+
});
|
|
306
|
+
process.env.VERCEL = "1";
|
|
307
|
+
const headers = { ...CLIENT_HEADERS, "x-vercel-forwarded-for": "203.0.113.5" };
|
|
308
|
+
for (let i = 0; i < 10; i++) {
|
|
309
|
+
expect((await POST(request(BODY, headers))).status).toBe(401);
|
|
310
|
+
}
|
|
311
|
+
mockPassword.mockClear();
|
|
312
|
+
const res = await POST(request(BODY, headers));
|
|
313
|
+
expect(res.status).toBe(429);
|
|
314
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
315
|
+
// Another caller is not.
|
|
316
|
+
const other = await POST(request(BODY, { ...CLIENT_HEADERS, "x-vercel-forwarded-for": "203.0.113.6" }));
|
|
317
|
+
expect(other.status).toBe(401);
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
describe("the hub", () => {
|
|
322
|
+
it("with no pinned origin → 503 before anything", async () => {
|
|
323
|
+
delete process.env.BETTER_AUTH_URL;
|
|
324
|
+
const res = await POST(request(BODY));
|
|
325
|
+
expect(res.status).toBe(503);
|
|
326
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("that cannot complete a reset → 503 before the API check charges a budget; nothing minted or sent", async () => {
|
|
330
|
+
mockResetSendConfigured.mockReturnValue(false);
|
|
331
|
+
const res = await POST(request(BODY));
|
|
332
|
+
expect(res.status).toBe(503);
|
|
333
|
+
expect(mockPassword).not.toHaveBeenCalled();
|
|
334
|
+
expect(mockCreateVerificationValue).not.toHaveBeenCalled();
|
|
335
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
it("whose row cannot be written → 503, nothing sent", async () => {
|
|
339
|
+
mockCreateVerificationValue.mockRejectedValue(new Error("db"));
|
|
340
|
+
const res = await POST(request(BODY));
|
|
341
|
+
expect(res.status).toBe(503);
|
|
342
|
+
expect(mockMailSend).not.toHaveBeenCalled();
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
it.each([
|
|
346
|
+
["a relay refusal", () => mockMailSend.mockResolvedValue({ ok: false, status: 500 })],
|
|
347
|
+
["a relay throw", () => mockMailSend.mockRejectedValue(new Error("network"))],
|
|
348
|
+
])("%s → 503, and the unused row is dropped", async (_label, arrange) => {
|
|
349
|
+
arrange();
|
|
350
|
+
const res = await POST(request(BODY));
|
|
351
|
+
expect(res.status).toBe(503);
|
|
352
|
+
expect(mockDeleteVerificationByIdentifier).toHaveBeenCalledWith(`reset-password:${mintedToken()}`);
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it("logs the outcome and nothing else — no address, credential, token or ref", async () => {
|
|
357
|
+
const info = jest.spyOn(console, "info").mockImplementation(() => undefined);
|
|
358
|
+
const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined);
|
|
359
|
+
const error = jest.spyOn(console, "error").mockImplementation(() => undefined);
|
|
360
|
+
await POST(request(BODY));
|
|
361
|
+
const token = mintedToken();
|
|
362
|
+
const logged = [...info.mock.calls, ...warn.mock.calls, ...error.mock.calls].flat().join(" ");
|
|
363
|
+
expect(logged).toContain('"outcome":"sent"');
|
|
364
|
+
expect(logged).not.toContain(USER.email);
|
|
365
|
+
expect(logged).not.toContain(CREDENTIAL);
|
|
366
|
+
expect(logged).not.toContain(token);
|
|
367
|
+
expect(logged).not.toContain(SPOKE_KEY);
|
|
368
|
+
});
|