@oauth-spa-kit/server 1.0.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/LICENSE +21 -0
- package/dist/cookies.d.ts +14 -0
- package/dist/cookies.js +30 -0
- package/dist/crypto.d.ts +9 -0
- package/dist/crypto.js +56 -0
- package/dist/handlers.d.ts +32 -0
- package/dist/handlers.js +220 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/pkceState.d.ts +25 -0
- package/dist/pkceState.js +17 -0
- package/dist/session.d.ts +22 -0
- package/dist/session.js +19 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ehncraft
|
|
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.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function parseCookies(request: Request): Record<string, string>;
|
|
2
|
+
export interface CookieOptions {
|
|
3
|
+
maxAgeSeconds?: number;
|
|
4
|
+
path?: string;
|
|
5
|
+
domain?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* `HttpOnly` + `Secure` + `SameSite=Lax` always: the whole point of the BFF
|
|
9
|
+
* pattern is that this value is never readable or writable from JS.
|
|
10
|
+
* `Lax` (not `Strict`) so the cookie still rides along on the top-level
|
|
11
|
+
* redirect back from the IdP after login.
|
|
12
|
+
*/
|
|
13
|
+
export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
14
|
+
export declare function expireCookie(name: string, options?: Pick<CookieOptions, "path" | "domain">): string;
|
package/dist/cookies.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function parseCookies(request) {
|
|
2
|
+
const header = request.headers.get("cookie");
|
|
3
|
+
if (!header)
|
|
4
|
+
return {};
|
|
5
|
+
const out = {};
|
|
6
|
+
for (const part of header.split(";")) {
|
|
7
|
+
const eq = part.indexOf("=");
|
|
8
|
+
if (eq === -1)
|
|
9
|
+
continue;
|
|
10
|
+
out[part.slice(0, eq).trim()] = decodeURIComponent(part.slice(eq + 1).trim());
|
|
11
|
+
}
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `HttpOnly` + `Secure` + `SameSite=Lax` always: the whole point of the BFF
|
|
16
|
+
* pattern is that this value is never readable or writable from JS.
|
|
17
|
+
* `Lax` (not `Strict`) so the cookie still rides along on the top-level
|
|
18
|
+
* redirect back from the IdP after login.
|
|
19
|
+
*/
|
|
20
|
+
export function serializeCookie(name, value, options = {}) {
|
|
21
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, "HttpOnly", "Secure", "SameSite=Lax", `Path=${options.path ?? "/"}`];
|
|
22
|
+
if (options.maxAgeSeconds !== undefined)
|
|
23
|
+
parts.push(`Max-Age=${options.maxAgeSeconds}`);
|
|
24
|
+
if (options.domain)
|
|
25
|
+
parts.push(`Domain=${options.domain}`);
|
|
26
|
+
return parts.join("; ");
|
|
27
|
+
}
|
|
28
|
+
export function expireCookie(name, options = {}) {
|
|
29
|
+
return serializeCookie(name, "", { ...options, maxAgeSeconds: 0 });
|
|
30
|
+
}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic authenticated encryption for cookie payloads (AES-256-GCM via Web
|
|
3
|
+
* Crypto). Same idea as nuxt-auth-utils' sealed session cookies
|
|
4
|
+
* (iron-session under the hood there), reimplemented directly against Web
|
|
5
|
+
* Crypto so it has zero dependencies and runs unmodified on Node >=18,
|
|
6
|
+
* Cloudflare Workers, Deno, and Vercel Edge.
|
|
7
|
+
*/
|
|
8
|
+
export declare function sealJson(payload: unknown, password: string): Promise<string>;
|
|
9
|
+
export declare function unsealJson<T>(sealed: string, password: string): Promise<T | null>;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic authenticated encryption for cookie payloads (AES-256-GCM via Web
|
|
3
|
+
* Crypto). Same idea as nuxt-auth-utils' sealed session cookies
|
|
4
|
+
* (iron-session under the hood there), reimplemented directly against Web
|
|
5
|
+
* Crypto so it has zero dependencies and runs unmodified on Node >=18,
|
|
6
|
+
* Cloudflare Workers, Deno, and Vercel Edge.
|
|
7
|
+
*/
|
|
8
|
+
function base64UrlEncode(bytes) {
|
|
9
|
+
let binary = "";
|
|
10
|
+
for (const b of bytes)
|
|
11
|
+
binary += String.fromCharCode(b);
|
|
12
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
13
|
+
}
|
|
14
|
+
// Concrete `Uint8Array<ArrayBuffer>`, not the bare `Uint8Array` (TS's dom
|
|
15
|
+
// lib parameterizes that over `ArrayBufferLike` including
|
|
16
|
+
// `SharedArrayBuffer`) -- `crypto.subtle.decrypt` requires an actual
|
|
17
|
+
// `ArrayBuffer`-backed view.
|
|
18
|
+
function base64UrlDecode(value) {
|
|
19
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
20
|
+
const binary = atob(padded);
|
|
21
|
+
const bytes = new Uint8Array(binary.length);
|
|
22
|
+
for (let i = 0; i < binary.length; i++)
|
|
23
|
+
bytes[i] = binary.charCodeAt(i);
|
|
24
|
+
return bytes;
|
|
25
|
+
}
|
|
26
|
+
async function deriveKey(password) {
|
|
27
|
+
if (password.length < 32) {
|
|
28
|
+
throw new Error("Cookie sealing password must be at least 32 characters -- generate one with `openssl rand -base64 32`.");
|
|
29
|
+
}
|
|
30
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(password));
|
|
31
|
+
return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
32
|
+
}
|
|
33
|
+
export async function sealJson(payload, password) {
|
|
34
|
+
const key = await deriveKey(password);
|
|
35
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
36
|
+
const plaintext = new TextEncoder().encode(JSON.stringify(payload));
|
|
37
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext));
|
|
38
|
+
const combined = new Uint8Array(iv.length + ciphertext.length);
|
|
39
|
+
combined.set(iv, 0);
|
|
40
|
+
combined.set(ciphertext, iv.length);
|
|
41
|
+
return base64UrlEncode(combined);
|
|
42
|
+
}
|
|
43
|
+
export async function unsealJson(sealed, password) {
|
|
44
|
+
try {
|
|
45
|
+
const key = await deriveKey(password);
|
|
46
|
+
const combined = base64UrlDecode(sealed);
|
|
47
|
+
const iv = combined.slice(0, 12);
|
|
48
|
+
const ciphertext = combined.slice(12);
|
|
49
|
+
const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
|
|
50
|
+
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Tampered, expired-key-rotation, or malformed cookie -- treat as "no session", never throw.
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type OAuthClientConfig } from "@oauth-spa-kit/core";
|
|
2
|
+
import { type SessionConfig } from "./session";
|
|
3
|
+
export interface OAuthHandlersConfig {
|
|
4
|
+
oauth: OAuthClientConfig;
|
|
5
|
+
session: SessionConfig;
|
|
6
|
+
/**
|
|
7
|
+
* How long before actual expiry to proactively refresh, evaluated on every
|
|
8
|
+
* `/auth/session` call and every `getAuthorizationHeader()` call. Same
|
|
9
|
+
* 60s default oidc-client-ts uses for its browser-side expiring timer --
|
|
10
|
+
* enforced here server-side instead, since the browser never sees the
|
|
11
|
+
* token or its expiry in this pattern.
|
|
12
|
+
*/
|
|
13
|
+
refreshThresholdSeconds?: number;
|
|
14
|
+
defaultReturnTo?: string;
|
|
15
|
+
fetchImpl?: typeof fetch;
|
|
16
|
+
}
|
|
17
|
+
export declare function createLoginHandler(config: OAuthHandlersConfig): (request: Request) => Promise<Response>;
|
|
18
|
+
export declare function createCallbackHandler(config: OAuthHandlersConfig): (request: Request) => Promise<Response>;
|
|
19
|
+
export declare function createSessionHandler(config: OAuthHandlersConfig): (request: Request) => Promise<Response>;
|
|
20
|
+
export declare function createLogoutHandler(config: OAuthHandlersConfig): (_request: Request) => Promise<Response>;
|
|
21
|
+
export interface AuthorizationHeaderResult {
|
|
22
|
+
header: string;
|
|
23
|
+
/** Set only when the token was refreshed -- forward this Set-Cookie on your outgoing response. */
|
|
24
|
+
setCookie?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* For the app's *own* backend routes to call upstream resource servers with
|
|
28
|
+
* a valid token, refreshing transparently if needed. This is the
|
|
29
|
+
* server-side analog of oidc-client-ts's `getUser()` -- the difference is
|
|
30
|
+
* the token never crosses back into the browser.
|
|
31
|
+
*/
|
|
32
|
+
export declare function getAuthorizationHeader(request: Request, config: OAuthHandlersConfig): Promise<AuthorizationHeaderResult | null>;
|
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { computeJwkThumbprint, createPkceParams, discoverOidcConfiguration, exchangeAuthorizationCode, exchangeRefreshToken, exportDpopKeyPair, fetchJwks, generateDpopKeyPair, importDpopKeyPair, pushAuthorizationRequest, verifyJwt, OAuthError, } from "@oauth-spa-kit/core";
|
|
2
|
+
import { clearPkceStateHeader, readPkceState, writePkceStateHeader } from "./pkceState";
|
|
3
|
+
import { clearSessionHeader, readSession, writeSessionHeader } from "./session";
|
|
4
|
+
async function resolveDiscovery(config) {
|
|
5
|
+
return config.oauth.discoveryDocument
|
|
6
|
+
?? discoverOidcConfiguration(config.oauth.authority, config.fetchImpl);
|
|
7
|
+
}
|
|
8
|
+
/** OIDC Core section 3.1.3.7 -- verify the id_token's signature and standard claims via the AS's JWKS before trusting anything in it. */
|
|
9
|
+
async function verifyIdToken(idToken, discovery, config, expectedNonce) {
|
|
10
|
+
if (!idToken)
|
|
11
|
+
throw new OAuthError("Token response did not include an id_token");
|
|
12
|
+
if (!discovery.jwks_uri)
|
|
13
|
+
throw new OAuthError("Discovery document has no jwks_uri -- cannot verify id_token");
|
|
14
|
+
const jwks = await fetchJwks(discovery.jwks_uri, config.fetchImpl);
|
|
15
|
+
const { payload } = await verifyJwt({
|
|
16
|
+
token: idToken,
|
|
17
|
+
jwks,
|
|
18
|
+
expectedIssuer: discovery.issuer,
|
|
19
|
+
expectedAudience: config.oauth.clientId,
|
|
20
|
+
expectedNonce,
|
|
21
|
+
});
|
|
22
|
+
return payload;
|
|
23
|
+
}
|
|
24
|
+
export function createLoginHandler(config) {
|
|
25
|
+
return async function loginHandler(request) {
|
|
26
|
+
const discovery = await resolveDiscovery(config);
|
|
27
|
+
const pkce = await createPkceParams();
|
|
28
|
+
const returnTo = new URL(request.url).searchParams.get("returnTo") ?? config.defaultReturnTo ?? "/";
|
|
29
|
+
// Generated here, not at the callback -- FAPI 2.0's `dpop_jkt` binds the
|
|
30
|
+
// authorization code itself to this key before any token exists, so
|
|
31
|
+
// the same key has to exist before the (pushed) authorization request
|
|
32
|
+
// goes out, and gets carried through the PKCE cookie to the callback.
|
|
33
|
+
const dpopEnabled = config.oauth.dpop !== false;
|
|
34
|
+
const dpopKeyPair = dpopEnabled ? await generateDpopKeyPair() : undefined;
|
|
35
|
+
const authParams = {
|
|
36
|
+
response_type: "code",
|
|
37
|
+
redirect_uri: config.oauth.redirectUri,
|
|
38
|
+
scope: config.oauth.scope,
|
|
39
|
+
state: pkce.state,
|
|
40
|
+
nonce: pkce.nonce,
|
|
41
|
+
code_challenge: pkce.codeChallenge,
|
|
42
|
+
code_challenge_method: pkce.codeChallengeMethod,
|
|
43
|
+
...(config.oauth.extraAuthorizationParams ?? {}),
|
|
44
|
+
};
|
|
45
|
+
if (dpopKeyPair) {
|
|
46
|
+
authParams.dpop_jkt = await computeJwkThumbprint(dpopKeyPair.publicKey);
|
|
47
|
+
}
|
|
48
|
+
const parEnabled = config.oauth.par !== false;
|
|
49
|
+
const authorizeUrl = new URL(discovery.authorization_endpoint);
|
|
50
|
+
authorizeUrl.searchParams.set("client_id", config.oauth.clientId);
|
|
51
|
+
if (parEnabled) {
|
|
52
|
+
if (!discovery.pushed_authorization_request_endpoint) {
|
|
53
|
+
throw new OAuthError("par is enabled (the default) but the discovery document has no pushed_authorization_request_endpoint -- "
|
|
54
|
+
+ "set oauth.par = false to fall back to a plain /authorize redirect if your AS doesn't support PAR.");
|
|
55
|
+
}
|
|
56
|
+
const pushed = await pushAuthorizationRequest({
|
|
57
|
+
parEndpoint: discovery.pushed_authorization_request_endpoint,
|
|
58
|
+
clientId: config.oauth.clientId,
|
|
59
|
+
clientAuthentication: config.oauth.clientAuthentication,
|
|
60
|
+
assertionAudience: discovery.pushed_authorization_request_endpoint,
|
|
61
|
+
params: authParams,
|
|
62
|
+
fetchImpl: config.fetchImpl,
|
|
63
|
+
});
|
|
64
|
+
authorizeUrl.searchParams.set("request_uri", pushed.request_uri);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
for (const [key, value] of Object.entries(authParams)) {
|
|
68
|
+
authorizeUrl.searchParams.set(key, value);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const setCookie = await writePkceStateHeader({
|
|
72
|
+
codeVerifier: pkce.codeVerifier,
|
|
73
|
+
state: pkce.state,
|
|
74
|
+
nonce: pkce.nonce,
|
|
75
|
+
returnTo,
|
|
76
|
+
dpopKeyPair: dpopKeyPair ? await exportDpopKeyPair(dpopKeyPair) : undefined,
|
|
77
|
+
}, config.session.password);
|
|
78
|
+
return new Response(null, {
|
|
79
|
+
status: 302,
|
|
80
|
+
headers: { Location: authorizeUrl.toString(), "Set-Cookie": setCookie },
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export function createCallbackHandler(config) {
|
|
85
|
+
return async function callbackHandler(request) {
|
|
86
|
+
const url = new URL(request.url);
|
|
87
|
+
const error = url.searchParams.get("error");
|
|
88
|
+
if (error)
|
|
89
|
+
return new Response(`OAuth error: ${error}`, { status: 400 });
|
|
90
|
+
const code = url.searchParams.get("code");
|
|
91
|
+
const state = url.searchParams.get("state");
|
|
92
|
+
const pkce = await readPkceState(request, config.session.password);
|
|
93
|
+
if (!code || !state || !pkce || state !== pkce.state) {
|
|
94
|
+
return new Response("Invalid or expired OAuth state -- restart login.", { status: 400 });
|
|
95
|
+
}
|
|
96
|
+
const discovery = await resolveDiscovery(config);
|
|
97
|
+
const dpopKeyPair = pkce.dpopKeyPair ? await importDpopKeyPair(pkce.dpopKeyPair) : undefined;
|
|
98
|
+
// Token exchange and id_token verification talk to the IdP and to
|
|
99
|
+
// untrusted-until-verified JWT parsing -- both are expected to fail
|
|
100
|
+
// sometimes (a replayed/expired code, a misconfigured JWKS). Catch here
|
|
101
|
+
// so the caller always gets back a Response, never an uncaught
|
|
102
|
+
// rejection a raw Web-standard fetch handler has no way to turn into
|
|
103
|
+
// one itself.
|
|
104
|
+
try {
|
|
105
|
+
const tokens = await exchangeAuthorizationCode({
|
|
106
|
+
config: config.oauth,
|
|
107
|
+
tokenEndpoint: discovery.token_endpoint,
|
|
108
|
+
code,
|
|
109
|
+
codeVerifier: pkce.codeVerifier,
|
|
110
|
+
dpopKeyPair,
|
|
111
|
+
fetchImpl: config.fetchImpl,
|
|
112
|
+
});
|
|
113
|
+
const user = await verifyIdToken(tokens.idToken, discovery, config, pkce.nonce);
|
|
114
|
+
const headers = new Headers({ Location: pkce.returnTo });
|
|
115
|
+
headers.append("Set-Cookie", await writeSessionHeader({ tokens, user, dpopKeyPair: pkce.dpopKeyPair }, config.session));
|
|
116
|
+
headers.append("Set-Cookie", clearPkceStateHeader());
|
|
117
|
+
return new Response(null, { status: 302, headers });
|
|
118
|
+
}
|
|
119
|
+
catch (cause) {
|
|
120
|
+
const message = cause instanceof Error ? cause.message : "Unknown error";
|
|
121
|
+
return new Response(`Login failed: ${message}`, { status: 400, headers: { "Set-Cookie": clearPkceStateHeader() } });
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export function createSessionHandler(config) {
|
|
126
|
+
return async function sessionHandler(request) {
|
|
127
|
+
const session = await readSession(request, config.session);
|
|
128
|
+
if (!session) {
|
|
129
|
+
return new Response(JSON.stringify({ user: null }), {
|
|
130
|
+
status: 401,
|
|
131
|
+
headers: { "content-type": "application/json" },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const thresholdMs = (config.refreshThresholdSeconds ?? 60) * 1000;
|
|
135
|
+
const expiringSoon = session.tokens.expiresAt !== null
|
|
136
|
+
&& session.tokens.expiresAt - Date.now() < thresholdMs;
|
|
137
|
+
if (!expiringSoon) {
|
|
138
|
+
return new Response(JSON.stringify({ user: session.user }), {
|
|
139
|
+
status: 200,
|
|
140
|
+
headers: { "content-type": "application/json" },
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (!session.tokens.refreshToken) {
|
|
144
|
+
return new Response(JSON.stringify({ user: null }), {
|
|
145
|
+
status: 401,
|
|
146
|
+
headers: { "content-type": "application/json", "Set-Cookie": clearSessionHeader(config.session) },
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const discovery = await resolveDiscovery(config);
|
|
151
|
+
const dpopKeyPair = session.dpopKeyPair ? await importDpopKeyPair(session.dpopKeyPair) : undefined;
|
|
152
|
+
session.tokens = await exchangeRefreshToken({
|
|
153
|
+
config: config.oauth,
|
|
154
|
+
tokenEndpoint: discovery.token_endpoint,
|
|
155
|
+
refreshToken: session.tokens.refreshToken,
|
|
156
|
+
dpopKeyPair,
|
|
157
|
+
fetchImpl: config.fetchImpl,
|
|
158
|
+
});
|
|
159
|
+
const setCookie = await writeSessionHeader(session, config.session);
|
|
160
|
+
return new Response(JSON.stringify({ user: session.user }), {
|
|
161
|
+
status: 200,
|
|
162
|
+
headers: { "content-type": "application/json", "Set-Cookie": setCookie },
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// Refresh token invalid, rotated-and-reused, or revoked -- force a
|
|
167
|
+
// real re-login rather than silently keep serving a stale session.
|
|
168
|
+
return new Response(JSON.stringify({ user: null }), {
|
|
169
|
+
status: 401,
|
|
170
|
+
headers: { "content-type": "application/json", "Set-Cookie": clearSessionHeader(config.session) },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
export function createLogoutHandler(config) {
|
|
176
|
+
// Takes a Request, unused, purely so all four handlers share the same
|
|
177
|
+
// `(Request) => Promise<Response>` shape for callers that dispatch on a
|
|
178
|
+
// uniform signature (see examples/react-spa/server.ts).
|
|
179
|
+
return async function logoutHandler(_request) {
|
|
180
|
+
const headers = new Headers({ "content-type": "application/json" });
|
|
181
|
+
headers.append("Set-Cookie", clearSessionHeader(config.session));
|
|
182
|
+
const discovery = await resolveDiscovery(config).catch(() => null);
|
|
183
|
+
if (discovery?.end_session_endpoint && config.oauth.postLogoutRedirectUri) {
|
|
184
|
+
const endSessionUrl = new URL(discovery.end_session_endpoint);
|
|
185
|
+
endSessionUrl.searchParams.set("client_id", config.oauth.clientId);
|
|
186
|
+
endSessionUrl.searchParams.set("post_logout_redirect_uri", config.oauth.postLogoutRedirectUri);
|
|
187
|
+
headers.set("Location", endSessionUrl.toString());
|
|
188
|
+
return new Response(null, { status: 302, headers });
|
|
189
|
+
}
|
|
190
|
+
return new Response(JSON.stringify({ loggedOut: true }), { status: 200, headers });
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* For the app's *own* backend routes to call upstream resource servers with
|
|
195
|
+
* a valid token, refreshing transparently if needed. This is the
|
|
196
|
+
* server-side analog of oidc-client-ts's `getUser()` -- the difference is
|
|
197
|
+
* the token never crosses back into the browser.
|
|
198
|
+
*/
|
|
199
|
+
export async function getAuthorizationHeader(request, config) {
|
|
200
|
+
const session = await readSession(request, config.session);
|
|
201
|
+
if (!session)
|
|
202
|
+
return null;
|
|
203
|
+
const thresholdMs = (config.refreshThresholdSeconds ?? 60) * 1000;
|
|
204
|
+
const expiringSoon = session.tokens.expiresAt !== null
|
|
205
|
+
&& session.tokens.expiresAt - Date.now() < thresholdMs;
|
|
206
|
+
if (expiringSoon && session.tokens.refreshToken) {
|
|
207
|
+
const discovery = await resolveDiscovery(config);
|
|
208
|
+
const dpopKeyPair = session.dpopKeyPair ? await importDpopKeyPair(session.dpopKeyPair) : undefined;
|
|
209
|
+
session.tokens = await exchangeRefreshToken({
|
|
210
|
+
config: config.oauth,
|
|
211
|
+
tokenEndpoint: discovery.token_endpoint,
|
|
212
|
+
refreshToken: session.tokens.refreshToken,
|
|
213
|
+
dpopKeyPair,
|
|
214
|
+
fetchImpl: config.fetchImpl,
|
|
215
|
+
});
|
|
216
|
+
const setCookie = await writeSessionHeader(session, config.session);
|
|
217
|
+
return { header: `${session.tokens.tokenType} ${session.tokens.accessToken}`, setCookie };
|
|
218
|
+
}
|
|
219
|
+
return { header: `${session.tokens.tokenType} ${session.tokens.accessToken}` };
|
|
220
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { SerializedDpopKeyPair } from "@oauth-spa-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* Holds the PKCE verifier + state + nonce for the ~seconds it takes the
|
|
4
|
+
* browser to round-trip through the IdP. A short-lived signed cookie
|
|
5
|
+
* instead of server-side memory keeps the BFF stateless (works fine behind
|
|
6
|
+
* a load balancer with no sticky sessions / shared store).
|
|
7
|
+
*/
|
|
8
|
+
export interface PkceState {
|
|
9
|
+
codeVerifier: string;
|
|
10
|
+
state: string;
|
|
11
|
+
nonce: string;
|
|
12
|
+
returnTo: string;
|
|
13
|
+
/**
|
|
14
|
+
* Generated at login time (not callback time) so its thumbprint can be
|
|
15
|
+
* sent as `dpop_jkt` in the (pushed) authorization request, binding the
|
|
16
|
+
* authorization code itself to this key -- RFC 9449 section 10. The same
|
|
17
|
+
* key pair is then reused for the token exchange and carried into the
|
|
18
|
+
* session for every subsequent refresh (a DPoP-bound refresh token must
|
|
19
|
+
* be renewed with the key that obtained it).
|
|
20
|
+
*/
|
|
21
|
+
dpopKeyPair?: SerializedDpopKeyPair;
|
|
22
|
+
}
|
|
23
|
+
export declare function writePkceStateHeader(pkce: PkceState, password: string): Promise<string>;
|
|
24
|
+
export declare function readPkceState(request: Request, password: string): Promise<PkceState | null>;
|
|
25
|
+
export declare function clearPkceStateHeader(): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { sealJson, unsealJson } from "./crypto";
|
|
2
|
+
import { parseCookies, serializeCookie, expireCookie } from "./cookies";
|
|
3
|
+
const COOKIE_NAME = "__oauth_pkce";
|
|
4
|
+
const MAX_AGE_SECONDS = 5 * 60;
|
|
5
|
+
export async function writePkceStateHeader(pkce, password) {
|
|
6
|
+
const sealed = await sealJson(pkce, password);
|
|
7
|
+
return serializeCookie(COOKIE_NAME, sealed, { maxAgeSeconds: MAX_AGE_SECONDS });
|
|
8
|
+
}
|
|
9
|
+
export async function readPkceState(request, password) {
|
|
10
|
+
const raw = parseCookies(request)[COOKIE_NAME];
|
|
11
|
+
if (!raw)
|
|
12
|
+
return null;
|
|
13
|
+
return unsealJson(raw, password);
|
|
14
|
+
}
|
|
15
|
+
export function clearPkceStateHeader() {
|
|
16
|
+
return expireCookie(COOKIE_NAME);
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AuthenticatedUser, SerializedDpopKeyPair, TokenSet } from "@oauth-spa-kit/core";
|
|
2
|
+
export interface StoredSession {
|
|
3
|
+
tokens: TokenSet;
|
|
4
|
+
user: AuthenticatedUser;
|
|
5
|
+
/** The exact key pair the tokens are DPoP-bound to -- reused for every refresh. Absent only if `config.oauth.dpop === false`. */
|
|
6
|
+
dpopKeyPair?: SerializedDpopKeyPair;
|
|
7
|
+
}
|
|
8
|
+
export interface SessionConfig {
|
|
9
|
+
/** >=32 char secret. Load from env (`OAUTH_SESSION_PASSWORD`); rotate by supporting two passwords during migration if you need zero-downtime rotation. */
|
|
10
|
+
password: string;
|
|
11
|
+
cookieName?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Hard ceiling on the *session* cookie's own lifetime, independent of the
|
|
14
|
+
* access token's `expiresAt`. Should comfortably exceed your refresh
|
|
15
|
+
* token's lifetime -- the cookie merely carries the (still-expiring)
|
|
16
|
+
* refresh token; it isn't itself a trust boundary extension.
|
|
17
|
+
*/
|
|
18
|
+
maxAgeSeconds?: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function readSession(request: Request, config: SessionConfig): Promise<StoredSession | null>;
|
|
21
|
+
export declare function writeSessionHeader(session: StoredSession, config: SessionConfig): Promise<string>;
|
|
22
|
+
export declare function clearSessionHeader(config: SessionConfig): string;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { sealJson, unsealJson } from "./crypto";
|
|
2
|
+
import { parseCookies, serializeCookie, expireCookie } from "./cookies";
|
|
3
|
+
const DEFAULTS = { cookieName: "__session", maxAgeSeconds: 30 * 24 * 60 * 60 };
|
|
4
|
+
export async function readSession(request, config) {
|
|
5
|
+
const cookieName = config.cookieName ?? DEFAULTS.cookieName;
|
|
6
|
+
const raw = parseCookies(request)[cookieName];
|
|
7
|
+
if (!raw)
|
|
8
|
+
return null;
|
|
9
|
+
return unsealJson(raw, config.password);
|
|
10
|
+
}
|
|
11
|
+
export async function writeSessionHeader(session, config) {
|
|
12
|
+
const sealed = await sealJson(session, config.password);
|
|
13
|
+
return serializeCookie(config.cookieName ?? DEFAULTS.cookieName, sealed, {
|
|
14
|
+
maxAgeSeconds: config.maxAgeSeconds ?? DEFAULTS.maxAgeSeconds,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export function clearSessionHeader(config) {
|
|
18
|
+
return expireCookie(config.cookieName ?? DEFAULTS.cookieName);
|
|
19
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oauth-spa-kit/server",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "BFF-pattern OAuth handlers: sealed HttpOnly-cookie sessions + login/callback/refresh/logout route factories, built on Web-standard Request/Response so they drop into Nitro, Next.js route handlers, Cloudflare Workers, or plain Node (via a small adapter).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ehncraft/oauth-spa-kit.git",
|
|
9
|
+
"directory": "packages/server"
|
|
10
|
+
},
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@oauth-spa-kit/core": "1.0.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^5.6.0",
|
|
29
|
+
"vitest": "^2.1.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.json",
|
|
33
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
34
|
+
"test": "vitest run --root ../.. packages/server/test"
|
|
35
|
+
}
|
|
36
|
+
}
|