@payez/next-mvp 4.1.12 → 4.1.14
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.d.ts +0 -3
- package/dist/auth/better-auth.js +152 -36
- package/package.json +2 -2
- package/scripts/check-internal-url-usage.sh +73 -73
- package/src/auth/better-auth.ts +568 -450
package/src/auth/better-auth.ts
CHANGED
|
@@ -1,450 +1,568 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Better Auth Configuration
|
|
3
|
-
*
|
|
4
|
-
* Primary auth configuration. Replaces the former NextAuth auth-options.ts.
|
|
5
|
-
*
|
|
6
|
-
* Architecture: No database adapter — Better Auth runs in stateless mode
|
|
7
|
-
* with JWE cookie cache. User management stays on IDP, sessions on Redis.
|
|
8
|
-
*
|
|
9
|
-
* @see BETTER-AUTH-MIGRATION-SPEC.md
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import 'server-only';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Better Auth Configuration
|
|
3
|
+
*
|
|
4
|
+
* Primary auth configuration. Replaces the former NextAuth auth-options.ts.
|
|
5
|
+
*
|
|
6
|
+
* Architecture: No database adapter — Better Auth runs in stateless mode
|
|
7
|
+
* with JWE cookie cache. User management stays on IDP, sessions on Redis.
|
|
8
|
+
*
|
|
9
|
+
* @see BETTER-AUTH-MIGRATION-SPEC.md
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import 'server-only';
|
|
13
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
14
|
+
import { decodeJwt } from 'jose'; // better-auth's own JWT dependency
|
|
15
|
+
import { betterAuth } from 'better-auth';
|
|
16
|
+
import { nextCookies } from 'better-auth/next-js';
|
|
17
|
+
import { toNextJsHandler } from 'better-auth/next-js';
|
|
18
|
+
import { magicLink, type MagicLinkOptions } from 'better-auth/plugins/magic-link';
|
|
19
|
+
import type { IDPClientConfig } from '../lib/idp-client-config';
|
|
20
|
+
import { getIDPClientConfig } from '../lib/idp-client-config';
|
|
21
|
+
import { getAppSlug } from '../lib/app-slug';
|
|
22
|
+
import { getRedis } from '../lib/redis';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Better Auth social provider config shape.
|
|
26
|
+
*/
|
|
27
|
+
export interface BetterAuthSocialProvider {
|
|
28
|
+
clientId: string;
|
|
29
|
+
clientSecret: string;
|
|
30
|
+
scope?: string[];
|
|
31
|
+
prompt?: string;
|
|
32
|
+
accessType?: 'offline' | 'online';
|
|
33
|
+
hd?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build Better Auth social providers from IDP config.
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* REQUEST-SCOPED carrier for the provider's raw id_token. Card 138635.
|
|
41
|
+
*
|
|
42
|
+
* WHY THIS EXISTS: /api/ExternalAuth/oauth-callback mints an IDP bearer for any
|
|
43
|
+
* ASSERTED email — we send {provider, email} and nothing verifiable. The fix is
|
|
44
|
+
* for the IDP to require a provider-signed id_token and verify it itself. This
|
|
45
|
+
* is the client half: capture the token Better Auth already receives, and
|
|
46
|
+
* forward it. Additive — the IDP ignores it until its gate flips.
|
|
47
|
+
*
|
|
48
|
+
* WHY AsyncLocalStorage AND NOT REDIS (BAPert's ruling: forward, do not persist):
|
|
49
|
+
* an id_token is credential material. Writing it to the session record would put
|
|
50
|
+
* it one allow-list edit away from leaking out of /api/internal/session-data,
|
|
51
|
+
* and it would outlive the request that needed it. ALS scopes it to the single
|
|
52
|
+
* request, and it is gone when the request ends — nothing to expire, nothing to
|
|
53
|
+
* scrub, nothing to leak.
|
|
54
|
+
*
|
|
55
|
+
* SAFE BY CONSTRUCTION: getUserInfo (which fills this) and the post-callback
|
|
56
|
+
* exchange (which reads it) both run inside createAuthGetHandler's own request.
|
|
57
|
+
* VERIFIED, not assumed: better-auth.ts:452 awaits ba.GET(request) — the call
|
|
58
|
+
* that invokes getUserInfo — and the exchange follows at :465 in the SAME
|
|
59
|
+
* function. Outside that scope the store is undefined and the body simply omits
|
|
60
|
+
* id_token, which is the correct additive behaviour.
|
|
61
|
+
*/
|
|
62
|
+
const idTokenScope = new AsyncLocalStorage<{ idToken?: string }>();
|
|
63
|
+
|
|
64
|
+
export function buildBetterAuthProviders(
|
|
65
|
+
config: IDPClientConfig
|
|
66
|
+
): Record<string, BetterAuthSocialProvider> {
|
|
67
|
+
const providers: Record<string, BetterAuthSocialProvider> = {};
|
|
68
|
+
|
|
69
|
+
for (const oauth of config.oauthProviders || []) {
|
|
70
|
+
if (!oauth.enabled) continue;
|
|
71
|
+
const name = oauth.provider.toLowerCase();
|
|
72
|
+
const additionalParams = oauth.additionalParams ?? {};
|
|
73
|
+
const rawPrompt = additionalParams.prompt;
|
|
74
|
+
const rawAccessType = additionalParams.accessType ?? additionalParams.access_type;
|
|
75
|
+
const rawHostedDomain = additionalParams.hd;
|
|
76
|
+
|
|
77
|
+
// Ensure profile scope is present for Google so avatar image is returned
|
|
78
|
+
const scopes = oauth.scopes?.split(' ') || [];
|
|
79
|
+
if (name === 'google' && !scopes.includes('profile')) {
|
|
80
|
+
scopes.push('profile');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
providers[name] = {
|
|
84
|
+
clientId: oauth.clientId,
|
|
85
|
+
clientSecret: oauth.clientSecret,
|
|
86
|
+
scope: scopes.length > 0 ? scopes : undefined,
|
|
87
|
+
// Google is overly eager to reuse the last account unless we
|
|
88
|
+
// explicitly ask for account selection on each social login.
|
|
89
|
+
prompt: typeof rawPrompt === 'string'
|
|
90
|
+
? rawPrompt
|
|
91
|
+
: name === 'google'
|
|
92
|
+
? 'select_account'
|
|
93
|
+
: undefined,
|
|
94
|
+
accessType: rawAccessType === 'online' ? 'online' : rawAccessType === 'offline' ? 'offline' : undefined,
|
|
95
|
+
hd: typeof rawHostedDomain === 'string' ? rawHostedDomain : undefined,
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* CAPTURE THE RAW id_token — card 138635, client half.
|
|
100
|
+
*
|
|
101
|
+
* getUserInfo is the ONLY provider hook that receives the token set.
|
|
102
|
+
* mapProfileToUser cannot do this: it is handed the DECODED claims, and a
|
|
103
|
+
* signed JWT cannot be reconstructed from them. We need the raw token
|
|
104
|
+
* because the IDP must verify the signature ITSELF — a client-decoded
|
|
105
|
+
* claim is just another assertable field, which is the defect restated.
|
|
106
|
+
*
|
|
107
|
+
* ⚠ THIS REPLACES THE DEFAULT google getUserInfo ENTIRELY. Upstream calls
|
|
108
|
+
* `if (options.getUserInfo) return options.getUserInfo(token)` FIRST and
|
|
109
|
+
* returns our result verbatim, so everything the default did is now ours to
|
|
110
|
+
* do — including the `hd` hosted-domain restriction.
|
|
111
|
+
*
|
|
112
|
+
* `hd` IS NOT HYPOTHETICAL: it is wired from additionalParams.hd four lines
|
|
113
|
+
* above, so a client can restrict sign-in to a Google Workspace domain.
|
|
114
|
+
* Silently dropping it would let ANY Google account into a client that had
|
|
115
|
+
* restricted itself — a security regression introduced by a security fix.
|
|
116
|
+
* (Measured on 93: zero clients set it today. That is a reason to be
|
|
117
|
+
* careful, not a reason to skip it — it is configurable and unused, which
|
|
118
|
+
* is exactly the state in which a regression goes unnoticed.)
|
|
119
|
+
*
|
|
120
|
+
* SO WE DO NOT OVERRIDE AT ALL WHEN `hd` IS SET. We take the hook over
|
|
121
|
+
* ONLY where upstream's check is PROVABLY VACUOUS — its own first line is
|
|
122
|
+
* `if (!configuredHostedDomain) return true`. With no hd configured the
|
|
123
|
+
* default would return true unconditionally, so omitting it is equivalent
|
|
124
|
+
* by the library's own definition rather than by our judgement.
|
|
125
|
+
*
|
|
126
|
+
* A client that DOES set hd keeps the stock provider, keeps its domain
|
|
127
|
+
* restriction, and simply does not contribute an id_token yet. Losing a
|
|
128
|
+
* capability is an acceptable cost; silently losing a security control is
|
|
129
|
+
* not. (better-auth does not re-export the predicate through its public
|
|
130
|
+
* types, and reimplementing a security check is how two copies drift — so
|
|
131
|
+
* the honest move is to not need it.)
|
|
132
|
+
*/
|
|
133
|
+
if (name === 'google' && !providers[name].hd) {
|
|
134
|
+
(providers[name] as unknown as Record<string, unknown>).getUserInfo = async (token: { idToken?: string }) => {
|
|
135
|
+
if (!token?.idToken) return null;
|
|
136
|
+
|
|
137
|
+
// The only new behaviour: hand the raw token to this request's scope.
|
|
138
|
+
const scope = idTokenScope.getStore();
|
|
139
|
+
if (scope) scope.idToken = token.idToken;
|
|
140
|
+
|
|
141
|
+
// Mirrors the upstream default (google.mjs) verbatim, minus the hd
|
|
142
|
+
// branch that cannot fire here — so overriding the hook changes WHAT WE
|
|
143
|
+
// KEEP, never what we ACCEPT.
|
|
144
|
+
const claims = decodeJwt(token.idToken) as Record<string, any>;
|
|
145
|
+
return {
|
|
146
|
+
user: {
|
|
147
|
+
id: claims.sub,
|
|
148
|
+
name: claims.name,
|
|
149
|
+
email: claims.email,
|
|
150
|
+
image: claims.picture,
|
|
151
|
+
emailVerified: claims.email_verified,
|
|
152
|
+
},
|
|
153
|
+
data: claims,
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return providers;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Optional configuration for `createBetterAuthInstance`.
|
|
164
|
+
*
|
|
165
|
+
* - `magicLink`: if provided, registers Better Auth's magic-link plugin.
|
|
166
|
+
* The host app supplies its own `sendMagicLink` callback — typically a
|
|
167
|
+
* fetch to its email service (e.g. ACP's `/v1/auth/magic-link/email`).
|
|
168
|
+
* Omit the `magicLink` key entirely to skip the plugin; the consuming
|
|
169
|
+
* app will not have a magic-link flow.
|
|
170
|
+
*/
|
|
171
|
+
export interface CreateBetterAuthInstanceOptions {
|
|
172
|
+
magicLink?: MagicLinkOptions;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Create Better Auth instance from IDP config.
|
|
177
|
+
*
|
|
178
|
+
* No database — runs in stateless mode with JWE cookie cache.
|
|
179
|
+
* Call after getIDPClientConfig() resolves.
|
|
180
|
+
*/
|
|
181
|
+
export function createBetterAuthInstance(
|
|
182
|
+
idpConfig: IDPClientConfig,
|
|
183
|
+
opts: CreateBetterAuthInstanceOptions = {}
|
|
184
|
+
) {
|
|
185
|
+
const appSlug = idpConfig.clientSlug || getAppSlug();
|
|
186
|
+
|
|
187
|
+
// Resolve base URL: BETTER_AUTH_URL env > IDP config > localhost fallback
|
|
188
|
+
// Must include /api/auth since that's where the catch-all route is mounted
|
|
189
|
+
const rawBaseURL = process.env.BETTER_AUTH_URL
|
|
190
|
+
|| idpConfig.baseClientUrl
|
|
191
|
+
|| `http://localhost:${process.env.PORT || '3000'}`;
|
|
192
|
+
const baseURL = rawBaseURL.replace(/\/+$/, '') + '/api/auth';
|
|
193
|
+
|
|
194
|
+
return betterAuth({
|
|
195
|
+
baseURL,
|
|
196
|
+
secret: idpConfig.authSecret as string,
|
|
197
|
+
|
|
198
|
+
socialProviders: buildBetterAuthProviders(idpConfig),
|
|
199
|
+
|
|
200
|
+
// Trust the app's own origin + any configured base URL
|
|
201
|
+
trustedOrigins: [
|
|
202
|
+
rawBaseURL,
|
|
203
|
+
baseURL,
|
|
204
|
+
...(idpConfig.baseClientUrl ? [idpConfig.baseClientUrl] : []),
|
|
205
|
+
'http://localhost:3000',
|
|
206
|
+
'http://localhost:3400',
|
|
207
|
+
'http://localhost:3600',
|
|
208
|
+
],
|
|
209
|
+
|
|
210
|
+
// Redis-backed session storage via secondaryStorage
|
|
211
|
+
secondaryStorage: {
|
|
212
|
+
get: async (key: string) => {
|
|
213
|
+
return await getRedis().get(`ba:${appSlug}:${key}`);
|
|
214
|
+
},
|
|
215
|
+
set: async (key: string, value: string, ttl?: number) => {
|
|
216
|
+
const redis = getRedis();
|
|
217
|
+
if (ttl) {
|
|
218
|
+
await redis.setex(`ba:${appSlug}:${key}`, ttl, value);
|
|
219
|
+
} else {
|
|
220
|
+
await redis.setex(`ba:${appSlug}:${key}`, 7 * 24 * 60 * 60, value);
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
delete: async (key: string) => {
|
|
224
|
+
try {
|
|
225
|
+
await getRedis().del(`ba:${appSlug}:${key}`);
|
|
226
|
+
} catch { /* ignore */ }
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
session: {
|
|
231
|
+
// Cookie cache DISABLED — Redis is canonical for session liveness.
|
|
232
|
+
//
|
|
233
|
+
// Previously: enabled with maxAge 300 + refreshCache false. That cached
|
|
234
|
+
// a decoded session in process memory for 5 minutes, bypassing Redis
|
|
235
|
+
// reads during the window. Consequence: if the canonical app session
|
|
236
|
+
// at `{slug}:{token}` was evicted, refreshed, or rotated mid-window,
|
|
237
|
+
// Better Auth's in-memory copy stayed alive — and callers got
|
|
238
|
+
// contradictory answers depending on whether they consulted Better
|
|
239
|
+
// Auth (alive per cache) or Redis (dead/rotated). Documented contradiction
|
|
240
|
+
// visible in production traces: viability 200 + idp-token 200 +
|
|
241
|
+
// getFreshIdpToken NO_SESSION terminal within milliseconds.
|
|
242
|
+
//
|
|
243
|
+
// Trade-off: every Better Auth getSession() call now incurs one Redis
|
|
244
|
+
// read on the secondary-storage path. Latency cost is acceptable
|
|
245
|
+
// (sub-ms in-region) and the alternative is duplicate Layer-1
|
|
246
|
+
// workarounds in every consumer app — already shipped in idealvibe.online
|
|
247
|
+
// at b6a91f6.
|
|
248
|
+
cookieCache: {
|
|
249
|
+
enabled: false,
|
|
250
|
+
maxAge: 300,
|
|
251
|
+
refreshCache: false,
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
|
|
255
|
+
// Cookie prefix must match slim-middleware expectations ({slug}.session-token)
|
|
256
|
+
advanced: {
|
|
257
|
+
cookiePrefix: appSlug,
|
|
258
|
+
cookies: {
|
|
259
|
+
session_token: {
|
|
260
|
+
name: `${appSlug}.session-token`,
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
|
|
265
|
+
plugins: [
|
|
266
|
+
nextCookies(),
|
|
267
|
+
...(opts.magicLink ? [magicLink(opts.magicLink)] : []),
|
|
268
|
+
],
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Better Auth is always enabled (NextAuth removed in 4.0).
|
|
274
|
+
*/
|
|
275
|
+
export function isBetterAuthEnabled(): boolean {
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Get Better Auth Next.js route handlers (GET, POST).
|
|
281
|
+
* Initializes Better Auth from IDP config on first call, caches the instance.
|
|
282
|
+
*/
|
|
283
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
284
|
+
let cachedInstance: any = null;
|
|
285
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
286
|
+
let initPromise: Promise<any> | null = null;
|
|
287
|
+
let configuredOpts: CreateBetterAuthInstanceOptions = {};
|
|
288
|
+
|
|
289
|
+
// Expose for server-side session access (decode-session.ts)
|
|
290
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
291
|
+
export { cachedInstance as __betterAuthInstance };
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Configure Better Auth instance options for this process.
|
|
295
|
+
*
|
|
296
|
+
* Must be called before the first auth request — before
|
|
297
|
+
* `getBetterAuthInstance()` caches an instance. Typically called once at
|
|
298
|
+
* app startup, e.g. from Next.js `instrumentation.ts` or an equivalent
|
|
299
|
+
* server bootstrap hook.
|
|
300
|
+
*
|
|
301
|
+
* Throws if called after the instance has already been resolved: options
|
|
302
|
+
* cannot be applied retroactively.
|
|
303
|
+
*/
|
|
304
|
+
export function configureBetterAuth(opts: CreateBetterAuthInstanceOptions): void {
|
|
305
|
+
if (cachedInstance) {
|
|
306
|
+
throw new Error(
|
|
307
|
+
'[BETTER_AUTH] configureBetterAuth() must run before the instance is first resolved. ' +
|
|
308
|
+
'Call it in Next.js instrumentation.ts or an equivalent startup hook.'
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
configuredOpts = opts;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export async function getBetterAuthInstance() {
|
|
315
|
+
if (cachedInstance) return cachedInstance;
|
|
316
|
+
|
|
317
|
+
if (!initPromise) {
|
|
318
|
+
initPromise = getIDPClientConfig(true).then(config => {
|
|
319
|
+
const instance = createBetterAuthInstance(config, configuredOpts);
|
|
320
|
+
cachedInstance = instance;
|
|
321
|
+
console.log('[BETTER_AUTH] Instance created for', config.clientSlug || config.clientId);
|
|
322
|
+
return instance;
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return initPromise;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Get flag-gated auth handler for Next.js route.
|
|
331
|
+
*
|
|
332
|
+
* When USE_BETTER_AUTH=true, returns Better Auth handlers.
|
|
333
|
+
* Otherwise returns null (auth disabled).
|
|
334
|
+
*
|
|
335
|
+
* Usage in host app route:
|
|
336
|
+
* ```ts
|
|
337
|
+
* import { getBetterAuthHandler } from '@payez/next-mvp/auth/better-auth';
|
|
338
|
+
*
|
|
339
|
+
* export async function GET(req: Request) {
|
|
340
|
+
* const ba = await getBetterAuthHandler();
|
|
341
|
+
* if (ba) return ba.GET(req);
|
|
342
|
+
* }
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
345
|
+
export async function getBetterAuthHandler(): Promise<{ GET: (req: Request) => Promise<Response>; POST: (req: Request) => Promise<Response> } | null> {
|
|
346
|
+
if (!isBetterAuthEnabled()) return null;
|
|
347
|
+
|
|
348
|
+
const auth = await getBetterAuthInstance();
|
|
349
|
+
return toNextJsHandler(auth);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Exchange OAuth identity for IDP tokens and store in the BA Redis session.
|
|
354
|
+
*
|
|
355
|
+
* Call this from the OAuth callback route AFTER better-auth has processed the
|
|
356
|
+
* callback and created the session. Reads the session token from the Set-Cookie
|
|
357
|
+
* header of the response to find the BA Redis key.
|
|
358
|
+
*
|
|
359
|
+
* This replaces the old databaseHooks approach which doesn't fire in stateless mode.
|
|
360
|
+
*/
|
|
361
|
+
export async function exchangeOAuthForIdpTokens(
|
|
362
|
+
sessionToken: string,
|
|
363
|
+
provider: string = 'google'
|
|
364
|
+
): Promise<boolean> {
|
|
365
|
+
try {
|
|
366
|
+
const config = await getIDPClientConfig();
|
|
367
|
+
const appSlug = config.clientSlug || getAppSlug();
|
|
368
|
+
const baKey = `ba:${appSlug}:${sessionToken}`;
|
|
369
|
+
|
|
370
|
+
// Read the BA session from Redis
|
|
371
|
+
const baRaw = await getRedis().get(baKey).catch(() => null);
|
|
372
|
+
if (!baRaw) {
|
|
373
|
+
console.warn('[BETTER_AUTH] exchangeOAuthForIdpTokens: session not found in Redis for token', sessionToken.substring(0, 10));
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const baData = JSON.parse(baRaw);
|
|
378
|
+
const email = baData?.user?.email;
|
|
379
|
+
const name = baData?.user?.name;
|
|
380
|
+
const image = baData?.user?.image;
|
|
381
|
+
const baUserId = baData?.session?.userId || baData?.user?.id;
|
|
382
|
+
|
|
383
|
+
if (!email) {
|
|
384
|
+
console.warn('[BETTER_AUTH] exchangeOAuthForIdpTokens: no email in session');
|
|
385
|
+
return false;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Call IDP oauth-callback
|
|
389
|
+
const idpUrl = process.env.IDP_URL || '';
|
|
390
|
+
if (!idpUrl) {
|
|
391
|
+
console.warn('[BETTER_AUTH] No IDP_URL configured, skipping token exchange');
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
console.log('[BETTER_AUTH] Exchanging OAuth identity for IDP tokens:', email);
|
|
396
|
+
|
|
397
|
+
const oauthRes = await fetch(`${idpUrl}/api/ExternalAuth/oauth-callback`, {
|
|
398
|
+
method: 'POST',
|
|
399
|
+
headers: { 'Content-Type': 'application/json' },
|
|
400
|
+
body: JSON.stringify({
|
|
401
|
+
provider,
|
|
402
|
+
provider_account_id: email, // Cross-System Identity Standard v1.1: always use verified email, never opaque session IDs
|
|
403
|
+
email,
|
|
404
|
+
name,
|
|
405
|
+
image,
|
|
406
|
+
client_id: config.clientSlug || String(config.clientId),
|
|
407
|
+
/**
|
|
408
|
+
* Card 138635 — the RAW provider id_token, forwarded verbatim.
|
|
409
|
+
*
|
|
410
|
+
* Every other field in this body is an ASSERTION. The endpoint mints an
|
|
411
|
+
* IDP bearer from them today with no cryptographic check of any kind,
|
|
412
|
+
* which is why it is a complete authentication bypass and why it has
|
|
413
|
+
* been publicly reachable for 488 days.
|
|
414
|
+
*
|
|
415
|
+
* This field is the only one the IDP can VERIFY: signature against
|
|
416
|
+
* Google's JWKS, plus iss / exp / aud, and then read email_verified
|
|
417
|
+
* from the verified claims. Additive — the IDP ignores it until its
|
|
418
|
+
* gate flips, so this cannot break a login on its own.
|
|
419
|
+
*
|
|
420
|
+
* RAW, AND NOTHING DERIVED FROM IT (BAPert's ruling). We do NOT send a
|
|
421
|
+
* decoded email_verified. A client-computed verification flag is a body
|
|
422
|
+
* field with a better story: an attacker posts email_verified:true and
|
|
423
|
+
* the defect is rebuilt one layer up. The IDP verifies for itself or
|
|
424
|
+
* the fix is theatre.
|
|
425
|
+
*
|
|
426
|
+
* Absent when this runs outside the OAuth callback scope — the key is
|
|
427
|
+
* simply omitted rather than sent null, so "we never captured one" stays
|
|
428
|
+
* distinguishable from "the provider issued none".
|
|
429
|
+
*/
|
|
430
|
+
...(idTokenScope.getStore()?.idToken ? { id_token: idTokenScope.getStore()!.idToken } : {}),
|
|
431
|
+
}),
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
const oauthResText = await oauthRes.text();
|
|
435
|
+
console.log('[BETTER_AUTH] IDP oauth-callback response:', oauthRes.status, oauthResText.substring(0, 500));
|
|
436
|
+
|
|
437
|
+
if (!oauthRes.ok) {
|
|
438
|
+
console.error('[BETTER_AUTH] IDP oauth-callback failed:', oauthRes.status);
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
let idpData: any;
|
|
443
|
+
try { idpData = JSON.parse(oauthResText); } catch { return false; }
|
|
444
|
+
const result = idpData?.data?.result || idpData?.data || idpData;
|
|
445
|
+
|
|
446
|
+
if (!result?.access_token) {
|
|
447
|
+
console.warn('[BETTER_AUTH] IDP oauth-callback returned no access_token. Keys:', Object.keys(result || {}));
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Build IDP token data
|
|
452
|
+
// CRITICAL: If the IDP withholds refresh_token without setting requiresTwoFactor,
|
|
453
|
+
// treat missing refresh token as "2FA required" so middleware redirects to verify-code.
|
|
454
|
+
const hasRefreshToken = !!result.refresh_token;
|
|
455
|
+
const requiresTwoFactor = result.user?.requiresTwoFactor ?? result.requiresTwoFactor ?? !hasRefreshToken;
|
|
456
|
+
const idpTokenData = {
|
|
457
|
+
idpAccessToken: result.access_token,
|
|
458
|
+
idpRefreshToken: result.refresh_token,
|
|
459
|
+
idpAccessTokenExpires: result.expires_in
|
|
460
|
+
? Date.now() + result.expires_in * 1000
|
|
461
|
+
: Date.now() + 15 * 60 * 1000,
|
|
462
|
+
userId: String(result.user?.user_id || result.user?.id || result.user_id || baUserId),
|
|
463
|
+
email: result.user?.email || result.email || email,
|
|
464
|
+
name: result.user?.full_name || result.user?.name || result.name || name,
|
|
465
|
+
image: image,
|
|
466
|
+
roles: result.user?.roles || result.roles || [],
|
|
467
|
+
mfaVerified: !requiresTwoFactor,
|
|
468
|
+
idpClientId: result.client_id ? String(result.client_id) : undefined,
|
|
469
|
+
merchantId: result.merchant_id ? String(result.merchant_id) : undefined,
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
// Store in BA Redis session (for decodeSession)
|
|
473
|
+
baData.idpTokens = idpTokenData;
|
|
474
|
+
await getRedis().setex(baKey, 7 * 24 * 60 * 60, JSON.stringify(baData));
|
|
475
|
+
|
|
476
|
+
// Write to canonical session store so refresh handler and token lifecycle can find the tokens.
|
|
477
|
+
// Key format: {sessionPrefix}{token} — same key that getSession() reads from.
|
|
478
|
+
try {
|
|
479
|
+
const { getSessionPrefix } = await import('../lib/app-slug');
|
|
480
|
+
const canonicalKey = `${getSessionPrefix()}${sessionToken}`;
|
|
481
|
+
await getRedis().setex(canonicalKey, 7 * 24 * 60 * 60, JSON.stringify({
|
|
482
|
+
...idpTokenData,
|
|
483
|
+
oauthProvider: provider,
|
|
484
|
+
}));
|
|
485
|
+
} catch (canonicalErr) {
|
|
486
|
+
console.warn('[BETTER_AUTH] Failed to write canonical session:', canonicalErr instanceof Error ? canonicalErr.message : String(canonicalErr));
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
console.log('[BETTER_AUTH] IDP tokens stored in session for', email);
|
|
490
|
+
return true;
|
|
491
|
+
} catch (err) {
|
|
492
|
+
console.error('[BETTER_AUTH] IDP token exchange failed:', err instanceof Error ? err.message : String(err));
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Create a production-ready GET handler for the auth catch-all route.
|
|
499
|
+
*
|
|
500
|
+
* Wraps better-auth's GET handler with:
|
|
501
|
+
* - OAuth state error recovery (redirects to login instead of error page)
|
|
502
|
+
* - IDP token exchange after successful OAuth callback
|
|
503
|
+
*
|
|
504
|
+
* Usage in host app:
|
|
505
|
+
* ```ts
|
|
506
|
+
* import { createAuthGetHandler, getBetterAuthHandler } from '@payez/next-mvp/auth/better-auth';
|
|
507
|
+
* export const GET = createAuthGetHandler('/account-auth/login');
|
|
508
|
+
* export async function POST(req: Request) {
|
|
509
|
+
* const ba = await getBetterAuthHandler();
|
|
510
|
+
* return ba!.POST(req);
|
|
511
|
+
* }
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
export function createAuthGetHandler(loginPath: string = '/account-auth/login') {
|
|
515
|
+
return async function GET(request: Request): Promise<Response> {
|
|
516
|
+
// Card 138635: establish the request-scoped carrier for the provider's raw
|
|
517
|
+
// id_token. It must wrap BOTH ba.GET (which invokes getUserInfo, the only
|
|
518
|
+
// hook that sees the token) and the exchange below (which forwards it).
|
|
519
|
+
// Wrapping the whole handler is what makes "never persisted" achievable —
|
|
520
|
+
// the token exists only for the life of this request.
|
|
521
|
+
return idTokenScope.run({}, async () => {
|
|
522
|
+
const ba = await getBetterAuthHandler();
|
|
523
|
+
if (!ba) {
|
|
524
|
+
return new Response('Auth handler not configured', { status: 500 });
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const response = await ba.GET(request);
|
|
528
|
+
|
|
529
|
+
// Intercept auth errors (state mismatch, expired cookies) — redirect to login cleanly
|
|
530
|
+
if (response.status === 302) {
|
|
531
|
+
const location = response.headers.get('location') || '';
|
|
532
|
+
if (location.includes('/api/auth/error') || location.includes('please_restart')) {
|
|
533
|
+
console.warn('[BETTER_AUTH] OAuth state error, redirecting to login');
|
|
534
|
+
return Response.redirect(new URL(loginPath, request.url), 302);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// After successful OAuth callback: exchange Google identity for IDP tokens
|
|
539
|
+
const url = new URL(request.url);
|
|
540
|
+
if (url.pathname.includes('/callback/') && response.status === 302) {
|
|
541
|
+
try {
|
|
542
|
+
const auth = await getBetterAuthInstance();
|
|
543
|
+
if (auth?.api?.getSession) {
|
|
544
|
+
const setCookies = response.headers.getSetCookie?.() || [];
|
|
545
|
+
const cookieHeader = setCookies
|
|
546
|
+
.map((c: string) => c.split(';')[0])
|
|
547
|
+
.join('; ');
|
|
548
|
+
|
|
549
|
+
const headers = new Headers();
|
|
550
|
+
headers.set('cookie', cookieHeader);
|
|
551
|
+
|
|
552
|
+
const session = await auth.api.getSession({ headers });
|
|
553
|
+
if (session?.session?.token) {
|
|
554
|
+
console.log('[BETTER_AUTH] Got session token from callback:', session.session.token.substring(0, 10), '| email:', session.user?.email);
|
|
555
|
+
await exchangeOAuthForIdpTokens(session.session.token);
|
|
556
|
+
} else {
|
|
557
|
+
console.warn('[BETTER_AUTH] Could not get session after OAuth callback');
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
} catch (err: any) {
|
|
561
|
+
console.error('[BETTER_AUTH] IDP token exchange failed:', err.message);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
return response;
|
|
566
|
+
});
|
|
567
|
+
};
|
|
568
|
+
}
|