@imtbl/auth-next-server 2.12.5-alpha.13
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/.eslintrc.cjs +17 -0
- package/LICENSE.md +176 -0
- package/dist/node/config.d.ts +21 -0
- package/dist/node/constants.d.ts +42 -0
- package/dist/node/index.cjs +436 -0
- package/dist/node/index.d.ts +301 -0
- package/dist/node/index.js +390 -0
- package/dist/node/refresh.d.ts +9 -0
- package/dist/node/types.d.ts +111 -0
- package/dist/node/utils/pathMatch.d.ts +10 -0
- package/jest.config.ts +16 -0
- package/package.json +60 -0
- package/src/config.ts +243 -0
- package/src/constants.ts +51 -0
- package/src/index.ts +662 -0
- package/src/refresh.ts +21 -0
- package/src/types.ts +124 -0
- package/src/utils/pathMatch.ts +16 -0
- package/tsconfig.eslint.json +5 -0
- package/tsconfig.json +16 -0
- package/tsconfig.types.json +8 -0
- package/tsup.config.ts +29 -0
package/.eslintrc.cjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
extends: ['../../.eslintrc'],
|
|
3
|
+
parserOptions: {
|
|
4
|
+
project: './tsconfig.eslint.json',
|
|
5
|
+
tsconfigRootDir: __dirname,
|
|
6
|
+
},
|
|
7
|
+
rules: {
|
|
8
|
+
'import/order': 'off',
|
|
9
|
+
'import/no-unresolved': 'off',
|
|
10
|
+
'import/named': 'off',
|
|
11
|
+
'import/default': 'off',
|
|
12
|
+
'import/namespace': 'off',
|
|
13
|
+
'import/no-cycle': 'off',
|
|
14
|
+
'import/no-named-as-default': 'off',
|
|
15
|
+
'import/no-named-as-default-member': 'off',
|
|
16
|
+
},
|
|
17
|
+
};
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { NextAuthConfig } from 'next-auth';
|
|
2
|
+
import type { ImmutableAuthConfig } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Create Auth.js v5 configuration for Immutable authentication
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* // lib/auth.ts
|
|
9
|
+
* import NextAuth from "next-auth";
|
|
10
|
+
* import { createAuthConfig } from "@imtbl/auth-next-server";
|
|
11
|
+
*
|
|
12
|
+
* const config = {
|
|
13
|
+
* clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
|
|
14
|
+
* redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
|
|
15
|
+
* };
|
|
16
|
+
*
|
|
17
|
+
* export const { handlers, auth, signIn, signOut } = NextAuth(createAuthConfig(config));
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare function createAuthConfig(config: ImmutableAuthConfig): NextAuthConfig;
|
|
21
|
+
export declare const createAuthOptions: typeof createAuthConfig;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared constants for @imtbl/auth-next-server
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Default Immutable authentication domain
|
|
6
|
+
*/
|
|
7
|
+
export declare const DEFAULT_AUTH_DOMAIN = "https://auth.immutable.com";
|
|
8
|
+
/**
|
|
9
|
+
* Default OAuth audience
|
|
10
|
+
*/
|
|
11
|
+
export declare const DEFAULT_AUDIENCE = "platform_api";
|
|
12
|
+
/**
|
|
13
|
+
* Default OAuth scopes
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_SCOPE = "openid profile email offline_access transact";
|
|
16
|
+
/**
|
|
17
|
+
* NextAuth credentials provider ID for Immutable
|
|
18
|
+
*/
|
|
19
|
+
export declare const IMMUTABLE_PROVIDER_ID = "immutable";
|
|
20
|
+
/**
|
|
21
|
+
* Default NextAuth API base path
|
|
22
|
+
*/
|
|
23
|
+
export declare const DEFAULT_NEXTAUTH_BASE_PATH = "/api/auth";
|
|
24
|
+
/**
|
|
25
|
+
* Default token expiry in seconds (15 minutes)
|
|
26
|
+
* Used as fallback when exp claim cannot be extracted from JWT
|
|
27
|
+
*/
|
|
28
|
+
export declare const DEFAULT_TOKEN_EXPIRY_SECONDS = 900;
|
|
29
|
+
/**
|
|
30
|
+
* Default token expiry in milliseconds
|
|
31
|
+
*/
|
|
32
|
+
export declare const DEFAULT_TOKEN_EXPIRY_MS: number;
|
|
33
|
+
/**
|
|
34
|
+
* Buffer time in seconds before token expiry to trigger refresh
|
|
35
|
+
* Tokens will be refreshed when they expire within this window
|
|
36
|
+
*/
|
|
37
|
+
export declare const TOKEN_EXPIRY_BUFFER_SECONDS = 60;
|
|
38
|
+
/**
|
|
39
|
+
* Default session max age in seconds (365 days)
|
|
40
|
+
* This is how long the NextAuth session cookie will be valid
|
|
41
|
+
*/
|
|
42
|
+
export declare const DEFAULT_SESSION_MAX_AGE_SECONDS: number;
|
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
createAuthConfig: () => createAuthConfig,
|
|
34
|
+
createAuthMiddleware: () => createAuthMiddleware,
|
|
35
|
+
createAuthOptions: () => createAuthOptions,
|
|
36
|
+
createImmutableAuth: () => createImmutableAuth,
|
|
37
|
+
createProtectedAuthProps: () => createProtectedAuthProps,
|
|
38
|
+
createProtectedDataFetcher: () => createProtectedDataFetcher,
|
|
39
|
+
createProtectedFetchers: () => createProtectedFetchers,
|
|
40
|
+
getAuthProps: () => getAuthProps,
|
|
41
|
+
getAuthenticatedData: () => getAuthenticatedData,
|
|
42
|
+
getValidSession: () => getValidSession,
|
|
43
|
+
withAuth: () => withAuth,
|
|
44
|
+
withServerAuth: () => withServerAuth
|
|
45
|
+
});
|
|
46
|
+
module.exports = __toCommonJS(src_exports);
|
|
47
|
+
var import_next_auth = __toESM(require("next-auth"), 1);
|
|
48
|
+
var import_server = require("next/server");
|
|
49
|
+
|
|
50
|
+
// src/config.ts
|
|
51
|
+
var import_credentials = __toESM(require("next-auth/providers/credentials"), 1);
|
|
52
|
+
|
|
53
|
+
// src/constants.ts
|
|
54
|
+
var DEFAULT_AUTH_DOMAIN = "https://auth.immutable.com";
|
|
55
|
+
var IMMUTABLE_PROVIDER_ID = "immutable";
|
|
56
|
+
var DEFAULT_TOKEN_EXPIRY_SECONDS = 900;
|
|
57
|
+
var DEFAULT_TOKEN_EXPIRY_MS = DEFAULT_TOKEN_EXPIRY_SECONDS * 1e3;
|
|
58
|
+
var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
|
|
59
|
+
var DEFAULT_SESSION_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;
|
|
60
|
+
|
|
61
|
+
// src/refresh.ts
|
|
62
|
+
function isTokenExpired(accessTokenExpires, bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS) {
|
|
63
|
+
if (typeof accessTokenExpires !== "number" || Number.isNaN(accessTokenExpires)) {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
return Date.now() >= accessTokenExpires - bufferSeconds * 1e3;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/config.ts
|
|
70
|
+
var Credentials = import_credentials.default.default || import_credentials.default;
|
|
71
|
+
async function validateTokens(accessToken, authDomain) {
|
|
72
|
+
try {
|
|
73
|
+
const response = await fetch(`${authDomain}/userinfo`, {
|
|
74
|
+
method: "GET",
|
|
75
|
+
headers: {
|
|
76
|
+
Authorization: `Bearer ${accessToken}`
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
console.error("[auth-next-server] Token validation failed:", response.status, response.statusText);
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
return await response.json();
|
|
84
|
+
} catch (error) {
|
|
85
|
+
console.error("[auth-next-server] Token validation error:", error);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function createAuthConfig(config) {
|
|
90
|
+
const authDomain = config.authenticationDomain || DEFAULT_AUTH_DOMAIN;
|
|
91
|
+
return {
|
|
92
|
+
providers: [
|
|
93
|
+
Credentials({
|
|
94
|
+
id: IMMUTABLE_PROVIDER_ID,
|
|
95
|
+
name: "Immutable",
|
|
96
|
+
credentials: {
|
|
97
|
+
tokens: { label: "Tokens", type: "text" }
|
|
98
|
+
},
|
|
99
|
+
async authorize(credentials) {
|
|
100
|
+
if (!credentials?.tokens || typeof credentials.tokens !== "string") {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
let tokenData;
|
|
104
|
+
try {
|
|
105
|
+
tokenData = JSON.parse(credentials.tokens);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error("[auth-next-server] Failed to parse token data:", error);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
if (!tokenData.accessToken || typeof tokenData.accessToken !== "string" || !tokenData.profile || typeof tokenData.profile !== "object" || !tokenData.profile.sub || typeof tokenData.profile.sub !== "string" || typeof tokenData.accessTokenExpires !== "number" || Number.isNaN(tokenData.accessTokenExpires)) {
|
|
111
|
+
console.error("[auth-next-server] Invalid token data structure - missing required fields");
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const userInfo = await validateTokens(tokenData.accessToken, authDomain);
|
|
115
|
+
if (!userInfo) {
|
|
116
|
+
console.error("[auth-next-server] Token validation failed - rejecting authentication");
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
if (userInfo.sub !== tokenData.profile.sub) {
|
|
120
|
+
console.error(
|
|
121
|
+
"[auth-next-server] User ID mismatch - userinfo sub:",
|
|
122
|
+
userInfo.sub,
|
|
123
|
+
"provided sub:",
|
|
124
|
+
tokenData.profile.sub
|
|
125
|
+
);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
id: userInfo.sub,
|
|
130
|
+
sub: userInfo.sub,
|
|
131
|
+
email: userInfo.email ?? tokenData.profile.email,
|
|
132
|
+
nickname: userInfo.nickname ?? tokenData.profile.nickname,
|
|
133
|
+
accessToken: tokenData.accessToken,
|
|
134
|
+
refreshToken: tokenData.refreshToken,
|
|
135
|
+
idToken: tokenData.idToken,
|
|
136
|
+
accessTokenExpires: tokenData.accessTokenExpires,
|
|
137
|
+
zkEvm: tokenData.zkEvm
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
],
|
|
142
|
+
callbacks: {
|
|
143
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
144
|
+
async jwt({
|
|
145
|
+
token,
|
|
146
|
+
user,
|
|
147
|
+
trigger,
|
|
148
|
+
session: sessionUpdate
|
|
149
|
+
}) {
|
|
150
|
+
if (user) {
|
|
151
|
+
return {
|
|
152
|
+
...token,
|
|
153
|
+
sub: user.sub,
|
|
154
|
+
email: user.email,
|
|
155
|
+
nickname: user.nickname,
|
|
156
|
+
accessToken: user.accessToken,
|
|
157
|
+
refreshToken: user.refreshToken,
|
|
158
|
+
idToken: user.idToken,
|
|
159
|
+
accessTokenExpires: user.accessTokenExpires,
|
|
160
|
+
zkEvm: user.zkEvm
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
if (trigger === "update" && sessionUpdate) {
|
|
164
|
+
const update = sessionUpdate;
|
|
165
|
+
return {
|
|
166
|
+
...token,
|
|
167
|
+
...update.accessToken ? { accessToken: update.accessToken } : {},
|
|
168
|
+
...update.refreshToken ? { refreshToken: update.refreshToken } : {},
|
|
169
|
+
...update.idToken ? { idToken: update.idToken } : {},
|
|
170
|
+
...update.accessTokenExpires ? { accessTokenExpires: update.accessTokenExpires } : {},
|
|
171
|
+
...update.zkEvm ? { zkEvm: update.zkEvm } : {},
|
|
172
|
+
// Clear any stale error when valid tokens are synced from client-side
|
|
173
|
+
error: void 0
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
if (!isTokenExpired(token.accessTokenExpires)) {
|
|
177
|
+
return token;
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
...token,
|
|
181
|
+
error: "TokenExpired"
|
|
182
|
+
};
|
|
183
|
+
},
|
|
184
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
185
|
+
async session({ session, token }) {
|
|
186
|
+
return {
|
|
187
|
+
...session,
|
|
188
|
+
user: {
|
|
189
|
+
...session.user,
|
|
190
|
+
sub: token.sub,
|
|
191
|
+
email: token.email,
|
|
192
|
+
nickname: token.nickname
|
|
193
|
+
},
|
|
194
|
+
accessToken: token.accessToken,
|
|
195
|
+
refreshToken: token.refreshToken,
|
|
196
|
+
idToken: token.idToken,
|
|
197
|
+
accessTokenExpires: token.accessTokenExpires,
|
|
198
|
+
zkEvm: token.zkEvm,
|
|
199
|
+
...token.error && { error: token.error }
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
session: {
|
|
204
|
+
strategy: "jwt",
|
|
205
|
+
// Session max age in seconds (365 days default)
|
|
206
|
+
maxAge: DEFAULT_SESSION_MAX_AGE_SECONDS
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
var createAuthOptions = createAuthConfig;
|
|
211
|
+
|
|
212
|
+
// src/utils/pathMatch.ts
|
|
213
|
+
function matchPathPrefix(pathname, pattern) {
|
|
214
|
+
if (pathname === pattern) return true;
|
|
215
|
+
const prefix = pattern.endsWith("/") ? pattern : `${pattern}/`;
|
|
216
|
+
return pathname.startsWith(prefix);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/index.ts
|
|
220
|
+
var NextAuth = import_next_auth.default.default || import_next_auth.default;
|
|
221
|
+
function createImmutableAuth(config, overrides) {
|
|
222
|
+
const baseConfig = createAuthConfig(config);
|
|
223
|
+
if (!overrides) {
|
|
224
|
+
return NextAuth(baseConfig);
|
|
225
|
+
}
|
|
226
|
+
const { callbacks: overrideCallbacks, ...otherOverrides } = overrides;
|
|
227
|
+
const composedCallbacks = { ...baseConfig.callbacks };
|
|
228
|
+
if (overrideCallbacks) {
|
|
229
|
+
if (overrideCallbacks.jwt) {
|
|
230
|
+
const baseJwt = baseConfig.callbacks?.jwt;
|
|
231
|
+
const userJwt = overrideCallbacks.jwt;
|
|
232
|
+
composedCallbacks.jwt = async (params) => {
|
|
233
|
+
const result = baseJwt ? await baseJwt(params) : params.token;
|
|
234
|
+
return userJwt({ ...params, token: result });
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
if (overrideCallbacks.session) {
|
|
238
|
+
const baseSession = baseConfig.callbacks?.session;
|
|
239
|
+
const userSession = overrideCallbacks.session;
|
|
240
|
+
composedCallbacks.session = async (params) => {
|
|
241
|
+
const result = baseSession ? await baseSession(params) : params.session;
|
|
242
|
+
return userSession({ ...params, session: result });
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
if (overrideCallbacks.signIn) {
|
|
246
|
+
composedCallbacks.signIn = overrideCallbacks.signIn;
|
|
247
|
+
}
|
|
248
|
+
if (overrideCallbacks.redirect) {
|
|
249
|
+
composedCallbacks.redirect = overrideCallbacks.redirect;
|
|
250
|
+
}
|
|
251
|
+
if (overrideCallbacks.authorized) {
|
|
252
|
+
composedCallbacks.authorized = overrideCallbacks.authorized;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const mergedConfig = {
|
|
256
|
+
...baseConfig,
|
|
257
|
+
...otherOverrides,
|
|
258
|
+
callbacks: composedCallbacks
|
|
259
|
+
};
|
|
260
|
+
return NextAuth(mergedConfig);
|
|
261
|
+
}
|
|
262
|
+
async function getAuthProps(auth) {
|
|
263
|
+
const session = await auth();
|
|
264
|
+
if (!session) {
|
|
265
|
+
return { session: null, ssr: false };
|
|
266
|
+
}
|
|
267
|
+
if (session.error === "TokenExpired") {
|
|
268
|
+
return { session: null, ssr: false };
|
|
269
|
+
}
|
|
270
|
+
if (session.error) {
|
|
271
|
+
return { session: null, ssr: false, authError: session.error };
|
|
272
|
+
}
|
|
273
|
+
return { session, ssr: true };
|
|
274
|
+
}
|
|
275
|
+
async function getAuthenticatedData(auth, fetcher) {
|
|
276
|
+
const session = await auth();
|
|
277
|
+
if (!session) {
|
|
278
|
+
return { session: null, ssr: false, data: null };
|
|
279
|
+
}
|
|
280
|
+
if (session.error === "TokenExpired") {
|
|
281
|
+
return { session: null, ssr: false, data: null };
|
|
282
|
+
}
|
|
283
|
+
if (session.error) {
|
|
284
|
+
return {
|
|
285
|
+
session: null,
|
|
286
|
+
ssr: false,
|
|
287
|
+
data: null,
|
|
288
|
+
authError: session.error
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
const data = await fetcher(session.accessToken);
|
|
293
|
+
return { session, ssr: true, data };
|
|
294
|
+
} catch (err) {
|
|
295
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
296
|
+
return {
|
|
297
|
+
session,
|
|
298
|
+
ssr: true,
|
|
299
|
+
data: null,
|
|
300
|
+
fetchError: errorMessage
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
async function getValidSession(auth) {
|
|
305
|
+
const session = await auth();
|
|
306
|
+
if (!session) {
|
|
307
|
+
return { status: "unauthenticated", session: null };
|
|
308
|
+
}
|
|
309
|
+
if (!session.error) {
|
|
310
|
+
return { status: "authenticated", session };
|
|
311
|
+
}
|
|
312
|
+
if (session.error === "TokenExpired") {
|
|
313
|
+
return { status: "token_expired", session };
|
|
314
|
+
}
|
|
315
|
+
return { status: "error", session, error: session.error };
|
|
316
|
+
}
|
|
317
|
+
function createProtectedDataFetcher(auth, onAuthError) {
|
|
318
|
+
return async function getProtectedData(fetcher) {
|
|
319
|
+
const result = await getAuthenticatedData(auth, fetcher);
|
|
320
|
+
if (result.authError) {
|
|
321
|
+
onAuthError(result.authError);
|
|
322
|
+
}
|
|
323
|
+
const { authError: handledAuthError, ...props } = result;
|
|
324
|
+
return props;
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function createProtectedAuthProps(auth, onAuthError) {
|
|
328
|
+
return async function getProtectedAuth() {
|
|
329
|
+
const result = await getAuthProps(auth);
|
|
330
|
+
if (result.authError) {
|
|
331
|
+
onAuthError(result.authError);
|
|
332
|
+
}
|
|
333
|
+
const { authError: handledAuthError, ...props } = result;
|
|
334
|
+
return props;
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function createProtectedFetchers(auth, onAuthError) {
|
|
338
|
+
return {
|
|
339
|
+
getAuthProps: createProtectedAuthProps(auth, onAuthError),
|
|
340
|
+
getData: createProtectedDataFetcher(auth, onAuthError)
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
async function withServerAuth(auth, serverRender, options = {}) {
|
|
344
|
+
const result = await getValidSession(auth);
|
|
345
|
+
switch (result.status) {
|
|
346
|
+
case "authenticated":
|
|
347
|
+
return serverRender(result.session);
|
|
348
|
+
case "token_expired":
|
|
349
|
+
if (options.onTokenExpired !== void 0) {
|
|
350
|
+
return typeof options.onTokenExpired === "function" ? options.onTokenExpired() : options.onTokenExpired;
|
|
351
|
+
}
|
|
352
|
+
return serverRender(result.session);
|
|
353
|
+
case "unauthenticated":
|
|
354
|
+
if (options.onUnauthenticated !== void 0) {
|
|
355
|
+
return typeof options.onUnauthenticated === "function" ? options.onUnauthenticated() : options.onUnauthenticated;
|
|
356
|
+
}
|
|
357
|
+
throw new Error("Unauthorized: No active session");
|
|
358
|
+
case "error":
|
|
359
|
+
if (options.onError !== void 0) {
|
|
360
|
+
return typeof options.onError === "function" ? options.onError(result.error) : options.onError;
|
|
361
|
+
}
|
|
362
|
+
throw new Error(`Unauthorized: ${result.error}`);
|
|
363
|
+
default:
|
|
364
|
+
throw new Error("Unknown auth state");
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function createAuthMiddleware(auth, options = {}) {
|
|
368
|
+
const { loginUrl = "/login", protectedPaths, publicPaths } = options;
|
|
369
|
+
return async function middleware(request) {
|
|
370
|
+
const { pathname } = request.nextUrl;
|
|
371
|
+
if (publicPaths) {
|
|
372
|
+
const isPublic = publicPaths.some((pattern) => {
|
|
373
|
+
if (typeof pattern === "string") {
|
|
374
|
+
return matchPathPrefix(pathname, pattern);
|
|
375
|
+
}
|
|
376
|
+
return pattern.test(pathname);
|
|
377
|
+
});
|
|
378
|
+
if (isPublic) {
|
|
379
|
+
return import_server.NextResponse.next();
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (protectedPaths) {
|
|
383
|
+
const isProtected = protectedPaths.some((pattern) => {
|
|
384
|
+
if (typeof pattern === "string") {
|
|
385
|
+
return matchPathPrefix(pathname, pattern);
|
|
386
|
+
}
|
|
387
|
+
return pattern.test(pathname);
|
|
388
|
+
});
|
|
389
|
+
if (!isProtected) {
|
|
390
|
+
return import_server.NextResponse.next();
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const session = await auth();
|
|
394
|
+
if (!session) {
|
|
395
|
+
const url = new URL(loginUrl, request.url);
|
|
396
|
+
const returnTo = request.nextUrl.search ? `${pathname}${request.nextUrl.search}` : pathname;
|
|
397
|
+
url.searchParams.set("returnTo", returnTo);
|
|
398
|
+
return import_server.NextResponse.redirect(url);
|
|
399
|
+
}
|
|
400
|
+
if (session.error && session.error !== "TokenExpired") {
|
|
401
|
+
const url = new URL(loginUrl, request.url);
|
|
402
|
+
const returnTo = request.nextUrl.search ? `${pathname}${request.nextUrl.search}` : pathname;
|
|
403
|
+
url.searchParams.set("returnTo", returnTo);
|
|
404
|
+
url.searchParams.set("error", session.error);
|
|
405
|
+
return import_server.NextResponse.redirect(url);
|
|
406
|
+
}
|
|
407
|
+
return import_server.NextResponse.next();
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
function withAuth(auth, handler) {
|
|
411
|
+
return async (...args) => {
|
|
412
|
+
const session = await auth();
|
|
413
|
+
if (!session) {
|
|
414
|
+
throw new Error("Unauthorized: No active session");
|
|
415
|
+
}
|
|
416
|
+
if (session.error && session.error !== "TokenExpired") {
|
|
417
|
+
throw new Error(`Unauthorized: ${session.error}`);
|
|
418
|
+
}
|
|
419
|
+
return handler(session, ...args);
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
423
|
+
0 && (module.exports = {
|
|
424
|
+
createAuthConfig,
|
|
425
|
+
createAuthMiddleware,
|
|
426
|
+
createAuthOptions,
|
|
427
|
+
createImmutableAuth,
|
|
428
|
+
createProtectedAuthProps,
|
|
429
|
+
createProtectedDataFetcher,
|
|
430
|
+
createProtectedFetchers,
|
|
431
|
+
getAuthProps,
|
|
432
|
+
getAuthenticatedData,
|
|
433
|
+
getValidSession,
|
|
434
|
+
withAuth,
|
|
435
|
+
withServerAuth
|
|
436
|
+
});
|