@multiplatform.one/auth 9.17.0 → 10.0.0
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/cjs/accessTokenRefresh.cjs +53 -51
- package/dist/cjs/accessTokenRefresh.native.cjs +79 -0
- package/dist/cjs/accessTokenRefresh.native.js +58 -55
- package/dist/cjs/accessTokenRefresh.native.js.map +1 -1
- package/dist/cjs/index.cjs +392 -436
- package/dist/cjs/index.native.cjs +498 -0
- package/dist/cjs/index.native.js +454 -497
- package/dist/cjs/index.native.js.map +1 -1
- package/dist/esm/accessTokenRefresh.mjs +35 -30
- package/dist/esm/accessTokenRefresh.mjs.map +1 -1
- package/dist/esm/accessTokenRefresh.native.js +40 -35
- package/dist/esm/accessTokenRefresh.native.js.map +1 -1
- package/dist/esm/index.mjs +370 -411
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/index.native.js +432 -473
- package/dist/esm/index.native.js.map +1 -1
- package/dist/jsx/accessTokenRefresh.mjs +35 -30
- package/dist/jsx/accessTokenRefresh.mjs.map +1 -1
- package/dist/jsx/accessTokenRefresh.native.cjs +79 -0
- package/dist/jsx/accessTokenRefresh.native.js +58 -55
- package/dist/jsx/accessTokenRefresh.native.js.map +1 -1
- package/dist/jsx/index.js +370 -411
- package/dist/jsx/index.js.map +1 -1
- package/dist/jsx/index.mjs +370 -411
- package/dist/jsx/index.mjs.map +1 -1
- package/dist/jsx/index.native.cjs +498 -0
- package/dist/jsx/index.native.js +454 -497
- package/dist/jsx/index.native.js.map +1 -1
- package/package.json +4 -4
package/dist/cjs/index.cjs
CHANGED
|
@@ -3,37 +3,35 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
3
3
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
4
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
5
|
var __export = (target, all) => {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
for (var name in all) __defProp(target, name, {
|
|
7
|
+
get: all[name],
|
|
8
|
+
enumerable: true
|
|
9
|
+
});
|
|
10
10
|
};
|
|
11
11
|
var __copyProps = (to, from, except, desc) => {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
14
|
+
get: () => from[key],
|
|
15
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
19
|
};
|
|
20
|
-
var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
|
|
21
|
-
value: true
|
|
22
|
-
}), mod);
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
23
21
|
var index_exports = {};
|
|
24
22
|
__export(index_exports, {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
23
|
+
ACCESS_TOKEN_RETRY_DELAYS_MS: () => import_accessTokenRefresh2.ACCESS_TOKEN_RETRY_DELAYS_MS,
|
|
24
|
+
FAILED_TO_GET_ACCESS_TOKEN: () => import_accessTokenRefresh2.FAILED_TO_GET_ACCESS_TOKEN,
|
|
25
|
+
OFFLINE_ACCESS_SCOPE: () => OFFLINE_ACCESS_SCOPE,
|
|
26
|
+
TOKEN_REFRESH_UNAVAILABLE: () => import_accessTokenRefresh2.TOKEN_REFRESH_UNAVAILABLE,
|
|
27
|
+
classifyAccessTokenResponse: () => import_accessTokenRefresh2.classifyAccessTokenResponse,
|
|
28
|
+
createAuth: () => createAuth,
|
|
29
|
+
createAuthRouteHandler: () => createAuthRouteHandler,
|
|
30
|
+
createSessionHelpers: () => createSessionHelpers,
|
|
31
|
+
isOfflineRefreshToken: () => isOfflineRefreshToken,
|
|
32
|
+
retryWhileTransient: () => import_accessTokenRefresh2.retryWhileTransient,
|
|
33
|
+
watchDocumentVisible: () => import_accessTokenRefresh2.watchDocumentVisible,
|
|
34
|
+
withOfflineAccessScope: () => withOfflineAccessScope
|
|
37
35
|
});
|
|
38
36
|
module.exports = __toCommonJS(index_exports);
|
|
39
37
|
var import_node_async_hooks = require("node:async_hooks");
|
|
@@ -46,433 +44,391 @@ var import_accessTokenRefresh = require("./accessTokenRefresh.cjs");
|
|
|
46
44
|
var import_accessTokenRefresh2 = require("./accessTokenRefresh.cjs");
|
|
47
45
|
const requestOriginStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
48
46
|
function deriveRequestOrigin(req) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
47
|
+
const isDevHost = (host) => DEV_LAN_HOST_PATTERNS.some((pattern) => (0, import_better_auth.matchesHostPattern)(host, pattern));
|
|
48
|
+
const forwardedHost = req.headers.get("x-forwarded-host");
|
|
49
|
+
if (forwardedHost && isDevHost(forwardedHost)) {
|
|
50
|
+
const proto = req.headers.get("x-forwarded-proto") === "https" ? "https" : "http";
|
|
51
|
+
return `${proto}://${forwardedHost}`;
|
|
52
|
+
}
|
|
53
|
+
for (const candidate of [req.headers.get("origin"), req.url]) {
|
|
54
|
+
if (!candidate) continue;
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(candidate);
|
|
57
|
+
if (isDevHost(url.host)) return url.origin;
|
|
58
|
+
} catch {}
|
|
59
|
+
}
|
|
60
|
+
return void 0;
|
|
63
61
|
}
|
|
64
|
-
const DEV_LAN_HOST_PATTERNS = [
|
|
62
|
+
const DEV_LAN_HOST_PATTERNS = [
|
|
63
|
+
"localhost",
|
|
64
|
+
"localhost:*",
|
|
65
|
+
"127.0.0.1",
|
|
66
|
+
"127.0.0.1:*",
|
|
67
|
+
"10.*",
|
|
68
|
+
"192.168.*",
|
|
69
|
+
"172.*",
|
|
70
|
+
"*.local",
|
|
71
|
+
"*.local:*"
|
|
72
|
+
];
|
|
65
73
|
const OFFLINE_ACCESS_SCOPE = "offline_access";
|
|
66
74
|
function isNativeRequest(headers) {
|
|
67
|
-
|
|
75
|
+
return !!headers?.get("expo-origin");
|
|
68
76
|
}
|
|
69
77
|
function withOfflineAccessScope(authorizationUrl) {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
78
|
+
const url = new URL(authorizationUrl);
|
|
79
|
+
const scopes = (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean);
|
|
80
|
+
if (scopes.includes(OFFLINE_ACCESS_SCOPE)) return authorizationUrl;
|
|
81
|
+
url.searchParams.set("scope", [...scopes, OFFLINE_ACCESS_SCOPE].join(" "));
|
|
82
|
+
return url.toString();
|
|
75
83
|
}
|
|
76
84
|
function isOfflineRefreshToken(token) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
+
const payload = token?.split(".")[1];
|
|
86
|
+
if (!payload) return false;
|
|
87
|
+
try {
|
|
88
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
89
|
+
return JSON.parse(json).typ === "Offline";
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
85
93
|
}
|
|
86
94
|
const accessTokenBodySchema = import_api.getAccessToken.options.body;
|
|
87
95
|
function acceptsAccessTokenBody(body) {
|
|
88
|
-
|
|
96
|
+
return accessTokenBodySchema?.safeParse?.(body).success !== false;
|
|
89
97
|
}
|
|
90
98
|
function createKeycloakSsoPlugin(options) {
|
|
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
|
-
if (!definitive) {
|
|
276
|
-
return new import_api.APIError("INTERNAL_SERVER_ERROR", {
|
|
277
|
-
message: "Keycloak token refresh temporarily unavailable",
|
|
278
|
-
code: import_accessTokenRefresh.TOKEN_REFRESH_UNAVAILABLE
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
ctx.context.logger.warn("Keycloak refresh token is dead (invalid_grant); revoking the stale Better Auth session");
|
|
282
|
-
const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
|
|
283
|
-
if (sessionToken) {
|
|
284
|
-
await ctx.context.internalAdapter.deleteSession(sessionToken).catch(error => {
|
|
285
|
-
ctx.context.logger.error("Failed to delete stale session", error);
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
(0, import_cookies.deleteSessionCookie)(ctx);
|
|
289
|
-
const headers = new Headers();
|
|
290
|
-
const accumulated = ctx.responseHeaders;
|
|
291
|
-
accumulated?.getSetCookie().forEach(cookie => {
|
|
292
|
-
headers.append("set-cookie", cookie);
|
|
293
|
-
});
|
|
294
|
-
return new import_api.APIError("BAD_REQUEST", {
|
|
295
|
-
message: body?.message || "Failed to get a valid access token",
|
|
296
|
-
code: import_accessTokenRefresh.FAILED_TO_GET_ACCESS_TOKEN
|
|
297
|
-
}, headers);
|
|
298
|
-
})
|
|
299
|
-
}]
|
|
300
|
-
}
|
|
301
|
-
};
|
|
99
|
+
const { realm, clientId, clientSecret, issuer, baseUrl, publicKeycloakBaseFor, nativeOfflineAccess } = options;
|
|
100
|
+
const tokenEndpoint = `${issuer}/protocol/openid-connect/token`;
|
|
101
|
+
const logoutEndpoint = `${issuer}/protocol/openid-connect/logout`;
|
|
102
|
+
const resolveVisitorOrigin = (request) => requestOriginStorage.getStore() ?? (request ? deriveRequestOrigin(request) : void 0);
|
|
103
|
+
const isRefreshDefinitivelyDead = async (refreshToken) => {
|
|
104
|
+
try {
|
|
105
|
+
const res = await fetch(tokenEndpoint, {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
108
|
+
body: new URLSearchParams({
|
|
109
|
+
grant_type: "refresh_token",
|
|
110
|
+
refresh_token: refreshToken,
|
|
111
|
+
client_id: clientId,
|
|
112
|
+
client_secret: clientSecret
|
|
113
|
+
}),
|
|
114
|
+
signal: AbortSignal.timeout(5e3)
|
|
115
|
+
});
|
|
116
|
+
if (res.ok) return false;
|
|
117
|
+
if (res.status !== 400 && res.status !== 401) return false;
|
|
118
|
+
const body = await res.json().catch(() => null);
|
|
119
|
+
return body?.error === "invalid_grant" || body?.error === "invalid_token";
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const findDeviceKeycloakAccount = async (ctx) => {
|
|
125
|
+
const accountCookie = await (0, import_cookies.getAccountCookie)(ctx).catch(() => null);
|
|
126
|
+
if (accountCookie?.providerId === "keycloak" && accountCookie.refreshToken) {
|
|
127
|
+
return accountCookie;
|
|
128
|
+
}
|
|
129
|
+
const session = await (0, import_api.getSessionFromCtx)(ctx).catch(() => null);
|
|
130
|
+
if (!session) return void 0;
|
|
131
|
+
const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
|
|
132
|
+
return accounts.find((account) => account.providerId === "keycloak");
|
|
133
|
+
};
|
|
134
|
+
const endOfflineSession = async (ctx, refreshToken) => {
|
|
135
|
+
if (!refreshToken || !isOfflineRefreshToken(refreshToken)) return;
|
|
136
|
+
try {
|
|
137
|
+
const res = await fetch(logoutEndpoint, {
|
|
138
|
+
method: "POST",
|
|
139
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
140
|
+
body: new URLSearchParams({
|
|
141
|
+
refresh_token: refreshToken,
|
|
142
|
+
client_id: clientId,
|
|
143
|
+
client_secret: clientSecret
|
|
144
|
+
}),
|
|
145
|
+
signal: AbortSignal.timeout(5e3)
|
|
146
|
+
});
|
|
147
|
+
if (!res.ok) {
|
|
148
|
+
ctx.context.logger.warn(`Keycloak offline session logout answered ${res.status}`);
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
ctx.context.logger.warn("Keycloak offline session logout failed", error);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const signOutSso = (0, import_api.createAuthEndpoint)("/sign-out/sso", { method: "GET" }, async (ctx) => {
|
|
155
|
+
const visitorOrigin = resolveVisitorOrigin(ctx.request) ?? baseUrl;
|
|
156
|
+
const searchParams = ctx.request ? new URL(ctx.request.url).searchParams : void 0;
|
|
157
|
+
const rawCallback = searchParams?.get("callbackURL") ?? null;
|
|
158
|
+
const jsonMode = searchParams?.get("mode") === "json";
|
|
159
|
+
const answer = (url, redirect) => {
|
|
160
|
+
if (jsonMode) return ctx.json({
|
|
161
|
+
redirect,
|
|
162
|
+
url
|
|
163
|
+
});
|
|
164
|
+
throw ctx.redirect(url);
|
|
165
|
+
};
|
|
166
|
+
const callbackURL = rawCallback || "/";
|
|
167
|
+
const postLogoutRedirect = callbackURL.startsWith("/") ? `${visitorOrigin}${callbackURL}` : callbackURL;
|
|
168
|
+
let idTokenHint;
|
|
169
|
+
const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
|
|
170
|
+
const session = await (0, import_api.getSessionFromCtx)(ctx).catch(() => null);
|
|
171
|
+
if (session) {
|
|
172
|
+
const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
|
|
173
|
+
idTokenHint = accounts.find((account) => account.providerId === "keycloak")?.idToken ?? void 0;
|
|
174
|
+
}
|
|
175
|
+
if (!idTokenHint) {
|
|
176
|
+
const accountCookie = await (0, import_cookies.getAccountCookie)(ctx).catch(() => null);
|
|
177
|
+
if (accountCookie?.providerId === "keycloak" && accountCookie.idToken) {
|
|
178
|
+
idTokenHint = accountCookie.idToken;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
|
|
182
|
+
if (sessionToken) {
|
|
183
|
+
await ctx.context.internalAdapter.deleteSession(sessionToken).catch((error) => {
|
|
184
|
+
ctx.context.logger.error("Failed to delete session during SSO sign-out", error);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
(0, import_cookies.deleteSessionCookie)(ctx);
|
|
188
|
+
const keycloakBase = publicKeycloakBaseFor(visitorOrigin);
|
|
189
|
+
if (!keycloakBase || !session && !idTokenHint && !sessionToken) {
|
|
190
|
+
return answer(postLogoutRedirect, false);
|
|
191
|
+
}
|
|
192
|
+
const endSession = new URL(`${keycloakBase}/realms/${realm}/protocol/openid-connect/logout`);
|
|
193
|
+
endSession.searchParams.set("post_logout_redirect_uri", postLogoutRedirect);
|
|
194
|
+
endSession.searchParams.set("client_id", clientId);
|
|
195
|
+
if (idTokenHint) endSession.searchParams.set("id_token_hint", idTokenHint);
|
|
196
|
+
return answer(endSession.toString(), true);
|
|
197
|
+
});
|
|
198
|
+
return {
|
|
199
|
+
id: "keycloak-sso",
|
|
200
|
+
endpoints: { signOutSso },
|
|
201
|
+
hooks: {
|
|
202
|
+
before: [{
|
|
203
|
+
matcher: (ctx) => ctx.path === "/sign-out",
|
|
204
|
+
handler: (0, import_api.createAuthMiddleware)(async (ctx) => {
|
|
205
|
+
await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
|
|
206
|
+
})
|
|
207
|
+
}, {
|
|
208
|
+
matcher: (ctx) => ctx.path === "/get-access-token",
|
|
209
|
+
handler: (0, import_api.createAuthMiddleware)(async (ctx) => {
|
|
210
|
+
const session = await (0, import_api.getSessionFromCtx)(ctx).catch(() => null);
|
|
211
|
+
if (!session) return ctx.json(null);
|
|
212
|
+
const body = ctx.body;
|
|
213
|
+
if (body?.useAccountCookie !== true || acceptsAccessTokenBody(body)) return;
|
|
214
|
+
const legacy = {
|
|
215
|
+
...body,
|
|
216
|
+
providerId: "keycloak"
|
|
217
|
+
};
|
|
218
|
+
if (acceptsAccessTokenBody(legacy)) return { context: { body: legacy } };
|
|
219
|
+
})
|
|
220
|
+
}],
|
|
221
|
+
after: [{
|
|
222
|
+
matcher: (ctx) => nativeOfflineAccess && (ctx.path === "/sign-in/social" || ctx.path === "/sign-in/oauth2"),
|
|
223
|
+
handler: (0, import_api.createAuthMiddleware)(async (ctx) => {
|
|
224
|
+
if (!isNativeRequest(ctx.request?.headers ?? ctx.headers)) return;
|
|
225
|
+
const body = ctx.body;
|
|
226
|
+
if ((body?.provider ?? body?.providerId) !== "keycloak") return;
|
|
227
|
+
const returned = ctx.context.returned;
|
|
228
|
+
if ((0, import_api.isAPIError)(returned) || typeof returned?.url !== "string") return;
|
|
229
|
+
const url = withOfflineAccessScope(returned.url);
|
|
230
|
+
if (ctx.context.responseHeaders?.has("location")) ctx.setHeader("location", url);
|
|
231
|
+
return ctx.json({
|
|
232
|
+
...returned,
|
|
233
|
+
url
|
|
234
|
+
});
|
|
235
|
+
})
|
|
236
|
+
}, {
|
|
237
|
+
matcher: (ctx) => ctx.path === "/get-access-token",
|
|
238
|
+
handler: (0, import_api.createAuthMiddleware)(async (ctx) => {
|
|
239
|
+
const returned = ctx.context.returned;
|
|
240
|
+
if (!(0, import_api.isAPIError)(returned)) return;
|
|
241
|
+
const body = returned.body;
|
|
242
|
+
if (body?.code !== import_accessTokenRefresh.FAILED_TO_GET_ACCESS_TOKEN) return;
|
|
243
|
+
const providerId = ctx.body?.providerId;
|
|
244
|
+
if (providerId && providerId !== "keycloak") return;
|
|
245
|
+
const session = await (0, import_api.getSessionFromCtx)(ctx).catch(() => null);
|
|
246
|
+
if (!session) return;
|
|
247
|
+
const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
|
|
248
|
+
let refreshToken = accounts.find((account) => account.providerId === "keycloak")?.refreshToken;
|
|
249
|
+
if (!refreshToken) {
|
|
250
|
+
const accountCookie = await (0, import_cookies.getAccountCookie)(ctx).catch(() => null);
|
|
251
|
+
if (accountCookie?.providerId === "keycloak") {
|
|
252
|
+
refreshToken = accountCookie.refreshToken;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const definitive = refreshToken ? await isRefreshDefinitivelyDead(refreshToken) : true;
|
|
256
|
+
if (!definitive) {
|
|
257
|
+
return new import_api.APIError("INTERNAL_SERVER_ERROR", {
|
|
258
|
+
message: "Keycloak token refresh temporarily unavailable",
|
|
259
|
+
code: import_accessTokenRefresh.TOKEN_REFRESH_UNAVAILABLE
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
ctx.context.logger.warn("Keycloak refresh token is dead (invalid_grant); revoking the stale Better Auth session");
|
|
263
|
+
const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
|
|
264
|
+
if (sessionToken) {
|
|
265
|
+
await ctx.context.internalAdapter.deleteSession(sessionToken).catch((error) => {
|
|
266
|
+
ctx.context.logger.error("Failed to delete stale session", error);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
(0, import_cookies.deleteSessionCookie)(ctx);
|
|
270
|
+
const headers = new Headers();
|
|
271
|
+
const accumulated = ctx.responseHeaders;
|
|
272
|
+
accumulated?.getSetCookie().forEach((cookie) => {
|
|
273
|
+
headers.append("set-cookie", cookie);
|
|
274
|
+
});
|
|
275
|
+
return new import_api.APIError("BAD_REQUEST", {
|
|
276
|
+
message: body?.message || "Failed to get a valid access token",
|
|
277
|
+
code: import_accessTokenRefresh.FAILED_TO_GET_ACCESS_TOKEN
|
|
278
|
+
}, headers);
|
|
279
|
+
})
|
|
280
|
+
}]
|
|
281
|
+
}
|
|
282
|
+
};
|
|
302
283
|
}
|
|
303
284
|
function runtimeEnv() {
|
|
304
|
-
|
|
285
|
+
return typeof process === "undefined" ? {} : process.env;
|
|
305
286
|
}
|
|
306
287
|
function createAuth(options = {}) {
|
|
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
|
-
// derives its callbackURL via Linking.createURL, which yields
|
|
428
|
-
// exp://<host>:<port>/--/ there. Never trusted in production builds.
|
|
429
|
-
// Dev also trusts private-network origins (see DEV_LAN_HOST_PATTERNS)
|
|
430
|
-
// so sign-in from a phone / the machine's LAN IP is not rejected.
|
|
431
|
-
...(isProduction ? [] : ["exp://", ...DEV_LAN_HOST_PATTERNS.map(host => `http://${host}`)])],
|
|
432
|
-
session: {
|
|
433
|
-
cookieCache: {
|
|
434
|
-
enabled: true,
|
|
435
|
-
maxAge: options.sessionMaxAge ?? 7 * 24 * 60 * 60,
|
|
436
|
-
strategy: "jwe",
|
|
437
|
-
refreshCache: true
|
|
438
|
-
}
|
|
439
|
-
},
|
|
440
|
-
account: {
|
|
441
|
-
storeStateStrategy: "cookie",
|
|
442
|
-
storeAccountCookie: true
|
|
443
|
-
},
|
|
444
|
-
plugins
|
|
445
|
-
});
|
|
288
|
+
const env = runtimeEnv();
|
|
289
|
+
const baseUrl = options.baseUrl || env.BASE_URL || `http://localhost:${env.ONE_PORT || "3000"}`;
|
|
290
|
+
const isProduction = process.env.NODE_ENV === "production";
|
|
291
|
+
const keycloakBaseUrl = options.keycloak?.baseUrl || env.KEYCLOAK_BACKCHANNEL_URL || `${baseUrl}/auth`;
|
|
292
|
+
const keycloakRealm = options.keycloak?.realm || env.KEYCLOAK_REALM || "master";
|
|
293
|
+
const issuer = `${keycloakBaseUrl}/realms/${keycloakRealm}`;
|
|
294
|
+
const keycloakClientId = options.keycloak?.clientId || env.KEYCLOAK_CLIENT_ID || "";
|
|
295
|
+
const keycloakClientSecret = options.keycloak?.clientSecret || env.KEYCLOAK_CLIENT_SECRET || "";
|
|
296
|
+
const expoPlugin = options.enableExpo !== false ? (0, import_expo.expo)() : void 0;
|
|
297
|
+
const basePath = options.basePath || "/api/auth";
|
|
298
|
+
const keycloakProviderConfig = {
|
|
299
|
+
...(0, import_plugins.keycloak)({
|
|
300
|
+
clientId: keycloakClientId,
|
|
301
|
+
clientSecret: keycloakClientSecret,
|
|
302
|
+
issuer
|
|
303
|
+
}),
|
|
304
|
+
tokenUrl: `${issuer}/protocol/openid-connect/token`,
|
|
305
|
+
userInfoUrl: `${issuer}/protocol/openid-connect/userinfo`,
|
|
306
|
+
mapProfileToUser: (profile) => {
|
|
307
|
+
const handle = profile.preferred_username || profile.sub || profile.id || profile.name;
|
|
308
|
+
const email = profile.email || (handle ? `${handle}@wallet` : void 0);
|
|
309
|
+
return {
|
|
310
|
+
...profile,
|
|
311
|
+
email,
|
|
312
|
+
emailVerified: profile.email_verified ?? true,
|
|
313
|
+
name: profile.name || handle
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
const keycloakPublicPath = (() => {
|
|
318
|
+
try {
|
|
319
|
+
const path = new URL(keycloakBaseUrl).pathname.replace(/\/+$/, "");
|
|
320
|
+
return path && path !== "/" ? path : void 0;
|
|
321
|
+
} catch {
|
|
322
|
+
return void 0;
|
|
323
|
+
}
|
|
324
|
+
})();
|
|
325
|
+
const publicKeycloakBaseFor = (requestOrigin) => {
|
|
326
|
+
if (!keycloakPublicPath) return keycloakBaseUrl;
|
|
327
|
+
try {
|
|
328
|
+
const url = new URL(baseUrl);
|
|
329
|
+
if (!isProduction && requestOrigin) {
|
|
330
|
+
url.hostname = new URL(requestOrigin).hostname;
|
|
331
|
+
}
|
|
332
|
+
return `${url.origin}${keycloakPublicPath}`;
|
|
333
|
+
} catch {
|
|
334
|
+
return void 0;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
if (!isProduction) {
|
|
338
|
+
Object.defineProperty(keycloakProviderConfig, "redirectURI", {
|
|
339
|
+
enumerable: true,
|
|
340
|
+
get() {
|
|
341
|
+
const origin = requestOriginStorage.getStore();
|
|
342
|
+
return origin ? `${origin}${basePath}/oauth2/callback/keycloak` : void 0;
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
const keycloakPublicBase = () => {
|
|
346
|
+
const origin = requestOriginStorage.getStore();
|
|
347
|
+
if (!origin || !keycloakPublicPath) return void 0;
|
|
348
|
+
return publicKeycloakBaseFor(origin);
|
|
349
|
+
};
|
|
350
|
+
if (keycloakPublicPath) {
|
|
351
|
+
Object.defineProperty(keycloakProviderConfig, "authorizationUrl", {
|
|
352
|
+
enumerable: true,
|
|
353
|
+
get() {
|
|
354
|
+
const base = keycloakPublicBase();
|
|
355
|
+
return base ? `${base}/realms/${keycloakRealm}/protocol/openid-connect/auth` : void 0;
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
Object.defineProperty(keycloakProviderConfig, "issuer", {
|
|
359
|
+
enumerable: true,
|
|
360
|
+
get() {
|
|
361
|
+
const base = keycloakPublicBase();
|
|
362
|
+
return base ? `${base}/realms/${keycloakRealm}` : void 0;
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const oauthPlugin = (0, import_plugins.genericOAuth)({ config: [keycloakProviderConfig] });
|
|
368
|
+
const keycloakSsoPlugin = createKeycloakSsoPlugin({
|
|
369
|
+
realm: keycloakRealm,
|
|
370
|
+
clientId: keycloakClientId,
|
|
371
|
+
clientSecret: keycloakClientSecret,
|
|
372
|
+
issuer,
|
|
373
|
+
baseUrl,
|
|
374
|
+
publicKeycloakBaseFor,
|
|
375
|
+
nativeOfflineAccess: options.nativeOfflineAccess !== false
|
|
376
|
+
});
|
|
377
|
+
const plugins = [
|
|
378
|
+
...expoPlugin ? [expoPlugin] : [],
|
|
379
|
+
oauthPlugin,
|
|
380
|
+
keycloakSsoPlugin,
|
|
381
|
+
...options.plugins ?? []
|
|
382
|
+
];
|
|
383
|
+
const database = options.database ?? (env.DATABASE_URL || void 0);
|
|
384
|
+
return (0, import_better_auth.betterAuth)({
|
|
385
|
+
basePath,
|
|
386
|
+
baseURL: baseUrl,
|
|
387
|
+
...database ? { database } : {},
|
|
388
|
+
secret: options.secret || env.SECRET || "",
|
|
389
|
+
trustedOrigins: options.trustedOrigins || [
|
|
390
|
+
baseUrl,
|
|
391
|
+
keycloakBaseUrl,
|
|
392
|
+
...env.ONE_PORT && !baseUrl.includes(`:${env.ONE_PORT}`) ? [`http://localhost:${env.ONE_PORT}`] : [],
|
|
393
|
+
"multiplatform-one://",
|
|
394
|
+
...isProduction ? [] : ["exp://", ...DEV_LAN_HOST_PATTERNS.map((host) => `http://${host}`)]
|
|
395
|
+
],
|
|
396
|
+
session: { cookieCache: {
|
|
397
|
+
enabled: true,
|
|
398
|
+
maxAge: options.sessionMaxAge ?? 7 * 24 * 60 * 60,
|
|
399
|
+
strategy: "jwe",
|
|
400
|
+
refreshCache: true
|
|
401
|
+
} },
|
|
402
|
+
account: {
|
|
403
|
+
storeStateStrategy: "cookie",
|
|
404
|
+
storeAccountCookie: true
|
|
405
|
+
},
|
|
406
|
+
plugins
|
|
407
|
+
});
|
|
446
408
|
}
|
|
447
409
|
function createAuthRouteHandler(auth) {
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
410
|
+
const handler = (req) => {
|
|
411
|
+
const origin = deriveRequestOrigin(req);
|
|
412
|
+
return origin ? requestOriginStorage.run(origin, () => auth.handler(req)) : auth.handler(req);
|
|
413
|
+
};
|
|
414
|
+
return {
|
|
415
|
+
GET: handler,
|
|
416
|
+
POST: handler
|
|
417
|
+
};
|
|
456
418
|
}
|
|
457
419
|
function createSessionHelpers(auth) {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
}
|
|
474
|
-
return {
|
|
475
|
-
verifyAuth,
|
|
476
|
-
getSession
|
|
477
|
-
};
|
|
478
|
-
}
|
|
420
|
+
async function getSession(req) {
|
|
421
|
+
return auth.api.getSession({ headers: req.headers });
|
|
422
|
+
}
|
|
423
|
+
async function verifyAuth(req) {
|
|
424
|
+
const session = await auth.api.getSession({ headers: req.headers });
|
|
425
|
+
if (!session) {
|
|
426
|
+
throw new Response("Unauthorized", { status: 401 });
|
|
427
|
+
}
|
|
428
|
+
return session;
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
verifyAuth,
|
|
432
|
+
getSession
|
|
433
|
+
};
|
|
434
|
+
}
|