@authowl/next 0.2.10 → 0.2.12

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/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  **[Complete SDK guide](https://authowl.dev/docs/sdks/next)** ·
4
4
  **[Next.js quickstart](https://authowl.dev/docs/getting-started/quickstart-nextjs)**
5
5
 
6
- Next.js (App Router) server helpers for [AuthOwl](https://authowl.dev), the
7
- multi-tenant auth service. `auth()` works in Server Components and route handlers.
6
+ Next.js (App Router) helpers for [AuthOwl](https://authowl.dev), the multi-tenant
7
+ auth service. `auth()` works in Server Components and route handlers.
8
8
 
9
9
  ```bash
10
10
  pnpm add @authowl/next @authowl/react
@@ -28,7 +28,53 @@ export default async function Page() {
28
28
  ```
29
29
 
30
30
  `initAuth({ publishableKey, apiUrl })` is optional (call it to override the env or
31
- surface config errors at boot). For the client-side provider and components, use
31
+ surface config errors at boot).
32
+
33
+ ## Cross-origin auth service
34
+
35
+ When AuthOwl and your Next.js application use different parent domains, add the
36
+ session bridge. It preserves AuthOwl's browser bearer fallback for browsers that
37
+ block cross-site cookies while giving `auth()` a validated, host-only HttpOnly
38
+ session on your application origin.
39
+
40
+ ```ts
41
+ // app/api/authowl/session/route.ts
42
+ import { createAuthOwlSessionBridge } from '@authowl/next/server';
43
+
44
+ export const POST = createAuthOwlSessionBridge();
45
+ ```
46
+
47
+ Pass the bridge-aware fetch to the same client provider that renders your
48
+ AuthOwl components:
49
+
50
+ ```tsx
51
+ 'use client';
52
+
53
+ import { createAuthOwlNextFetch } from '@authowl/next/client';
54
+ import { AuthOwlProvider } from '@authowl/react';
55
+
56
+ const publishableKey = process.env.NEXT_PUBLIC_AUTHOWL_PUBLISHABLE_KEY!;
57
+ const apiUrl = process.env.NEXT_PUBLIC_AUTHOWL_API_URL!;
58
+ const authOwlFetch = createAuthOwlNextFetch({ publishableKey, apiUrl });
59
+
60
+ export function Providers({ children }: { children: React.ReactNode }) {
61
+ return (
62
+ <AuthOwlProvider
63
+ publishableKey={publishableKey}
64
+ apiUrl={apiUrl}
65
+ fetch={authOwlFetch}
66
+ >
67
+ {children}
68
+ </AuthOwlProvider>
69
+ );
70
+ }
71
+ ```
72
+
73
+ The route accepts only same-origin browser requests and stores a token only
74
+ after AuthOwl validates that it belongs to a live session whose MFA enrollment
75
+ is complete. Never proxy this route through a different origin.
76
+
77
+ For the remaining client-side components, use
32
78
  [`@authowl/react`](https://www.npmjs.com/package/@authowl/react).
33
79
  Those components use AuthOwl gold (`#F5B84C`) by default and automatically
34
80
  honor project branding or an explicit `appearance.primaryColor` override.
@@ -0,0 +1,14 @@
1
+ // src/bridge-contract.ts
2
+ var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
3
+ function appSessionCookieNames(projectId) {
4
+ const suffix = projectId.toLowerCase().replace(/-/g, "");
5
+ return {
6
+ secure: `__Host-authowl_app_${suffix}`,
7
+ local: `authowl_app_${suffix}`
8
+ };
9
+ }
10
+
11
+ export {
12
+ APP_SESSION_BRIDGE_HEADER,
13
+ appSessionCookieNames
14
+ };
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/client.ts
22
+ var client_exports = {};
23
+ __export(client_exports, {
24
+ AuthOwlNextSessionBridgeError: () => AuthOwlNextSessionBridgeError,
25
+ createAuthOwlNextFetch: () => createAuthOwlNextFetch
26
+ });
27
+ module.exports = __toCommonJS(client_exports);
28
+ var import_core = require("@authowl/core");
29
+
30
+ // src/bridge-contract.ts
31
+ var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
32
+
33
+ // src/client.ts
34
+ var AuthOwlNextSessionBridgeError = class extends Error {
35
+ status;
36
+ constructor(message, status) {
37
+ super(message);
38
+ this.name = "AuthOwlNextSessionBridgeError";
39
+ this.status = status;
40
+ }
41
+ };
42
+ function requestUrl(input) {
43
+ try {
44
+ if (input instanceof Request) return new URL(input.url);
45
+ return new URL(String(input));
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ function sameOriginBridgePath(value) {
51
+ const base = new URL("https://authowl.invalid");
52
+ let parsed;
53
+ try {
54
+ parsed = new URL(value, base);
55
+ } catch {
56
+ throw new TypeError("bridgePath must be a same-origin absolute path");
57
+ }
58
+ if (!value.startsWith("/") || parsed.origin !== base.origin || parsed.hash || parsed.username || parsed.password) {
59
+ throw new TypeError("bridgePath must be a same-origin absolute path");
60
+ }
61
+ return `${parsed.pathname}${parsed.search}`;
62
+ }
63
+ function rememberIntent(init) {
64
+ if (typeof init?.body !== "string") return void 0;
65
+ try {
66
+ const body = JSON.parse(init.body);
67
+ return typeof body.rememberMe === "boolean" ? body.rememberMe : void 0;
68
+ } catch {
69
+ return void 0;
70
+ }
71
+ }
72
+ function requestHeaders(input, init) {
73
+ if (init?.headers) return new Headers(init.headers);
74
+ return input instanceof Request ? new Headers(input.headers) : new Headers();
75
+ }
76
+ function createAuthOwlNextFetch(options) {
77
+ const target = (0, import_core.resolveAuthTarget)(options);
78
+ const apiOrigin = target.apiUrl;
79
+ const authPath = `/api/projects/${target.decoded.projectId}/auth/`;
80
+ const bridgePath = sameOriginBridgePath(options.bridgePath ?? "/api/authowl/session");
81
+ const baseFetch = options.fetch ?? globalThis.fetch;
82
+ let synchronization = Promise.resolve();
83
+ const sync = (token, remember) => {
84
+ synchronization = synchronization.catch(() => void 0).then(async () => {
85
+ const response = await baseFetch(bridgePath, {
86
+ method: "POST",
87
+ headers: {
88
+ "content-type": "application/json",
89
+ [APP_SESSION_BRIDGE_HEADER]: "1"
90
+ },
91
+ credentials: "same-origin",
92
+ cache: "no-store",
93
+ redirect: "error",
94
+ body: JSON.stringify({ token, remember })
95
+ });
96
+ if (!response.ok) {
97
+ throw new AuthOwlNextSessionBridgeError(
98
+ `AuthOwl Next.js session projection failed with status ${response.status}.`,
99
+ response.status
100
+ );
101
+ }
102
+ });
103
+ return synchronization;
104
+ };
105
+ return async (input, init) => {
106
+ const response = await baseFetch(input, init);
107
+ const url = requestUrl(input);
108
+ if (!url || url.origin !== apiOrigin || !url.pathname.startsWith(authPath)) {
109
+ return response;
110
+ }
111
+ const token = response.headers.get(import_core.SESSION_TOKEN_HEADER);
112
+ if (token) {
113
+ const remember = rememberIntent(init) ?? !(0, import_core.sessionChallengeIsEphemeral)(requestHeaders(input, init));
114
+ await sync(token, remember);
115
+ } else if (response.ok && url.pathname === `${authPath}sign-out`) {
116
+ await sync(null, true);
117
+ }
118
+ return response;
119
+ };
120
+ }
121
+ // Annotate the CommonJS export names for ESM import in node:
122
+ 0 && (module.exports = {
123
+ AuthOwlNextSessionBridgeError,
124
+ createAuthOwlNextFetch
125
+ });
@@ -0,0 +1,17 @@
1
+ declare class AuthOwlNextSessionBridgeError extends Error {
2
+ readonly status?: number;
3
+ constructor(message: string, status?: number);
4
+ }
5
+ type AuthOwlNextFetchOptions = Readonly<{
6
+ publishableKey: string;
7
+ apiUrl: string;
8
+ bridgePath?: string;
9
+ fetch?: typeof fetch;
10
+ }>;
11
+ /**
12
+ * Wrap the fetch passed to AuthOwlProvider so every issued browser session is
13
+ * validated and projected onto the Next.js origin before a drop-in redirects.
14
+ */
15
+ declare function createAuthOwlNextFetch(options: AuthOwlNextFetchOptions): typeof fetch;
16
+
17
+ export { type AuthOwlNextFetchOptions, AuthOwlNextSessionBridgeError, createAuthOwlNextFetch };
@@ -0,0 +1,17 @@
1
+ declare class AuthOwlNextSessionBridgeError extends Error {
2
+ readonly status?: number;
3
+ constructor(message: string, status?: number);
4
+ }
5
+ type AuthOwlNextFetchOptions = Readonly<{
6
+ publishableKey: string;
7
+ apiUrl: string;
8
+ bridgePath?: string;
9
+ fetch?: typeof fetch;
10
+ }>;
11
+ /**
12
+ * Wrap the fetch passed to AuthOwlProvider so every issued browser session is
13
+ * validated and projected onto the Next.js origin before a drop-in redirects.
14
+ */
15
+ declare function createAuthOwlNextFetch(options: AuthOwlNextFetchOptions): typeof fetch;
16
+
17
+ export { type AuthOwlNextFetchOptions, AuthOwlNextSessionBridgeError, createAuthOwlNextFetch };
package/dist/client.js ADDED
@@ -0,0 +1,102 @@
1
+ "use client";
2
+ import {
3
+ APP_SESSION_BRIDGE_HEADER
4
+ } from "./chunk-MZJVERMC.js";
5
+
6
+ // src/client.ts
7
+ import {
8
+ resolveAuthTarget,
9
+ SESSION_TOKEN_HEADER,
10
+ sessionChallengeIsEphemeral
11
+ } from "@authowl/core";
12
+ var AuthOwlNextSessionBridgeError = class extends Error {
13
+ status;
14
+ constructor(message, status) {
15
+ super(message);
16
+ this.name = "AuthOwlNextSessionBridgeError";
17
+ this.status = status;
18
+ }
19
+ };
20
+ function requestUrl(input) {
21
+ try {
22
+ if (input instanceof Request) return new URL(input.url);
23
+ return new URL(String(input));
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function sameOriginBridgePath(value) {
29
+ const base = new URL("https://authowl.invalid");
30
+ let parsed;
31
+ try {
32
+ parsed = new URL(value, base);
33
+ } catch {
34
+ throw new TypeError("bridgePath must be a same-origin absolute path");
35
+ }
36
+ if (!value.startsWith("/") || parsed.origin !== base.origin || parsed.hash || parsed.username || parsed.password) {
37
+ throw new TypeError("bridgePath must be a same-origin absolute path");
38
+ }
39
+ return `${parsed.pathname}${parsed.search}`;
40
+ }
41
+ function rememberIntent(init) {
42
+ if (typeof init?.body !== "string") return void 0;
43
+ try {
44
+ const body = JSON.parse(init.body);
45
+ return typeof body.rememberMe === "boolean" ? body.rememberMe : void 0;
46
+ } catch {
47
+ return void 0;
48
+ }
49
+ }
50
+ function requestHeaders(input, init) {
51
+ if (init?.headers) return new Headers(init.headers);
52
+ return input instanceof Request ? new Headers(input.headers) : new Headers();
53
+ }
54
+ function createAuthOwlNextFetch(options) {
55
+ const target = resolveAuthTarget(options);
56
+ const apiOrigin = target.apiUrl;
57
+ const authPath = `/api/projects/${target.decoded.projectId}/auth/`;
58
+ const bridgePath = sameOriginBridgePath(options.bridgePath ?? "/api/authowl/session");
59
+ const baseFetch = options.fetch ?? globalThis.fetch;
60
+ let synchronization = Promise.resolve();
61
+ const sync = (token, remember) => {
62
+ synchronization = synchronization.catch(() => void 0).then(async () => {
63
+ const response = await baseFetch(bridgePath, {
64
+ method: "POST",
65
+ headers: {
66
+ "content-type": "application/json",
67
+ [APP_SESSION_BRIDGE_HEADER]: "1"
68
+ },
69
+ credentials: "same-origin",
70
+ cache: "no-store",
71
+ redirect: "error",
72
+ body: JSON.stringify({ token, remember })
73
+ });
74
+ if (!response.ok) {
75
+ throw new AuthOwlNextSessionBridgeError(
76
+ `AuthOwl Next.js session projection failed with status ${response.status}.`,
77
+ response.status
78
+ );
79
+ }
80
+ });
81
+ return synchronization;
82
+ };
83
+ return async (input, init) => {
84
+ const response = await baseFetch(input, init);
85
+ const url = requestUrl(input);
86
+ if (!url || url.origin !== apiOrigin || !url.pathname.startsWith(authPath)) {
87
+ return response;
88
+ }
89
+ const token = response.headers.get(SESSION_TOKEN_HEADER);
90
+ if (token) {
91
+ const remember = rememberIntent(init) ?? !sessionChallengeIsEphemeral(requestHeaders(input, init));
92
+ await sync(token, remember);
93
+ } else if (response.ok && url.pathname === `${authPath}sign-out`) {
94
+ await sync(null, true);
95
+ }
96
+ return response;
97
+ };
98
+ }
99
+ export {
100
+ AuthOwlNextSessionBridgeError,
101
+ createAuthOwlNextFetch
102
+ };
@@ -25,13 +25,27 @@ __export(middleware_exports, {
25
25
  });
26
26
  module.exports = __toCommonJS(middleware_exports);
27
27
  var import_server = require("next/server");
28
+ var import_core = require("@authowl/core");
28
29
  var import_server2 = require("@authowl/core/server");
30
+
31
+ // src/bridge-contract.ts
32
+ function appSessionCookieNames(projectId) {
33
+ const suffix = projectId.toLowerCase().replace(/-/g, "");
34
+ return {
35
+ secure: `__Host-authowl_app_${suffix}`,
36
+ local: `authowl_app_${suffix}`
37
+ };
38
+ }
39
+
40
+ // src/middleware.ts
29
41
  function createAuthRedirectMiddleware(opts) {
30
- const projectId = opts.publishableKey.split("_")[2];
31
- if (!projectId) {
32
- throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<random>");
33
- }
34
- const cookieNames = [true, false].map((secure) => (0, import_server2.sessionCookieName)(projectId, { secure }));
42
+ const { projectId } = (0, import_core.decodePublishableKey)(opts.publishableKey);
43
+ const bridgeNames = appSessionCookieNames(projectId);
44
+ const cookieNames = [
45
+ ...[true, false].map((secure) => (0, import_server2.sessionCookieName)(projectId, { secure })),
46
+ bridgeNames.secure,
47
+ bridgeNames.local
48
+ ];
35
49
  const loginPath = opts.loginPath ?? "/sign-in";
36
50
  const normalizedLoginPath = loginPath.endsWith("/") && loginPath !== "/" ? loginPath.slice(0, -1) : loginPath;
37
51
  const matchers = opts.protectedPaths ?? [/^\/.*/];
@@ -1,12 +1,19 @@
1
+ import {
2
+ appSessionCookieNames
3
+ } from "./chunk-MZJVERMC.js";
4
+
1
5
  // src/middleware.ts
2
6
  import { NextResponse } from "next/server";
7
+ import { decodePublishableKey } from "@authowl/core";
3
8
  import { sessionCookieName } from "@authowl/core/server";
4
9
  function createAuthRedirectMiddleware(opts) {
5
- const projectId = opts.publishableKey.split("_")[2];
6
- if (!projectId) {
7
- throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<random>");
8
- }
9
- const cookieNames = [true, false].map((secure) => sessionCookieName(projectId, { secure }));
10
+ const { projectId } = decodePublishableKey(opts.publishableKey);
11
+ const bridgeNames = appSessionCookieNames(projectId);
12
+ const cookieNames = [
13
+ ...[true, false].map((secure) => sessionCookieName(projectId, { secure })),
14
+ bridgeNames.secure,
15
+ bridgeNames.local
16
+ ];
10
17
  const loginPath = opts.loginPath ?? "/sign-in";
11
18
  const normalizedLoginPath = loginPath.endsWith("/") && loginPath !== "/" ? loginPath.slice(0, -1) : loginPath;
12
19
  const matchers = opts.protectedPaths ?? [/^\/.*/];
package/dist/server.cjs CHANGED
@@ -21,44 +21,200 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var server_exports = {};
22
22
  __export(server_exports, {
23
23
  AuthServiceError: () => AuthServiceError,
24
- TokenVerificationError: () => import_server2.TokenVerificationError,
24
+ TokenVerificationError: () => import_server4.TokenVerificationError,
25
25
  auth: () => auth,
26
- has: () => import_server2.has,
27
- hasPermission: () => import_server2.hasPermission,
26
+ createAuthOwlSessionBridge: () => createAuthOwlSessionBridge,
27
+ has: () => import_server4.has,
28
+ hasAuthOwlSessionCookie: () => hasAuthOwlSessionCookie,
29
+ hasPermission: () => import_server4.hasPermission,
28
30
  initAuth: () => initAuth,
29
- verifyToken: () => import_server2.verifyToken
31
+ verifyToken: () => import_server4.verifyToken
30
32
  });
31
33
  module.exports = __toCommonJS(server_exports);
32
34
  var import_headers = require("next/headers");
35
+ var import_server3 = require("@authowl/core/server");
36
+
37
+ // src/bridge-contract.ts
38
+ var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
39
+ function appSessionCookieNames(projectId) {
40
+ const suffix = projectId.toLowerCase().replace(/-/g, "");
41
+ return {
42
+ secure: `__Host-authowl_app_${suffix}`,
43
+ local: `authowl_app_${suffix}`
44
+ };
45
+ }
46
+
47
+ // src/server-config.ts
33
48
  var import_server = require("@authowl/core/server");
34
- var import_server2 = require("@authowl/core/server");
35
- var AUTH_FETCH_TIMEOUT_MS = 1e4;
36
- var AuthServiceError = class extends Error {
37
- status;
38
- constructor(message, options = {}) {
39
- super(message, { cause: options.cause });
40
- this.name = "AuthServiceError";
41
- this.status = options.status;
42
- }
43
- };
49
+ function serverConfig(config) {
50
+ const resolved = (0, import_server.resolveAuthTarget)(config);
51
+ return {
52
+ publishableKey: resolved.publishableKey,
53
+ apiUrl: resolved.apiUrl,
54
+ projectId: resolved.decoded.projectId
55
+ };
56
+ }
44
57
  var cachedConfig = null;
45
- function initAuth(config) {
46
- (0, import_server.resolveConfig)(config);
47
- cachedConfig = { publishableKey: config.publishableKey, apiUrl: config.apiUrl };
58
+ function initAuthConfig(config) {
59
+ cachedConfig = serverConfig(config);
48
60
  }
49
- function getConfig() {
61
+ function getAuthConfig() {
50
62
  if (cachedConfig) return cachedConfig;
51
63
  const publishableKey = process.env.AUTHOWL_PUBLISHABLE_KEY;
52
64
  const apiUrl = process.env.AUTHOWL_API_URL;
53
65
  if (publishableKey && apiUrl) {
54
- (0, import_server.resolveConfig)({ publishableKey, apiUrl });
55
- cachedConfig = { publishableKey, apiUrl };
66
+ cachedConfig = serverConfig({ publishableKey, apiUrl });
56
67
  return cachedConfig;
57
68
  }
58
69
  throw new Error(
59
70
  "AuthOwl is not configured. Set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL, or call initAuth({ publishableKey, apiUrl })."
60
71
  );
61
72
  }
73
+ function resolveAuthConfig(config) {
74
+ if (!config) return getAuthConfig();
75
+ return serverConfig(config);
76
+ }
77
+
78
+ // src/session-bridge.ts
79
+ var import_server2 = require("@authowl/core/server");
80
+ var MAX_BODY_BYTES = 16384;
81
+ var AUTH_FETCH_TIMEOUT_MS = 1e4;
82
+ function response(status, body) {
83
+ return body ? Response.json(body, { status, headers: { "cache-control": "no-store" } }) : new Response(null, { status, headers: { "cache-control": "no-store" } });
84
+ }
85
+ function singleForwardingHeader(headers, name) {
86
+ const value = headers.get(name);
87
+ if (!value || value !== value.trim() || value.includes(",")) return null;
88
+ return value;
89
+ }
90
+ function forwardedRequestOrigin(request) {
91
+ const protocol = singleForwardingHeader(request.headers, "x-forwarded-proto");
92
+ const host = singleForwardingHeader(request.headers, "x-forwarded-host") ?? singleForwardingHeader(request.headers, "host");
93
+ if (protocol !== "http" && protocol !== "https" || !host) return null;
94
+ try {
95
+ const url = new URL(`${protocol}://${host}`);
96
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
97
+ return null;
98
+ }
99
+ return url.origin;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+ function sameOriginBrowserPostOrigin(request) {
105
+ const origin = request.headers.get("origin");
106
+ const site = request.headers.get("sec-fetch-site");
107
+ const requestOrigin = new URL(request.url).origin;
108
+ if (request.method !== "POST" || origin === null || site !== null && site !== "same-origin" || request.headers.get(APP_SESSION_BRIDGE_HEADER) !== "1" || request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") {
109
+ return null;
110
+ }
111
+ if (origin === requestOrigin) return requestOrigin;
112
+ return origin === forwardedRequestOrigin(request) ? origin : null;
113
+ }
114
+ function validToken(value) {
115
+ return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
116
+ }
117
+ function serializeCookie(name, value, options) {
118
+ const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
119
+ if (options.secure) attributes.push("Secure");
120
+ if (options.clear) attributes.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
121
+ else if (options.expires) attributes.push(`Expires=${options.expires.toUTCString()}`);
122
+ return attributes.join("; ");
123
+ }
124
+ function clearCookies(projectId) {
125
+ const names = appSessionCookieNames(projectId);
126
+ const result = response(204);
127
+ result.headers.append("set-cookie", serializeCookie(names.secure, "", { secure: true, clear: true }));
128
+ result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
129
+ return result;
130
+ }
131
+ function createAuthOwlSessionBridge(input) {
132
+ const configured = input ? resolveAuthConfig(input) : null;
133
+ const remoteFetch = input?.fetch ?? globalThis.fetch;
134
+ return async function authOwlSessionBridge(request) {
135
+ const config = configured ?? getAuthConfig();
136
+ const projectId = config.projectId;
137
+ const browserOrigin = sameOriginBrowserPostOrigin(request);
138
+ if (!browserOrigin) {
139
+ return response(403, { error: "forbidden" });
140
+ }
141
+ const raw = await request.text();
142
+ if (raw.length > MAX_BODY_BYTES) return response(413, { error: "payload_too_large" });
143
+ let body;
144
+ try {
145
+ body = JSON.parse(raw);
146
+ } catch {
147
+ return response(400, { error: "invalid_request" });
148
+ }
149
+ if (body.token === null) return clearCookies(projectId);
150
+ if (!validToken(body.token) || body.remember !== void 0 && typeof body.remember !== "boolean") {
151
+ return response(400, { error: "invalid_request" });
152
+ }
153
+ let sessionResponse;
154
+ try {
155
+ sessionResponse = await remoteFetch(
156
+ `${config.apiUrl}/api/projects/${projectId}/auth/get-session`,
157
+ {
158
+ method: "GET",
159
+ headers: {
160
+ authorization: `Bearer ${body.token}`,
161
+ [import_server2.SESSION_TRANSPORT_HEADER]: import_server2.SESSION_TRANSPORT_BEARER,
162
+ "x-publishable-key": config.publishableKey
163
+ },
164
+ cache: "no-store",
165
+ redirect: "error",
166
+ signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
167
+ }
168
+ );
169
+ } catch {
170
+ return response(503, { error: "auth_service_unavailable" });
171
+ }
172
+ if (sessionResponse.status === 401) return response(401, { error: "invalid_session" });
173
+ if (!sessionResponse.ok) return response(502, { error: "auth_service_error" });
174
+ let session;
175
+ try {
176
+ session = await sessionResponse.json();
177
+ } catch {
178
+ return response(502, { error: "invalid_auth_response" });
179
+ }
180
+ if (!session.user || !session.session || session.session.pendingMfaEnrollment === true) {
181
+ return response(401, { error: "invalid_session" });
182
+ }
183
+ if (typeof session.session.expiresAt !== "string") {
184
+ return response(401, { error: "invalid_session" });
185
+ }
186
+ const expires = new Date(session.session.expiresAt);
187
+ if (!Number.isFinite(expires.getTime()) || expires.getTime() <= Date.now()) {
188
+ return response(401, { error: "invalid_session" });
189
+ }
190
+ const secure = new URL(browserOrigin).protocol === "https:";
191
+ const names = appSessionCookieNames(projectId);
192
+ const result = response(204);
193
+ result.headers.append(
194
+ "set-cookie",
195
+ serializeCookie(secure ? names.secure : names.local, body.token, {
196
+ secure,
197
+ expires: body.remember === false ? void 0 : expires
198
+ })
199
+ );
200
+ return result;
201
+ };
202
+ }
203
+
204
+ // src/server.ts
205
+ var import_server4 = require("@authowl/core/server");
206
+ var AUTH_FETCH_TIMEOUT_MS2 = 1e4;
207
+ var AuthServiceError = class extends Error {
208
+ status;
209
+ constructor(message, options = {}) {
210
+ super(message, { cause: options.cause });
211
+ this.name = "AuthServiceError";
212
+ this.status = options.status;
213
+ }
214
+ };
215
+ function initAuth(config) {
216
+ initAuthConfig(config);
217
+ }
62
218
  function createTimeoutSignal(timeoutMs) {
63
219
  if (typeof AbortSignal.timeout === "function") {
64
220
  return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
@@ -72,15 +228,18 @@ function isTimeoutError(error) {
72
228
  return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
73
229
  }
74
230
  async function auth() {
75
- const cfg = getConfig();
76
- const projectId = cfg.publishableKey.split("_")[2].toLowerCase();
231
+ const cfg = getAuthConfig();
232
+ const projectId = cfg.projectId;
77
233
  const secure = new URL(cfg.apiUrl).protocol === "https:";
78
- const cookieName = (0, import_server.sessionCookieName)(projectId, { secure });
234
+ const cookieName = (0, import_server3.sessionCookieName)(projectId, { secure });
79
235
  const cookieStore = await (0, import_headers.cookies)();
80
- const cookieHeader = cookieStore.getAll().filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
236
+ const allCookies = cookieStore.getAll();
237
+ const cookieHeader = allCookies.filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
238
+ const bridgeNames = appSessionCookieNames(projectId);
239
+ const bridgeToken = cookieHeader ? null : allCookies.find((cookie) => cookie.name === bridgeNames.secure)?.value ?? allCookies.find((cookie) => cookie.name === bridgeNames.local)?.value ?? null;
81
240
  const hdrs = await (0, import_headers.headers)();
82
241
  const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
83
- const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS);
242
+ const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS2);
84
243
  let res;
85
244
  try {
86
245
  res = await fetch(url, {
@@ -88,13 +247,17 @@ async function auth() {
88
247
  headers: {
89
248
  cookie: cookieHeader,
90
249
  "x-publishable-key": cfg.publishableKey,
91
- "user-agent": hdrs.get("user-agent") ?? "next-auth-helper"
250
+ "user-agent": hdrs.get("user-agent") ?? "next-auth-helper",
251
+ ...bridgeToken ? {
252
+ authorization: `Bearer ${bridgeToken}`,
253
+ [import_server3.SESSION_TRANSPORT_HEADER]: import_server3.SESSION_TRANSPORT_BEARER
254
+ } : {}
92
255
  },
93
256
  cache: "no-store",
94
257
  signal: timeout.signal
95
258
  });
96
259
  } catch (error) {
97
- const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS}ms.` : "Auth service request failed.";
260
+ const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS2}ms.` : "Auth service request failed.";
98
261
  throw new AuthServiceError(message, { cause: error });
99
262
  } finally {
100
263
  timeout.cleanup();
@@ -115,12 +278,22 @@ async function auth() {
115
278
  return null;
116
279
  }
117
280
  }
281
+ async function hasAuthOwlSessionCookie() {
282
+ const cfg = getAuthConfig();
283
+ const secure = new URL(cfg.apiUrl).protocol === "https:";
284
+ const native = (0, import_server3.sessionCookieName)(cfg.projectId, { secure });
285
+ const bridge = appSessionCookieNames(cfg.projectId);
286
+ const names = /* @__PURE__ */ new Set([native, bridge.secure, bridge.local]);
287
+ return (await (0, import_headers.cookies)()).getAll().some((cookie) => names.has(cookie.name));
288
+ }
118
289
  // Annotate the CommonJS export names for ESM import in node:
119
290
  0 && (module.exports = {
120
291
  AuthServiceError,
121
292
  TokenVerificationError,
122
293
  auth,
294
+ createAuthOwlSessionBridge,
123
295
  has,
296
+ hasAuthOwlSessionCookie,
124
297
  hasPermission,
125
298
  initAuth,
126
299
  verifyToken
package/dist/server.d.cts CHANGED
@@ -1,6 +1,14 @@
1
1
  import { AuthConfig } from '@authowl/core/server';
2
2
  export { HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, verifyToken } from '@authowl/core/server';
3
3
 
4
+ type AuthOwlSessionBridgeOptions = AuthConfig;
5
+ /**
6
+ * Build the same-origin endpoint that projects an AuthOwl browser session into
7
+ * an application-owned HttpOnly cookie. The token is accepted only after the
8
+ * AuthOwl project validates it as a completed, live session.
9
+ */
10
+ declare function createAuthOwlSessionBridge(input?: AuthOwlSessionBridgeOptions): (request: Request) => Promise<Response>;
11
+
4
12
  type Session = {
5
13
  user: {
6
14
  id: string;
@@ -44,10 +52,15 @@ declare function initAuth(config: AuthConfig): void;
44
52
  * Get the current session by forwarding only the expected auth session
45
53
  * cookie to the auth server. Returns null if not signed in.
46
54
  *
47
- * The auth cookie must be scoped so this app can read it and proxy it back to
48
- * cfg.apiUrl, for example by sharing a parent cookie domain between the app and
49
- * auth service. Unrelated application cookies are deliberately not forwarded.
55
+ * A native AuthOwl cookie is preferred when the application and auth service
56
+ * can share it. Otherwise the validated app-origin bridge cookie is forwarded
57
+ * through AuthOwl's paired bearer transport. Unrelated cookies are not sent.
50
58
  */
51
59
  declare function auth(): Promise<Session>;
60
+ /**
61
+ * Cheap presence check for UI routing only. This does not validate the session;
62
+ * call auth() for any authorization decision.
63
+ */
64
+ declare function hasAuthOwlSessionCookie(): Promise<boolean>;
52
65
 
53
- export { AuthServiceError, type Session, auth, initAuth };
66
+ export { type AuthOwlSessionBridgeOptions, AuthServiceError, type Session, auth, createAuthOwlSessionBridge, hasAuthOwlSessionCookie, initAuth };
package/dist/server.d.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  import { AuthConfig } from '@authowl/core/server';
2
2
  export { HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, verifyToken } from '@authowl/core/server';
3
3
 
4
+ type AuthOwlSessionBridgeOptions = AuthConfig;
5
+ /**
6
+ * Build the same-origin endpoint that projects an AuthOwl browser session into
7
+ * an application-owned HttpOnly cookie. The token is accepted only after the
8
+ * AuthOwl project validates it as a completed, live session.
9
+ */
10
+ declare function createAuthOwlSessionBridge(input?: AuthOwlSessionBridgeOptions): (request: Request) => Promise<Response>;
11
+
4
12
  type Session = {
5
13
  user: {
6
14
  id: string;
@@ -44,10 +52,15 @@ declare function initAuth(config: AuthConfig): void;
44
52
  * Get the current session by forwarding only the expected auth session
45
53
  * cookie to the auth server. Returns null if not signed in.
46
54
  *
47
- * The auth cookie must be scoped so this app can read it and proxy it back to
48
- * cfg.apiUrl, for example by sharing a parent cookie domain between the app and
49
- * auth service. Unrelated application cookies are deliberately not forwarded.
55
+ * A native AuthOwl cookie is preferred when the application and auth service
56
+ * can share it. Otherwise the validated app-origin bridge cookie is forwarded
57
+ * through AuthOwl's paired bearer transport. Unrelated cookies are not sent.
50
58
  */
51
59
  declare function auth(): Promise<Session>;
60
+ /**
61
+ * Cheap presence check for UI routing only. This does not validate the session;
62
+ * call auth() for any authorization decision.
63
+ */
64
+ declare function hasAuthOwlSessionCookie(): Promise<boolean>;
52
65
 
53
- export { AuthServiceError, type Session, auth, initAuth };
66
+ export { type AuthOwlSessionBridgeOptions, AuthServiceError, type Session, auth, createAuthOwlSessionBridge, hasAuthOwlSessionCookie, initAuth };
package/dist/server.js CHANGED
@@ -1,13 +1,184 @@
1
+ import {
2
+ APP_SESSION_BRIDGE_HEADER,
3
+ appSessionCookieNames
4
+ } from "./chunk-MZJVERMC.js";
5
+
1
6
  // src/server.ts
2
7
  import { headers as nextHeaders, cookies as nextCookies } from "next/headers";
3
- import { resolveConfig, sessionCookieName } from "@authowl/core/server";
8
+ import {
9
+ SESSION_TRANSPORT_BEARER as SESSION_TRANSPORT_BEARER2,
10
+ SESSION_TRANSPORT_HEADER as SESSION_TRANSPORT_HEADER2,
11
+ sessionCookieName
12
+ } from "@authowl/core/server";
13
+
14
+ // src/server-config.ts
15
+ import { resolveAuthTarget } from "@authowl/core/server";
16
+ function serverConfig(config) {
17
+ const resolved = resolveAuthTarget(config);
18
+ return {
19
+ publishableKey: resolved.publishableKey,
20
+ apiUrl: resolved.apiUrl,
21
+ projectId: resolved.decoded.projectId
22
+ };
23
+ }
24
+ var cachedConfig = null;
25
+ function initAuthConfig(config) {
26
+ cachedConfig = serverConfig(config);
27
+ }
28
+ function getAuthConfig() {
29
+ if (cachedConfig) return cachedConfig;
30
+ const publishableKey = process.env.AUTHOWL_PUBLISHABLE_KEY;
31
+ const apiUrl = process.env.AUTHOWL_API_URL;
32
+ if (publishableKey && apiUrl) {
33
+ cachedConfig = serverConfig({ publishableKey, apiUrl });
34
+ return cachedConfig;
35
+ }
36
+ throw new Error(
37
+ "AuthOwl is not configured. Set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL, or call initAuth({ publishableKey, apiUrl })."
38
+ );
39
+ }
40
+ function resolveAuthConfig(config) {
41
+ if (!config) return getAuthConfig();
42
+ return serverConfig(config);
43
+ }
44
+
45
+ // src/session-bridge.ts
46
+ import {
47
+ SESSION_TRANSPORT_BEARER,
48
+ SESSION_TRANSPORT_HEADER
49
+ } from "@authowl/core/server";
50
+ var MAX_BODY_BYTES = 16384;
51
+ var AUTH_FETCH_TIMEOUT_MS = 1e4;
52
+ function response(status, body) {
53
+ return body ? Response.json(body, { status, headers: { "cache-control": "no-store" } }) : new Response(null, { status, headers: { "cache-control": "no-store" } });
54
+ }
55
+ function singleForwardingHeader(headers, name) {
56
+ const value = headers.get(name);
57
+ if (!value || value !== value.trim() || value.includes(",")) return null;
58
+ return value;
59
+ }
60
+ function forwardedRequestOrigin(request) {
61
+ const protocol = singleForwardingHeader(request.headers, "x-forwarded-proto");
62
+ const host = singleForwardingHeader(request.headers, "x-forwarded-host") ?? singleForwardingHeader(request.headers, "host");
63
+ if (protocol !== "http" && protocol !== "https" || !host) return null;
64
+ try {
65
+ const url = new URL(`${protocol}://${host}`);
66
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
67
+ return null;
68
+ }
69
+ return url.origin;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+ function sameOriginBrowserPostOrigin(request) {
75
+ const origin = request.headers.get("origin");
76
+ const site = request.headers.get("sec-fetch-site");
77
+ const requestOrigin = new URL(request.url).origin;
78
+ if (request.method !== "POST" || origin === null || site !== null && site !== "same-origin" || request.headers.get(APP_SESSION_BRIDGE_HEADER) !== "1" || request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") {
79
+ return null;
80
+ }
81
+ if (origin === requestOrigin) return requestOrigin;
82
+ return origin === forwardedRequestOrigin(request) ? origin : null;
83
+ }
84
+ function validToken(value) {
85
+ return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
86
+ }
87
+ function serializeCookie(name, value, options) {
88
+ const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
89
+ if (options.secure) attributes.push("Secure");
90
+ if (options.clear) attributes.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
91
+ else if (options.expires) attributes.push(`Expires=${options.expires.toUTCString()}`);
92
+ return attributes.join("; ");
93
+ }
94
+ function clearCookies(projectId) {
95
+ const names = appSessionCookieNames(projectId);
96
+ const result = response(204);
97
+ result.headers.append("set-cookie", serializeCookie(names.secure, "", { secure: true, clear: true }));
98
+ result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
99
+ return result;
100
+ }
101
+ function createAuthOwlSessionBridge(input) {
102
+ const configured = input ? resolveAuthConfig(input) : null;
103
+ const remoteFetch = input?.fetch ?? globalThis.fetch;
104
+ return async function authOwlSessionBridge(request) {
105
+ const config = configured ?? getAuthConfig();
106
+ const projectId = config.projectId;
107
+ const browserOrigin = sameOriginBrowserPostOrigin(request);
108
+ if (!browserOrigin) {
109
+ return response(403, { error: "forbidden" });
110
+ }
111
+ const raw = await request.text();
112
+ if (raw.length > MAX_BODY_BYTES) return response(413, { error: "payload_too_large" });
113
+ let body;
114
+ try {
115
+ body = JSON.parse(raw);
116
+ } catch {
117
+ return response(400, { error: "invalid_request" });
118
+ }
119
+ if (body.token === null) return clearCookies(projectId);
120
+ if (!validToken(body.token) || body.remember !== void 0 && typeof body.remember !== "boolean") {
121
+ return response(400, { error: "invalid_request" });
122
+ }
123
+ let sessionResponse;
124
+ try {
125
+ sessionResponse = await remoteFetch(
126
+ `${config.apiUrl}/api/projects/${projectId}/auth/get-session`,
127
+ {
128
+ method: "GET",
129
+ headers: {
130
+ authorization: `Bearer ${body.token}`,
131
+ [SESSION_TRANSPORT_HEADER]: SESSION_TRANSPORT_BEARER,
132
+ "x-publishable-key": config.publishableKey
133
+ },
134
+ cache: "no-store",
135
+ redirect: "error",
136
+ signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
137
+ }
138
+ );
139
+ } catch {
140
+ return response(503, { error: "auth_service_unavailable" });
141
+ }
142
+ if (sessionResponse.status === 401) return response(401, { error: "invalid_session" });
143
+ if (!sessionResponse.ok) return response(502, { error: "auth_service_error" });
144
+ let session;
145
+ try {
146
+ session = await sessionResponse.json();
147
+ } catch {
148
+ return response(502, { error: "invalid_auth_response" });
149
+ }
150
+ if (!session.user || !session.session || session.session.pendingMfaEnrollment === true) {
151
+ return response(401, { error: "invalid_session" });
152
+ }
153
+ if (typeof session.session.expiresAt !== "string") {
154
+ return response(401, { error: "invalid_session" });
155
+ }
156
+ const expires = new Date(session.session.expiresAt);
157
+ if (!Number.isFinite(expires.getTime()) || expires.getTime() <= Date.now()) {
158
+ return response(401, { error: "invalid_session" });
159
+ }
160
+ const secure = new URL(browserOrigin).protocol === "https:";
161
+ const names = appSessionCookieNames(projectId);
162
+ const result = response(204);
163
+ result.headers.append(
164
+ "set-cookie",
165
+ serializeCookie(secure ? names.secure : names.local, body.token, {
166
+ secure,
167
+ expires: body.remember === false ? void 0 : expires
168
+ })
169
+ );
170
+ return result;
171
+ };
172
+ }
173
+
174
+ // src/server.ts
4
175
  import {
5
176
  has,
6
177
  hasPermission,
7
178
  verifyToken,
8
179
  TokenVerificationError
9
180
  } from "@authowl/core/server";
10
- var AUTH_FETCH_TIMEOUT_MS = 1e4;
181
+ var AUTH_FETCH_TIMEOUT_MS2 = 1e4;
11
182
  var AuthServiceError = class extends Error {
12
183
  status;
13
184
  constructor(message, options = {}) {
@@ -16,23 +187,8 @@ var AuthServiceError = class extends Error {
16
187
  this.status = options.status;
17
188
  }
18
189
  };
19
- var cachedConfig = null;
20
190
  function initAuth(config) {
21
- resolveConfig(config);
22
- cachedConfig = { publishableKey: config.publishableKey, apiUrl: config.apiUrl };
23
- }
24
- function getConfig() {
25
- if (cachedConfig) return cachedConfig;
26
- const publishableKey = process.env.AUTHOWL_PUBLISHABLE_KEY;
27
- const apiUrl = process.env.AUTHOWL_API_URL;
28
- if (publishableKey && apiUrl) {
29
- resolveConfig({ publishableKey, apiUrl });
30
- cachedConfig = { publishableKey, apiUrl };
31
- return cachedConfig;
32
- }
33
- throw new Error(
34
- "AuthOwl is not configured. Set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL, or call initAuth({ publishableKey, apiUrl })."
35
- );
191
+ initAuthConfig(config);
36
192
  }
37
193
  function createTimeoutSignal(timeoutMs) {
38
194
  if (typeof AbortSignal.timeout === "function") {
@@ -47,15 +203,18 @@ function isTimeoutError(error) {
47
203
  return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
48
204
  }
49
205
  async function auth() {
50
- const cfg = getConfig();
51
- const projectId = cfg.publishableKey.split("_")[2].toLowerCase();
206
+ const cfg = getAuthConfig();
207
+ const projectId = cfg.projectId;
52
208
  const secure = new URL(cfg.apiUrl).protocol === "https:";
53
209
  const cookieName = sessionCookieName(projectId, { secure });
54
210
  const cookieStore = await nextCookies();
55
- const cookieHeader = cookieStore.getAll().filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
211
+ const allCookies = cookieStore.getAll();
212
+ const cookieHeader = allCookies.filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
213
+ const bridgeNames = appSessionCookieNames(projectId);
214
+ const bridgeToken = cookieHeader ? null : allCookies.find((cookie) => cookie.name === bridgeNames.secure)?.value ?? allCookies.find((cookie) => cookie.name === bridgeNames.local)?.value ?? null;
56
215
  const hdrs = await nextHeaders();
57
216
  const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
58
- const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS);
217
+ const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS2);
59
218
  let res;
60
219
  try {
61
220
  res = await fetch(url, {
@@ -63,13 +222,17 @@ async function auth() {
63
222
  headers: {
64
223
  cookie: cookieHeader,
65
224
  "x-publishable-key": cfg.publishableKey,
66
- "user-agent": hdrs.get("user-agent") ?? "next-auth-helper"
225
+ "user-agent": hdrs.get("user-agent") ?? "next-auth-helper",
226
+ ...bridgeToken ? {
227
+ authorization: `Bearer ${bridgeToken}`,
228
+ [SESSION_TRANSPORT_HEADER2]: SESSION_TRANSPORT_BEARER2
229
+ } : {}
67
230
  },
68
231
  cache: "no-store",
69
232
  signal: timeout.signal
70
233
  });
71
234
  } catch (error) {
72
- const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS}ms.` : "Auth service request failed.";
235
+ const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS2}ms.` : "Auth service request failed.";
73
236
  throw new AuthServiceError(message, { cause: error });
74
237
  } finally {
75
238
  timeout.cleanup();
@@ -90,11 +253,21 @@ async function auth() {
90
253
  return null;
91
254
  }
92
255
  }
256
+ async function hasAuthOwlSessionCookie() {
257
+ const cfg = getAuthConfig();
258
+ const secure = new URL(cfg.apiUrl).protocol === "https:";
259
+ const native = sessionCookieName(cfg.projectId, { secure });
260
+ const bridge = appSessionCookieNames(cfg.projectId);
261
+ const names = /* @__PURE__ */ new Set([native, bridge.secure, bridge.local]);
262
+ return (await nextCookies()).getAll().some((cookie) => names.has(cookie.name));
263
+ }
93
264
  export {
94
265
  AuthServiceError,
95
266
  TokenVerificationError,
96
267
  auth,
268
+ createAuthOwlSessionBridge,
97
269
  has,
270
+ hasAuthOwlSessionCookie,
98
271
  hasPermission,
99
272
  initAuth,
100
273
  verifyToken
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authowl/next",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
4
4
  "description": "Next.js (App Router) server helpers for AuthOwl, the multi-tenant auth SaaS.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -24,6 +24,16 @@
24
24
  "type": "module",
25
25
  "sideEffects": false,
26
26
  "exports": {
27
+ "./client": {
28
+ "import": {
29
+ "types": "./dist/client.d.ts",
30
+ "default": "./dist/client.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/client.d.cts",
34
+ "default": "./dist/client.cjs"
35
+ }
36
+ },
27
37
  "./server": {
28
38
  "import": {
29
39
  "types": "./dist/server.d.ts",
@@ -51,7 +61,7 @@
51
61
  "LICENSE"
52
62
  ],
53
63
  "dependencies": {
54
- "@authowl/core": "0.15.2"
64
+ "@authowl/core": "0.15.3"
55
65
  },
56
66
  "peerDependencies": {
57
67
  "next": ">=14"
@@ -63,8 +73,8 @@
63
73
  "vitest": "^4.1.10"
64
74
  },
65
75
  "scripts": {
66
- "build": "tsup src/server.ts src/middleware.ts --format esm,cjs --dts --clean --external next && node ../../scripts/gen-notices.mjs src/server.ts src/middleware.ts",
67
- "dev": "tsup src/server.ts src/middleware.ts --format esm,cjs --dts --watch --external next",
76
+ "build": "tsup src/client.ts src/server.ts src/middleware.ts --format esm,cjs --dts --clean --external next && node ../../scripts/gen-notices.mjs src/client.ts src/server.ts src/middleware.ts",
77
+ "dev": "tsup src/client.ts src/server.ts src/middleware.ts --format esm,cjs --dts --watch --external next",
68
78
  "typecheck": "tsc --noEmit",
69
79
  "test": "vitest run --passWithNoTests"
70
80
  }