@payez/next-mvp 4.5.6 → 4.7.9
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/auth/credential-login-email-code.d.ts +24 -0
- package/dist/api-handlers/auth/credential-login-email-code.js +83 -0
- package/dist/api-handlers/auth/credential-login.d.ts +41 -0
- package/dist/api-handlers/auth/credential-login.js +858 -0
- package/dist/api-handlers/oauth/resume.d.ts +16 -0
- package/dist/api-handlers/oauth/resume.js +207 -0
- package/dist/auth/better-auth.d.ts +14 -2
- package/dist/auth/better-auth.js +59 -34
- package/dist/auth/idp-oauth.d.ts +106 -0
- package/dist/auth/idp-oauth.js +280 -0
- package/dist/auth/safe-callback.js +15 -2
- package/dist/auth/session-cookie-clear.d.ts +7 -0
- package/dist/auth/session-cookie-clear.js +24 -0
- package/dist/auth/session-reset-link.d.ts +43 -0
- package/dist/auth/session-reset-link.js +144 -0
- package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
- package/dist/components/auth/CredentialSignInForm.js +134 -0
- package/dist/lib/authorize-resume.d.ts +87 -0
- package/dist/lib/authorize-resume.js +190 -0
- package/dist/lib/bearer-fetch.d.ts +17 -0
- package/dist/lib/bearer-fetch.js +32 -0
- package/dist/lib/code-step-copy.d.ts +53 -0
- package/dist/lib/code-step-copy.js +73 -0
- package/dist/lib/credential-sign-in-client.d.ts +59 -0
- package/dist/lib/credential-sign-in-client.js +89 -0
- package/dist/lib/device-id.d.ts +37 -0
- package/dist/lib/device-id.js +70 -0
- package/dist/lib/lock-window.d.ts +29 -0
- package/dist/lib/lock-window.js +53 -0
- package/dist/lib/login-error-message.d.ts +18 -0
- package/dist/lib/login-error-message.js +47 -0
- package/dist/lib/twofa-rejection.d.ts +20 -0
- package/dist/lib/twofa-rejection.js +73 -0
- package/dist/middleware/create-middleware.d.ts +25 -1
- package/dist/middleware/create-middleware.js +75 -27
- package/dist/pages/login/page.js +11 -37
- package/dist/routes/auth/credential-login-email-code.d.ts +6 -0
- package/dist/routes/auth/credential-login-email-code.js +10 -0
- package/dist/routes/auth/credential-login.d.ts +6 -0
- package/dist/routes/auth/credential-login.js +10 -0
- package/dist/routes/auth/session-reset.d.ts +21 -0
- package/dist/routes/auth/session-reset.js +40 -0
- package/dist/routes/oauth/resume.d.ts +11 -0
- package/dist/routes/oauth/resume.js +16 -0
- package/package.json +1102 -1042
- package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
- package/src/api-handlers/auth/credential-login.ts +948 -0
- package/src/api-handlers/oauth/resume.ts +182 -0
- package/src/auth/better-auth.ts +81 -5
- package/src/auth/idp-oauth.ts +310 -0
- package/src/auth/safe-callback.ts +16 -2
- package/src/auth/session-cookie-clear.ts +30 -0
- package/src/auth/session-reset-link.ts +159 -0
- package/src/components/auth/CredentialSignInForm.tsx +240 -0
- package/src/lib/authorize-resume.ts +187 -0
- package/src/lib/bearer-fetch.ts +31 -0
- package/src/lib/code-step-copy.ts +83 -0
- package/src/lib/credential-sign-in-client.ts +101 -0
- package/src/lib/device-id.ts +67 -0
- package/src/lib/lock-window.ts +49 -0
- package/src/lib/login-error-message.ts +41 -0
- package/src/lib/twofa-rejection.ts +91 -0
- package/src/middleware/create-middleware.ts +124 -30
- package/src/pages/login/page.tsx +20 -34
- package/src/routes/auth/credential-login-email-code.ts +6 -0
- package/src/routes/auth/credential-login.ts +6 -0
- package/src/routes/auth/session-reset.ts +37 -0
- package/src/routes/oauth/resume.ts +11 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ONE body that writes the session-cookie expiry Set-Cookie headers. Shared by the middleware
|
|
3
|
+
* (create-middleware.ts clearSessionCookies, behind its prefetch guard) and the PAY-2218 session-reset route, so
|
|
4
|
+
* the two clearing sites cannot drift apart on which cookies they expire or with which attributes.
|
|
5
|
+
*/
|
|
6
|
+
import type { NextResponse } from 'next/server';
|
|
7
|
+
import { getSessionCookieName, getSecureSessionCookieName } from '../lib/app-slug';
|
|
8
|
+
|
|
9
|
+
export function expireSessionCookies(response: NextResponse, requestCookieNames: Iterable<string>): void {
|
|
10
|
+
const sessionCookie = getSessionCookieName();
|
|
11
|
+
const secureCookie = getSecureSessionCookieName();
|
|
12
|
+
|
|
13
|
+
// Clear main cookies
|
|
14
|
+
response.cookies.set(sessionCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax' });
|
|
15
|
+
response.cookies.set(secureCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax', secure: true });
|
|
16
|
+
|
|
17
|
+
// Clear any chunked cookies (NextAuth chunks large cookies)
|
|
18
|
+
for (const name of requestCookieNames) {
|
|
19
|
+
if (name.startsWith(`${sessionCookie}.`) || name.startsWith(`${secureCookie}.`)) {
|
|
20
|
+
const isSecure = name.startsWith('__Secure-');
|
|
21
|
+
response.cookies.set(name, '', {
|
|
22
|
+
path: '/',
|
|
23
|
+
expires: new Date(0),
|
|
24
|
+
httpOnly: true,
|
|
25
|
+
sameSite: 'lax',
|
|
26
|
+
...(isSecure && { secure: true })
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2218 PR 2: the hand-off between the middleware and the session-reset route.
|
|
3
|
+
*
|
|
4
|
+
* WHY A ROUTE AT ALL. Next 15.5.x and 16.x (16.2.x without `skipProxyUrlNormalize`) strip every router flight
|
|
5
|
+
* header (`rsc`, `next-router-prefetch`, `next-router-segment-prefetch`, `next-router-state-tree`) from the request
|
|
6
|
+
* handed to middleware, so middleware cannot tell a router prefetch from a real navigation and its prefetch guard is
|
|
7
|
+
* dead. A ROUTE HANDLER does see them, on 15.5.9, 16.1.5 and 16.2.12 (measured with a real Chromium against real
|
|
8
|
+
* `next start` servers, PAY-2218 comments 2026-10-11). So the middleware no longer writes the clearing Set-Cookie
|
|
9
|
+
* itself: it redirects to the reset route, and the route decides.
|
|
10
|
+
*
|
|
11
|
+
* WHY THE ROUTE ANSWERS A PREFETCH WITH 204, NOT A REDIRECT. On 15.5.9 the router CACHES a prefetched redirect chain
|
|
12
|
+
* and the later click reuses it without calling middleware or the route again - so "decline on the prefetch, clear
|
|
13
|
+
* on the real navigation" never clears there. A 204 + no-store gives the router nothing to cache, so the real click
|
|
14
|
+
* reaches the route and clears (measured 2/2 on 15.5.9 and 16.2.12; the 307 mutant never clears on 15.5.9).
|
|
15
|
+
*
|
|
16
|
+
* WHY SIGNED. The route clears cookies on a GET. Unsigned, any page could link a signed-in user to it and log them
|
|
17
|
+
* out. The middleware signs (callbackUrl, reason, error, exp, session binding); the route clears only on a valid,
|
|
18
|
+
* unexpired signature and otherwise just sends the user to the login page with the cookies untouched.
|
|
19
|
+
*
|
|
20
|
+
* KEY SEPARATION (BAPert 72219). The signing key is DERIVED - HMAC(authSecret, 'next-mvp/session-reset/v1') - never
|
|
21
|
+
* the raw auth secret, so no value the app signs with that secret for any other purpose can pass as a reset token.
|
|
22
|
+
*
|
|
23
|
+
* SESSION BINDING (BAPert 72219). The signature covers SHA-256 of the session cookie the redirect was issued FOR. The
|
|
24
|
+
* route recomputes it from ITS OWN request's cookie and clears only on a match, so a token captured from one user
|
|
25
|
+
* clears nothing when sent to another (logout-CSRF), and a second use is a no-op (the first use cleared the cookie it
|
|
26
|
+
* was bound to). The hash never travels in the URL; it is only an input to the signature.
|
|
27
|
+
*
|
|
28
|
+
* WHY THE ROUTE REBUILDS THE LOGIN URL. The route never redirects to a URL it was handed. It takes `callbackUrl`
|
|
29
|
+
* (through safeCallbackPath), `reason` and `error` (allowlisted) and builds `${LOGIN_PAGE}?...` itself, so it cannot
|
|
30
|
+
* become an open redirect whatever the query says.
|
|
31
|
+
*
|
|
32
|
+
* Edge-safe: Web Crypto only (middleware runs on the edge runtime on 15.5.x).
|
|
33
|
+
*/
|
|
34
|
+
import { safeCallbackPath } from './safe-callback';
|
|
35
|
+
|
|
36
|
+
export const LOGIN_PAGE = '/account-auth/login';
|
|
37
|
+
|
|
38
|
+
/** The mount point consumers use: `app/api/auth/session-reset/route.ts` (under /api/auth/, which middleware bypasses). */
|
|
39
|
+
export const DEFAULT_SESSION_RESET_ROUTE = '/api/auth/session-reset';
|
|
40
|
+
|
|
41
|
+
/** How long a signed reset link stays valid. A real navigation follows the 307 at once; this only bounds replay. */
|
|
42
|
+
export const RESET_LINK_TTL_SECONDS = 300;
|
|
43
|
+
|
|
44
|
+
/** The purpose label for the derived signing key. Changing it invalidates every outstanding reset link. */
|
|
45
|
+
export const RESET_KEY_PURPOSE = 'next-mvp/session-reset/v1';
|
|
46
|
+
|
|
47
|
+
/** The only `reason` / `error` values the middleware emits on a clearing redirect. Anything else is dropped. */
|
|
48
|
+
export const RESET_REASONS: readonly string[] = ['stale', 'invalidated'];
|
|
49
|
+
export const RESET_ERRORS: readonly string[] = ['SessionExpired', 'TwoFactorTimeout'];
|
|
50
|
+
|
|
51
|
+
export interface ResetParams {
|
|
52
|
+
callbackUrl: string;
|
|
53
|
+
reason?: string;
|
|
54
|
+
error?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const encoder = new TextEncoder();
|
|
58
|
+
const FIELD_SEPARATOR = String.fromCharCode(10);
|
|
59
|
+
|
|
60
|
+
function b64url(bytes: Uint8Array): string {
|
|
61
|
+
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function hmacBytes(key: Uint8Array, message: string): Promise<Uint8Array> {
|
|
65
|
+
const k = await crypto.subtle.importKey('raw', key as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
66
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', k, encoder.encode(message)));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Sign with the DERIVED key: HMAC(HMAC(authSecret, purpose), message). Never with the raw auth secret. */
|
|
70
|
+
async function sign(secret: string, message: string): Promise<string> {
|
|
71
|
+
const derived = await hmacBytes(encoder.encode(secret), RESET_KEY_PURPOSE);
|
|
72
|
+
return b64url(await hmacBytes(derived, message));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** SHA-256 of the session cookie value, b64url. No session cookie binds to the empty string. */
|
|
76
|
+
async function sessionBinding(sessionCookieValue: string | undefined): Promise<string> {
|
|
77
|
+
if (!sessionCookieValue) return '';
|
|
78
|
+
return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(sessionCookieValue))));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Constant-time over equal lengths, and unequal lengths never match. */
|
|
82
|
+
function sameString(a: string, b: string): boolean {
|
|
83
|
+
if (a.length !== b.length) return false;
|
|
84
|
+
let diff = 0;
|
|
85
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
86
|
+
return diff === 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The secret the app already signs its session cookie with. Undefined means "cannot sign": callers fall back. */
|
|
90
|
+
export function resetSecret(): string | undefined {
|
|
91
|
+
return process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET || undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The session cookie a reset is bound to: the __Secure- one when present, else the plain one. */
|
|
95
|
+
export function boundSessionCookie(get: (name: string) => string | undefined, plainName: string, secureName: string): string | undefined {
|
|
96
|
+
return get(secureName) || get(plainName) || undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Normalise to exactly what the route will honour, so what is signed is what is verified. */
|
|
100
|
+
export function normaliseResetParams(raw: { callbackUrl?: string | null; reason?: string | null; error?: string | null }): ResetParams {
|
|
101
|
+
const out: ResetParams = { callbackUrl: safeCallbackPath(raw.callbackUrl ?? '') };
|
|
102
|
+
if (raw.reason && RESET_REASONS.includes(raw.reason)) out.reason = raw.reason;
|
|
103
|
+
if (raw.error && RESET_ERRORS.includes(raw.error)) out.error = raw.error;
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** What the signature covers. Exported for the key-separation row, which signs it with the RAW secret. */
|
|
108
|
+
export function resetPayload(p: ResetParams, exp: number, binding: string): string {
|
|
109
|
+
return ['v2', p.callbackUrl, p.reason ?? '', p.error ?? '', String(exp), binding].join(FIELD_SEPARATOR);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The login URL for these params, in the exact shape the middleware has always emitted. */
|
|
113
|
+
export function loginLocation(p: ResetParams): string {
|
|
114
|
+
let loc = `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(p.callbackUrl)}`;
|
|
115
|
+
if (p.reason) loc += `&reason=${p.reason}`;
|
|
116
|
+
if (p.error) loc += `&error=${p.error}`;
|
|
117
|
+
return loc;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Path + query for the reset route, bound to `sessionCookieValue` (the session cookie on the request being ended).
|
|
122
|
+
* `nowMs` is injectable for tests.
|
|
123
|
+
*/
|
|
124
|
+
export async function signedResetHref(
|
|
125
|
+
route: string,
|
|
126
|
+
p: ResetParams,
|
|
127
|
+
secret: string,
|
|
128
|
+
sessionCookieValue: string | undefined,
|
|
129
|
+
nowMs: number = Date.now()
|
|
130
|
+
): Promise<string> {
|
|
131
|
+
const exp = Math.floor(nowMs / 1000) + RESET_LINK_TTL_SECONDS;
|
|
132
|
+
const q = new URLSearchParams({ callbackUrl: p.callbackUrl });
|
|
133
|
+
if (p.reason) q.set('reason', p.reason);
|
|
134
|
+
if (p.error) q.set('error', p.error);
|
|
135
|
+
q.set('exp', String(exp));
|
|
136
|
+
q.set('sig', await sign(secret, resetPayload(p, exp, await sessionBinding(sessionCookieValue))));
|
|
137
|
+
return `${route}?${q.toString()}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Read a reset request's query. `signed` is true only for a valid, unexpired signature over the normalised params AND
|
|
142
|
+
* this request's own session cookie (`sessionCookieValue`). With no session cookie there is nothing to clear: false.
|
|
143
|
+
* The params are returned either way: an unsigned request still gets a sensible login redirect, just no clearing.
|
|
144
|
+
*/
|
|
145
|
+
export async function readResetRequest(
|
|
146
|
+
search: URLSearchParams,
|
|
147
|
+
secret: string | undefined,
|
|
148
|
+
sessionCookieValue: string | undefined,
|
|
149
|
+
nowMs: number = Date.now()
|
|
150
|
+
): Promise<{ params: ResetParams; signed: boolean }> {
|
|
151
|
+
const params = normaliseResetParams({ callbackUrl: search.get('callbackUrl'), reason: search.get('reason'), error: search.get('error') });
|
|
152
|
+
const sig = search.get('sig');
|
|
153
|
+
const exp = Number(search.get('exp'));
|
|
154
|
+
if (!secret || !sig || !sessionCookieValue || !Number.isInteger(exp) || exp < Math.floor(nowMs / 1000)) return { params, signed: false };
|
|
155
|
+
// The signature covers the NORMALISED params and THIS request's session, so a tampered value, or the token arriving
|
|
156
|
+
// with a different session cookie (another user, or the same user after signing in again), fails here.
|
|
157
|
+
const want = await sign(secret, resetPayload(params, exp, await sessionBinding(sessionCookieValue)));
|
|
158
|
+
return { params, signed: sameString(sig, want) };
|
|
159
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import React, { useState } from 'react';
|
|
4
|
+
import { TraditionalAuthSection } from './TraditionalAuthSection';
|
|
5
|
+
import { safeCallbackPath } from '../../auth/safe-callback';
|
|
6
|
+
import { authorizeResumeHref } from '../../lib/authorize-resume';
|
|
7
|
+
import { NO_CODE_REQUEST, codeStepInstruction, type CodeRequest } from '../../lib/code-step-copy';
|
|
8
|
+
import {
|
|
9
|
+
credentialSignIn,
|
|
10
|
+
requestEmailCode,
|
|
11
|
+
validateCredentials,
|
|
12
|
+
type FetchLike,
|
|
13
|
+
} from '../../lib/credential-sign-in-client';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* PAY-2302 cut 1b: the package's email + password (+ 2FA code) sign-in form.
|
|
17
|
+
*
|
|
18
|
+
* WHY IT EXISTS. The package's own Better Auth instance has no emailAndPassword, so the login page had no credential form
|
|
19
|
+
* (removed 2026-08-02, BAPert 17586: "restore this form together" with the backend that makes it work). This is that pair:
|
|
20
|
+
* the backend is routes/auth/credential-login (+ credential-login-email-code), which the app mounts at
|
|
21
|
+
* /api/auth/admin-login[/email-code]; this component drives it. Moved from the portal's AdminLoginCard (VibeID-Customer-Portal
|
|
22
|
+
* 3d654917), re-styled with the package's own TraditionalAuthSection instead of the portal's AuthCard chrome.
|
|
23
|
+
*
|
|
24
|
+
* MOUNT IT through the login page's slot, so nothing changes for a consumer that does not opt in:
|
|
25
|
+
* <LoginPage altAuthSlot={<CredentialSignInForm />} />
|
|
26
|
+
* (An app that has not mounted the two routes must NOT mount this form: it would be the dead control 17586 removed.)
|
|
27
|
+
*
|
|
28
|
+
* Two steps, the IdP's own contract (an access token with no refresh token means a second factor is outstanding):
|
|
29
|
+
* 'credentials' - email + password
|
|
30
|
+
* 'code' - the 2FA code; the door parks the provisional bearer in an httpOnly cookie, this step resubmits with the code.
|
|
31
|
+
*
|
|
32
|
+
* After success the browser goes to the callbackUrl, passed through safeCallbackPath (same-origin paths only); when the page
|
|
33
|
+
* carries ?return_url (an IdP authorize request) it goes to the app's /api/oauth/resume instead, which resumes that request.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
interface Props {
|
|
37
|
+
/** Where to go after sign-in. Default: the page's ?callbackUrl, else /dashboard. Always passed through safeCallbackPath. */
|
|
38
|
+
callbackUrl?: string;
|
|
39
|
+
/** Test seam: the fetch used for both doors. */
|
|
40
|
+
fetchImpl?: FetchLike;
|
|
41
|
+
/** Test seam: navigation after success. */
|
|
42
|
+
onSignedIn?: (destination: string) => void;
|
|
43
|
+
showForgotPassword?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const inputStyle: React.CSSProperties = {
|
|
47
|
+
borderColor: 'var(--border-default, #e5e7eb)',
|
|
48
|
+
color: 'var(--text-primary, #111827)',
|
|
49
|
+
background: 'var(--bg-input, white)',
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export function resolveDestination(explicit?: string): string {
|
|
53
|
+
let raw = explicit;
|
|
54
|
+
let returnUrl: string | null = null;
|
|
55
|
+
if (typeof window !== 'undefined') {
|
|
56
|
+
const params = new URLSearchParams(window.location.search);
|
|
57
|
+
if (raw === undefined) raw = params.get('callbackUrl') ?? undefined;
|
|
58
|
+
// PAY-2302 cut 2: an IdP that sent the user here mid-authorize (?return_url=<IdP authorize request>) must get the
|
|
59
|
+
// authorize request resumed after sign-in. The href points at the app's OWN /api/oauth/resume, which validates the
|
|
60
|
+
// URL against IDP_URL server-side; nothing absolute is navigated to from here, and the result is still guarded.
|
|
61
|
+
returnUrl = params.get('return_url');
|
|
62
|
+
}
|
|
63
|
+
return safeCallbackPath(authorizeResumeHref(returnUrl), safeCallbackPath(raw, '/dashboard'));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function CredentialSignInForm({ callbackUrl, fetchImpl, onSignedIn, showForgotPassword = false }: Props) {
|
|
67
|
+
const [step, setStep] = useState<'credentials' | 'code'>('credentials');
|
|
68
|
+
const [email, setEmail] = useState('');
|
|
69
|
+
const [password, setPassword] = useState('');
|
|
70
|
+
const [code, setCode] = useState('');
|
|
71
|
+
const [busy, setBusy] = useState(false);
|
|
72
|
+
const [error, setError] = useState<string | null>(null);
|
|
73
|
+
const [fieldError, setFieldError] = useState<string | null>(null);
|
|
74
|
+
const [codeRequest, setCodeRequest] = useState<CodeRequest>(NO_CODE_REQUEST);
|
|
75
|
+
const [offerEmailCode, setOfferEmailCode] = useState(false);
|
|
76
|
+
const [emailCodeMsg, setEmailCodeMsg] = useState<string | null>(null);
|
|
77
|
+
|
|
78
|
+
async function submit(withCode?: string) {
|
|
79
|
+
setBusy(true);
|
|
80
|
+
setError(null);
|
|
81
|
+
setOfferEmailCode(false);
|
|
82
|
+
try {
|
|
83
|
+
const r = await credentialSignIn({ email, password, code: withCode }, fetchImpl);
|
|
84
|
+
if (r.kind === 'success') {
|
|
85
|
+
const destination = resolveDestination(callbackUrl);
|
|
86
|
+
if (onSignedIn) onSignedIn(destination);
|
|
87
|
+
else window.location.href = destination;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (r.kind === 'two_factor') {
|
|
91
|
+
setCodeRequest(r.codeRequest);
|
|
92
|
+
setStep('code');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
setError(r.message);
|
|
96
|
+
if (r.kind === 'error') setOfferEmailCode(r.offerEmailCode);
|
|
97
|
+
} finally {
|
|
98
|
+
setBusy(false);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function onCredentialsSubmit(e: React.FormEvent) {
|
|
103
|
+
e.preventDefault();
|
|
104
|
+
const invalid = validateCredentials(email, password);
|
|
105
|
+
if (invalid) {
|
|
106
|
+
setFieldError(invalid.email ?? invalid.password ?? null);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
setFieldError(null);
|
|
110
|
+
void submit();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function onCodeSubmit(e: React.FormEvent) {
|
|
114
|
+
e.preventDefault();
|
|
115
|
+
const trimmed = code.trim();
|
|
116
|
+
if (!trimmed) {
|
|
117
|
+
setFieldError('Enter your authentication code.');
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
setFieldError(null);
|
|
121
|
+
void submit(trimmed);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function onBack() {
|
|
125
|
+
setStep('credentials');
|
|
126
|
+
setCodeRequest(NO_CODE_REQUEST);
|
|
127
|
+
setCode('');
|
|
128
|
+
setFieldError(null);
|
|
129
|
+
setError(null);
|
|
130
|
+
setOfferEmailCode(false);
|
|
131
|
+
setEmailCodeMsg(null);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function askForEmailCode() {
|
|
135
|
+
setBusy(true);
|
|
136
|
+
setEmailCodeMsg(null);
|
|
137
|
+
try {
|
|
138
|
+
const r = await requestEmailCode(fetchImpl);
|
|
139
|
+
if (r.kind === 'requested') {
|
|
140
|
+
setCodeRequest(r.codeRequest);
|
|
141
|
+
setError(null);
|
|
142
|
+
setOfferEmailCode(false);
|
|
143
|
+
setEmailCodeMsg('We asked for a code to be emailed to you. Enter it above when it arrives.');
|
|
144
|
+
} else {
|
|
145
|
+
setEmailCodeMsg(r.message);
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
setBusy(false);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const problem = fieldError ?? error;
|
|
153
|
+
const problemLine = problem && (
|
|
154
|
+
<p role="alert" data-testid="credential-sign-in-error" className="text-sm mt-3" style={{ color: 'var(--color-error, #ef4444)' }}>
|
|
155
|
+
{problem}
|
|
156
|
+
</p>
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
if (step === 'code') {
|
|
160
|
+
return (
|
|
161
|
+
<div data-testid="credential-sign-in-code-step" className="text-left">
|
|
162
|
+
<p className="text-sm mb-4" style={{ color: 'var(--text-primary, #111827)' }}>{codeStepInstruction(email, codeRequest)}</p>
|
|
163
|
+
<form onSubmit={onCodeSubmit} noValidate className="space-y-4">
|
|
164
|
+
<div>
|
|
165
|
+
<label htmlFor="credential-code" className="block text-sm font-medium mb-2" style={{ color: 'var(--text-primary, #111827)' }}>
|
|
166
|
+
Authentication code
|
|
167
|
+
</label>
|
|
168
|
+
<input
|
|
169
|
+
id="credential-code"
|
|
170
|
+
name="code"
|
|
171
|
+
type="text"
|
|
172
|
+
inputMode="numeric"
|
|
173
|
+
autoComplete="one-time-code"
|
|
174
|
+
required
|
|
175
|
+
placeholder="000000"
|
|
176
|
+
value={code}
|
|
177
|
+
disabled={busy}
|
|
178
|
+
onChange={(e) => {
|
|
179
|
+
setCode(e.target.value);
|
|
180
|
+
setFieldError(null);
|
|
181
|
+
}}
|
|
182
|
+
className="w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 disabled:opacity-50"
|
|
183
|
+
style={inputStyle}
|
|
184
|
+
/>
|
|
185
|
+
</div>
|
|
186
|
+
<button
|
|
187
|
+
type="submit"
|
|
188
|
+
disabled={busy}
|
|
189
|
+
className="w-full py-3 px-4 rounded-lg font-semibold focus:outline-none focus:ring-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
|
190
|
+
style={{ background: 'var(--btn-primary-bg, #11B588)', color: 'var(--btn-primary-text, white)' }}
|
|
191
|
+
>
|
|
192
|
+
{busy ? 'Verifying…' : 'Verify'}
|
|
193
|
+
</button>
|
|
194
|
+
</form>
|
|
195
|
+
<button type="button" onClick={onBack} disabled={busy} className="text-sm underline mt-4" style={{ background: 'none', border: 'none', padding: 0, color: 'var(--text-muted, #6b7280)' }}>
|
|
196
|
+
Back
|
|
197
|
+
</button>
|
|
198
|
+
{problemLine}
|
|
199
|
+
{(offerEmailCode || emailCodeMsg) && (
|
|
200
|
+
<div data-testid="email-code-offer" className="mt-4">
|
|
201
|
+
{offerEmailCode && (
|
|
202
|
+
<button type="button" onClick={() => void askForEmailCode()} disabled={busy} className="text-sm font-semibold underline" style={{ background: 'none', border: 'none', padding: 0, color: 'var(--text-primary, #111827)' }}>
|
|
203
|
+
Email me a code instead
|
|
204
|
+
</button>
|
|
205
|
+
)}
|
|
206
|
+
{emailCodeMsg && (
|
|
207
|
+
<p role="status" data-testid="email-code-offer-msg" className="text-sm mt-2" style={{ color: 'var(--text-primary, #111827)' }}>
|
|
208
|
+
{emailCodeMsg}
|
|
209
|
+
</p>
|
|
210
|
+
)}
|
|
211
|
+
</div>
|
|
212
|
+
)}
|
|
213
|
+
</div>
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return (
|
|
218
|
+
<div data-testid="credential-sign-in" className="text-left">
|
|
219
|
+
<TraditionalAuthSection
|
|
220
|
+
email={email}
|
|
221
|
+
password={password}
|
|
222
|
+
onEmailChange={(v) => {
|
|
223
|
+
setEmail(v);
|
|
224
|
+
setFieldError(null);
|
|
225
|
+
}}
|
|
226
|
+
onPasswordChange={(v) => {
|
|
227
|
+
setPassword(v);
|
|
228
|
+
setFieldError(null);
|
|
229
|
+
}}
|
|
230
|
+
onSubmit={onCredentialsSubmit}
|
|
231
|
+
isLoading={busy}
|
|
232
|
+
buttonText="Sign in"
|
|
233
|
+
showForgotPassword={showForgotPassword}
|
|
234
|
+
/>
|
|
235
|
+
{problemLine}
|
|
236
|
+
</div>
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export default CredentialSignInForm;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2302 cut 2: moved VERBATIM (logic unchanged) from VibeID-Customer-Portal src/lib/auth/authorize-resume.ts.
|
|
3
|
+
* PAY-1500 (portal half of PAY-1479): resume the IdP OAuth authorize request after 2FA.
|
|
4
|
+
*
|
|
5
|
+
* The IdP sends an OAuth principal who still owes 2FA to the portal's /account-auth/verify-code with
|
|
6
|
+
* ?next_step=enroll_mfa|mfa_verify&callbackUrl=<absolute IdP authorize URL>&return_url=<same>
|
|
7
|
+
* (OAuthController.Authorize; hotfix-2 66ca7a8eb routes BOTH cases to verify-code, /account/security is gone). safeCallbackPath rightly refuses that absolute URL,
|
|
8
|
+
* so after 2FA the user used to land on the default page and sign-in never finished.
|
|
9
|
+
*
|
|
10
|
+
* This is NOT a relaxation of safeCallbackPath. The browser is sent to the portal's own
|
|
11
|
+
* /api/oauth/resume, which checks return_url SERVER-SIDE against IDP_URL (origin + the authorize path)
|
|
12
|
+
* and only then redirects. Anything else is refused. IDP_URL never reaches the client.
|
|
13
|
+
*/
|
|
14
|
+
export const AUTHORIZE_RESUME_ROUTE = '/api/oauth/resume';
|
|
15
|
+
const AUTHORIZE_PATH = '/api/oauth/authorize';
|
|
16
|
+
|
|
17
|
+
/** True only for `<IDP_URL origin>/api/oauth/authorize` (path case-insensitive, as ASP.NET routes). */
|
|
18
|
+
export function isIdpAuthorizeUrl(candidate: string | null | undefined, idpBaseUrl: string): boolean {
|
|
19
|
+
if (typeof candidate !== 'string' || candidate === '') return false;
|
|
20
|
+
try {
|
|
21
|
+
const u = new URL(candidate);
|
|
22
|
+
const idp = new URL(idpBaseUrl);
|
|
23
|
+
return (u.protocol === 'https:' || u.protocol === 'http:') && u.origin === idp.origin && u.pathname.toLowerCase() === AUTHORIZE_PATH;
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Server side: the redirect target, REBUILT from trusted parts - IDP_URL's origin and the authorize path
|
|
31
|
+
* are ours; only the query string comes from the request. Null unless isIdpAuthorizeUrl holds.
|
|
32
|
+
*/
|
|
33
|
+
export function idpAuthorizeRedirect(candidate: string | null | undefined, idpBaseUrl: string): string | null {
|
|
34
|
+
if (!isIdpAuthorizeUrl(candidate, idpBaseUrl)) return null;
|
|
35
|
+
const query = new URL(candidate as string).search;
|
|
36
|
+
return `${new URL(idpBaseUrl).origin}/api/OAuth/authorize${query}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Client side: the SAME-ORIGIN portal path that resumes authorize, or null when the IdP did not ask for one.
|
|
41
|
+
* Callers still pass the result through safeCallbackPath before navigating.
|
|
42
|
+
*
|
|
43
|
+
* WHY THE ASTERISK IS RE-ENCODED (PAY-1547, measured by NextPert 59939, completeness measured here).
|
|
44
|
+
* One consumer of this value is `authClient.signIn.social({ callbackURL })`, which POSTs to better-auth
|
|
45
|
+
* and is validated by its own originCheckMiddleware BEFORE anything redirects. For a relative path that
|
|
46
|
+
* check is decided entirely by one regex (better-auth 1.5.6, auth/trusted-origins.mjs:16 - the
|
|
47
|
+
* `allowRelativePaths` branch, and api/middlewares/origin-check.mjs:51 passes
|
|
48
|
+
* `allowRelativePaths: label !== 'origin'`, so it IS that branch for a callbackURL):
|
|
49
|
+
*
|
|
50
|
+
* /^\/(?!\/|\\|%2f|%5c)[\w\-.\+\/@]*(?:\?[\w\-.\+\/=&%@]*)?$/
|
|
51
|
+
*
|
|
52
|
+
* A character this helper emits RAW and that charset rejects is a hard 403 INVALID_CALLBACK_URL on the
|
|
53
|
+
* Google button - not a silent fallback. Measured exhaustively over printable ASCII by diffing what
|
|
54
|
+
* `URLSearchParams` leaves raw against that charset: the raw set is alphanumerics plus `* - . _`, and
|
|
55
|
+
* *** `*` IS THE ONLY REJECTED MEMBER *** (`%` is permitted, which is why every other special character
|
|
56
|
+
* survives - URLSearchParams already percent-encoded it).
|
|
57
|
+
*
|
|
58
|
+
* `*` is reachable because `state` and `scope` are chosen by the OAuth CLIENT, not by us, so we cannot
|
|
59
|
+
* decline to emit it. `%2A` is the same character to every parser: re-reading this query string returns
|
|
60
|
+
* the byte-identical `return_url` (asserted in test/authorize-resume.test.cjs), so this is an encoding
|
|
61
|
+
* change and NOT a value change. It is applied here, at the ONE computation, rather than at the sinks -
|
|
62
|
+
* the two `window.location.href` sinks are browser navigations that touch no library and for which this
|
|
63
|
+
* is a behavioural no-op, so there is no reason to make them each carry it.
|
|
64
|
+
*/
|
|
65
|
+
export function authorizeResumeHref(returnUrl: string | null | undefined): string | null {
|
|
66
|
+
if (typeof returnUrl !== 'string' || returnUrl === '') return null;
|
|
67
|
+
const query = new URLSearchParams({ return_url: returnUrl }).toString().replace(/\*/g, '%2A');
|
|
68
|
+
return `${AUTHORIZE_RESUME_ROUTE}?${query}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ───────────────────────── 4.7.5 (PAY-2305): the authorize call is made SERVER-SIDE ─────────────────────────
|
|
72
|
+
//
|
|
73
|
+
// WHY: Core's /api/oauth/authorize identifies a user ONLY from an `Authorization: Bearer` header (JwtMiddleware reads no cookie,
|
|
74
|
+
// and a browser navigation cannot send a header), so the 4.7.0-4.7.4 behaviour - 302 the BROWSER to authorize - could never
|
|
75
|
+
// produce a code for anyone. The resume route now calls authorize itself with the signed-in user's IdP access token and relays
|
|
76
|
+
// only the verified outcome. These helpers are the pure, testable parts.
|
|
77
|
+
|
|
78
|
+
export interface ServerAuthorizeParams {
|
|
79
|
+
idpBaseUrl: string;
|
|
80
|
+
/** This app's IdP client slug (CLIENT_ID). The request's client_id must equal it. */
|
|
81
|
+
clientId: string;
|
|
82
|
+
/** The app's REGISTERED redirect_uri, e.g. http://localhost:3000/api/auth/callback. The request's redirect_uri must equal it exactly. */
|
|
83
|
+
redirectUri: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ServerAuthorizeRequest {
|
|
87
|
+
/** Built from constants + validated pieces only. This is what gets fetched. */
|
|
88
|
+
url: string;
|
|
89
|
+
state: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const CHALLENGE_RE = /^[A-Za-z0-9_-]{43,128}$/;
|
|
93
|
+
const STATE_RE = /^[A-Za-z0-9._~-]{1,256}$/;
|
|
94
|
+
const SCOPE_RE = /^[A-Za-z0-9:._ -]{1,200}$/;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Build the authorize URL to call, or null (refuse). Origin, path, response_type, client_id and redirect_uri are OURS; from
|
|
98
|
+
* return_url only code_challenge (+ method, S256 only), state and scope are taken, each charset/length validated. A return_url for
|
|
99
|
+
* another client or another redirect_uri is refused (no "someone else's client"). Unknown extra parameters are NOT forwarded.
|
|
100
|
+
*/
|
|
101
|
+
export function buildServerAuthorizeRequest(returnUrl: string | null | undefined, p: ServerAuthorizeParams): ServerAuthorizeRequest | null {
|
|
102
|
+
if (!isIdpAuthorizeUrl(returnUrl, p.idpBaseUrl) || !p.clientId || !p.redirectUri) return null;
|
|
103
|
+
const q = new URL(returnUrl as string).searchParams;
|
|
104
|
+
const once = (name: string): string | null => {
|
|
105
|
+
const all = q.getAll(name);
|
|
106
|
+
return all.length === 1 ? all[0] : all.length === 0 ? null : '\u0000'; // a repeated parameter is ambiguous: refused below
|
|
107
|
+
};
|
|
108
|
+
const responseType = once('response_type');
|
|
109
|
+
if (responseType !== null && responseType !== 'code') return null;
|
|
110
|
+
if (once('client_id') !== p.clientId) return null;
|
|
111
|
+
if (once('redirect_uri') !== p.redirectUri) return null;
|
|
112
|
+
const challenge = once('code_challenge');
|
|
113
|
+
const method = once('code_challenge_method');
|
|
114
|
+
const state = once('state');
|
|
115
|
+
const scope = once('scope');
|
|
116
|
+
if (challenge === null || !CHALLENGE_RE.test(challenge)) return null;
|
|
117
|
+
if (method !== 'S256') return null;
|
|
118
|
+
if (state === null || !STATE_RE.test(state)) return null;
|
|
119
|
+
if (scope !== null && !SCOPE_RE.test(scope)) return null;
|
|
120
|
+
|
|
121
|
+
const out = new URLSearchParams();
|
|
122
|
+
out.set('response_type', 'code');
|
|
123
|
+
out.set('client_id', p.clientId);
|
|
124
|
+
out.set('redirect_uri', p.redirectUri);
|
|
125
|
+
if (scope !== null) out.set('scope', scope);
|
|
126
|
+
out.set('state', state);
|
|
127
|
+
out.set('code_challenge', challenge);
|
|
128
|
+
out.set('code_challenge_method', 'S256');
|
|
129
|
+
return { url: `${new URL(p.idpBaseUrl).origin}${AUTHORIZE_PATH}?${out.toString()}`, state };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The IdP's answer to the server-side authorize call. Returns the RELATIVE path+query to send the browser to, or null (refuse).
|
|
134
|
+
* Only a redirect whose Location is EXACTLY the registered redirect_uri (origin + path), with a code and the state we sent and no
|
|
135
|
+
* error, qualifies. The relayed value is REBUILT from the validated code and state, never copied from the Location.
|
|
136
|
+
*/
|
|
137
|
+
export function relayRegisteredCallback(status: number, location: string | null | undefined, redirectUri: string, sentState: string): string | null {
|
|
138
|
+
if (status < 300 || status > 399 || typeof location !== 'string' || location === '') return null;
|
|
139
|
+
let loc: URL;
|
|
140
|
+
let reg: URL;
|
|
141
|
+
try {
|
|
142
|
+
reg = new URL(redirectUri);
|
|
143
|
+
loc = new URL(location, reg.origin);
|
|
144
|
+
} catch {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
if (loc.origin !== reg.origin || loc.pathname !== reg.pathname) return null;
|
|
148
|
+
if (loc.searchParams.has('error')) return null;
|
|
149
|
+
const codes = loc.searchParams.getAll('code');
|
|
150
|
+
const states = loc.searchParams.getAll('state');
|
|
151
|
+
if (codes.length !== 1 || !/^[A-Za-z0-9._~+/=-]{8,512}$/.test(codes[0])) return null;
|
|
152
|
+
if (states.length !== 1 || states[0] !== sentState) return null;
|
|
153
|
+
return `${reg.pathname}?${new URLSearchParams({ code: codes[0], state: sentState }).toString()}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The resume must be a same-site navigation. Sec-Fetch-Site decides when the browser sends it; otherwise Referer must be this
|
|
158
|
+
* app's own origin; with neither it is refused (a crafted cross-site link must not make the victim's browser trigger authorize
|
|
159
|
+
* with the victim's token).
|
|
160
|
+
*/
|
|
161
|
+
export function isSameSiteResume(headers: { get(name: string): string | null }, appOrigin: string): boolean {
|
|
162
|
+
const sfs = headers.get('sec-fetch-site');
|
|
163
|
+
// same-origin or none only: a sibling subdomain ('same-site') is not this app.
|
|
164
|
+
if (sfs !== null) return sfs === 'same-origin' || sfs === 'none';
|
|
165
|
+
const referer = headers.get('referer');
|
|
166
|
+
if (!referer) return false;
|
|
167
|
+
try {
|
|
168
|
+
return new URL(referer).origin === appOrigin;
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Binds the resume to a browser that STARTED this app's OAuth flow: better-auth (storeStateStrategy 'cookie') sets an
|
|
176
|
+
* `oauth_state` cookie (Max-Age 600; name may carry a `__Secure-` and an app prefix) when sign-in begins. Its value is sealed, so only
|
|
177
|
+
* its presence is checked; the state MATCH is enforced by better-auth's callback, which fails closed. A crafted link opened in a
|
|
178
|
+
* browser that never began the flow has no such cookie and is refused here, before the user's token is used.
|
|
179
|
+
*/
|
|
180
|
+
export function hasOAuthStateCookie(cookieHeader: string | null | undefined): boolean {
|
|
181
|
+
if (typeof cookieHeader !== 'string') return false;
|
|
182
|
+
return cookieHeader.split(';').some((part) => {
|
|
183
|
+
const i = part.indexOf('=');
|
|
184
|
+
const name = (i < 0 ? part : part.slice(0, i)).trim();
|
|
185
|
+
return /(^|[._-])oauth_state$/.test(name) && i >= 0 && part.slice(i + 1).trim() !== '';
|
|
186
|
+
});
|
|
187
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-1777 item 5 (QAPert-NightHawk, PR 663 G4 thread 4395; coverage widened per BAPert 64034): THE way a server-side call
|
|
3
|
+
* that carries a user's (or a provisional) bearer token talks to the identity service.
|
|
4
|
+
*
|
|
5
|
+
* A bearer must never follow a redirect. Modern fetch drops Authorization on a CROSS-origin hop, but a same-origin hop - or
|
|
6
|
+
* an older runtime - does not, and we do not rely on that. So:
|
|
7
|
+
* - the request is always sent with redirect: 'manual' (set AFTER the caller's init, so no caller can switch it back);
|
|
8
|
+
* - any 3xx, or an opaque redirect, is never followed and never relayed: the caller receives a synthetic
|
|
9
|
+
* 502 { success:false, error:{ code:'IDP_UNREACHABLE' } } Response instead, which every existing non-2xx branch at the
|
|
10
|
+
* call sites already handles. Every other response is returned untouched.
|
|
11
|
+
*
|
|
12
|
+
* Moved from VibeID-Customer-Portal (src/lib/idp/bearer-fetch.ts) into the package by PAY-2302; the portal's gate
|
|
13
|
+
* (testing/qa/idp-bearer-no-redirect-gate.js) keeps inventorying its own Authorization-bearing fetches.
|
|
14
|
+
*/
|
|
15
|
+
export const REDIRECT_REFUSED_CODE = 'IDP_UNREACHABLE';
|
|
16
|
+
|
|
17
|
+
export function isRedirectResponse(res: Response): boolean {
|
|
18
|
+
return res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function bearerFetch(input: string | URL, init: RequestInit = {}): Promise<Response> {
|
|
22
|
+
const res = await fetch(input, { ...init, redirect: 'manual' });
|
|
23
|
+
if (!isRedirectResponse(res)) return res;
|
|
24
|
+
return new Response(
|
|
25
|
+
JSON.stringify({
|
|
26
|
+
success: false,
|
|
27
|
+
error: { code: REDIRECT_REFUSED_CODE, message: 'The identity service answered with a redirect; the call was not followed' },
|
|
28
|
+
}),
|
|
29
|
+
{ status: 502, headers: { 'Content-Type': 'application/json' } },
|
|
30
|
+
);
|
|
31
|
+
}
|