@payez/next-mvp 4.5.4 → 4.5.5
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/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/stores/authStore.js +6 -19
- package/package.json +1042 -1042
- package/src/auth/better-auth.ts +5 -1
- package/src/auth/session-response-sanitizer.ts +151 -0
- package/src/stores/authStore.ts +7 -17
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
|
+
}
|
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
|
|