@coreiam/auth 1.0.8 → 1.0.10
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/nextjs/actions.d.ts +1 -1
- package/dist/nextjs/actions.js +8 -37
- package/dist/nextjs/index.js +0 -2
- package/dist/nextjs/middleware.js +2 -23
- package/dist/nextjs/provider.d.ts +1 -10
- package/dist/nextjs/provider.js +51 -25
- package/package.json +1 -1
package/dist/nextjs/actions.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export interface AuthResult {
|
|
|
4
4
|
status: number;
|
|
5
5
|
data: any;
|
|
6
6
|
}
|
|
7
|
-
export declare
|
|
7
|
+
export declare function getSession(): Promise<CoreIAMIdentity | null>;
|
|
8
8
|
export declare function loginActionSdk(identifier: string, password: string): Promise<AuthResult>;
|
|
9
9
|
export declare function registerActionSdk(userData: any): Promise<AuthResult>;
|
|
10
10
|
export declare function logoutActionSdk(): Promise<AuthResult>;
|
package/dist/nextjs/actions.js
CHANGED
|
@@ -1,25 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
2
|
+
// src/nextjs/actions.ts
|
|
3
|
+
// REMOVE 'use server' from here.
|
|
3
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.getSession =
|
|
5
|
+
exports.getSession = getSession;
|
|
5
6
|
exports.loginActionSdk = loginActionSdk;
|
|
6
7
|
exports.registerActionSdk = registerActionSdk;
|
|
7
8
|
exports.logoutActionSdk = logoutActionSdk;
|
|
8
|
-
const react_1 = require("react");
|
|
9
9
|
const headers_1 = require("next/headers");
|
|
10
10
|
const core_1 = require("../core");
|
|
11
|
-
// FIX: lazy singleton instead of `const iam = new CoreIAM();` at module
|
|
12
|
-
// scope. The constructor throws if COREIAM_API_KEY/COREIAM_API_URL are
|
|
13
|
-
// missing — fine on the server, where those env vars exist — but a
|
|
14
|
-
// module-level throw happens the instant the module is evaluated, before
|
|
15
|
-
// any function in it is even called. If this module's 'use server'
|
|
16
|
-
// boundary is ever not recognized correctly by the bundler (see the note
|
|
17
|
-
// on the browser error below), the real module gets included in the client
|
|
18
|
-
// bundle instead of being swapped for action-reference stubs, and that
|
|
19
|
-
// throw fires in the browser instead, where those env vars are never
|
|
20
|
-
// defined. Making this lazy doesn't fix a lost 'use server' boundary by
|
|
21
|
-
// itself, but it does mean import alone can never crash — only an actual
|
|
22
|
-
// invocation can, which is strictly better either way.
|
|
23
11
|
let _iam = null;
|
|
24
12
|
function getIam() {
|
|
25
13
|
if (!_iam)
|
|
@@ -71,27 +59,8 @@ async function syncCookiesToNext(response) {
|
|
|
71
59
|
}
|
|
72
60
|
}
|
|
73
61
|
}
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
// same request/render (direct calls, or nested inside a consumer's own
|
|
77
|
-
// currentUser()-style wrapper) now collapse into a single network round trip
|
|
78
|
-
// to CoreIAM automatically, for every current and future call site.
|
|
79
|
-
//
|
|
80
|
-
// Deliberately NOT adding a refresh-retry fallback here (an earlier draft in
|
|
81
|
-
// this thread did). Next.js only allows cookies().set()/cookies().delete()
|
|
82
|
-
// inside a Server Action or Route Handler — never during a Server Component
|
|
83
|
-
// render — and getSession() is called from both (e.g. from a plain
|
|
84
|
-
// RootLayout render, and from consumers' currentUser()-style wrappers used
|
|
85
|
-
// throughout Server Components). A refresh path that can only sometimes
|
|
86
|
-
// persist its new cookies isn't safe: on the render-context call it would
|
|
87
|
-
// still redeem the refresh token server-side (rotating/burning it) but never
|
|
88
|
-
// deliver the new one to the browser, stranding the client on a now-dead
|
|
89
|
-
// refresh token. Refresh belongs solely in middleware.ts, which is the one
|
|
90
|
-
// place in the request lifecycle actually allowed to mutate response
|
|
91
|
-
// cookies. If middleware already refreshed upstream, this succeeds; if
|
|
92
|
-
// middleware's refresh also failed, returning null here is correct, not a
|
|
93
|
-
// bug to work around.
|
|
94
|
-
exports.getSession = (0, react_1.cache)(async () => {
|
|
62
|
+
// This is called by Server Components (e.g., layout.tsx)
|
|
63
|
+
async function getSession() {
|
|
95
64
|
const reqHeaders = await (0, headers_1.headers)();
|
|
96
65
|
const response = await getIam().proxy('/auth/profile', { method: 'GET' }, reqHeaders);
|
|
97
66
|
if (!response.ok)
|
|
@@ -100,7 +69,9 @@ exports.getSession = (0, react_1.cache)(async () => {
|
|
|
100
69
|
if (!coreIamIdentity?.sub)
|
|
101
70
|
return null;
|
|
102
71
|
return coreIamIdentity;
|
|
103
|
-
}
|
|
72
|
+
}
|
|
73
|
+
// These are no longer called by the SDK's provider.tsx,
|
|
74
|
+
// but can still be used by Qalam's Server Actions if needed.
|
|
104
75
|
async function loginActionSdk(identifier, password) {
|
|
105
76
|
const reqHeaders = await (0, headers_1.headers)();
|
|
106
77
|
try {
|
package/dist/nextjs/index.js
CHANGED
|
@@ -10,7 +10,6 @@ Object.defineProperty(exports, "loginActionSdk", { enumerable: true, get: functi
|
|
|
10
10
|
Object.defineProperty(exports, "registerActionSdk", { enumerable: true, get: function () { return actions_1.registerActionSdk; } });
|
|
11
11
|
Object.defineProperty(exports, "logoutActionSdk", { enumerable: true, get: function () { return actions_1.logoutActionSdk; } });
|
|
12
12
|
Object.defineProperty(exports, "getSession", { enumerable: true, get: function () { return actions_1.getSession; } });
|
|
13
|
-
// FIX: Export the new handleCoreIamAuth function instead of the old middleware
|
|
14
13
|
var middleware_1 = require("./middleware");
|
|
15
14
|
Object.defineProperty(exports, "coreIamMiddleware", { enumerable: true, get: function () { return middleware_1.coreIamMiddleware; } });
|
|
16
15
|
const server_1 = require("next/server");
|
|
@@ -18,7 +17,6 @@ const core_1 = require("../core");
|
|
|
18
17
|
class NextHandlers {
|
|
19
18
|
iam;
|
|
20
19
|
constructor(iam) {
|
|
21
|
-
// If no iam client is provided, instantiate one using the env variables
|
|
22
20
|
this.iam = iam || new core_1.CoreIAM({ apiKey: process.env.COREIAM_API_KEY, baseUrl: process.env.COREIAM_API_URL });
|
|
23
21
|
}
|
|
24
22
|
async handleProxy(req, internalPath) {
|
|
@@ -4,24 +4,6 @@ exports.coreIamMiddleware = coreIamMiddleware;
|
|
|
4
4
|
// src/nextjs/middleware.ts
|
|
5
5
|
const server_1 = require("next/server");
|
|
6
6
|
const jwt_decode_1 = require("jwt-decode");
|
|
7
|
-
// Module-level: persists across requests as long as this runs in a single,
|
|
8
|
-
// long-running Node process (true for a VPS deploy). This lets concurrent
|
|
9
|
-
// middleware invocations on THIS process share one in-flight refresh
|
|
10
|
-
// instead of each independently redeeming the same (single-use) refresh
|
|
11
|
-
// token and knocking each other out with 401 Invalid refresh token.
|
|
12
|
-
//
|
|
13
|
-
// This lock is per-process by nature — no amount of cleverness here makes
|
|
14
|
-
// it coordinate across multiple Node processes/instances, since it's just
|
|
15
|
-
// in-memory state. That's fine: it's an optimization (avoids the latency
|
|
16
|
-
// and CoreIAM load of firing off N calls that are mostly doomed to fail
|
|
17
|
-
// anyway), not the thing that makes rotation actually correct under
|
|
18
|
-
// concurrency. That guarantee now lives where all callers ultimately
|
|
19
|
-
// converge regardless of how many Qalam or CoreIAM processes exist: a
|
|
20
|
-
// conditional (WHERE isRevoked: false) update inside a transaction in
|
|
21
|
-
// auth.service.ts's refreshToken(), enforced by Postgres itself. If this
|
|
22
|
-
// lock is ever bypassed or scaled beyond one process, refreshes just get a
|
|
23
|
-
// little less efficient (a few requests eagerly hit CoreIAM instead of
|
|
24
|
-
// waiting on a local promise) — they don't get less correct.
|
|
25
7
|
let refreshInFlight = null;
|
|
26
8
|
async function performRefresh(refreshTokenCookie, jwtCookie, gatewayUrl) {
|
|
27
9
|
try {
|
|
@@ -92,21 +74,18 @@ async function coreIamMiddleware(request) {
|
|
|
92
74
|
const response = server_1.NextResponse.next({
|
|
93
75
|
request: { headers: requestHeaders },
|
|
94
76
|
});
|
|
95
|
-
// FIX: flags now match cookie.util.ts exactly (httpOnly, sameSite:
|
|
96
|
-
// 'strict', secure in production only, correct maxAge per cookie),
|
|
97
|
-
// instead of the placeholder flags used before that file was reviewed.
|
|
98
77
|
const isProd = process.env.NODE_ENV === 'production';
|
|
99
78
|
response.cookies.set('jwt', result.jwt, {
|
|
100
79
|
httpOnly: true,
|
|
101
80
|
secure: isProd,
|
|
102
81
|
sameSite: 'strict',
|
|
103
|
-
maxAge: 24 * 60 * 60,
|
|
82
|
+
maxAge: 24 * 60 * 60,
|
|
104
83
|
});
|
|
105
84
|
response.cookies.set('refreshToken', result.refreshToken, {
|
|
106
85
|
httpOnly: true,
|
|
107
86
|
secure: isProd,
|
|
108
87
|
sameSite: 'strict',
|
|
109
|
-
maxAge: 7 * 24 * 60 * 60,
|
|
88
|
+
maxAge: 7 * 24 * 60 * 60,
|
|
110
89
|
});
|
|
111
90
|
return { response, isAuthenticated: true };
|
|
112
91
|
}
|
|
@@ -1,22 +1,15 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import type { CoreIAMIdentity } from '../core';
|
|
3
3
|
export interface CoreIAMRedirects {
|
|
4
|
-
/** Where to send the user after a successful login, if no callbackUrl is passed to login(). */
|
|
5
4
|
afterLogin?: string;
|
|
6
|
-
/** Where to send the user after logout. */
|
|
7
5
|
afterLogout?: string;
|
|
8
6
|
}
|
|
9
7
|
interface LoginResult {
|
|
10
8
|
success?: boolean;
|
|
11
9
|
error?: string;
|
|
10
|
+
twoFactor?: boolean;
|
|
12
11
|
}
|
|
13
12
|
interface AuthContextType {
|
|
14
|
-
/**
|
|
15
|
-
* Generic CoreIAM identity (sub/email/roles/tenantId) — NOT an app-shaped
|
|
16
|
-
* user. This SDK has no knowledge of any consumer's local user model
|
|
17
|
-
* (roles, profile fields, etc). Consumers that need an enriched user
|
|
18
|
-
* object should build their own layer on top of this, keyed off `sub`.
|
|
19
|
-
*/
|
|
20
13
|
identity: CoreIAMIdentity | null;
|
|
21
14
|
isLoading: boolean;
|
|
22
15
|
isAuthenticated: boolean;
|
|
@@ -30,9 +23,7 @@ interface AuthContextType {
|
|
|
30
23
|
}
|
|
31
24
|
export declare function CoreIAMProvider({ children, initialIdentity, redirects, }: {
|
|
32
25
|
children: React.ReactNode;
|
|
33
|
-
/** Pass the result of a server-side getSession() call to skip the client fetch on first paint. */
|
|
34
26
|
initialIdentity?: CoreIAMIdentity | null;
|
|
35
|
-
/** Where to redirect after login/logout. Omit for no redirect (caller handles navigation itself). */
|
|
36
27
|
redirects?: CoreIAMRedirects;
|
|
37
28
|
}): import("react/jsx-runtime").JSX.Element;
|
|
38
29
|
export declare function useAuth(): AuthContextType;
|
package/dist/nextjs/provider.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
// src/nextjs/provider.tsx
|
|
2
3
|
'use client';
|
|
3
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
5
|
exports.CoreIAMProvider = CoreIAMProvider;
|
|
@@ -6,7 +7,6 @@ exports.useAuth = useAuth;
|
|
|
6
7
|
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
7
8
|
const react_1 = require("react");
|
|
8
9
|
const navigation_1 = require("next/navigation");
|
|
9
|
-
const actions_1 = require("./actions");
|
|
10
10
|
const AuthContext = (0, react_1.createContext)({
|
|
11
11
|
identity: null,
|
|
12
12
|
isLoading: true,
|
|
@@ -20,10 +20,11 @@ function CoreIAMProvider({ children, initialIdentity, redirects = {}, }) {
|
|
|
20
20
|
const [identity, setIdentity] = (0, react_1.useState)(initialIdentity ?? null);
|
|
21
21
|
const [isLoading, setIsLoading] = (0, react_1.useState)(initialIdentity === undefined);
|
|
22
22
|
const router = (0, navigation_1.useRouter)();
|
|
23
|
-
const refetchIdentity = async () => {
|
|
23
|
+
const refetchIdentity = (0, react_1.useCallback)(async () => {
|
|
24
24
|
try {
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
// Call the Next.js API route, which securely calls CoreIAM
|
|
26
|
+
const res = await fetch('/api/auth/session', { credentials: 'include' });
|
|
27
|
+
setIdentity(res.ok ? await res.json() : null);
|
|
27
28
|
}
|
|
28
29
|
catch {
|
|
29
30
|
setIdentity(null);
|
|
@@ -31,33 +32,40 @@ function CoreIAMProvider({ children, initialIdentity, redirects = {}, }) {
|
|
|
31
32
|
finally {
|
|
32
33
|
setIsLoading(false);
|
|
33
34
|
}
|
|
34
|
-
};
|
|
35
|
+
}, []);
|
|
35
36
|
(0, react_1.useEffect)(() => {
|
|
36
|
-
// FIX: was `initialIdentity === null`, which can't tell "SSR ran and
|
|
37
|
-
// confirmed you're logged out" (a correct, final null) apart from "no
|
|
38
|
-
// SSR value was ever provided" (a real undefined). Since layout.tsx
|
|
39
|
-
// always calls getSession() and passes its result — even when that
|
|
40
|
-
// result legitimately is null — every logged-out page view was
|
|
41
|
-
// treated as "no SSR value, fetch again," firing a second, wholly
|
|
42
|
-
// redundant /auth/profile call for something SSR had already
|
|
43
|
-
// determined. undefined (the prop genuinely omitted) is the only case
|
|
44
|
-
// that should trigger this fallback fetch.
|
|
45
37
|
if (initialIdentity === undefined) {
|
|
46
38
|
refetchIdentity();
|
|
47
39
|
}
|
|
48
40
|
else {
|
|
49
41
|
setIsLoading(false);
|
|
50
42
|
}
|
|
51
|
-
// Intentionally only on mount — initialIdentity is a one-time SSR seed,
|
|
52
|
-
// not something we want to re-run this effect for if it changes identity.
|
|
53
43
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
54
44
|
}, []);
|
|
55
45
|
const login = async (values, callbackUrl) => {
|
|
56
46
|
setIsLoading(true);
|
|
57
47
|
try {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
48
|
+
// Fetch CSRF token first
|
|
49
|
+
const csrfRes = await fetch('/api/auth/csrf', { credentials: 'include' });
|
|
50
|
+
if (!csrfRes.ok)
|
|
51
|
+
return { error: 'Failed to get CSRF token' };
|
|
52
|
+
const { csrfToken } = await csrfRes.json();
|
|
53
|
+
// Call login API route
|
|
54
|
+
const loginRes = await fetch('/api/auth/login', {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: {
|
|
57
|
+
'Content-Type': 'application/json',
|
|
58
|
+
'x-csrf-token': csrfToken,
|
|
59
|
+
},
|
|
60
|
+
credentials: 'include',
|
|
61
|
+
body: JSON.stringify(values),
|
|
62
|
+
});
|
|
63
|
+
const data = await loginRes.json();
|
|
64
|
+
if (!loginRes.ok) {
|
|
65
|
+
return { error: data.message || data.error || 'Invalid credentials' };
|
|
66
|
+
}
|
|
67
|
+
if (data.twoFactor) {
|
|
68
|
+
return { twoFactor: true };
|
|
61
69
|
}
|
|
62
70
|
await refetchIdentity();
|
|
63
71
|
const target = callbackUrl || redirects.afterLogin;
|
|
@@ -74,7 +82,10 @@ function CoreIAMProvider({ children, initialIdentity, redirects = {}, }) {
|
|
|
74
82
|
};
|
|
75
83
|
const logout = async () => {
|
|
76
84
|
try {
|
|
77
|
-
await (
|
|
85
|
+
await fetch('/api/auth/logout', {
|
|
86
|
+
method: 'POST',
|
|
87
|
+
credentials: 'include',
|
|
88
|
+
});
|
|
78
89
|
}
|
|
79
90
|
finally {
|
|
80
91
|
setIdentity(null);
|
|
@@ -85,14 +96,29 @@ function CoreIAMProvider({ children, initialIdentity, redirects = {}, }) {
|
|
|
85
96
|
const register = async (userData) => {
|
|
86
97
|
setIsLoading(true);
|
|
87
98
|
try {
|
|
88
|
-
const
|
|
89
|
-
if (!
|
|
90
|
-
return { error:
|
|
99
|
+
const csrfRes = await fetch('/api/auth/csrf', { credentials: 'include' });
|
|
100
|
+
if (!csrfRes.ok)
|
|
101
|
+
return { error: 'Failed to get CSRF token' };
|
|
102
|
+
const { csrfToken } = await csrfRes.json();
|
|
103
|
+
const registerRes = await fetch('/api/auth/register', {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: {
|
|
106
|
+
'Content-Type': 'application/json',
|
|
107
|
+
'x-csrf-token': csrfToken,
|
|
108
|
+
},
|
|
109
|
+
credentials: 'include',
|
|
110
|
+
body: JSON.stringify(userData),
|
|
111
|
+
});
|
|
112
|
+
if (!registerRes.ok) {
|
|
113
|
+
const error = await registerRes.json();
|
|
114
|
+
return { error: error.message || error.error || 'Registration failed' };
|
|
91
115
|
}
|
|
92
|
-
//
|
|
93
|
-
// immediately after, same as the flow this replaces did.
|
|
116
|
+
// Auto-login after registration
|
|
94
117
|
return await login({ email: userData.email, password: userData.password });
|
|
95
118
|
}
|
|
119
|
+
catch {
|
|
120
|
+
return { error: 'Something went wrong' };
|
|
121
|
+
}
|
|
96
122
|
finally {
|
|
97
123
|
setIsLoading(false);
|
|
98
124
|
}
|