@authowl/next 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/{chunk-MZJVERMC.js → chunk-6Q45QLET.js} +4 -0
- package/dist/client.cjs +141 -52
- package/dist/client.d.cts +7 -2
- package/dist/client.d.ts +7 -2
- package/dist/client.js +143 -55
- package/dist/middleware.js +1 -1
- package/dist/server.cjs +136 -35
- package/dist/server.d.cts +10 -4
- package/dist/server.d.ts +10 -4
- package/dist/server.js +137 -36
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -16,6 +16,8 @@ Zero-config: set the env and call `auth()`.
|
|
|
16
16
|
# .env.local
|
|
17
17
|
AUTHOWL_PUBLISHABLE_KEY=pk_live_…
|
|
18
18
|
AUTHOWL_API_URL=https://auth.yourdomain.com
|
|
19
|
+
# Required only for the cross-origin bridge below. Keep it server-only.
|
|
20
|
+
AUTHOWL_SECRET_KEY=sk_live_…
|
|
19
21
|
```
|
|
20
22
|
|
|
21
23
|
```ts
|
|
@@ -35,7 +37,9 @@ surface config errors at boot).
|
|
|
35
37
|
When AuthOwl and your Next.js application use different parent domains, add the
|
|
36
38
|
session bridge. It preserves AuthOwl's browser bearer fallback for browsers that
|
|
37
39
|
block cross-site cookies while giving `auth()` a validated, host-only HttpOnly
|
|
38
|
-
session on your application origin.
|
|
40
|
+
session on your application origin. `AUTHOWL_SECRET_KEY` is required and must
|
|
41
|
+
belong to the same project and environment with the `sessions:read` scope. It is
|
|
42
|
+
used only by the server route and must never use a `NEXT_PUBLIC_` prefix.
|
|
39
43
|
|
|
40
44
|
```ts
|
|
41
45
|
// app/api/authowl/session/route.ts
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// src/bridge-contract.ts
|
|
2
2
|
var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
|
|
3
|
+
var AUTHOWL_SECRET_KEY_HEADER = "x-authowl-secret-key";
|
|
4
|
+
var APP_SESSION_BRIDGE_CODE_MAX_LENGTH = 4096;
|
|
3
5
|
function appSessionCookieNames(projectId) {
|
|
4
6
|
const suffix = projectId.toLowerCase().replace(/-/g, "");
|
|
5
7
|
return {
|
|
@@ -10,5 +12,7 @@ function appSessionCookieNames(projectId) {
|
|
|
10
12
|
|
|
11
13
|
export {
|
|
12
14
|
APP_SESSION_BRIDGE_HEADER,
|
|
15
|
+
AUTHOWL_SECRET_KEY_HEADER,
|
|
16
|
+
APP_SESSION_BRIDGE_CODE_MAX_LENGTH,
|
|
13
17
|
appSessionCookieNames
|
|
14
18
|
};
|
package/dist/client.cjs
CHANGED
|
@@ -29,6 +29,7 @@ var import_core = require("@authowl/core");
|
|
|
29
29
|
|
|
30
30
|
// src/bridge-contract.ts
|
|
31
31
|
var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
|
|
32
|
+
var APP_SESSION_BRIDGE_CODE_MAX_LENGTH = 4096;
|
|
32
33
|
|
|
33
34
|
// src/client.ts
|
|
34
35
|
var AuthOwlNextSessionBridgeError = class extends Error {
|
|
@@ -39,14 +40,6 @@ var AuthOwlNextSessionBridgeError = class extends Error {
|
|
|
39
40
|
this.status = status;
|
|
40
41
|
}
|
|
41
42
|
};
|
|
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
43
|
function sameOriginBridgePath(value) {
|
|
51
44
|
const base = new URL("https://authowl.invalid");
|
|
52
45
|
let parsed;
|
|
@@ -60,63 +53,159 @@ function sameOriginBridgePath(value) {
|
|
|
60
53
|
}
|
|
61
54
|
return `${parsed.pathname}${parsed.search}`;
|
|
62
55
|
}
|
|
63
|
-
function
|
|
64
|
-
if (
|
|
56
|
+
async function bridgeError(response) {
|
|
57
|
+
if (!response.headers.get("content-type")?.toLowerCase().includes("application/json")) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
65
60
|
try {
|
|
66
|
-
const
|
|
67
|
-
return typeof
|
|
61
|
+
const payload = await response.json();
|
|
62
|
+
return typeof payload?.error === "string" ? payload.error : null;
|
|
68
63
|
} catch {
|
|
69
|
-
return
|
|
64
|
+
return null;
|
|
70
65
|
}
|
|
71
66
|
}
|
|
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
67
|
function createAuthOwlNextFetch(options) {
|
|
68
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
77
69
|
const target = (0, import_core.resolveAuthTarget)(options);
|
|
78
|
-
const
|
|
79
|
-
const authPath = `/api/projects/${target.decoded.projectId}/auth/`;
|
|
70
|
+
const mintUrl = `${target.projectBaseURL}/session/bridge-code`;
|
|
80
71
|
const bridgePath = sameOriginBridgePath(options.bridgePath ?? "/api/authowl/session");
|
|
81
|
-
const
|
|
72
|
+
const storageKey = `authowl:next-session-bridge:${target.decoded.projectId}`;
|
|
73
|
+
let connection = null;
|
|
74
|
+
let detachLifecycle = null;
|
|
75
|
+
let detachSessionStore = null;
|
|
82
76
|
let synchronization = Promise.resolve();
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
77
|
+
let memoryEnsured = false;
|
|
78
|
+
let currentSessionId = null;
|
|
79
|
+
let remember = false;
|
|
80
|
+
let bridgeUnavailable = false;
|
|
81
|
+
let sessionEnding = null;
|
|
82
|
+
const storedEnsured = () => {
|
|
83
|
+
try {
|
|
84
|
+
return globalThis.sessionStorage?.getItem(storageKey) === "1";
|
|
85
|
+
} catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const hasEnsuredProjection = () => memoryEnsured || storedEnsured();
|
|
90
|
+
const markEnsured = () => {
|
|
91
|
+
memoryEnsured = true;
|
|
92
|
+
try {
|
|
93
|
+
globalThis.sessionStorage?.setItem(storageKey, "1");
|
|
94
|
+
} catch {
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const resetEnsured = () => {
|
|
98
|
+
memoryEnsured = false;
|
|
99
|
+
try {
|
|
100
|
+
globalThis.sessionStorage?.removeItem(storageKey);
|
|
101
|
+
} catch {
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
const serialize = (work) => {
|
|
105
|
+
synchronization = synchronization.catch(() => void 0).then(work).catch(() => void 0);
|
|
103
106
|
return synchronization;
|
|
104
107
|
};
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
const postToBridge = (body) => baseFetch(bridgePath, {
|
|
109
|
+
method: "POST",
|
|
110
|
+
headers: {
|
|
111
|
+
"content-type": "application/json",
|
|
112
|
+
[APP_SESSION_BRIDGE_HEADER]: "1"
|
|
113
|
+
},
|
|
114
|
+
credentials: "same-origin",
|
|
115
|
+
cache: "no-store",
|
|
116
|
+
redirect: "error",
|
|
117
|
+
body: JSON.stringify(body)
|
|
118
|
+
});
|
|
119
|
+
const clear = () => serialize(async () => {
|
|
120
|
+
await postToBridge({ token: null });
|
|
121
|
+
});
|
|
122
|
+
const beginClear = () => {
|
|
123
|
+
if (sessionEnding) return sessionEnding;
|
|
124
|
+
const task = clear().finally(() => {
|
|
125
|
+
if (sessionEnding === task) sessionEnding = null;
|
|
126
|
+
});
|
|
127
|
+
sessionEnding = task;
|
|
128
|
+
return task;
|
|
129
|
+
};
|
|
130
|
+
const ensure = (remembered) => serialize(async () => {
|
|
131
|
+
if (bridgeUnavailable || hasEnsuredProjection()) return;
|
|
132
|
+
const authenticatedFetch = connection?.authenticatedFetch;
|
|
133
|
+
if (!authenticatedFetch) return;
|
|
134
|
+
const minted = await authenticatedFetch(mintUrl, {
|
|
135
|
+
method: "POST",
|
|
136
|
+
headers: { "x-publishable-key": target.publishableKey },
|
|
137
|
+
credentials: "include",
|
|
138
|
+
cache: "no-store",
|
|
139
|
+
redirect: "error"
|
|
140
|
+
});
|
|
141
|
+
if (minted.status === 404) {
|
|
142
|
+
bridgeUnavailable = true;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (!minted.ok) return;
|
|
146
|
+
const payload = await minted.json();
|
|
147
|
+
if (typeof payload.code !== "string" || payload.code.length > APP_SESSION_BRIDGE_CODE_MAX_LENGTH) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const bridged = await postToBridge({ code: payload.code, remember: remembered });
|
|
151
|
+
if (bridged.ok) {
|
|
152
|
+
markEnsured();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (await bridgeError(bridged) === "bridge_misconfigured") {
|
|
156
|
+
bridgeUnavailable = true;
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
const onLifecycle = (event) => {
|
|
160
|
+
if (event.type === "beginSession") {
|
|
161
|
+
remember = event.remember;
|
|
162
|
+
currentSessionId = null;
|
|
163
|
+
resetEnsured();
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
currentSessionId = null;
|
|
167
|
+
resetEnsured();
|
|
168
|
+
void beginClear();
|
|
169
|
+
};
|
|
170
|
+
const synchronizeSession = () => {
|
|
171
|
+
const snapshot = connection?.sessionStore.getSnapshot();
|
|
172
|
+
if (!snapshot || snapshot.isPending || snapshot.isRefetching) return;
|
|
173
|
+
const sessionId = snapshot.data?.session.id ?? null;
|
|
174
|
+
if (!sessionId) {
|
|
175
|
+
const projected = currentSessionId !== null || hasEnsuredProjection();
|
|
176
|
+
currentSessionId = null;
|
|
177
|
+
if (projected) {
|
|
178
|
+
resetEnsured();
|
|
179
|
+
void clear();
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (currentSessionId !== null && currentSessionId !== sessionId) {
|
|
184
|
+
resetEnsured();
|
|
110
185
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
186
|
+
if (currentSessionId !== sessionId) {
|
|
187
|
+
currentSessionId = sessionId;
|
|
188
|
+
}
|
|
189
|
+
void ensure(remember);
|
|
190
|
+
};
|
|
191
|
+
const integration = {
|
|
192
|
+
connect(next) {
|
|
193
|
+
detachLifecycle?.();
|
|
194
|
+
detachSessionStore?.();
|
|
195
|
+
connection = next;
|
|
196
|
+
detachLifecycle = next.subscribeLifecycle(onLifecycle);
|
|
197
|
+
detachSessionStore = next.sessionStore.subscribe(synchronizeSession);
|
|
198
|
+
synchronizeSession();
|
|
199
|
+
},
|
|
200
|
+
sessionEstablished() {
|
|
201
|
+
return ensure(remember);
|
|
202
|
+
},
|
|
203
|
+
sessionEnded() {
|
|
204
|
+
return beginClear();
|
|
117
205
|
}
|
|
118
|
-
return response;
|
|
119
206
|
};
|
|
207
|
+
const passthrough = ((input, init) => baseFetch(input, init));
|
|
208
|
+
return (0, import_core.withSessionTransportIntegration)(passthrough, integration);
|
|
120
209
|
}
|
|
121
210
|
// Annotate the CommonJS export names for ESM import in node:
|
|
122
211
|
0 && (module.exports = {
|
package/dist/client.d.cts
CHANGED
|
@@ -9,8 +9,13 @@ type AuthOwlNextFetchOptions = Readonly<{
|
|
|
9
9
|
fetch?: typeof fetch;
|
|
10
10
|
}>;
|
|
11
11
|
/**
|
|
12
|
-
* Wrap the fetch passed to AuthOwlProvider so
|
|
13
|
-
*
|
|
12
|
+
* Wrap the fetch passed to AuthOwlProvider so a live browser session is handed
|
|
13
|
+
* to the app origin without exposing its bearer token to application script.
|
|
14
|
+
*
|
|
15
|
+
* Core connects this adapter to the exact resolved session transport. The
|
|
16
|
+
* bridge therefore uses the same cookie/bearer verdict and sender proof as the
|
|
17
|
+
* client instead of constructing a shadow config or guessing lifecycle from
|
|
18
|
+
* endpoint URLs.
|
|
14
19
|
*/
|
|
15
20
|
declare function createAuthOwlNextFetch(options: AuthOwlNextFetchOptions): typeof fetch;
|
|
16
21
|
|
package/dist/client.d.ts
CHANGED
|
@@ -9,8 +9,13 @@ type AuthOwlNextFetchOptions = Readonly<{
|
|
|
9
9
|
fetch?: typeof fetch;
|
|
10
10
|
}>;
|
|
11
11
|
/**
|
|
12
|
-
* Wrap the fetch passed to AuthOwlProvider so
|
|
13
|
-
*
|
|
12
|
+
* Wrap the fetch passed to AuthOwlProvider so a live browser session is handed
|
|
13
|
+
* to the app origin without exposing its bearer token to application script.
|
|
14
|
+
*
|
|
15
|
+
* Core connects this adapter to the exact resolved session transport. The
|
|
16
|
+
* bridge therefore uses the same cookie/bearer verdict and sender proof as the
|
|
17
|
+
* client instead of constructing a shadow config or guessing lifecycle from
|
|
18
|
+
* endpoint URLs.
|
|
14
19
|
*/
|
|
15
20
|
declare function createAuthOwlNextFetch(options: AuthOwlNextFetchOptions): typeof fetch;
|
|
16
21
|
|
package/dist/client.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import {
|
|
3
|
+
APP_SESSION_BRIDGE_CODE_MAX_LENGTH,
|
|
3
4
|
APP_SESSION_BRIDGE_HEADER
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-6Q45QLET.js";
|
|
5
6
|
|
|
6
7
|
// src/client.ts
|
|
7
8
|
import {
|
|
8
9
|
resolveAuthTarget,
|
|
9
|
-
|
|
10
|
-
sessionChallengeIsEphemeral
|
|
10
|
+
withSessionTransportIntegration
|
|
11
11
|
} from "@authowl/core";
|
|
12
12
|
var AuthOwlNextSessionBridgeError = class extends Error {
|
|
13
13
|
status;
|
|
@@ -17,14 +17,6 @@ var AuthOwlNextSessionBridgeError = class extends Error {
|
|
|
17
17
|
this.status = status;
|
|
18
18
|
}
|
|
19
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
20
|
function sameOriginBridgePath(value) {
|
|
29
21
|
const base = new URL("https://authowl.invalid");
|
|
30
22
|
let parsed;
|
|
@@ -38,63 +30,159 @@ function sameOriginBridgePath(value) {
|
|
|
38
30
|
}
|
|
39
31
|
return `${parsed.pathname}${parsed.search}`;
|
|
40
32
|
}
|
|
41
|
-
function
|
|
42
|
-
if (
|
|
33
|
+
async function bridgeError(response) {
|
|
34
|
+
if (!response.headers.get("content-type")?.toLowerCase().includes("application/json")) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
43
37
|
try {
|
|
44
|
-
const
|
|
45
|
-
return typeof
|
|
38
|
+
const payload = await response.json();
|
|
39
|
+
return typeof payload?.error === "string" ? payload.error : null;
|
|
46
40
|
} catch {
|
|
47
|
-
return
|
|
41
|
+
return null;
|
|
48
42
|
}
|
|
49
43
|
}
|
|
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
44
|
function createAuthOwlNextFetch(options) {
|
|
45
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
55
46
|
const target = resolveAuthTarget(options);
|
|
56
|
-
const
|
|
57
|
-
const authPath = `/api/projects/${target.decoded.projectId}/auth/`;
|
|
47
|
+
const mintUrl = `${target.projectBaseURL}/session/bridge-code`;
|
|
58
48
|
const bridgePath = sameOriginBridgePath(options.bridgePath ?? "/api/authowl/session");
|
|
59
|
-
const
|
|
49
|
+
const storageKey = `authowl:next-session-bridge:${target.decoded.projectId}`;
|
|
50
|
+
let connection = null;
|
|
51
|
+
let detachLifecycle = null;
|
|
52
|
+
let detachSessionStore = null;
|
|
60
53
|
let synchronization = Promise.resolve();
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
54
|
+
let memoryEnsured = false;
|
|
55
|
+
let currentSessionId = null;
|
|
56
|
+
let remember = false;
|
|
57
|
+
let bridgeUnavailable = false;
|
|
58
|
+
let sessionEnding = null;
|
|
59
|
+
const storedEnsured = () => {
|
|
60
|
+
try {
|
|
61
|
+
return globalThis.sessionStorage?.getItem(storageKey) === "1";
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const hasEnsuredProjection = () => memoryEnsured || storedEnsured();
|
|
67
|
+
const markEnsured = () => {
|
|
68
|
+
memoryEnsured = true;
|
|
69
|
+
try {
|
|
70
|
+
globalThis.sessionStorage?.setItem(storageKey, "1");
|
|
71
|
+
} catch {
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const resetEnsured = () => {
|
|
75
|
+
memoryEnsured = false;
|
|
76
|
+
try {
|
|
77
|
+
globalThis.sessionStorage?.removeItem(storageKey);
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const serialize = (work) => {
|
|
82
|
+
synchronization = synchronization.catch(() => void 0).then(work).catch(() => void 0);
|
|
81
83
|
return synchronization;
|
|
82
84
|
};
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
85
|
+
const postToBridge = (body) => 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(body)
|
|
95
|
+
});
|
|
96
|
+
const clear = () => serialize(async () => {
|
|
97
|
+
await postToBridge({ token: null });
|
|
98
|
+
});
|
|
99
|
+
const beginClear = () => {
|
|
100
|
+
if (sessionEnding) return sessionEnding;
|
|
101
|
+
const task = clear().finally(() => {
|
|
102
|
+
if (sessionEnding === task) sessionEnding = null;
|
|
103
|
+
});
|
|
104
|
+
sessionEnding = task;
|
|
105
|
+
return task;
|
|
106
|
+
};
|
|
107
|
+
const ensure = (remembered) => serialize(async () => {
|
|
108
|
+
if (bridgeUnavailable || hasEnsuredProjection()) return;
|
|
109
|
+
const authenticatedFetch = connection?.authenticatedFetch;
|
|
110
|
+
if (!authenticatedFetch) return;
|
|
111
|
+
const minted = await authenticatedFetch(mintUrl, {
|
|
112
|
+
method: "POST",
|
|
113
|
+
headers: { "x-publishable-key": target.publishableKey },
|
|
114
|
+
credentials: "include",
|
|
115
|
+
cache: "no-store",
|
|
116
|
+
redirect: "error"
|
|
117
|
+
});
|
|
118
|
+
if (minted.status === 404) {
|
|
119
|
+
bridgeUnavailable = true;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!minted.ok) return;
|
|
123
|
+
const payload = await minted.json();
|
|
124
|
+
if (typeof payload.code !== "string" || payload.code.length > APP_SESSION_BRIDGE_CODE_MAX_LENGTH) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const bridged = await postToBridge({ code: payload.code, remember: remembered });
|
|
128
|
+
if (bridged.ok) {
|
|
129
|
+
markEnsured();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (await bridgeError(bridged) === "bridge_misconfigured") {
|
|
133
|
+
bridgeUnavailable = true;
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
const onLifecycle = (event) => {
|
|
137
|
+
if (event.type === "beginSession") {
|
|
138
|
+
remember = event.remember;
|
|
139
|
+
currentSessionId = null;
|
|
140
|
+
resetEnsured();
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
currentSessionId = null;
|
|
144
|
+
resetEnsured();
|
|
145
|
+
void beginClear();
|
|
146
|
+
};
|
|
147
|
+
const synchronizeSession = () => {
|
|
148
|
+
const snapshot = connection?.sessionStore.getSnapshot();
|
|
149
|
+
if (!snapshot || snapshot.isPending || snapshot.isRefetching) return;
|
|
150
|
+
const sessionId = snapshot.data?.session.id ?? null;
|
|
151
|
+
if (!sessionId) {
|
|
152
|
+
const projected = currentSessionId !== null || hasEnsuredProjection();
|
|
153
|
+
currentSessionId = null;
|
|
154
|
+
if (projected) {
|
|
155
|
+
resetEnsured();
|
|
156
|
+
void clear();
|
|
157
|
+
}
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (currentSessionId !== null && currentSessionId !== sessionId) {
|
|
161
|
+
resetEnsured();
|
|
88
162
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
163
|
+
if (currentSessionId !== sessionId) {
|
|
164
|
+
currentSessionId = sessionId;
|
|
165
|
+
}
|
|
166
|
+
void ensure(remember);
|
|
167
|
+
};
|
|
168
|
+
const integration = {
|
|
169
|
+
connect(next) {
|
|
170
|
+
detachLifecycle?.();
|
|
171
|
+
detachSessionStore?.();
|
|
172
|
+
connection = next;
|
|
173
|
+
detachLifecycle = next.subscribeLifecycle(onLifecycle);
|
|
174
|
+
detachSessionStore = next.sessionStore.subscribe(synchronizeSession);
|
|
175
|
+
synchronizeSession();
|
|
176
|
+
},
|
|
177
|
+
sessionEstablished() {
|
|
178
|
+
return ensure(remember);
|
|
179
|
+
},
|
|
180
|
+
sessionEnded() {
|
|
181
|
+
return beginClear();
|
|
95
182
|
}
|
|
96
|
-
return response;
|
|
97
183
|
};
|
|
184
|
+
const passthrough = ((input, init) => baseFetch(input, init));
|
|
185
|
+
return withSessionTransportIntegration(passthrough, integration);
|
|
98
186
|
}
|
|
99
187
|
export {
|
|
100
188
|
AuthOwlNextSessionBridgeError,
|
package/dist/middleware.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -42,6 +42,8 @@ var import_server3 = require("@authowl/core/server");
|
|
|
42
42
|
|
|
43
43
|
// src/bridge-contract.ts
|
|
44
44
|
var APP_SESSION_BRIDGE_HEADER = "x-authowl-session-bridge";
|
|
45
|
+
var AUTHOWL_SECRET_KEY_HEADER = "x-authowl-secret-key";
|
|
46
|
+
var APP_SESSION_BRIDGE_CODE_MAX_LENGTH = 4096;
|
|
45
47
|
function appSessionCookieNames(projectId) {
|
|
46
48
|
const suffix = projectId.toLowerCase().replace(/-/g, "");
|
|
47
49
|
return {
|
|
@@ -54,10 +56,12 @@ function appSessionCookieNames(projectId) {
|
|
|
54
56
|
var import_server = require("@authowl/core/server");
|
|
55
57
|
function serverConfig(config) {
|
|
56
58
|
const resolved = (0, import_server.resolveAuthTarget)(config);
|
|
59
|
+
const secretKey = config.secretKey ?? process.env.AUTHOWL_SECRET_KEY;
|
|
57
60
|
return {
|
|
58
61
|
publishableKey: resolved.publishableKey,
|
|
59
62
|
apiUrl: resolved.apiUrl,
|
|
60
|
-
projectId: resolved.decoded.projectId
|
|
63
|
+
projectId: resolved.decoded.projectId,
|
|
64
|
+
...secretKey ? { secretKey } : {}
|
|
61
65
|
};
|
|
62
66
|
}
|
|
63
67
|
var cachedConfig = null;
|
|
@@ -120,6 +124,11 @@ function sameOriginBrowserPostOrigin(request) {
|
|
|
120
124
|
function validToken(value) {
|
|
121
125
|
return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
|
|
122
126
|
}
|
|
127
|
+
function futureExpiry(value) {
|
|
128
|
+
if (typeof value !== "string") return null;
|
|
129
|
+
const expires = new Date(value);
|
|
130
|
+
return Number.isFinite(expires.getTime()) && expires.getTime() > Date.now() ? expires : null;
|
|
131
|
+
}
|
|
123
132
|
function serializeCookie(name, value, options) {
|
|
124
133
|
const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
125
134
|
if (options.secure) attributes.push("Secure");
|
|
@@ -134,12 +143,81 @@ function clearCookies(projectId) {
|
|
|
134
143
|
result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
|
|
135
144
|
return result;
|
|
136
145
|
}
|
|
146
|
+
function configuredBridge(config) {
|
|
147
|
+
return config.secretKey ? { ...config, secretKey: config.secretKey } : null;
|
|
148
|
+
}
|
|
149
|
+
function requireConfiguredBridge(config) {
|
|
150
|
+
const configured = configuredBridge(config);
|
|
151
|
+
if (configured) return configured;
|
|
152
|
+
throw new Error(
|
|
153
|
+
"AuthOwl session bridge is not configured. Set AUTHOWL_SECRET_KEY or pass secretKey to createAuthOwlSessionBridge()."
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
async function redeemBridgeCode(remoteFetch, config, code) {
|
|
157
|
+
let upstream;
|
|
158
|
+
try {
|
|
159
|
+
upstream = await remoteFetch(`${config.apiUrl}/api/v1/sessions/bridge-code`, {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: {
|
|
162
|
+
authorization: `Bearer ${config.secretKey}`,
|
|
163
|
+
"content-type": "application/json"
|
|
164
|
+
},
|
|
165
|
+
cache: "no-store",
|
|
166
|
+
redirect: "error",
|
|
167
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS),
|
|
168
|
+
body: JSON.stringify({ code })
|
|
169
|
+
});
|
|
170
|
+
} catch {
|
|
171
|
+
return { kind: "auth_service_unavailable" };
|
|
172
|
+
}
|
|
173
|
+
if (upstream.status === 422) return { kind: "invalid_code" };
|
|
174
|
+
if (upstream.status === 401 || upstream.status === 403) {
|
|
175
|
+
return { kind: "bridge_misconfigured" };
|
|
176
|
+
}
|
|
177
|
+
if (upstream.status >= 500) return { kind: "auth_service_unavailable" };
|
|
178
|
+
if (!upstream.ok) return { kind: "auth_service_error" };
|
|
179
|
+
return { kind: "ok", response: upstream };
|
|
180
|
+
}
|
|
181
|
+
async function validateSession(remoteFetch, config, token) {
|
|
182
|
+
let upstream;
|
|
183
|
+
try {
|
|
184
|
+
upstream = await remoteFetch(
|
|
185
|
+
`${config.apiUrl}/api/projects/${config.projectId}/auth/get-session`,
|
|
186
|
+
{
|
|
187
|
+
method: "GET",
|
|
188
|
+
headers: {
|
|
189
|
+
authorization: `Bearer ${token}`,
|
|
190
|
+
[import_server2.SESSION_TRANSPORT_HEADER]: import_server2.SESSION_TRANSPORT_BEARER,
|
|
191
|
+
[AUTHOWL_SECRET_KEY_HEADER]: config.secretKey,
|
|
192
|
+
"x-publishable-key": config.publishableKey
|
|
193
|
+
},
|
|
194
|
+
cache: "no-store",
|
|
195
|
+
redirect: "error",
|
|
196
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
|
|
197
|
+
}
|
|
198
|
+
);
|
|
199
|
+
} catch {
|
|
200
|
+
return { kind: "auth_service_unavailable" };
|
|
201
|
+
}
|
|
202
|
+
if (upstream.status === 401) return { kind: "invalid_session" };
|
|
203
|
+
if (!upstream.ok) return { kind: "auth_service_error" };
|
|
204
|
+
return { kind: "ok", response: upstream };
|
|
205
|
+
}
|
|
137
206
|
function createAuthOwlSessionBridge(input) {
|
|
138
|
-
const configured = input ? resolveAuthConfig(input) : null;
|
|
207
|
+
const configured = input ? requireConfiguredBridge(resolveAuthConfig(input)) : null;
|
|
139
208
|
const remoteFetch = input?.fetch ?? globalThis.fetch;
|
|
209
|
+
let deferredConfig;
|
|
210
|
+
const configForRequest = () => {
|
|
211
|
+
if (configured) return configured;
|
|
212
|
+
if (deferredConfig !== void 0) return deferredConfig;
|
|
213
|
+
try {
|
|
214
|
+
deferredConfig = configuredBridge(getAuthConfig());
|
|
215
|
+
} catch {
|
|
216
|
+
deferredConfig = null;
|
|
217
|
+
}
|
|
218
|
+
return deferredConfig;
|
|
219
|
+
};
|
|
140
220
|
return async function authOwlSessionBridge(request) {
|
|
141
|
-
const config = configured ?? getAuthConfig();
|
|
142
|
-
const projectId = config.projectId;
|
|
143
221
|
const browserOrigin = sameOriginBrowserPostOrigin(request);
|
|
144
222
|
if (!browserOrigin) {
|
|
145
223
|
return response(403, { error: "forbidden" });
|
|
@@ -152,31 +230,55 @@ function createAuthOwlSessionBridge(input) {
|
|
|
152
230
|
} catch {
|
|
153
231
|
return response(400, { error: "invalid_request" });
|
|
154
232
|
}
|
|
155
|
-
|
|
156
|
-
if (
|
|
157
|
-
|
|
233
|
+
let action;
|
|
234
|
+
if (body.token === null) {
|
|
235
|
+
action = { kind: "clear" };
|
|
236
|
+
} else {
|
|
237
|
+
if (typeof body.code !== "string" || body.code.length > APP_SESSION_BRIDGE_CODE_MAX_LENGTH || body.remember !== void 0 && typeof body.remember !== "boolean") {
|
|
238
|
+
return response(400, { error: "invalid_request" });
|
|
239
|
+
}
|
|
240
|
+
action = { kind: "bridge", code: body.code, remember: body.remember };
|
|
241
|
+
}
|
|
242
|
+
const config = configForRequest();
|
|
243
|
+
if (!config) {
|
|
244
|
+
return response(503, { error: "bridge_misconfigured" });
|
|
245
|
+
}
|
|
246
|
+
if (action.kind === "clear") return clearCookies(config.projectId);
|
|
247
|
+
const redeemedResult = await redeemBridgeCode(remoteFetch, config, action.code);
|
|
248
|
+
if (redeemedResult.kind === "invalid_code") {
|
|
249
|
+
return response(401, { error: "invalid_session" });
|
|
158
250
|
}
|
|
159
|
-
|
|
251
|
+
if (redeemedResult.kind === "bridge_misconfigured") {
|
|
252
|
+
return response(503, { error: "bridge_misconfigured" });
|
|
253
|
+
}
|
|
254
|
+
if (redeemedResult.kind === "auth_service_unavailable") {
|
|
255
|
+
return response(503, { error: "auth_service_unavailable" });
|
|
256
|
+
}
|
|
257
|
+
if (redeemedResult.kind === "auth_service_error") {
|
|
258
|
+
return response(502, { error: "auth_service_error" });
|
|
259
|
+
}
|
|
260
|
+
const redeemedResponse = redeemedResult.response;
|
|
261
|
+
let redeemed;
|
|
160
262
|
try {
|
|
161
|
-
|
|
162
|
-
`${config.apiUrl}/api/projects/${projectId}/auth/get-session`,
|
|
163
|
-
{
|
|
164
|
-
method: "GET",
|
|
165
|
-
headers: {
|
|
166
|
-
authorization: `Bearer ${body.token}`,
|
|
167
|
-
[import_server2.SESSION_TRANSPORT_HEADER]: import_server2.SESSION_TRANSPORT_BEARER,
|
|
168
|
-
"x-publishable-key": config.publishableKey
|
|
169
|
-
},
|
|
170
|
-
cache: "no-store",
|
|
171
|
-
redirect: "error",
|
|
172
|
-
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
|
|
173
|
-
}
|
|
174
|
-
);
|
|
263
|
+
redeemed = await redeemedResponse.json();
|
|
175
264
|
} catch {
|
|
265
|
+
return response(502, { error: "invalid_auth_response" });
|
|
266
|
+
}
|
|
267
|
+
const redeemedExpiry = futureExpiry(redeemed.expiresAt);
|
|
268
|
+
if (!validToken(redeemed.token) || !redeemedExpiry) {
|
|
269
|
+
return response(502, { error: "invalid_auth_response" });
|
|
270
|
+
}
|
|
271
|
+
const sessionResult = await validateSession(remoteFetch, config, redeemed.token);
|
|
272
|
+
if (sessionResult.kind === "invalid_session") {
|
|
273
|
+
return response(401, { error: "invalid_session" });
|
|
274
|
+
}
|
|
275
|
+
if (sessionResult.kind === "auth_service_unavailable") {
|
|
176
276
|
return response(503, { error: "auth_service_unavailable" });
|
|
177
277
|
}
|
|
178
|
-
if (
|
|
179
|
-
|
|
278
|
+
if (sessionResult.kind === "auth_service_error") {
|
|
279
|
+
return response(502, { error: "auth_service_error" });
|
|
280
|
+
}
|
|
281
|
+
const sessionResponse = sessionResult.response;
|
|
180
282
|
let session;
|
|
181
283
|
try {
|
|
182
284
|
session = await sessionResponse.json();
|
|
@@ -186,21 +288,19 @@ function createAuthOwlSessionBridge(input) {
|
|
|
186
288
|
if (!session?.user || !session.session || session.session.pendingMfaEnrollment === true) {
|
|
187
289
|
return response(401, { error: "invalid_session" });
|
|
188
290
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
const expires = new Date(session.session.expiresAt);
|
|
193
|
-
if (!Number.isFinite(expires.getTime()) || expires.getTime() <= Date.now()) {
|
|
194
|
-
return response(401, { error: "invalid_session" });
|
|
195
|
-
}
|
|
291
|
+
const sessionExpiry = futureExpiry(session.session.expiresAt);
|
|
292
|
+
if (!sessionExpiry) return response(401, { error: "invalid_session" });
|
|
196
293
|
const secure = new URL(browserOrigin).protocol === "https:";
|
|
197
|
-
const names = appSessionCookieNames(projectId);
|
|
294
|
+
const names = appSessionCookieNames(config.projectId);
|
|
198
295
|
const result = response(204);
|
|
199
296
|
result.headers.append(
|
|
200
297
|
"set-cookie",
|
|
201
|
-
serializeCookie(secure ? names.secure : names.local,
|
|
298
|
+
serializeCookie(secure ? names.secure : names.local, redeemed.token, {
|
|
202
299
|
secure,
|
|
203
|
-
|
|
300
|
+
// Both values describe the same session. Taking the earlier one keeps a
|
|
301
|
+
// malformed upstream response from extending the app cookie past either
|
|
302
|
+
// authority's stated lifetime.
|
|
303
|
+
expires: action.remember === false ? void 0 : new Date(Math.min(redeemedExpiry.getTime(), sessionExpiry.getTime()))
|
|
204
304
|
})
|
|
205
305
|
);
|
|
206
306
|
return result;
|
|
@@ -257,7 +357,8 @@ async function auth() {
|
|
|
257
357
|
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper",
|
|
258
358
|
...bridgeToken ? {
|
|
259
359
|
authorization: `Bearer ${bridgeToken}`,
|
|
260
|
-
[import_server3.SESSION_TRANSPORT_HEADER]: import_server3.SESSION_TRANSPORT_BEARER
|
|
360
|
+
[import_server3.SESSION_TRANSPORT_HEADER]: import_server3.SESSION_TRANSPORT_BEARER,
|
|
361
|
+
...cfg.secretKey ? { [AUTHOWL_SECRET_KEY_HEADER]: cfg.secretKey } : {}
|
|
261
362
|
} : {}
|
|
262
363
|
},
|
|
263
364
|
cache: "no-store",
|
package/dist/server.d.cts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { AuthConfig } from '@authowl/core/server';
|
|
2
2
|
export { AuthorizationError, AuthorizationFailureReason, HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, isAuthorizationError, requireAuth, requireGrant, requireOrg, requirePermission, verifyToken } from '@authowl/core/server';
|
|
3
3
|
|
|
4
|
-
type
|
|
4
|
+
type AuthOwlNextServerConfig = AuthConfig & Readonly<{
|
|
5
|
+
secretKey?: string;
|
|
6
|
+
}>;
|
|
7
|
+
|
|
8
|
+
type AuthOwlSessionBridgeOptions = Omit<AuthOwlNextServerConfig, 'secretKey'> & Readonly<{
|
|
9
|
+
secretKey: string;
|
|
10
|
+
}>;
|
|
5
11
|
/**
|
|
6
12
|
* Build the same-origin endpoint that projects an AuthOwl browser session into
|
|
7
|
-
* an application-owned HttpOnly cookie. The
|
|
8
|
-
*
|
|
13
|
+
* an application-owned HttpOnly cookie. The browser supplies only a single-use
|
|
14
|
+
* code; the secret-bearing app route redeems and validates the session token.
|
|
9
15
|
*/
|
|
10
16
|
declare function createAuthOwlSessionBridge(input?: AuthOwlSessionBridgeOptions): (request: Request) => Promise<Response>;
|
|
11
17
|
|
|
@@ -47,7 +53,7 @@ declare class AuthServiceError extends Error {
|
|
|
47
53
|
* every server-side call too (a server fetch has no Origin, but the publishable
|
|
48
54
|
* key + bearer cookie still identify the project on the auth server).
|
|
49
55
|
*/
|
|
50
|
-
declare function initAuth(config:
|
|
56
|
+
declare function initAuth(config: AuthOwlNextServerConfig): void;
|
|
51
57
|
/**
|
|
52
58
|
* Get the current session by forwarding only the expected auth session
|
|
53
59
|
* cookie to the auth server. Returns null if not signed in.
|
package/dist/server.d.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { AuthConfig } from '@authowl/core/server';
|
|
2
2
|
export { AuthorizationError, AuthorizationFailureReason, HasParams, OrganizationMembership, TokenVerificationError, VerifiedProjectToken, VerifyTokenConfig, has, hasPermission, isAuthorizationError, requireAuth, requireGrant, requireOrg, requirePermission, verifyToken } from '@authowl/core/server';
|
|
3
3
|
|
|
4
|
-
type
|
|
4
|
+
type AuthOwlNextServerConfig = AuthConfig & Readonly<{
|
|
5
|
+
secretKey?: string;
|
|
6
|
+
}>;
|
|
7
|
+
|
|
8
|
+
type AuthOwlSessionBridgeOptions = Omit<AuthOwlNextServerConfig, 'secretKey'> & Readonly<{
|
|
9
|
+
secretKey: string;
|
|
10
|
+
}>;
|
|
5
11
|
/**
|
|
6
12
|
* Build the same-origin endpoint that projects an AuthOwl browser session into
|
|
7
|
-
* an application-owned HttpOnly cookie. The
|
|
8
|
-
*
|
|
13
|
+
* an application-owned HttpOnly cookie. The browser supplies only a single-use
|
|
14
|
+
* code; the secret-bearing app route redeems and validates the session token.
|
|
9
15
|
*/
|
|
10
16
|
declare function createAuthOwlSessionBridge(input?: AuthOwlSessionBridgeOptions): (request: Request) => Promise<Response>;
|
|
11
17
|
|
|
@@ -47,7 +53,7 @@ declare class AuthServiceError extends Error {
|
|
|
47
53
|
* every server-side call too (a server fetch has no Origin, but the publishable
|
|
48
54
|
* key + bearer cookie still identify the project on the auth server).
|
|
49
55
|
*/
|
|
50
|
-
declare function initAuth(config:
|
|
56
|
+
declare function initAuth(config: AuthOwlNextServerConfig): void;
|
|
51
57
|
/**
|
|
52
58
|
* Get the current session by forwarding only the expected auth session
|
|
53
59
|
* cookie to the auth server. Returns null if not signed in.
|
package/dist/server.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
+
APP_SESSION_BRIDGE_CODE_MAX_LENGTH,
|
|
2
3
|
APP_SESSION_BRIDGE_HEADER,
|
|
4
|
+
AUTHOWL_SECRET_KEY_HEADER,
|
|
3
5
|
appSessionCookieNames
|
|
4
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-6Q45QLET.js";
|
|
5
7
|
|
|
6
8
|
// src/server.ts
|
|
7
9
|
import { headers as nextHeaders, cookies as nextCookies } from "next/headers.js";
|
|
@@ -15,10 +17,12 @@ import {
|
|
|
15
17
|
import { resolveAuthTarget } from "@authowl/core/server";
|
|
16
18
|
function serverConfig(config) {
|
|
17
19
|
const resolved = resolveAuthTarget(config);
|
|
20
|
+
const secretKey = config.secretKey ?? process.env.AUTHOWL_SECRET_KEY;
|
|
18
21
|
return {
|
|
19
22
|
publishableKey: resolved.publishableKey,
|
|
20
23
|
apiUrl: resolved.apiUrl,
|
|
21
|
-
projectId: resolved.decoded.projectId
|
|
24
|
+
projectId: resolved.decoded.projectId,
|
|
25
|
+
...secretKey ? { secretKey } : {}
|
|
22
26
|
};
|
|
23
27
|
}
|
|
24
28
|
var cachedConfig = null;
|
|
@@ -84,6 +88,11 @@ function sameOriginBrowserPostOrigin(request) {
|
|
|
84
88
|
function validToken(value) {
|
|
85
89
|
return typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\u0021-\u007e]+$/.test(value) && !/[",;\\]/.test(value);
|
|
86
90
|
}
|
|
91
|
+
function futureExpiry(value) {
|
|
92
|
+
if (typeof value !== "string") return null;
|
|
93
|
+
const expires = new Date(value);
|
|
94
|
+
return Number.isFinite(expires.getTime()) && expires.getTime() > Date.now() ? expires : null;
|
|
95
|
+
}
|
|
87
96
|
function serializeCookie(name, value, options) {
|
|
88
97
|
const attributes = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
89
98
|
if (options.secure) attributes.push("Secure");
|
|
@@ -98,12 +107,81 @@ function clearCookies(projectId) {
|
|
|
98
107
|
result.headers.append("set-cookie", serializeCookie(names.local, "", { secure: false, clear: true }));
|
|
99
108
|
return result;
|
|
100
109
|
}
|
|
110
|
+
function configuredBridge(config) {
|
|
111
|
+
return config.secretKey ? { ...config, secretKey: config.secretKey } : null;
|
|
112
|
+
}
|
|
113
|
+
function requireConfiguredBridge(config) {
|
|
114
|
+
const configured = configuredBridge(config);
|
|
115
|
+
if (configured) return configured;
|
|
116
|
+
throw new Error(
|
|
117
|
+
"AuthOwl session bridge is not configured. Set AUTHOWL_SECRET_KEY or pass secretKey to createAuthOwlSessionBridge()."
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
async function redeemBridgeCode(remoteFetch, config, code) {
|
|
121
|
+
let upstream;
|
|
122
|
+
try {
|
|
123
|
+
upstream = await remoteFetch(`${config.apiUrl}/api/v1/sessions/bridge-code`, {
|
|
124
|
+
method: "POST",
|
|
125
|
+
headers: {
|
|
126
|
+
authorization: `Bearer ${config.secretKey}`,
|
|
127
|
+
"content-type": "application/json"
|
|
128
|
+
},
|
|
129
|
+
cache: "no-store",
|
|
130
|
+
redirect: "error",
|
|
131
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS),
|
|
132
|
+
body: JSON.stringify({ code })
|
|
133
|
+
});
|
|
134
|
+
} catch {
|
|
135
|
+
return { kind: "auth_service_unavailable" };
|
|
136
|
+
}
|
|
137
|
+
if (upstream.status === 422) return { kind: "invalid_code" };
|
|
138
|
+
if (upstream.status === 401 || upstream.status === 403) {
|
|
139
|
+
return { kind: "bridge_misconfigured" };
|
|
140
|
+
}
|
|
141
|
+
if (upstream.status >= 500) return { kind: "auth_service_unavailable" };
|
|
142
|
+
if (!upstream.ok) return { kind: "auth_service_error" };
|
|
143
|
+
return { kind: "ok", response: upstream };
|
|
144
|
+
}
|
|
145
|
+
async function validateSession(remoteFetch, config, token) {
|
|
146
|
+
let upstream;
|
|
147
|
+
try {
|
|
148
|
+
upstream = await remoteFetch(
|
|
149
|
+
`${config.apiUrl}/api/projects/${config.projectId}/auth/get-session`,
|
|
150
|
+
{
|
|
151
|
+
method: "GET",
|
|
152
|
+
headers: {
|
|
153
|
+
authorization: `Bearer ${token}`,
|
|
154
|
+
[SESSION_TRANSPORT_HEADER]: SESSION_TRANSPORT_BEARER,
|
|
155
|
+
[AUTHOWL_SECRET_KEY_HEADER]: config.secretKey,
|
|
156
|
+
"x-publishable-key": config.publishableKey
|
|
157
|
+
},
|
|
158
|
+
cache: "no-store",
|
|
159
|
+
redirect: "error",
|
|
160
|
+
signal: AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS)
|
|
161
|
+
}
|
|
162
|
+
);
|
|
163
|
+
} catch {
|
|
164
|
+
return { kind: "auth_service_unavailable" };
|
|
165
|
+
}
|
|
166
|
+
if (upstream.status === 401) return { kind: "invalid_session" };
|
|
167
|
+
if (!upstream.ok) return { kind: "auth_service_error" };
|
|
168
|
+
return { kind: "ok", response: upstream };
|
|
169
|
+
}
|
|
101
170
|
function createAuthOwlSessionBridge(input) {
|
|
102
|
-
const configured = input ? resolveAuthConfig(input) : null;
|
|
171
|
+
const configured = input ? requireConfiguredBridge(resolveAuthConfig(input)) : null;
|
|
103
172
|
const remoteFetch = input?.fetch ?? globalThis.fetch;
|
|
173
|
+
let deferredConfig;
|
|
174
|
+
const configForRequest = () => {
|
|
175
|
+
if (configured) return configured;
|
|
176
|
+
if (deferredConfig !== void 0) return deferredConfig;
|
|
177
|
+
try {
|
|
178
|
+
deferredConfig = configuredBridge(getAuthConfig());
|
|
179
|
+
} catch {
|
|
180
|
+
deferredConfig = null;
|
|
181
|
+
}
|
|
182
|
+
return deferredConfig;
|
|
183
|
+
};
|
|
104
184
|
return async function authOwlSessionBridge(request) {
|
|
105
|
-
const config = configured ?? getAuthConfig();
|
|
106
|
-
const projectId = config.projectId;
|
|
107
185
|
const browserOrigin = sameOriginBrowserPostOrigin(request);
|
|
108
186
|
if (!browserOrigin) {
|
|
109
187
|
return response(403, { error: "forbidden" });
|
|
@@ -116,31 +194,55 @@ function createAuthOwlSessionBridge(input) {
|
|
|
116
194
|
} catch {
|
|
117
195
|
return response(400, { error: "invalid_request" });
|
|
118
196
|
}
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
|
|
197
|
+
let action;
|
|
198
|
+
if (body.token === null) {
|
|
199
|
+
action = { kind: "clear" };
|
|
200
|
+
} else {
|
|
201
|
+
if (typeof body.code !== "string" || body.code.length > APP_SESSION_BRIDGE_CODE_MAX_LENGTH || body.remember !== void 0 && typeof body.remember !== "boolean") {
|
|
202
|
+
return response(400, { error: "invalid_request" });
|
|
203
|
+
}
|
|
204
|
+
action = { kind: "bridge", code: body.code, remember: body.remember };
|
|
205
|
+
}
|
|
206
|
+
const config = configForRequest();
|
|
207
|
+
if (!config) {
|
|
208
|
+
return response(503, { error: "bridge_misconfigured" });
|
|
209
|
+
}
|
|
210
|
+
if (action.kind === "clear") return clearCookies(config.projectId);
|
|
211
|
+
const redeemedResult = await redeemBridgeCode(remoteFetch, config, action.code);
|
|
212
|
+
if (redeemedResult.kind === "invalid_code") {
|
|
213
|
+
return response(401, { error: "invalid_session" });
|
|
122
214
|
}
|
|
123
|
-
|
|
215
|
+
if (redeemedResult.kind === "bridge_misconfigured") {
|
|
216
|
+
return response(503, { error: "bridge_misconfigured" });
|
|
217
|
+
}
|
|
218
|
+
if (redeemedResult.kind === "auth_service_unavailable") {
|
|
219
|
+
return response(503, { error: "auth_service_unavailable" });
|
|
220
|
+
}
|
|
221
|
+
if (redeemedResult.kind === "auth_service_error") {
|
|
222
|
+
return response(502, { error: "auth_service_error" });
|
|
223
|
+
}
|
|
224
|
+
const redeemedResponse = redeemedResult.response;
|
|
225
|
+
let redeemed;
|
|
124
226
|
try {
|
|
125
|
-
|
|
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
|
-
);
|
|
227
|
+
redeemed = await redeemedResponse.json();
|
|
139
228
|
} catch {
|
|
229
|
+
return response(502, { error: "invalid_auth_response" });
|
|
230
|
+
}
|
|
231
|
+
const redeemedExpiry = futureExpiry(redeemed.expiresAt);
|
|
232
|
+
if (!validToken(redeemed.token) || !redeemedExpiry) {
|
|
233
|
+
return response(502, { error: "invalid_auth_response" });
|
|
234
|
+
}
|
|
235
|
+
const sessionResult = await validateSession(remoteFetch, config, redeemed.token);
|
|
236
|
+
if (sessionResult.kind === "invalid_session") {
|
|
237
|
+
return response(401, { error: "invalid_session" });
|
|
238
|
+
}
|
|
239
|
+
if (sessionResult.kind === "auth_service_unavailable") {
|
|
140
240
|
return response(503, { error: "auth_service_unavailable" });
|
|
141
241
|
}
|
|
142
|
-
if (
|
|
143
|
-
|
|
242
|
+
if (sessionResult.kind === "auth_service_error") {
|
|
243
|
+
return response(502, { error: "auth_service_error" });
|
|
244
|
+
}
|
|
245
|
+
const sessionResponse = sessionResult.response;
|
|
144
246
|
let session;
|
|
145
247
|
try {
|
|
146
248
|
session = await sessionResponse.json();
|
|
@@ -150,21 +252,19 @@ function createAuthOwlSessionBridge(input) {
|
|
|
150
252
|
if (!session?.user || !session.session || session.session.pendingMfaEnrollment === true) {
|
|
151
253
|
return response(401, { error: "invalid_session" });
|
|
152
254
|
}
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
}
|
|
255
|
+
const sessionExpiry = futureExpiry(session.session.expiresAt);
|
|
256
|
+
if (!sessionExpiry) return response(401, { error: "invalid_session" });
|
|
160
257
|
const secure = new URL(browserOrigin).protocol === "https:";
|
|
161
|
-
const names = appSessionCookieNames(projectId);
|
|
258
|
+
const names = appSessionCookieNames(config.projectId);
|
|
162
259
|
const result = response(204);
|
|
163
260
|
result.headers.append(
|
|
164
261
|
"set-cookie",
|
|
165
|
-
serializeCookie(secure ? names.secure : names.local,
|
|
262
|
+
serializeCookie(secure ? names.secure : names.local, redeemed.token, {
|
|
166
263
|
secure,
|
|
167
|
-
|
|
264
|
+
// Both values describe the same session. Taking the earlier one keeps a
|
|
265
|
+
// malformed upstream response from extending the app cookie past either
|
|
266
|
+
// authority's stated lifetime.
|
|
267
|
+
expires: action.remember === false ? void 0 : new Date(Math.min(redeemedExpiry.getTime(), sessionExpiry.getTime()))
|
|
168
268
|
})
|
|
169
269
|
);
|
|
170
270
|
return result;
|
|
@@ -233,7 +333,8 @@ async function auth() {
|
|
|
233
333
|
"user-agent": hdrs.get("user-agent") ?? "next-auth-helper",
|
|
234
334
|
...bridgeToken ? {
|
|
235
335
|
authorization: `Bearer ${bridgeToken}`,
|
|
236
|
-
[SESSION_TRANSPORT_HEADER2]: SESSION_TRANSPORT_BEARER2
|
|
336
|
+
[SESSION_TRANSPORT_HEADER2]: SESSION_TRANSPORT_BEARER2,
|
|
337
|
+
...cfg.secretKey ? { [AUTHOWL_SECRET_KEY_HEADER]: cfg.secretKey } : {}
|
|
237
338
|
} : {}
|
|
238
339
|
},
|
|
239
340
|
cache: "no-store",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authowl/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Next.js (App Router) server helpers for AuthOwl, the multi-tenant auth SaaS.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"LICENSE"
|
|
62
62
|
],
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@authowl/core": "0.
|
|
64
|
+
"@authowl/core": "0.23.0"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
67
|
"next": ">=14"
|