@multiplatform.one/auth 7.61.1 → 7.63.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/src/index.ts CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { AsyncLocalStorage } from "node:async_hooks";
18
18
  import { betterAuth, matchesHostPattern } from "better-auth";
19
- import type { BetterAuthPlugin } from "better-auth";
19
+ import type { BetterAuthPlugin, GenericEndpointContext } from "better-auth";
20
20
  import {
21
21
  APIError,
22
22
  createAuthEndpoint,
@@ -107,6 +107,13 @@ export interface CreateAuthOptions {
107
107
  sessionMaxAge?: number;
108
108
  /** Include @better-auth/expo plugin (default: true) */
109
109
  enableExpo?: boolean;
110
+ /**
111
+ * Native sign-ins (requests carrying `expo-origin`) ask Keycloak for an
112
+ * offline token, so the app stays signed in past the realm's SSO idle and
113
+ * max lifespan until the user logs out; logout ends that offline session.
114
+ * Web sign-ins keep the normal SSO session. Default: true.
115
+ */
116
+ nativeOfflineAccess?: boolean;
110
117
  /** Additional better-auth plugins */
111
118
  plugins?: Parameters<typeof betterAuth>[0]["plugins"];
112
119
  /**
@@ -161,6 +168,40 @@ interface KeycloakSsoPluginOptions {
161
168
  baseUrl: string;
162
169
  /** Browser-facing Keycloak base for a visitor origin (proxy-aware). */
163
170
  publicKeycloakBaseFor: (requestOrigin?: string) => string | undefined;
171
+ /** Native sign-ins request `offline_access` (see CreateAuthOptions). */
172
+ nativeOfflineAccess: boolean;
173
+ }
174
+
175
+ export const OFFLINE_ACCESS_SCOPE = "offline_access";
176
+
177
+ /** Whether a request comes from a native (Expo) client. */
178
+ function isNativeRequest(headers?: Headers | null): boolean {
179
+ return !!headers?.get("expo-origin");
180
+ }
181
+
182
+ /**
183
+ * Add `offline_access` to an authorization URL's `scope`. The genericOAuth
184
+ * provider builds the URL from its static scopes and ignores the sign-in
185
+ * body's `scopes`, so the native request is widened on the URL it returns.
186
+ */
187
+ export function withOfflineAccessScope(authorizationUrl: string): string {
188
+ const url = new URL(authorizationUrl);
189
+ const scopes = (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean);
190
+ if (scopes.includes(OFFLINE_ACCESS_SCOPE)) return authorizationUrl;
191
+ url.searchParams.set("scope", [...scopes, OFFLINE_ACCESS_SCOPE].join(" "));
192
+ return url.toString();
193
+ }
194
+
195
+ /** Keycloak refresh tokens are JWTs whose `typ` is `Offline` for offline tokens. */
196
+ export function isOfflineRefreshToken(token?: string | null): boolean {
197
+ const payload = token?.split(".")[1];
198
+ if (!payload) return false;
199
+ try {
200
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
201
+ return (JSON.parse(json) as { typ?: unknown }).typ === "Offline";
202
+ } catch {
203
+ return false;
204
+ }
164
205
  }
165
206
 
166
207
  const accessTokenBodySchema = getAccessToken.options.body as
@@ -208,8 +249,17 @@ interface KeycloakAccountLike {
208
249
  * never looks like a logout.
209
250
  */
210
251
  function createKeycloakSsoPlugin(options: KeycloakSsoPluginOptions) {
211
- const { realm, clientId, clientSecret, issuer, baseUrl, publicKeycloakBaseFor } = options;
252
+ const {
253
+ realm,
254
+ clientId,
255
+ clientSecret,
256
+ issuer,
257
+ baseUrl,
258
+ publicKeycloakBaseFor,
259
+ nativeOfflineAccess,
260
+ } = options;
212
261
  const tokenEndpoint = `${issuer}/protocol/openid-connect/token`;
262
+ const logoutEndpoint = `${issuer}/protocol/openid-connect/logout`;
213
263
 
214
264
  /** Visitor origin for the current request (route-handler ALS, then headers). */
215
265
  const resolveVisitorOrigin = (request?: Request): string | undefined =>
@@ -243,6 +293,55 @@ function createKeycloakSsoPlugin(options: KeycloakSsoPluginOptions) {
243
293
  }
244
294
  };
245
295
 
296
+ /**
297
+ * This device's Keycloak account: the account cookie first, as
298
+ * `/get-access-token` reads it. The account row is one per user and holds
299
+ * whichever device refreshed last.
300
+ */
301
+ const findDeviceKeycloakAccount = async (
302
+ ctx: GenericEndpointContext,
303
+ ): Promise<KeycloakAccountLike | undefined> => {
304
+ const accountCookie = (await getAccountCookie(ctx).catch(
305
+ () => null,
306
+ )) as KeycloakAccountLike | null;
307
+ if (accountCookie?.providerId === "keycloak" && accountCookie.refreshToken) {
308
+ return accountCookie;
309
+ }
310
+ const session = await getSessionFromCtx(ctx).catch(() => null);
311
+ if (!session) return undefined;
312
+ const accounts = (await ctx.context.internalAdapter
313
+ .findAccounts(session.user.id)
314
+ .catch(() => [])) as KeycloakAccountLike[];
315
+ return accounts.find((account) => account.providerId === "keycloak");
316
+ };
317
+
318
+ /**
319
+ * End this device's offline session. Keycloak's browser end-session leaves
320
+ * offline sessions alive, and the revocation endpoint revokes the client
321
+ * for every device of the user, so the client-authenticated logout with
322
+ * the offline refresh token is the one call that ends just this one.
323
+ */
324
+ const endOfflineSession = async (ctx: GenericEndpointContext, refreshToken?: string | null) => {
325
+ if (!refreshToken || !isOfflineRefreshToken(refreshToken)) return;
326
+ try {
327
+ const res = await fetch(logoutEndpoint, {
328
+ method: "POST",
329
+ headers: { "content-type": "application/x-www-form-urlencoded" },
330
+ body: new URLSearchParams({
331
+ refresh_token: refreshToken,
332
+ client_id: clientId,
333
+ client_secret: clientSecret,
334
+ }),
335
+ signal: AbortSignal.timeout(5000),
336
+ });
337
+ if (!res.ok) {
338
+ ctx.context.logger.warn(`Keycloak offline session logout answered ${res.status}`);
339
+ }
340
+ } catch (error) {
341
+ ctx.context.logger.warn("Keycloak offline session logout failed", error);
342
+ }
343
+ };
344
+
246
345
  const signOutSso = createAuthEndpoint("/sign-out/sso", { method: "GET" }, async (ctx) => {
247
346
  const visitorOrigin = resolveVisitorOrigin(ctx.request) ?? baseUrl;
248
347
  const searchParams = ctx.request ? new URL(ctx.request.url).searchParams : undefined;
@@ -286,6 +385,7 @@ function createKeycloakSsoPlugin(options: KeycloakSsoPluginOptions) {
286
385
  idTokenHint = accountCookie.idToken;
287
386
  }
288
387
  }
388
+ await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
289
389
 
290
390
  if (sessionToken) {
291
391
  await ctx.context.internalAdapter.deleteSession(sessionToken).catch((error: unknown) => {
@@ -318,6 +418,12 @@ function createKeycloakSsoPlugin(options: KeycloakSsoPluginOptions) {
318
418
  },
319
419
  hooks: {
320
420
  before: [
421
+ {
422
+ matcher: (ctx) => ctx.path === "/sign-out",
423
+ handler: createAuthMiddleware(async (ctx) => {
424
+ await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
425
+ }),
426
+ },
321
427
  {
322
428
  // Signed out is the expected answer on every anonymous page load,
323
429
  // so it is a 200 with no token, as /get-session answers, instead
@@ -338,6 +444,23 @@ function createKeycloakSsoPlugin(options: KeycloakSsoPluginOptions) {
338
444
  },
339
445
  ],
340
446
  after: [
447
+ {
448
+ matcher: (ctx) =>
449
+ nativeOfflineAccess &&
450
+ (ctx.path === "/sign-in/social" || ctx.path === "/sign-in/oauth2"),
451
+ handler: createAuthMiddleware(async (ctx) => {
452
+ if (!isNativeRequest(ctx.request?.headers ?? ctx.headers)) return;
453
+ const body = ctx.body as { provider?: string; providerId?: string } | undefined;
454
+ if ((body?.provider ?? body?.providerId) !== "keycloak") return;
455
+ const returned = ctx.context.returned as
456
+ | { url?: unknown; redirect?: boolean }
457
+ | undefined;
458
+ if (isAPIError(returned) || typeof returned?.url !== "string") return;
459
+ const url = withOfflineAccessScope(returned.url);
460
+ if (ctx.context.responseHeaders?.has("location")) ctx.setHeader("location", url);
461
+ return ctx.json({ ...returned, url });
462
+ }),
463
+ },
341
464
  {
342
465
  matcher: (ctx) => ctx.path === "/get-access-token",
343
466
  handler: createAuthMiddleware(async (ctx) => {
@@ -590,6 +713,7 @@ export function createAuth(options: CreateAuthOptions = {}) {
590
713
  issuer,
591
714
  baseUrl,
592
715
  publicKeycloakBaseFor,
716
+ nativeOfflineAccess: options.nativeOfflineAccess !== false,
593
717
  });
594
718
 
595
719
  const plugins: any[] = [
package/types/index.d.ts CHANGED
@@ -37,6 +37,13 @@ export interface CreateAuthOptions {
37
37
  sessionMaxAge?: number;
38
38
  /** Include @better-auth/expo plugin (default: true) */
39
39
  enableExpo?: boolean;
40
+ /**
41
+ * Native sign-ins (requests carrying `expo-origin`) ask Keycloak for an
42
+ * offline token, so the app stays signed in past the realm's SSO idle and
43
+ * max lifespan until the user logs out; logout ends that offline session.
44
+ * Web sign-ins keep the normal SSO session. Default: true.
45
+ */
46
+ nativeOfflineAccess?: boolean;
40
47
  /** Additional better-auth plugins */
41
48
  plugins?: Parameters<typeof betterAuth>[0]["plugins"];
42
49
  /**
@@ -54,6 +61,15 @@ export interface AuthLike {
54
61
  }) => Promise<unknown>;
55
62
  };
56
63
  }
64
+ export declare const OFFLINE_ACCESS_SCOPE = "offline_access";
65
+ /**
66
+ * Add `offline_access` to an authorization URL's `scope`. The genericOAuth
67
+ * provider builds the URL from its static scopes and ignores the sign-in
68
+ * body's `scopes`, so the native request is widened on the URL it returns.
69
+ */
70
+ export declare function withOfflineAccessScope(authorizationUrl: string): string;
71
+ /** Keycloak refresh tokens are JWTs whose `typ` is `Offline` for offline tokens. */
72
+ export declare function isOfflineRefreshToken(token?: string | null): boolean;
57
73
  /**
58
74
  * Create a Better Auth instance configured for Keycloak.
59
75
  * Keycloak is expected at ${BASE_URL}/auth (proxied by Frappe in dev).
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAsB,MAAM,aAAa,CAAC;AAe7D,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,EAC1B,yBAAyB,EACzB,2BAA2B,EAC3B,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AA+CvF,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MA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