@authowl/next 0.2.10 → 0.2.11
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 +49 -3
- package/dist/chunk-MZJVERMC.js +14 -0
- package/dist/client.cjs +125 -0
- package/dist/client.d.cts +17 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.js +102 -0
- package/dist/middleware.cjs +19 -5
- package/dist/middleware.js +12 -5
- package/dist/server.cjs +175 -27
- package/dist/server.d.cts +17 -4
- package/dist/server.d.ts +17 -4
- package/dist/server.js +172 -24
- package/package.json +14 -4
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)
|
|
7
|
-
|
|
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).
|
|
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
|
+
};
|
package/dist/client.cjs
ADDED
|
@@ -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 };
|
package/dist/client.d.ts
ADDED
|
@@ -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
|
+
};
|
package/dist/middleware.cjs
CHANGED
|
@@ -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
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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 ?? [/^\/.*/];
|
package/dist/middleware.js
CHANGED
|
@@ -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
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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,175 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var server_exports = {};
|
|
22
22
|
__export(server_exports, {
|
|
23
23
|
AuthServiceError: () => AuthServiceError,
|
|
24
|
-
TokenVerificationError: () =>
|
|
24
|
+
TokenVerificationError: () => import_server4.TokenVerificationError,
|
|
25
25
|
auth: () => auth,
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
createAuthOwlSessionBridge: () => createAuthOwlSessionBridge,
|
|
27
|
+
has: () => import_server4.has,
|
|
28
|
+
hasAuthOwlSessionCookie: () => hasAuthOwlSessionCookie,
|
|
29
|
+
hasPermission: () => import_server4.hasPermission,
|
|
28
30
|
initAuth: () => initAuth,
|
|
29
|
-
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
|
46
|
-
|
|
47
|
-
cachedConfig = { publishableKey: config.publishableKey, apiUrl: config.apiUrl };
|
|
58
|
+
function initAuthConfig(config) {
|
|
59
|
+
cachedConfig = serverConfig(config);
|
|
48
60
|
}
|
|
49
|
-
function
|
|
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
|
-
|
|
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 requestIsSameOriginBrowserPost(request) {
|
|
86
|
+
const origin = request.headers.get("origin");
|
|
87
|
+
const site = request.headers.get("sec-fetch-site");
|
|
88
|
+
return request.method === "POST" && origin === new URL(request.url).origin && (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";
|
|
89
|
+
}
|
|
90
|
+
function validToken(value) {
|
|
91
|
+
return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
|
|
92
|
+
}
|
|
93
|
+
function serializeCookie(name, value, options) {
|
|
94
|
+
const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
95
|
+
if (options.secure) attributes.push("Secure");
|
|
96
|
+
if (options.clear) attributes.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
|
|
97
|
+
else if (options.expires) attributes.push(`Expires=${options.expires.toUTCString()}`);
|
|
98
|
+
return attributes.join("; ");
|
|
99
|
+
}
|
|
100
|
+
function clearCookies(projectId) {
|
|
101
|
+
const names = appSessionCookieNames(projectId);
|
|
102
|
+
const result = response(204);
|
|
103
|
+
result.headers.append("set-cookie", serializeCookie(names.secure, "", { secure: true, clear: true }));
|
|
104
|
+
result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
function createAuthOwlSessionBridge(input) {
|
|
108
|
+
const configured = input ? resolveAuthConfig(input) : null;
|
|
109
|
+
const remoteFetch = input?.fetch ?? globalThis.fetch;
|
|
110
|
+
return async function authOwlSessionBridge(request) {
|
|
111
|
+
const config = configured ?? getAuthConfig();
|
|
112
|
+
const projectId = config.projectId;
|
|
113
|
+
if (!requestIsSameOriginBrowserPost(request)) {
|
|
114
|
+
return response(403, { error: "forbidden" });
|
|
115
|
+
}
|
|
116
|
+
const raw = await request.text();
|
|
117
|
+
if (raw.length > MAX_BODY_BYTES) return response(413, { error: "payload_too_large" });
|
|
118
|
+
let body;
|
|
119
|
+
try {
|
|
120
|
+
body = JSON.parse(raw);
|
|
121
|
+
} catch {
|
|
122
|
+
return response(400, { error: "invalid_request" });
|
|
123
|
+
}
|
|
124
|
+
if (body.token === null) return clearCookies(projectId);
|
|
125
|
+
if (!validToken(body.token) || body.remember !== void 0 && typeof body.remember !== "boolean") {
|
|
126
|
+
return response(400, { error: "invalid_request" });
|
|
127
|
+
}
|
|
128
|
+
let sessionResponse;
|
|
129
|
+
try {
|
|
130
|
+
sessionResponse = await remoteFetch(
|
|
131
|
+
`${config.apiUrl}/api/projects/${projectId}/auth/get-session`,
|
|
132
|
+
{
|
|
133
|
+
method: "GET",
|
|
134
|
+
headers: {
|
|
135
|
+
authorization: `Bearer ${body.token}`,
|
|
136
|
+
[import_server2.SESSION_TRANSPORT_HEADER]: import_server2.SESSION_TRANSPORT_BEARER,
|
|
137
|
+
"x-publishable-key": config.publishableKey
|
|
138
|
+
},
|
|
139
|
+
cache: "no-store",
|
|
140
|
+
redirect: "error",
|
|
141
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
|
|
142
|
+
}
|
|
143
|
+
);
|
|
144
|
+
} catch {
|
|
145
|
+
return response(503, { error: "auth_service_unavailable" });
|
|
146
|
+
}
|
|
147
|
+
if (sessionResponse.status === 401) return response(401, { error: "invalid_session" });
|
|
148
|
+
if (!sessionResponse.ok) return response(502, { error: "auth_service_error" });
|
|
149
|
+
let session;
|
|
150
|
+
try {
|
|
151
|
+
session = await sessionResponse.json();
|
|
152
|
+
} catch {
|
|
153
|
+
return response(502, { error: "invalid_auth_response" });
|
|
154
|
+
}
|
|
155
|
+
if (!session.user || !session.session || session.session.pendingMfaEnrollment === true) {
|
|
156
|
+
return response(401, { error: "invalid_session" });
|
|
157
|
+
}
|
|
158
|
+
if (typeof session.session.expiresAt !== "string") {
|
|
159
|
+
return response(401, { error: "invalid_session" });
|
|
160
|
+
}
|
|
161
|
+
const expires = new Date(session.session.expiresAt);
|
|
162
|
+
if (!Number.isFinite(expires.getTime()) || expires.getTime() <= Date.now()) {
|
|
163
|
+
return response(401, { error: "invalid_session" });
|
|
164
|
+
}
|
|
165
|
+
const secure = new URL(request.url).protocol === "https:";
|
|
166
|
+
const names = appSessionCookieNames(projectId);
|
|
167
|
+
const result = response(204);
|
|
168
|
+
result.headers.append(
|
|
169
|
+
"set-cookie",
|
|
170
|
+
serializeCookie(secure ? names.secure : names.local, body.token, {
|
|
171
|
+
secure,
|
|
172
|
+
expires: body.remember === false ? void 0 : expires
|
|
173
|
+
})
|
|
174
|
+
);
|
|
175
|
+
return result;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/server.ts
|
|
180
|
+
var import_server4 = require("@authowl/core/server");
|
|
181
|
+
var AUTH_FETCH_TIMEOUT_MS2 = 1e4;
|
|
182
|
+
var AuthServiceError = class extends Error {
|
|
183
|
+
status;
|
|
184
|
+
constructor(message, options = {}) {
|
|
185
|
+
super(message, { cause: options.cause });
|
|
186
|
+
this.name = "AuthServiceError";
|
|
187
|
+
this.status = options.status;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
function initAuth(config) {
|
|
191
|
+
initAuthConfig(config);
|
|
192
|
+
}
|
|
62
193
|
function createTimeoutSignal(timeoutMs) {
|
|
63
194
|
if (typeof AbortSignal.timeout === "function") {
|
|
64
195
|
return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
|
|
@@ -72,15 +203,18 @@ function isTimeoutError(error) {
|
|
|
72
203
|
return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
73
204
|
}
|
|
74
205
|
async function auth() {
|
|
75
|
-
const cfg =
|
|
76
|
-
const projectId = cfg.
|
|
206
|
+
const cfg = getAuthConfig();
|
|
207
|
+
const projectId = cfg.projectId;
|
|
77
208
|
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
78
|
-
const cookieName = (0,
|
|
209
|
+
const cookieName = (0, import_server3.sessionCookieName)(projectId, { secure });
|
|
79
210
|
const cookieStore = await (0, import_headers.cookies)();
|
|
80
|
-
const
|
|
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;
|
|
81
215
|
const hdrs = await (0, import_headers.headers)();
|
|
82
216
|
const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
|
|
83
|
-
const timeout = createTimeoutSignal(
|
|
217
|
+
const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS2);
|
|
84
218
|
let res;
|
|
85
219
|
try {
|
|
86
220
|
res = await fetch(url, {
|
|
@@ -88,13 +222,17 @@ async function auth() {
|
|
|
88
222
|
headers: {
|
|
89
223
|
cookie: cookieHeader,
|
|
90
224
|
"x-publishable-key": cfg.publishableKey,
|
|
91
|
-
"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
|
+
[import_server3.SESSION_TRANSPORT_HEADER]: import_server3.SESSION_TRANSPORT_BEARER
|
|
229
|
+
} : {}
|
|
92
230
|
},
|
|
93
231
|
cache: "no-store",
|
|
94
232
|
signal: timeout.signal
|
|
95
233
|
});
|
|
96
234
|
} catch (error) {
|
|
97
|
-
const message = isTimeoutError(error) ? `Auth service request timed out after ${
|
|
235
|
+
const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS2}ms.` : "Auth service request failed.";
|
|
98
236
|
throw new AuthServiceError(message, { cause: error });
|
|
99
237
|
} finally {
|
|
100
238
|
timeout.cleanup();
|
|
@@ -115,12 +253,22 @@ async function auth() {
|
|
|
115
253
|
return null;
|
|
116
254
|
}
|
|
117
255
|
}
|
|
256
|
+
async function hasAuthOwlSessionCookie() {
|
|
257
|
+
const cfg = getAuthConfig();
|
|
258
|
+
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
259
|
+
const native = (0, import_server3.sessionCookieName)(cfg.projectId, { secure });
|
|
260
|
+
const bridge = appSessionCookieNames(cfg.projectId);
|
|
261
|
+
const names = /* @__PURE__ */ new Set([native, bridge.secure, bridge.local]);
|
|
262
|
+
return (await (0, import_headers.cookies)()).getAll().some((cookie) => names.has(cookie.name));
|
|
263
|
+
}
|
|
118
264
|
// Annotate the CommonJS export names for ESM import in node:
|
|
119
265
|
0 && (module.exports = {
|
|
120
266
|
AuthServiceError,
|
|
121
267
|
TokenVerificationError,
|
|
122
268
|
auth,
|
|
269
|
+
createAuthOwlSessionBridge,
|
|
123
270
|
has,
|
|
271
|
+
hasAuthOwlSessionCookie,
|
|
124
272
|
hasPermission,
|
|
125
273
|
initAuth,
|
|
126
274
|
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
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
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
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
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,159 @@
|
|
|
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 {
|
|
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 requestIsSameOriginBrowserPost(request) {
|
|
56
|
+
const origin = request.headers.get("origin");
|
|
57
|
+
const site = request.headers.get("sec-fetch-site");
|
|
58
|
+
return request.method === "POST" && origin === new URL(request.url).origin && (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";
|
|
59
|
+
}
|
|
60
|
+
function validToken(value) {
|
|
61
|
+
return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
|
|
62
|
+
}
|
|
63
|
+
function serializeCookie(name, value, options) {
|
|
64
|
+
const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
65
|
+
if (options.secure) attributes.push("Secure");
|
|
66
|
+
if (options.clear) attributes.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
|
|
67
|
+
else if (options.expires) attributes.push(`Expires=${options.expires.toUTCString()}`);
|
|
68
|
+
return attributes.join("; ");
|
|
69
|
+
}
|
|
70
|
+
function clearCookies(projectId) {
|
|
71
|
+
const names = appSessionCookieNames(projectId);
|
|
72
|
+
const result = response(204);
|
|
73
|
+
result.headers.append("set-cookie", serializeCookie(names.secure, "", { secure: true, clear: true }));
|
|
74
|
+
result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
function createAuthOwlSessionBridge(input) {
|
|
78
|
+
const configured = input ? resolveAuthConfig(input) : null;
|
|
79
|
+
const remoteFetch = input?.fetch ?? globalThis.fetch;
|
|
80
|
+
return async function authOwlSessionBridge(request) {
|
|
81
|
+
const config = configured ?? getAuthConfig();
|
|
82
|
+
const projectId = config.projectId;
|
|
83
|
+
if (!requestIsSameOriginBrowserPost(request)) {
|
|
84
|
+
return response(403, { error: "forbidden" });
|
|
85
|
+
}
|
|
86
|
+
const raw = await request.text();
|
|
87
|
+
if (raw.length > MAX_BODY_BYTES) return response(413, { error: "payload_too_large" });
|
|
88
|
+
let body;
|
|
89
|
+
try {
|
|
90
|
+
body = JSON.parse(raw);
|
|
91
|
+
} catch {
|
|
92
|
+
return response(400, { error: "invalid_request" });
|
|
93
|
+
}
|
|
94
|
+
if (body.token === null) return clearCookies(projectId);
|
|
95
|
+
if (!validToken(body.token) || body.remember !== void 0 && typeof body.remember !== "boolean") {
|
|
96
|
+
return response(400, { error: "invalid_request" });
|
|
97
|
+
}
|
|
98
|
+
let sessionResponse;
|
|
99
|
+
try {
|
|
100
|
+
sessionResponse = await remoteFetch(
|
|
101
|
+
`${config.apiUrl}/api/projects/${projectId}/auth/get-session`,
|
|
102
|
+
{
|
|
103
|
+
method: "GET",
|
|
104
|
+
headers: {
|
|
105
|
+
authorization: `Bearer ${body.token}`,
|
|
106
|
+
[SESSION_TRANSPORT_HEADER]: SESSION_TRANSPORT_BEARER,
|
|
107
|
+
"x-publishable-key": config.publishableKey
|
|
108
|
+
},
|
|
109
|
+
cache: "no-store",
|
|
110
|
+
redirect: "error",
|
|
111
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
|
|
112
|
+
}
|
|
113
|
+
);
|
|
114
|
+
} catch {
|
|
115
|
+
return response(503, { error: "auth_service_unavailable" });
|
|
116
|
+
}
|
|
117
|
+
if (sessionResponse.status === 401) return response(401, { error: "invalid_session" });
|
|
118
|
+
if (!sessionResponse.ok) return response(502, { error: "auth_service_error" });
|
|
119
|
+
let session;
|
|
120
|
+
try {
|
|
121
|
+
session = await sessionResponse.json();
|
|
122
|
+
} catch {
|
|
123
|
+
return response(502, { error: "invalid_auth_response" });
|
|
124
|
+
}
|
|
125
|
+
if (!session.user || !session.session || session.session.pendingMfaEnrollment === true) {
|
|
126
|
+
return response(401, { error: "invalid_session" });
|
|
127
|
+
}
|
|
128
|
+
if (typeof session.session.expiresAt !== "string") {
|
|
129
|
+
return response(401, { error: "invalid_session" });
|
|
130
|
+
}
|
|
131
|
+
const expires = new Date(session.session.expiresAt);
|
|
132
|
+
if (!Number.isFinite(expires.getTime()) || expires.getTime() <= Date.now()) {
|
|
133
|
+
return response(401, { error: "invalid_session" });
|
|
134
|
+
}
|
|
135
|
+
const secure = new URL(request.url).protocol === "https:";
|
|
136
|
+
const names = appSessionCookieNames(projectId);
|
|
137
|
+
const result = response(204);
|
|
138
|
+
result.headers.append(
|
|
139
|
+
"set-cookie",
|
|
140
|
+
serializeCookie(secure ? names.secure : names.local, body.token, {
|
|
141
|
+
secure,
|
|
142
|
+
expires: body.remember === false ? void 0 : expires
|
|
143
|
+
})
|
|
144
|
+
);
|
|
145
|
+
return result;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/server.ts
|
|
4
150
|
import {
|
|
5
151
|
has,
|
|
6
152
|
hasPermission,
|
|
7
153
|
verifyToken,
|
|
8
154
|
TokenVerificationError
|
|
9
155
|
} from "@authowl/core/server";
|
|
10
|
-
var
|
|
156
|
+
var AUTH_FETCH_TIMEOUT_MS2 = 1e4;
|
|
11
157
|
var AuthServiceError = class extends Error {
|
|
12
158
|
status;
|
|
13
159
|
constructor(message, options = {}) {
|
|
@@ -16,23 +162,8 @@ var AuthServiceError = class extends Error {
|
|
|
16
162
|
this.status = options.status;
|
|
17
163
|
}
|
|
18
164
|
};
|
|
19
|
-
var cachedConfig = null;
|
|
20
165
|
function initAuth(config) {
|
|
21
|
-
|
|
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
|
-
);
|
|
166
|
+
initAuthConfig(config);
|
|
36
167
|
}
|
|
37
168
|
function createTimeoutSignal(timeoutMs) {
|
|
38
169
|
if (typeof AbortSignal.timeout === "function") {
|
|
@@ -47,15 +178,18 @@ function isTimeoutError(error) {
|
|
|
47
178
|
return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
48
179
|
}
|
|
49
180
|
async function auth() {
|
|
50
|
-
const cfg =
|
|
51
|
-
const projectId = cfg.
|
|
181
|
+
const cfg = getAuthConfig();
|
|
182
|
+
const projectId = cfg.projectId;
|
|
52
183
|
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
53
184
|
const cookieName = sessionCookieName(projectId, { secure });
|
|
54
185
|
const cookieStore = await nextCookies();
|
|
55
|
-
const
|
|
186
|
+
const allCookies = cookieStore.getAll();
|
|
187
|
+
const cookieHeader = allCookies.filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
|
|
188
|
+
const bridgeNames = appSessionCookieNames(projectId);
|
|
189
|
+
const bridgeToken = cookieHeader ? null : allCookies.find((cookie) => cookie.name === bridgeNames.secure)?.value ?? allCookies.find((cookie) => cookie.name === bridgeNames.local)?.value ?? null;
|
|
56
190
|
const hdrs = await nextHeaders();
|
|
57
191
|
const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
|
|
58
|
-
const timeout = createTimeoutSignal(
|
|
192
|
+
const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS2);
|
|
59
193
|
let res;
|
|
60
194
|
try {
|
|
61
195
|
res = await fetch(url, {
|
|
@@ -63,13 +197,17 @@ async function auth() {
|
|
|
63
197
|
headers: {
|
|
64
198
|
cookie: cookieHeader,
|
|
65
199
|
"x-publishable-key": cfg.publishableKey,
|
|
66
|
-
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper"
|
|
200
|
+
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper",
|
|
201
|
+
...bridgeToken ? {
|
|
202
|
+
authorization: `Bearer ${bridgeToken}`,
|
|
203
|
+
[SESSION_TRANSPORT_HEADER2]: SESSION_TRANSPORT_BEARER2
|
|
204
|
+
} : {}
|
|
67
205
|
},
|
|
68
206
|
cache: "no-store",
|
|
69
207
|
signal: timeout.signal
|
|
70
208
|
});
|
|
71
209
|
} catch (error) {
|
|
72
|
-
const message = isTimeoutError(error) ? `Auth service request timed out after ${
|
|
210
|
+
const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS2}ms.` : "Auth service request failed.";
|
|
73
211
|
throw new AuthServiceError(message, { cause: error });
|
|
74
212
|
} finally {
|
|
75
213
|
timeout.cleanup();
|
|
@@ -90,11 +228,21 @@ async function auth() {
|
|
|
90
228
|
return null;
|
|
91
229
|
}
|
|
92
230
|
}
|
|
231
|
+
async function hasAuthOwlSessionCookie() {
|
|
232
|
+
const cfg = getAuthConfig();
|
|
233
|
+
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
234
|
+
const native = sessionCookieName(cfg.projectId, { secure });
|
|
235
|
+
const bridge = appSessionCookieNames(cfg.projectId);
|
|
236
|
+
const names = /* @__PURE__ */ new Set([native, bridge.secure, bridge.local]);
|
|
237
|
+
return (await nextCookies()).getAll().some((cookie) => names.has(cookie.name));
|
|
238
|
+
}
|
|
93
239
|
export {
|
|
94
240
|
AuthServiceError,
|
|
95
241
|
TokenVerificationError,
|
|
96
242
|
auth,
|
|
243
|
+
createAuthOwlSessionBridge,
|
|
97
244
|
has,
|
|
245
|
+
hasAuthOwlSessionCookie,
|
|
98
246
|
hasPermission,
|
|
99
247
|
initAuth,
|
|
100
248
|
verifyToken
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authowl/next",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
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.
|
|
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
|
}
|