@authowl/next 0.2.2
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/LICENSE +21 -0
- package/README.md +40 -0
- package/THIRD_PARTY_NOTICES.md +8 -0
- package/dist/middleware.cjs +58 -0
- package/dist/middleware.d.cts +24 -0
- package/dist/middleware.d.ts +24 -0
- package/dist/middleware.js +32 -0
- package/dist/server.cjs +127 -0
- package/dist/server.d.cts +53 -0
- package/dist/server.d.ts +53 -0
- package/dist/server.js +101 -0
- package/package.json +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AuthOwl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# @authowl/next
|
|
2
|
+
|
|
3
|
+
Next.js (App Router) server helpers for [AuthOwl](https://authowl.dev), the
|
|
4
|
+
multi-tenant auth service. `auth()` works in Server Components and route handlers.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pnpm add @authowl/next
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Zero-config: set the env and call `auth()`.
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
# .env.local
|
|
14
|
+
AUTHOWL_PUBLISHABLE_KEY=pk_live_…
|
|
15
|
+
AUTHOWL_API_URL=https://auth.yourdomain.com
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { auth } from '@authowl/next/server';
|
|
20
|
+
|
|
21
|
+
export default async function Page() {
|
|
22
|
+
const session = await auth(); // null if not signed in
|
|
23
|
+
return <p>{session ? `Hi, ${session.user.email ?? session.user.phoneNumber}` : 'Signed out'}</p>;
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`initAuth({ publishableKey, apiUrl })` is optional (call it to override the env or
|
|
28
|
+
surface config errors at boot). For the client-side provider and components, use
|
|
29
|
+
[`@authowl/react`](https://www.npmjs.com/package/@authowl/react).
|
|
30
|
+
|
|
31
|
+
**Optional UX middleware** (`@authowl/next/middleware`,
|
|
32
|
+
`createAuthRedirectMiddleware`) redirects unauthenticated users by cookie
|
|
33
|
+
presence — it is a UX helper, **not** an authorization boundary. Always authorize
|
|
34
|
+
on the server with `auth()`, which re-validates against the auth service.
|
|
35
|
+
|
|
36
|
+
See the full integration guide in the AuthOwl app repo (`INTEGRATION.md`).
|
|
37
|
+
|
|
38
|
+
## License
|
|
39
|
+
|
|
40
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
`@authowl/next` bundles third-party components into its published `dist/`. Each
|
|
4
|
+
is redistributed under its own license, with the required copyright and
|
|
5
|
+
permission notices reproduced in full below, grouped by copyright holder. This
|
|
6
|
+
file is generated by `scripts/gen-notices.mjs`; do not edit by hand.
|
|
7
|
+
|
|
8
|
+
No third-party code is bundled into this package.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/middleware.ts
|
|
21
|
+
var middleware_exports = {};
|
|
22
|
+
__export(middleware_exports, {
|
|
23
|
+
createAuthMiddleware: () => createAuthMiddleware,
|
|
24
|
+
createAuthRedirectMiddleware: () => createAuthRedirectMiddleware
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(middleware_exports);
|
|
27
|
+
var import_server = require("next/server");
|
|
28
|
+
var import_server2 = require("@authowl/core/server");
|
|
29
|
+
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 }));
|
|
35
|
+
const loginPath = opts.loginPath ?? "/sign-in";
|
|
36
|
+
const normalizedLoginPath = loginPath.endsWith("/") && loginPath !== "/" ? loginPath.slice(0, -1) : loginPath;
|
|
37
|
+
const matchers = opts.protectedPaths ?? [/^\/.*/];
|
|
38
|
+
const usesDefaultMatchers = !opts.protectedPaths;
|
|
39
|
+
return function middleware(req) {
|
|
40
|
+
const pathname = req.nextUrl.pathname;
|
|
41
|
+
const isDefaultPublicPath = usesDefaultMatchers && (pathname === normalizedLoginPath || normalizedLoginPath !== "/" && pathname.startsWith(`${normalizedLoginPath}/`) || pathname.startsWith("/_next/") || pathname === "/favicon.ico");
|
|
42
|
+
if (isDefaultPublicPath) return import_server.NextResponse.next();
|
|
43
|
+
const isProtected = matchers.some((re) => re.test(pathname));
|
|
44
|
+
if (!isProtected) return import_server.NextResponse.next();
|
|
45
|
+
if (cookieNames.some((name) => req.cookies.has(name))) return import_server.NextResponse.next();
|
|
46
|
+
const url = req.nextUrl.clone();
|
|
47
|
+
url.pathname = loginPath;
|
|
48
|
+
return import_server.NextResponse.redirect(url);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function createAuthMiddleware(opts) {
|
|
52
|
+
return createAuthRedirectMiddleware(opts);
|
|
53
|
+
}
|
|
54
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
55
|
+
0 && (module.exports = {
|
|
56
|
+
createAuthMiddleware,
|
|
57
|
+
createAuthRedirectMiddleware
|
|
58
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Optional middleware factory for consumer Next.js apps that want to gate
|
|
5
|
+
* routes by likely session presence for UX redirects only. This is not an
|
|
6
|
+
* authorization boundary: a client can forge a cookie with the expected name,
|
|
7
|
+
* and this helper does not validate it with the auth server.
|
|
8
|
+
*
|
|
9
|
+
* Always enforce authorization with `auth()` in the page or route handler. The
|
|
10
|
+
* default matcher protects all paths except loginPath and common static/public
|
|
11
|
+
* paths; callers can override that by passing protectedPaths explicitly.
|
|
12
|
+
*/
|
|
13
|
+
declare function createAuthRedirectMiddleware(opts: {
|
|
14
|
+
publishableKey: string;
|
|
15
|
+
loginPath?: string;
|
|
16
|
+
protectedPaths?: RegExp[];
|
|
17
|
+
}): (req: NextRequest) => NextResponse<unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* @deprecated Use createAuthRedirectMiddleware. This compatibility export is a
|
|
20
|
+
* UX redirect helper only and must not be treated as an authorization boundary.
|
|
21
|
+
*/
|
|
22
|
+
declare function createAuthMiddleware(opts: Parameters<typeof createAuthRedirectMiddleware>[0]): (req: NextRequest) => NextResponse<unknown>;
|
|
23
|
+
|
|
24
|
+
export { createAuthMiddleware, createAuthRedirectMiddleware };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Optional middleware factory for consumer Next.js apps that want to gate
|
|
5
|
+
* routes by likely session presence for UX redirects only. This is not an
|
|
6
|
+
* authorization boundary: a client can forge a cookie with the expected name,
|
|
7
|
+
* and this helper does not validate it with the auth server.
|
|
8
|
+
*
|
|
9
|
+
* Always enforce authorization with `auth()` in the page or route handler. The
|
|
10
|
+
* default matcher protects all paths except loginPath and common static/public
|
|
11
|
+
* paths; callers can override that by passing protectedPaths explicitly.
|
|
12
|
+
*/
|
|
13
|
+
declare function createAuthRedirectMiddleware(opts: {
|
|
14
|
+
publishableKey: string;
|
|
15
|
+
loginPath?: string;
|
|
16
|
+
protectedPaths?: RegExp[];
|
|
17
|
+
}): (req: NextRequest) => NextResponse<unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* @deprecated Use createAuthRedirectMiddleware. This compatibility export is a
|
|
20
|
+
* UX redirect helper only and must not be treated as an authorization boundary.
|
|
21
|
+
*/
|
|
22
|
+
declare function createAuthMiddleware(opts: Parameters<typeof createAuthRedirectMiddleware>[0]): (req: NextRequest) => NextResponse<unknown>;
|
|
23
|
+
|
|
24
|
+
export { createAuthMiddleware, createAuthRedirectMiddleware };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/middleware.ts
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
import { sessionCookieName } from "@authowl/core/server";
|
|
4
|
+
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 loginPath = opts.loginPath ?? "/sign-in";
|
|
11
|
+
const normalizedLoginPath = loginPath.endsWith("/") && loginPath !== "/" ? loginPath.slice(0, -1) : loginPath;
|
|
12
|
+
const matchers = opts.protectedPaths ?? [/^\/.*/];
|
|
13
|
+
const usesDefaultMatchers = !opts.protectedPaths;
|
|
14
|
+
return function middleware(req) {
|
|
15
|
+
const pathname = req.nextUrl.pathname;
|
|
16
|
+
const isDefaultPublicPath = usesDefaultMatchers && (pathname === normalizedLoginPath || normalizedLoginPath !== "/" && pathname.startsWith(`${normalizedLoginPath}/`) || pathname.startsWith("/_next/") || pathname === "/favicon.ico");
|
|
17
|
+
if (isDefaultPublicPath) return NextResponse.next();
|
|
18
|
+
const isProtected = matchers.some((re) => re.test(pathname));
|
|
19
|
+
if (!isProtected) return NextResponse.next();
|
|
20
|
+
if (cookieNames.some((name) => req.cookies.has(name))) return NextResponse.next();
|
|
21
|
+
const url = req.nextUrl.clone();
|
|
22
|
+
url.pathname = loginPath;
|
|
23
|
+
return NextResponse.redirect(url);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function createAuthMiddleware(opts) {
|
|
27
|
+
return createAuthRedirectMiddleware(opts);
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
createAuthMiddleware,
|
|
31
|
+
createAuthRedirectMiddleware
|
|
32
|
+
};
|
package/dist/server.cjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/server.ts
|
|
21
|
+
var server_exports = {};
|
|
22
|
+
__export(server_exports, {
|
|
23
|
+
AuthServiceError: () => AuthServiceError,
|
|
24
|
+
TokenVerificationError: () => import_server2.TokenVerificationError,
|
|
25
|
+
auth: () => auth,
|
|
26
|
+
has: () => import_server2.has,
|
|
27
|
+
hasPermission: () => import_server2.hasPermission,
|
|
28
|
+
initAuth: () => initAuth,
|
|
29
|
+
verifyToken: () => import_server2.verifyToken
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(server_exports);
|
|
32
|
+
var import_headers = require("next/headers");
|
|
33
|
+
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
|
+
};
|
|
44
|
+
var cachedConfig = null;
|
|
45
|
+
function initAuth(config) {
|
|
46
|
+
(0, import_server.resolveConfig)(config);
|
|
47
|
+
cachedConfig = { publishableKey: config.publishableKey, apiUrl: config.apiUrl };
|
|
48
|
+
}
|
|
49
|
+
function getConfig() {
|
|
50
|
+
if (cachedConfig) return cachedConfig;
|
|
51
|
+
const publishableKey = process.env.AUTHOWL_PUBLISHABLE_KEY;
|
|
52
|
+
const apiUrl = process.env.AUTHOWL_API_URL;
|
|
53
|
+
if (publishableKey && apiUrl) {
|
|
54
|
+
(0, import_server.resolveConfig)({ publishableKey, apiUrl });
|
|
55
|
+
cachedConfig = { publishableKey, apiUrl };
|
|
56
|
+
return cachedConfig;
|
|
57
|
+
}
|
|
58
|
+
throw new Error(
|
|
59
|
+
"AuthOwl is not configured. Set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL, or call initAuth({ publishableKey, apiUrl })."
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
function createTimeoutSignal(timeoutMs) {
|
|
63
|
+
if (typeof AbortSignal.timeout === "function") {
|
|
64
|
+
return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
|
|
65
|
+
} };
|
|
66
|
+
}
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
69
|
+
return { signal: controller.signal, cleanup: () => clearTimeout(timeoutId) };
|
|
70
|
+
}
|
|
71
|
+
function isTimeoutError(error) {
|
|
72
|
+
return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
73
|
+
}
|
|
74
|
+
async function auth() {
|
|
75
|
+
const cfg = getConfig();
|
|
76
|
+
const projectId = cfg.publishableKey.split("_")[2];
|
|
77
|
+
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
78
|
+
const cookieName = (0, import_server.sessionCookieName)(projectId, { secure });
|
|
79
|
+
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("; ");
|
|
81
|
+
const hdrs = await (0, import_headers.headers)();
|
|
82
|
+
const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
|
|
83
|
+
const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS);
|
|
84
|
+
let res;
|
|
85
|
+
try {
|
|
86
|
+
res = await fetch(url, {
|
|
87
|
+
method: "GET",
|
|
88
|
+
headers: {
|
|
89
|
+
cookie: cookieHeader,
|
|
90
|
+
"x-publishable-key": cfg.publishableKey,
|
|
91
|
+
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper"
|
|
92
|
+
},
|
|
93
|
+
cache: "no-store",
|
|
94
|
+
signal: timeout.signal
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS}ms.` : "Auth service request failed.";
|
|
98
|
+
throw new AuthServiceError(message, { cause: error });
|
|
99
|
+
} finally {
|
|
100
|
+
timeout.cleanup();
|
|
101
|
+
}
|
|
102
|
+
if (res.status === 401) return null;
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
throw new AuthServiceError(`Auth service returned ${res.status} ${res.statusText}`.trim(), {
|
|
105
|
+
status: res.status
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const data = await res.json();
|
|
110
|
+
if (!data || !data.user) return null;
|
|
111
|
+
const session = data.session;
|
|
112
|
+
if (session?.pendingMfaEnrollment === true) return null;
|
|
113
|
+
return data;
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
119
|
+
0 && (module.exports = {
|
|
120
|
+
AuthServiceError,
|
|
121
|
+
TokenVerificationError,
|
|
122
|
+
auth,
|
|
123
|
+
has,
|
|
124
|
+
hasPermission,
|
|
125
|
+
initAuth,
|
|
126
|
+
verifyToken
|
|
127
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { AuthConfig } from '@authowl/core/server';
|
|
2
|
+
export { HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, verifyToken } from '@authowl/core/server';
|
|
3
|
+
|
|
4
|
+
type Session = {
|
|
5
|
+
user: {
|
|
6
|
+
id: string;
|
|
7
|
+
email: string | null;
|
|
8
|
+
phoneNumber?: string | null;
|
|
9
|
+
name?: string | null;
|
|
10
|
+
image?: string | null;
|
|
11
|
+
};
|
|
12
|
+
session: {
|
|
13
|
+
id: string;
|
|
14
|
+
expiresAt: string;
|
|
15
|
+
activeOrganizationId?: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* The active-org membership (role + advisory permission claim), mirrored
|
|
18
|
+
* from `/get-session`. UX affordance only - for real authorization verify a
|
|
19
|
+
* project token and use the server `has()` over the VERIFIED claim.
|
|
20
|
+
*/
|
|
21
|
+
membership?: {
|
|
22
|
+
role: string;
|
|
23
|
+
permissions: string[];
|
|
24
|
+
} | null;
|
|
25
|
+
};
|
|
26
|
+
} | null;
|
|
27
|
+
declare class AuthServiceError extends Error {
|
|
28
|
+
readonly status?: number;
|
|
29
|
+
constructor(message: string, options?: {
|
|
30
|
+
status?: number;
|
|
31
|
+
cause?: unknown;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Initialize the SDK explicitly. Optional: if unset, the SDK reads
|
|
36
|
+
* `AUTHOWL_PUBLISHABLE_KEY` / `AUTHOWL_API_URL` from the environment on first use
|
|
37
|
+
* (zero-config). Call this only to override the env, or to surface config errors
|
|
38
|
+
* eagerly at boot rather than on the first request. The publishableKey is sent on
|
|
39
|
+
* every server-side call too (a server fetch has no Origin, but the publishable
|
|
40
|
+
* key + bearer cookie still identify the project on the auth server).
|
|
41
|
+
*/
|
|
42
|
+
declare function initAuth(config: AuthConfig): void;
|
|
43
|
+
/**
|
|
44
|
+
* Get the current session by forwarding only the expected auth session
|
|
45
|
+
* cookie to the auth server. Returns null if not signed in.
|
|
46
|
+
*
|
|
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.
|
|
50
|
+
*/
|
|
51
|
+
declare function auth(): Promise<Session>;
|
|
52
|
+
|
|
53
|
+
export { AuthServiceError, type Session, auth, initAuth };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { AuthConfig } from '@authowl/core/server';
|
|
2
|
+
export { HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, verifyToken } from '@authowl/core/server';
|
|
3
|
+
|
|
4
|
+
type Session = {
|
|
5
|
+
user: {
|
|
6
|
+
id: string;
|
|
7
|
+
email: string | null;
|
|
8
|
+
phoneNumber?: string | null;
|
|
9
|
+
name?: string | null;
|
|
10
|
+
image?: string | null;
|
|
11
|
+
};
|
|
12
|
+
session: {
|
|
13
|
+
id: string;
|
|
14
|
+
expiresAt: string;
|
|
15
|
+
activeOrganizationId?: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* The active-org membership (role + advisory permission claim), mirrored
|
|
18
|
+
* from `/get-session`. UX affordance only - for real authorization verify a
|
|
19
|
+
* project token and use the server `has()` over the VERIFIED claim.
|
|
20
|
+
*/
|
|
21
|
+
membership?: {
|
|
22
|
+
role: string;
|
|
23
|
+
permissions: string[];
|
|
24
|
+
} | null;
|
|
25
|
+
};
|
|
26
|
+
} | null;
|
|
27
|
+
declare class AuthServiceError extends Error {
|
|
28
|
+
readonly status?: number;
|
|
29
|
+
constructor(message: string, options?: {
|
|
30
|
+
status?: number;
|
|
31
|
+
cause?: unknown;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Initialize the SDK explicitly. Optional: if unset, the SDK reads
|
|
36
|
+
* `AUTHOWL_PUBLISHABLE_KEY` / `AUTHOWL_API_URL` from the environment on first use
|
|
37
|
+
* (zero-config). Call this only to override the env, or to surface config errors
|
|
38
|
+
* eagerly at boot rather than on the first request. The publishableKey is sent on
|
|
39
|
+
* every server-side call too (a server fetch has no Origin, but the publishable
|
|
40
|
+
* key + bearer cookie still identify the project on the auth server).
|
|
41
|
+
*/
|
|
42
|
+
declare function initAuth(config: AuthConfig): void;
|
|
43
|
+
/**
|
|
44
|
+
* Get the current session by forwarding only the expected auth session
|
|
45
|
+
* cookie to the auth server. Returns null if not signed in.
|
|
46
|
+
*
|
|
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.
|
|
50
|
+
*/
|
|
51
|
+
declare function auth(): Promise<Session>;
|
|
52
|
+
|
|
53
|
+
export { AuthServiceError, type Session, auth, initAuth };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import { headers as nextHeaders, cookies as nextCookies } from "next/headers";
|
|
3
|
+
import { resolveConfig, sessionCookieName } from "@authowl/core/server";
|
|
4
|
+
import {
|
|
5
|
+
has,
|
|
6
|
+
hasPermission,
|
|
7
|
+
verifyToken,
|
|
8
|
+
TokenVerificationError
|
|
9
|
+
} from "@authowl/core/server";
|
|
10
|
+
var AUTH_FETCH_TIMEOUT_MS = 1e4;
|
|
11
|
+
var AuthServiceError = class extends Error {
|
|
12
|
+
status;
|
|
13
|
+
constructor(message, options = {}) {
|
|
14
|
+
super(message, { cause: options.cause });
|
|
15
|
+
this.name = "AuthServiceError";
|
|
16
|
+
this.status = options.status;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var cachedConfig = null;
|
|
20
|
+
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
|
+
);
|
|
36
|
+
}
|
|
37
|
+
function createTimeoutSignal(timeoutMs) {
|
|
38
|
+
if (typeof AbortSignal.timeout === "function") {
|
|
39
|
+
return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
|
|
40
|
+
} };
|
|
41
|
+
}
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
44
|
+
return { signal: controller.signal, cleanup: () => clearTimeout(timeoutId) };
|
|
45
|
+
}
|
|
46
|
+
function isTimeoutError(error) {
|
|
47
|
+
return error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
48
|
+
}
|
|
49
|
+
async function auth() {
|
|
50
|
+
const cfg = getConfig();
|
|
51
|
+
const projectId = cfg.publishableKey.split("_")[2];
|
|
52
|
+
const secure = new URL(cfg.apiUrl).protocol === "https:";
|
|
53
|
+
const cookieName = sessionCookieName(projectId, { secure });
|
|
54
|
+
const cookieStore = await nextCookies();
|
|
55
|
+
const cookieHeader = cookieStore.getAll().filter((c) => c.name === cookieName).map((c) => `${c.name}=${encodeURIComponent(c.value)}`).join("; ");
|
|
56
|
+
const hdrs = await nextHeaders();
|
|
57
|
+
const url = `${new URL(cfg.apiUrl).origin}/api/projects/${projectId}/auth/get-session`;
|
|
58
|
+
const timeout = createTimeoutSignal(AUTH_FETCH_TIMEOUT_MS);
|
|
59
|
+
let res;
|
|
60
|
+
try {
|
|
61
|
+
res = await fetch(url, {
|
|
62
|
+
method: "GET",
|
|
63
|
+
headers: {
|
|
64
|
+
cookie: cookieHeader,
|
|
65
|
+
"x-publishable-key": cfg.publishableKey,
|
|
66
|
+
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper"
|
|
67
|
+
},
|
|
68
|
+
cache: "no-store",
|
|
69
|
+
signal: timeout.signal
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
const message = isTimeoutError(error) ? `Auth service request timed out after ${AUTH_FETCH_TIMEOUT_MS}ms.` : "Auth service request failed.";
|
|
73
|
+
throw new AuthServiceError(message, { cause: error });
|
|
74
|
+
} finally {
|
|
75
|
+
timeout.cleanup();
|
|
76
|
+
}
|
|
77
|
+
if (res.status === 401) return null;
|
|
78
|
+
if (!res.ok) {
|
|
79
|
+
throw new AuthServiceError(`Auth service returned ${res.status} ${res.statusText}`.trim(), {
|
|
80
|
+
status: res.status
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const data = await res.json();
|
|
85
|
+
if (!data || !data.user) return null;
|
|
86
|
+
const session = data.session;
|
|
87
|
+
if (session?.pendingMfaEnrollment === true) return null;
|
|
88
|
+
return data;
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
AuthServiceError,
|
|
95
|
+
TokenVerificationError,
|
|
96
|
+
auth,
|
|
97
|
+
has,
|
|
98
|
+
hasPermission,
|
|
99
|
+
initAuth,
|
|
100
|
+
verifyToken
|
|
101
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@authowl/next",
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "Next.js (App Router) server helpers for AuthOwl, the multi-tenant auth SaaS.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/mstfash/authowl-sdk.git",
|
|
12
|
+
"directory": "packages/auth-next"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/mstfash/authowl-sdk#readme",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"authentication",
|
|
17
|
+
"auth",
|
|
18
|
+
"authowl",
|
|
19
|
+
"nextjs",
|
|
20
|
+
"next",
|
|
21
|
+
"app-router",
|
|
22
|
+
"sso"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"exports": {
|
|
27
|
+
"./server": {
|
|
28
|
+
"import": {
|
|
29
|
+
"types": "./dist/server.d.ts",
|
|
30
|
+
"default": "./dist/server.js"
|
|
31
|
+
},
|
|
32
|
+
"require": {
|
|
33
|
+
"types": "./dist/server.d.cts",
|
|
34
|
+
"default": "./dist/server.cjs"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"./middleware": {
|
|
38
|
+
"import": {
|
|
39
|
+
"types": "./dist/middleware.d.ts",
|
|
40
|
+
"default": "./dist/middleware.js"
|
|
41
|
+
},
|
|
42
|
+
"require": {
|
|
43
|
+
"types": "./dist/middleware.d.cts",
|
|
44
|
+
"default": "./dist/middleware.cjs"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"files": [
|
|
49
|
+
"dist",
|
|
50
|
+
"THIRD_PARTY_NOTICES.md",
|
|
51
|
+
"LICENSE"
|
|
52
|
+
],
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@authowl/core": "0.10.0"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"next": ">=14"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"next": "^15.1.3",
|
|
61
|
+
"tsup": "^8.3.5",
|
|
62
|
+
"typescript": "^5.7.2"
|
|
63
|
+
},
|
|
64
|
+
"scripts": {
|
|
65
|
+
"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",
|
|
66
|
+
"dev": "tsup src/server.ts src/middleware.ts --format esm,cjs --dts --watch --external next",
|
|
67
|
+
"typecheck": "tsc --noEmit"
|
|
68
|
+
}
|
|
69
|
+
}
|