@payez/next-mvp 4.5.4 → 4.5.6
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/dist/api-handlers/session/refresh-viability.d.ts +3 -4
- package/dist/api-handlers/session/refresh-viability.js +19 -1
- package/dist/api-handlers/session/viability.js +16 -2
- package/dist/auth/better-auth.js +5 -1
- package/dist/auth/session-response-sanitizer.d.ts +70 -0
- package/dist/auth/session-response-sanitizer.js +136 -0
- package/dist/routes/auth/viability.d.ts +7 -8
- package/dist/routes/auth/viability.js +32 -2
- package/dist/server/auth.d.ts +38 -0
- package/dist/server/auth.js +25 -5
- package/dist/stores/authStore.js +6 -19
- package/package.json +1042 -1042
- package/src/api-handlers/session/refresh-viability.ts +18 -1
- package/src/api-handlers/session/viability.ts +20 -3
- package/src/auth/better-auth.ts +5 -1
- package/src/auth/session-response-sanitizer.ts +151 -0
- package/src/routes/auth/viability.ts +36 -3
- package/src/server/auth.ts +53 -5
- package/src/stores/authStore.ts +7 -17
|
@@ -4,12 +4,29 @@ import { checkRefreshViability } from '../../lib/refresh-token-validator';
|
|
|
4
4
|
import { getTokenTestAware } from '../../lib/test-aware-get-token';
|
|
5
5
|
import { logger } from '../../config/logger';
|
|
6
6
|
import { tokenLogId } from '../../lib/token-log-id';
|
|
7
|
+
import { resolveSessionState } from '../../server/auth';
|
|
7
8
|
|
|
8
9
|
export async function GET(req: NextRequest) {
|
|
9
10
|
try {
|
|
10
11
|
const sessionToken = req.nextUrl.searchParams.get('token');
|
|
11
12
|
let finalSessionToken = sessionToken;
|
|
12
|
-
if (!finalSessionToken) {
|
|
13
|
+
if (!finalSessionToken && process.env.TEST_MODE !== 'true') {
|
|
14
|
+
// PAY-2216: outside TEST_MODE getTokenTestAware is getSession(), which answered null for a store outage AND
|
|
15
|
+
// for a deleted session, so this route said not_logged_in to both and its own session_not_found arm (below)
|
|
16
|
+
// was unreachable from a cookie. Ask for the state instead. Same rules as routes/auth/viability.ts:
|
|
17
|
+
// 'unknown' never reads as logged out or stale; 'missing' requires a verified cookie.
|
|
18
|
+
const sessionState = await resolveSessionState(req);
|
|
19
|
+
if (sessionState.state === 'unknown') {
|
|
20
|
+
logger.warn('[REFRESH-VIABILITY] Session store unavailable - session state unknown');
|
|
21
|
+
return NextResponse.json({ canRefresh: false, reason: 'store_unavailable', error: 'Session store unavailable', code: 'STORE_UNAVAILABLE' }, { status: 500 });
|
|
22
|
+
}
|
|
23
|
+
if (sessionState.state === 'missing') {
|
|
24
|
+
return NextResponse.json({ canRefresh: false, reason: 'session_not_found', sessionTokenId: tokenLogId(sessionState.sessionToken) }, { status: 200 });
|
|
25
|
+
}
|
|
26
|
+
if (sessionState.state === 'live') {
|
|
27
|
+
finalSessionToken = sessionState.session?.session?.token ?? null;
|
|
28
|
+
}
|
|
29
|
+
} else if (!finalSessionToken) {
|
|
13
30
|
const token = await getTokenTestAware(req);
|
|
14
31
|
// Support both field names: sessionToken (auth.ts JWT) and redisSessionId (legacy)
|
|
15
32
|
finalSessionToken = (token?.sessionToken || token?.redisSessionId) as string;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import { NextRequest, NextResponse } from 'next/server';
|
|
8
8
|
import { getSession as getRedisSession, getBetterAuthSession } from '../../lib/session-store';
|
|
9
|
-
import {
|
|
9
|
+
import { resolveSessionState } from '../../server/auth';
|
|
10
10
|
import { isInitializationFailed, ensureInitialized } from '../../lib/startup-init';
|
|
11
11
|
import { getIDPClientConfig } from '../../lib/idp-client-config';
|
|
12
12
|
import { tokenLogId } from '../../lib/token-log-id';
|
|
@@ -45,8 +45,25 @@ export async function GET(req: NextRequest) {
|
|
|
45
45
|
);
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
//
|
|
49
|
-
|
|
48
|
+
// PAY-2216: the TWIN of routes/auth/viability.ts - same tri-state, same answers, or an app mounting this export
|
|
49
|
+
// keeps the defect. 'unknown' (store did not answer) is a 5xx and never stale; 'missing' (verified cookie, store
|
|
50
|
+
// answered "not here") is the stale shape with a token id; 'none' stays { authenticated: false }.
|
|
51
|
+
const sessionState = await resolveSessionState(req);
|
|
52
|
+
if (sessionState.state === 'unknown') {
|
|
53
|
+
console.warn('[VIABILITY] Session store unavailable - session state unknown');
|
|
54
|
+
return NextResponse.json(
|
|
55
|
+
{ authenticated: false, revocationStatus: 'unknown' as RevocationStatus, error: 'Session store unavailable', code: 'STORE_UNAVAILABLE' },
|
|
56
|
+
{ status: 500 }
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
if (sessionState.state === 'missing') {
|
|
60
|
+
console.warn('[VIABILITY] Stale cookie detected - verified cookie, session not in Redis');
|
|
61
|
+
return NextResponse.json({
|
|
62
|
+
authenticated: false,
|
|
63
|
+
sessionTokenId: tokenLogId(sessionState.sessionToken) // PAY-1481: correlation id, never the token
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const betterAuthSession = sessionState.state === 'live' ? sessionState.session : null;
|
|
50
67
|
|
|
51
68
|
// Debug logging
|
|
52
69
|
if (!betterAuthSession) {
|
package/src/auth/better-auth.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { decodeJwt } from 'jose'; // better-auth's own JWT dependency
|
|
|
16
16
|
import { betterAuth } from 'better-auth';
|
|
17
17
|
import { nextCookies } from 'better-auth/next-js';
|
|
18
18
|
import { toNextJsHandler } from 'better-auth/next-js';
|
|
19
|
+
import { wrapBetterAuthHandler } from './session-response-sanitizer';
|
|
19
20
|
import { magicLink, type MagicLinkOptions } from 'better-auth/plugins/magic-link';
|
|
20
21
|
import { resolveClientKey } from '../lib/client-key';
|
|
21
22
|
import { genericOAuth } from 'better-auth/plugins/generic-oauth';
|
|
@@ -996,7 +997,10 @@ export async function getBetterAuthHandler(): Promise<{ GET: (req: Request) => P
|
|
|
996
997
|
if (!isBetterAuthEnabled()) return null;
|
|
997
998
|
|
|
998
999
|
const auth = await getBetterAuthInstance();
|
|
999
|
-
|
|
1000
|
+
// PAY-2217: Better Auth's native endpoints (get-session, list-sessions, sign-in/*, sign-up/*) put the session
|
|
1001
|
+
// token in the body. Strip it at the HTTP boundary here, so every consumer that mounts this handler gets it;
|
|
1002
|
+
// auth.api (server-side) is untouched and still sees the token. See session-response-sanitizer.ts.
|
|
1003
|
+
return wrapBetterAuthHandler(auth as any, toNextJsHandler(auth));
|
|
1000
1004
|
}
|
|
1001
1005
|
|
|
1002
1006
|
/**
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2217: no session token reaches browser JS from Better Auth's own HTTP endpoints.
|
|
3
|
+
*
|
|
4
|
+
* WHAT WAS WRONG. PAY-1481 removed token material from the package's own GET /api/auth/session. Better Auth's native
|
|
5
|
+
* endpoints are a separate surface served by the catch-all mount, and their default bodies carry the session
|
|
6
|
+
* credential identifier:
|
|
7
|
+
* GET /get-session -> { session: { id, token, userId, ... }, user }
|
|
8
|
+
* GET /list-sessions -> [ { id, token, ... } ] (EVERY session of the user, not just this one)
|
|
9
|
+
* POST /sign-in/* -> { token, user, ... }
|
|
10
|
+
* POST /sign-up/* -> { token, user }
|
|
11
|
+
* GET /magic-link/verify (no callbackURL) -> { token, user } (NightHawk G4 on PR 1190, measured on a real instance)
|
|
12
|
+
* and any plugin endpoint (passkey verify, two-factor verify, genericOAuth) answers a session object the same way.
|
|
13
|
+
* `token` is the Redis key of the session. The cookie is token.HMAC and Path B verifies the signature, so a bare
|
|
14
|
+
* token is not a replayable cookie (gate rows B1-B4 measure that), but it is a credential identifier readable by any
|
|
15
|
+
* script on the page, for this session and for every other session the user has. It breaks the PAY-1481 rule.
|
|
16
|
+
*
|
|
17
|
+
* EVERY 2xx JSON BODY IS STRIPPED, not a named list of paths. A list protects the endpoints someone remembered and
|
|
18
|
+
* silently misses the next plugin; the strip is a function of the response, so a new endpoint is covered the day it is
|
|
19
|
+
* mounted. A 2xx JSON body that legitimately needs one of these names to reach the browser would have to be
|
|
20
|
+
* allowlisted here on purpose (none is known: no client in this package reads one).
|
|
21
|
+
*
|
|
22
|
+
* WHERE THE FIX LIVES, AND WHY NOT customSession. Server-side code in this package reads session.session.token from
|
|
23
|
+
* auth.api.getSession() (viability, refresh, status, the OAuth exchange). A customSession plugin or an after-hook
|
|
24
|
+
* runs for those calls too and would strip the token from them. So the strip is applied at the HTTP BOUNDARY only:
|
|
25
|
+
* getBetterAuthHandler() returns handlers wrapped by wrapBetterAuthHandler(), and auth.api stays untouched.
|
|
26
|
+
*
|
|
27
|
+
* WHAT THE BROWSER GETS INSTEAD.
|
|
28
|
+
* - list-sessions rows carry `isCurrent` (computed here against the caller's cookie-resolved session) and `id`.
|
|
29
|
+
* - POST /revoke-session-by-id { id }: revokes ONE of the CALLER's sessions by its id. An id that is not one of the
|
|
30
|
+
* caller's own sessions answers 404 (never 403: do not confirm that another user's session id exists).
|
|
31
|
+
* - Better Auth's native POST /revoke-session { token } still exists and still requires a cookie-resolved session
|
|
32
|
+
* that owns the token, but no browser ever holds a token to send it.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** Credential-bearing key names, compared case- and separator-insensitively. */
|
|
36
|
+
const STRIP_KEYS = new Set(['token', 'sessiontoken', 'accesstoken', 'refreshtoken', 'idtoken']);
|
|
37
|
+
|
|
38
|
+
const norm = (k: string): string => k.toLowerCase().replace(/[_\-\s]/g, '');
|
|
39
|
+
|
|
40
|
+
/** Deep copy of `value` with every credential-named key removed, at any depth, in objects and arrays. */
|
|
41
|
+
export function stripSessionCredentials(value: unknown): unknown {
|
|
42
|
+
if (Array.isArray(value)) return value.map(stripSessionCredentials);
|
|
43
|
+
if (value !== null && typeof value === 'object') {
|
|
44
|
+
const out: Record<string, unknown> = {};
|
|
45
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
46
|
+
if (STRIP_KEYS.has(norm(k))) continue;
|
|
47
|
+
out[k] = stripSessionCredentials(v);
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** "/api/auth/get-session" -> "/get-session". Anything not under an /auth/ segment is returned as-is. */
|
|
55
|
+
export function authSubPath(pathname: string): string {
|
|
56
|
+
const i = pathname.indexOf('/api/auth/');
|
|
57
|
+
if (i >= 0) return pathname.slice(i + '/api/auth'.length).replace(/\/+$/, '') || '/';
|
|
58
|
+
return pathname.replace(/\/+$/, '') || '/';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isJson(res: Response): boolean {
|
|
62
|
+
return (res.headers.get('content-type') || '').toLowerCase().includes('application/json');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A Response with a new JSON body and the original status and headers (content-length recomputed by the runtime). */
|
|
66
|
+
function withJsonBody(res: Response, body: unknown): Response {
|
|
67
|
+
const headers = new Headers(res.headers);
|
|
68
|
+
headers.delete('content-length');
|
|
69
|
+
return new Response(JSON.stringify(body), { status: res.status, statusText: res.statusText, headers });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface AuthApi {
|
|
73
|
+
getSession: (opts: { headers: Headers }) => Promise<any>;
|
|
74
|
+
listSessions: (opts: { headers: Headers }) => Promise<any>;
|
|
75
|
+
revokeSession: (opts: { headers: Headers; body: { token: string }; asResponse?: boolean }) => Promise<any>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Sanitise one already-produced Better Auth response. Pure function of (request, response, current token). */
|
|
79
|
+
export async function sanitizeBetterAuthResponse(
|
|
80
|
+
req: Request,
|
|
81
|
+
res: Response,
|
|
82
|
+
currentToken: () => Promise<string | undefined>,
|
|
83
|
+
): Promise<Response> {
|
|
84
|
+
const sub = authSubPath(new URL(req.url).pathname);
|
|
85
|
+
if (!res.ok || !isJson(res)) return res;
|
|
86
|
+
|
|
87
|
+
let body: unknown;
|
|
88
|
+
try {
|
|
89
|
+
body = await res.clone().json();
|
|
90
|
+
} catch {
|
|
91
|
+
return res; // unreadable body: nothing to strip, and do not turn it into a different failure
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (sub === '/list-sessions' && Array.isArray(body)) {
|
|
95
|
+
const cur = await currentToken().catch(() => undefined);
|
|
96
|
+
body = body.map((row: any) =>
|
|
97
|
+
row && typeof row === 'object' ? { ...row, isCurrent: !!cur && row.token === cur } : row,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return withJsonBody(res, stripSessionCredentials(body));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const json = (status: number, body: unknown): Response =>
|
|
104
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
105
|
+
|
|
106
|
+
/** POST /revoke-session-by-id { id }: revoke one of the caller's own sessions by id. */
|
|
107
|
+
async function revokeById(req: Request, api: AuthApi): Promise<Response> {
|
|
108
|
+
let id: unknown;
|
|
109
|
+
try {
|
|
110
|
+
id = (await req.json())?.id;
|
|
111
|
+
} catch {
|
|
112
|
+
return json(400, { code: 'INVALID_REQUEST', message: 'Body must be JSON { id }' });
|
|
113
|
+
}
|
|
114
|
+
if (typeof id !== 'string' || id.length === 0) {
|
|
115
|
+
return json(400, { code: 'INVALID_REQUEST', message: 'id is required' });
|
|
116
|
+
}
|
|
117
|
+
const headers = new Headers(req.headers);
|
|
118
|
+
const rows = await api.listSessions({ headers }).catch(() => null);
|
|
119
|
+
if (rows === null) return json(401, { code: 'UNAUTHORIZED', message: 'No session' });
|
|
120
|
+
// listSessions returns ONLY the caller's own sessions, so a foreign id cannot match: 404, not 403.
|
|
121
|
+
const row = Array.isArray(rows) ? rows.find((r: any) => r && r.id === id && typeof r.token === 'string') : undefined;
|
|
122
|
+
if (!row) return json(404, { code: 'SESSION_NOT_FOUND', message: 'No such session' });
|
|
123
|
+
const res = await api.revokeSession({ headers, body: { token: row.token }, asResponse: true });
|
|
124
|
+
// Pass Better Auth's own answer (and its Set-Cookie when the current session was the one revoked) through.
|
|
125
|
+
return res instanceof Response ? res : json(200, { status: true });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
type Handler = (req: Request) => Promise<Response>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Wrap Better Auth's Next.js handlers so no response carries a session credential to the browser.
|
|
132
|
+
* `auth` is the Better Auth instance; its `api` is used server-side only (to find the caller's current session and to
|
|
133
|
+
* revoke by id) and is not modified.
|
|
134
|
+
*/
|
|
135
|
+
export function wrapBetterAuthHandler(
|
|
136
|
+
auth: { api: AuthApi },
|
|
137
|
+
handlers: { GET: Handler; POST: Handler },
|
|
138
|
+
): { GET: Handler; POST: Handler } {
|
|
139
|
+
const currentTokenFor = (req: Request) => async (): Promise<string | undefined> => {
|
|
140
|
+
const s = await auth.api.getSession({ headers: new Headers(req.headers) });
|
|
141
|
+
return s?.session?.token;
|
|
142
|
+
};
|
|
143
|
+
return {
|
|
144
|
+
GET: async (req) => sanitizeBetterAuthResponse(req, await handlers.GET(req), currentTokenFor(req)),
|
|
145
|
+
POST: async (req) => {
|
|
146
|
+
const sub = authSubPath(new URL(req.url).pathname);
|
|
147
|
+
if (sub === '/revoke-session-by-id') return revokeById(req, auth.api);
|
|
148
|
+
return sanitizeBetterAuthResponse(req, await handlers.POST(req), currentTokenFor(req));
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { NextRequest, NextResponse } from 'next/server';
|
|
18
|
-
import {
|
|
18
|
+
import { resolveSessionState } from '../../server/auth';
|
|
19
19
|
import {
|
|
20
20
|
getSession as getRedisSession,
|
|
21
21
|
getBetterAuthSession as getBetterAuthRedisSession,
|
|
@@ -142,9 +142,40 @@ function resolveClientId(sessionClientId: string | undefined): string | null {
|
|
|
142
142
|
*/
|
|
143
143
|
export async function GET(req: NextRequest) {
|
|
144
144
|
try {
|
|
145
|
-
|
|
145
|
+
// PAY-2216: ask for the session's STATE, not a session-or-null. A null used to cover a store outage, a deleted
|
|
146
|
+
// session and no cookie alike, so this route answered 'No session found' to all three and the middleware could
|
|
147
|
+
// never clear a dead cookie (it must not clear on an outage). See SessionState in server/auth.
|
|
148
|
+
const sessionState = await resolveSessionState(req);
|
|
146
149
|
|
|
147
|
-
if (
|
|
150
|
+
if (sessionState.state === 'unknown') {
|
|
151
|
+
// The store did not answer. NOT a statement about the session: never stale, never 'No session found'.
|
|
152
|
+
// Same shape as this route's catch (PAY-1882 step 4): 'unknown' revocation -> the middleware's fail-closed
|
|
153
|
+
// path, a non-OK answer -> service_error, which never clears cookies.
|
|
154
|
+
console.warn('[VIABILITY] Session store unavailable - session state unknown');
|
|
155
|
+
return NextResponse.json({
|
|
156
|
+
viable: false,
|
|
157
|
+
needsRefresh: false,
|
|
158
|
+
authenticated: false,
|
|
159
|
+
revocationStatus: 'unknown' as RevocationStatus,
|
|
160
|
+
error: 'Session store unavailable',
|
|
161
|
+
code: 'STORE_UNAVAILABLE'
|
|
162
|
+
}, { status: 500 });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (sessionState.state === 'missing') {
|
|
166
|
+
// A VERIFIED cookie and a store that answered "not here". The existing stale shape, so the middleware's
|
|
167
|
+
// stale_session arm (PAY-2216 / 4.5.4) clears it.
|
|
168
|
+
console.warn('[VIABILITY] Stale cookie detected - verified cookie, session not in Redis');
|
|
169
|
+
return NextResponse.json({
|
|
170
|
+
viable: false,
|
|
171
|
+
needsRefresh: false,
|
|
172
|
+
authenticated: false,
|
|
173
|
+
sessionTokenId: tokenLogId(sessionState.sessionToken), // PAY-1481: a correlation id, never the token
|
|
174
|
+
reason: 'Stale session - cookie exists but session not found in Redis'
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (sessionState.state === 'none') {
|
|
148
179
|
return NextResponse.json({
|
|
149
180
|
viable: false,
|
|
150
181
|
needsRefresh: false,
|
|
@@ -153,6 +184,8 @@ export async function GET(req: NextRequest) {
|
|
|
153
184
|
});
|
|
154
185
|
}
|
|
155
186
|
|
|
187
|
+
const baSession = sessionState.session;
|
|
188
|
+
|
|
156
189
|
const token = baSession as any;
|
|
157
190
|
const sessionToken = baSession.session?.token;
|
|
158
191
|
|
package/src/server/auth.ts
CHANGED
|
@@ -221,17 +221,60 @@ function logNoSessionWithKeys(origin: 'b' | 'c', sessionToken: string): void {
|
|
|
221
221
|
* getFreshIdpToken → NO_SESSION (Better Auth cache miss)
|
|
222
222
|
*
|
|
223
223
|
* Returns the session object or null if not authenticated per Redis.
|
|
224
|
+
*
|
|
225
|
+
* PAY-2216: this is now a thin wrapper over {@link resolveSessionState} and returns the session ONLY for `live`.
|
|
226
|
+
* Its signature and every answer it gives are unchanged; callers that must tell a dead session from an
|
|
227
|
+
* unreachable store call resolveSessionState directly.
|
|
224
228
|
*/
|
|
225
229
|
export async function getSession(request?: Request): Promise<any> {
|
|
230
|
+
const state = await resolveSessionState(request);
|
|
231
|
+
return state.state === 'live' ? state.session : null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* PAY-2216: what the session store said about this request's cookie. `getSession()` collapses all three
|
|
236
|
+
* non-live answers to `null`, and that collapse is the defect this type exists to undo.
|
|
237
|
+
*
|
|
238
|
+
* MEASURED (PAY-2216, NextPert 2026-10-11, portal fe547fa4 / next-mvp 4.5.4 / ioredis 5.3.2, real server):
|
|
239
|
+
* a Redis OUTAGE and a really DELETED key both came out of getSession() as `null`, so viability answered the
|
|
240
|
+
* identical `200 No session found` for both. Clearing on that shape would log every live user out on an
|
|
241
|
+
* outage (the PAY-2147 class), so nothing cleared at all and a dead cookie lingered.
|
|
242
|
+
*
|
|
243
|
+
* live - the session resolved. `session` is exactly what getSession() returns.
|
|
244
|
+
* missing - a cookie whose signature VERIFIED (HMAC or JWS, resolveVerifiedSessionTokenFromRequest) and BOTH
|
|
245
|
+
* store reads (canonical `{slug}:sess:{t}` and Better Auth's `ba:{slug}:{t}`) COMPLETED and found
|
|
246
|
+
* nothing. The store answered; the session is gone. Clearing the cookie is correct. This includes
|
|
247
|
+
* a Redis that restarted EMPTY: those sessions really are gone (BAPert 72093, gate row 6).
|
|
248
|
+
* unknown - a store read THREW (connection refused, commandTimeout, max retries). The store did not answer,
|
|
249
|
+
* so nothing is known about the session. NEVER clear on this. Callers answer 5xx.
|
|
250
|
+
* none - no session cookie, or a cookie whose signature does not verify, with the store not failing.
|
|
251
|
+
* Nothing to clear on our authority: a forged cookie never yields `missing`.
|
|
252
|
+
*
|
|
253
|
+
* The rule the whole type exists for: `missing` REQUIRES a verified cookie AND reads that completed. Weaken
|
|
254
|
+
* either and an outage or a forged cookie becomes a clear.
|
|
255
|
+
*/
|
|
256
|
+
export type SessionState =
|
|
257
|
+
| { state: 'live'; session: any }
|
|
258
|
+
| { state: 'missing'; sessionToken: string }
|
|
259
|
+
| { state: 'unknown' }
|
|
260
|
+
| { state: 'none' };
|
|
261
|
+
|
|
262
|
+
export async function resolveSessionState(request?: Request): Promise<SessionState> {
|
|
226
263
|
const auth = await getAuthInstance();
|
|
227
|
-
if (!request) return
|
|
264
|
+
if (!request) return { state: 'none' };
|
|
228
265
|
|
|
229
266
|
// Path A — Better Auth primary path (cookie cache → secondary storage).
|
|
230
267
|
// Fast happy-path when both Better Auth and Redis agree.
|
|
268
|
+
//
|
|
269
|
+
// PAY-2216: secondaryStorage.get RETHROWS a Redis failure on purpose (170033), so a throw here means "the store
|
|
270
|
+
// could not be asked". It is remembered: if Path B then has no verified token to read with, the honest answer is
|
|
271
|
+
// `unknown`, not `none`.
|
|
231
272
|
let betterAuthSession: any = null;
|
|
273
|
+
let primaryThrew = false;
|
|
232
274
|
try {
|
|
233
275
|
betterAuthSession = await auth.api.getSession({ headers: request.headers });
|
|
234
276
|
} catch (err) {
|
|
277
|
+
primaryThrew = true;
|
|
235
278
|
logSessionReadSwallowed('primary', err); // fall through to canonical Redis path
|
|
236
279
|
}
|
|
237
280
|
|
|
@@ -245,7 +288,7 @@ export async function getSession(request?: Request): Promise<any> {
|
|
|
245
288
|
logSessionReadSwallowed('A', err); // Redis unavailable
|
|
246
289
|
}
|
|
247
290
|
if (!sessionData) sessionData = buildSessionDataFromAuthSession(betterAuthSession);
|
|
248
|
-
return attachSessionData(betterAuthSession, sessionData, sessionToken);
|
|
291
|
+
return { state: 'live', session: attachSessionData(betterAuthSession, sessionData, sessionToken) };
|
|
249
292
|
}
|
|
250
293
|
|
|
251
294
|
// Path B — Better Auth said null/incomplete. Fall back to a VERIFIED cookie
|
|
@@ -260,16 +303,21 @@ export async function getSession(request?: Request): Promise<any> {
|
|
|
260
303
|
// the signature position, and a forged JWS too. The token now comes only from
|
|
261
304
|
// the shared verified resolver (HMAC or JWS signature checked first).
|
|
262
305
|
const sessionToken = await resolveVerifiedSessionTokenFromRequest(request);
|
|
263
|
-
|
|
306
|
+
// No verified token. If Better Auth's read THREW, the store was failing, so we cannot say the cookie is
|
|
307
|
+
// unverifiable rather than unreadable: `unknown`. Otherwise there is nothing to act on: `none`.
|
|
308
|
+
if (!sessionToken) return primaryThrew ? { state: 'unknown' } : { state: 'none' };
|
|
264
309
|
|
|
310
|
+
// PAY-2216: both reads must COMPLETE for a miss to mean anything. Either one throwing is `unknown`, which
|
|
311
|
+
// nobody may clear on. These two functions do a bare redis.get and do not swallow (verified at 4.5.4).
|
|
265
312
|
let sessionData: SessionData | null = null;
|
|
266
313
|
try {
|
|
267
314
|
sessionData = await getRedisSession(sessionToken);
|
|
268
315
|
if (!sessionData) sessionData = await getBetterAuthRedisSession(sessionToken);
|
|
269
316
|
} catch (err) {
|
|
270
317
|
logSessionReadSwallowed('B', err); // Redis unavailable
|
|
318
|
+
return { state: 'unknown' };
|
|
271
319
|
}
|
|
272
|
-
if (!sessionData) return
|
|
320
|
+
if (!sessionData) return { state: 'missing', sessionToken };
|
|
273
321
|
|
|
274
322
|
// Synthesize a minimal session shape compatible with downstream callers.
|
|
275
323
|
// The `session.token` field is what `getFreshIdpToken` and other callers
|
|
@@ -283,7 +331,7 @@ export async function getSession(request?: Request): Promise<any> {
|
|
|
283
331
|
roles: sessionData.roles,
|
|
284
332
|
},
|
|
285
333
|
};
|
|
286
|
-
return attachSessionData(synthetic, sessionData, sessionToken);
|
|
334
|
+
return { state: 'live', session: attachSessionData(synthetic, sessionData, sessionToken) };
|
|
287
335
|
}
|
|
288
336
|
|
|
289
337
|
/**
|
package/src/stores/authStore.ts
CHANGED
|
@@ -637,23 +637,13 @@ export const useAuthStore = create<AuthStore>()(
|
|
|
637
637
|
// COORDINATED REFRESH: The server now handles distributed locking
|
|
638
638
|
// We just need to make the refresh call and let the server coordinate
|
|
639
639
|
|
|
640
|
-
//
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
token = (s as any)?.sessionToken;
|
|
648
|
-
if (!token) {
|
|
649
|
-
await new Promise(r => setTimeout(r, 150));
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
} catch {
|
|
653
|
-
authLogger.warn('[AuthStore] Failed to resolve session token from Better Auth during refresh');
|
|
654
|
-
}
|
|
655
|
-
return token;
|
|
656
|
-
};
|
|
640
|
+
// PAY-2217: the session token is NOT read from Better Auth's getSession() any more. The HTTP body no
|
|
641
|
+
// longer carries it (wrapBetterAuthHandler), and this read was already dead: getSession() returns
|
|
642
|
+
// { session: { token } }, never a top-level `sessionToken`, so the 3 x 150 ms retry loop that used to sit
|
|
643
|
+
// here always ran to exhaustion. The server resolves the session from the cookie and REJECTS an
|
|
644
|
+
// x-session-token header when it cannot (refresh.ts, 246007), so the header is advisory at best.
|
|
645
|
+
const resolveSessionTokenForHeader = async (): Promise<string | undefined> =>
|
|
646
|
+
get().session?.sessionToken as string | undefined;
|
|
657
647
|
|
|
658
648
|
const sessionTokenHeader = await resolveSessionTokenForHeader();
|
|
659
649
|
|