@evup/auth 0.0.0-stage → 0.2.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +793 -2
  4. package/dist/astro/index.d.ts +22 -0
  5. package/dist/astro/index.js +34 -0
  6. package/dist/astro/integration-middleware.d.ts +1 -0
  7. package/dist/astro/integration-middleware.js +3 -0
  8. package/dist/astro/middleware.d.ts +9 -0
  9. package/dist/astro/middleware.js +36 -0
  10. package/dist/astro/route.d.ts +3 -0
  11. package/dist/astro/route.js +6 -0
  12. package/dist/astro/runtime.d.ts +8 -0
  13. package/dist/astro/runtime.js +58 -0
  14. package/dist/client/index.d.ts +15 -0
  15. package/dist/client/index.js +34 -0
  16. package/dist/errors.d.ts +11 -0
  17. package/dist/errors.js +12 -0
  18. package/dist/hono/index.d.ts +26 -0
  19. package/dist/hono/index.js +53 -0
  20. package/dist/next/index.d.ts +25 -0
  21. package/dist/next/index.js +84 -0
  22. package/dist/next/read.d.ts +7 -0
  23. package/dist/next/read.js +11 -0
  24. package/dist/resource/index.d.ts +48 -0
  25. package/dist/resource/index.js +174 -0
  26. package/dist/server/auth.d.ts +4 -0
  27. package/dist/server/auth.js +386 -0
  28. package/dist/server/config.d.ts +42 -0
  29. package/dist/server/config.js +103 -0
  30. package/dist/server/cookie.d.ts +30 -0
  31. package/dist/server/cookie.js +105 -0
  32. package/dist/server/index.d.ts +5 -0
  33. package/dist/server/index.js +3 -0
  34. package/dist/server/oidc.d.ts +17 -0
  35. package/dist/server/oidc.js +44 -0
  36. package/dist/server/pages.d.ts +3 -0
  37. package/dist/server/pages.js +12 -0
  38. package/dist/server/redirect.d.ts +5 -0
  39. package/dist/server/redirect.js +28 -0
  40. package/dist/server/types.d.ts +109 -0
  41. package/dist/server/types.js +1 -0
  42. package/package.json +86 -4
@@ -0,0 +1,174 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from "jose";
2
+ import { EvupAuthError } from "../errors.js";
3
+ import { DEFAULT_ISSUER, isLoopbackHost } from "../server/config.js";
4
+ export { EvupAuthError } from "../errors.js";
5
+ const METADATA_PREFIX = "/.well-known/oauth-protected-resource";
6
+ const DISCOVERY_TTL_MS = 60 * 60 * 1000;
7
+ const PREFLIGHT = {
8
+ "access-control-allow-origin": "*",
9
+ "access-control-allow-headers": "Authorization, Content-Type, Mcp-Protocol-Version",
10
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
11
+ "access-control-max-age": "86400",
12
+ };
13
+ const CORS = { "access-control-allow-origin": "*", "access-control-expose-headers": "WWW-Authenticate" };
14
+ /** Per isolate: the discovery document and the remote JWKS (jose refetches it on an unknown kid), keyed by fetch implementation and issuer. */
15
+ const state = new WeakMap();
16
+ /** Problems with the presented token. Any other JOSE error (a JWKS that answers non-200, is not JSON or is malformed) is the issuer's fault. */
17
+ const isTokenProblem = (err) => err instanceof errors.JWTClaimValidationFailed ||
18
+ err instanceof errors.JWTExpired ||
19
+ err instanceof errors.JWTInvalid ||
20
+ err instanceof errors.JWSInvalid ||
21
+ err instanceof errors.JWEInvalid ||
22
+ err instanceof errors.JWEDecryptionFailed ||
23
+ err instanceof errors.JWSSignatureVerificationFailed ||
24
+ err instanceof errors.JOSEAlgNotAllowed ||
25
+ err instanceof errors.JOSENotSupported ||
26
+ err instanceof errors.JWKSNoMatchingKey ||
27
+ err instanceof errors.JWKSMultipleMatchingKeys;
28
+ const scopeList = (value) => (typeof value === "string" ? value.split(" ").filter(Boolean) : []);
29
+ /** Same format as the IdP's own challenge (src/lib/mcp/access.ts): error, error_description, scope, resource_metadata. */
30
+ function challenge(prm, opts = {}) {
31
+ const attrs = [];
32
+ if (opts.error)
33
+ attrs.push(`error="${opts.error}"`);
34
+ if (opts.description)
35
+ attrs.push(`error_description="${opts.description.replace(/["\\]/g, "")}"`);
36
+ if (opts.scope)
37
+ attrs.push(`scope="${opts.scope}"`);
38
+ attrs.push(`resource_metadata="${prm}"`);
39
+ return `Bearer ${attrs.join(", ")}`;
40
+ }
41
+ function bearerToken(input) {
42
+ const raw = typeof input === "string" ? input : input.headers.get("authorization");
43
+ if (!raw)
44
+ return null;
45
+ const value = raw.trim();
46
+ if (/^bearer$/i.test(value))
47
+ return null;
48
+ const match = /^bearer\s+(.+)$/i.exec(value);
49
+ // A request must use the Bearer scheme; a bare string is taken as the token itself
50
+ const token = match ? match[1] : typeof input === "string" ? value : null;
51
+ return token?.trim() || null;
52
+ }
53
+ export function createEvupResource(config) {
54
+ let resourceUrl;
55
+ try {
56
+ resourceUrl = new URL(config.resource);
57
+ }
58
+ catch {
59
+ throw new EvupAuthError("config", `resource must be an absolute URL, got "${config.resource}"`);
60
+ }
61
+ if (resourceUrl.protocol !== "https:" && !(resourceUrl.protocol === "http:" && isLoopbackHost(resourceUrl.hostname))) {
62
+ throw new EvupAuthError("config", "resource must use https (http is allowed for localhost only)");
63
+ }
64
+ const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
65
+ const required = config.scopes ?? [];
66
+ const tolerance = config.clockTolerance ?? 30;
67
+ const pathname = resourceUrl.pathname === "/" ? "" : resourceUrl.pathname.replace(/\/+$/, "");
68
+ const metadataPath = `${METADATA_PREFIX}${pathname}`;
69
+ const prmUrl = `${resourceUrl.origin}${metadataPath}`;
70
+ const fetchImpl = (url, init) => (config.fetch ?? fetch)(url, init);
71
+ const cacheKey = config.fetch ?? globalThis;
72
+ async function keys() {
73
+ let perFetch = state.get(cacheKey);
74
+ if (!perFetch)
75
+ state.set(cacheKey, (perFetch = new Map()));
76
+ const hit = perFetch.get(issuer);
77
+ if (hit && hit.discovery.until > Date.now())
78
+ return hit;
79
+ try {
80
+ const issuerUrl = new URL(issuer);
81
+ if (issuerUrl.protocol !== "https:" && !isLoopbackHost(issuerUrl.hostname))
82
+ throw new Error("issuer must use https");
83
+ const res = await fetchImpl(`${issuer}/.well-known/openid-configuration`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
84
+ if (!res.ok)
85
+ throw new Error(`discovery answered ${res.status}`);
86
+ const doc = (await res.json());
87
+ if (doc.issuer !== issuer)
88
+ throw new Error("the discovery issuer does not match the configured issuer");
89
+ if (typeof doc.jwks_uri !== "string")
90
+ throw new Error("discovery has no jwks_uri");
91
+ const algs = Array.isArray(doc.id_token_signing_alg_values_supported) ? doc.id_token_signing_alg_values_supported.filter((a) => typeof a === "string" && a !== "none") : [];
92
+ const discovery = { jwksUri: doc.jwks_uri, algorithms: algs.length ? algs : ["EdDSA"], until: Date.now() + DISCOVERY_TTL_MS };
93
+ const entry = { discovery, keys: createRemoteJWKSet(new URL(doc.jwks_uri), { [customFetch]: fetchImpl }) };
94
+ perFetch.set(issuer, entry);
95
+ return entry;
96
+ }
97
+ catch (cause) {
98
+ throw new EvupAuthError("discovery_failed", `Could not load the OpenID configuration of ${issuer}`, { cause });
99
+ }
100
+ }
101
+ const metadata = () => ({
102
+ resource: config.resource,
103
+ authorization_servers: [issuer],
104
+ ...(required.length ? { scopes_supported: required } : {}),
105
+ bearer_methods_supported: ["header"],
106
+ ...(config.resourceName ? { resource_name: config.resourceName } : {}),
107
+ });
108
+ function metadataResponse() {
109
+ return new Response(JSON.stringify(metadata()), { status: 200, headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", ...CORS } });
110
+ }
111
+ function failure(status, error, description, www) {
112
+ const response = new Response(JSON.stringify({ error, error_description: description }), {
113
+ status,
114
+ headers: { "content-type": "application/json", "cache-control": "no-store", "www-authenticate": www, ...CORS },
115
+ });
116
+ return { ok: false, status, response };
117
+ }
118
+ async function verify(input) {
119
+ const scopeAttr = required.length ? required.join(" ") : undefined;
120
+ const raw = bearerToken(input);
121
+ if (!raw)
122
+ return failure(401, "invalid_token", "A Bearer access token is required", challenge(prmUrl, { scope: scopeAttr }));
123
+ const invalid = (description) => failure(401, "invalid_token", description, challenge(prmUrl, { error: "invalid_token", description, scope: scopeAttr }));
124
+ const { discovery, keys: jwks } = await keys();
125
+ let payload;
126
+ try {
127
+ // Mirrors the IdP's own resource server (src/lib/mcp/token.ts): typ at+jwt, exact iss, aud contains the resource
128
+ ({ payload } = await jwtVerify(raw, jwks, {
129
+ issuer,
130
+ audience: config.resource,
131
+ typ: "at+jwt",
132
+ algorithms: discovery.algorithms,
133
+ requiredClaims: ["sub", "exp", "azp", "scope"],
134
+ clockTolerance: tolerance,
135
+ }));
136
+ }
137
+ catch (err) {
138
+ if (err instanceof errors.JWTExpired)
139
+ return invalid("The access token has expired");
140
+ // Unreachable, non-200, non-JSON or malformed JWKS is the issuer's problem, not the caller's: surface it as a server error
141
+ if (!isTokenProblem(err))
142
+ throw new EvupAuthError("discovery_failed", "Could not fetch the signing keys of the issuer", { cause: err });
143
+ return invalid("The access token is invalid");
144
+ }
145
+ // A DPoP-bound token (cnf) is refused: proof of possession is not checked here, so accepting it would drop the binding
146
+ if ("cnf" in payload)
147
+ return invalid("Sender-constrained tokens are not supported");
148
+ const { sub, azp, scope, exp } = payload;
149
+ if (typeof sub !== "string" || typeof azp !== "string" || typeof scope !== "string" || typeof exp !== "number")
150
+ return invalid("The access token is invalid");
151
+ const granted = scopeList(scope);
152
+ if (required.some((s) => !granted.includes(s))) {
153
+ const description = `The access token lacks a required scope: ${required.join(" ")}`;
154
+ return failure(403, "insufficient_scope", description, challenge(prmUrl, { error: "insufficient_scope", description, scope: required.join(" ") }));
155
+ }
156
+ const permissions = Array.isArray(payload.permissions) ? payload.permissions.filter((p) => typeof p === "string") : [];
157
+ return { ok: true, token: { sub, clientId: azp, scopes: granted, permissions, exp, claims: payload } };
158
+ }
159
+ return {
160
+ metadataPath,
161
+ metadata,
162
+ metadataResponse,
163
+ preflightResponse: () => new Response(null, { status: 204, headers: PREFLIGHT }),
164
+ verify,
165
+ async handle(req, next) {
166
+ if (req.method === "OPTIONS")
167
+ return new Response(null, { status: 204, headers: PREFLIGHT });
168
+ if (new URL(req.url).pathname.replace(/\/+$/, "") === metadataPath && (req.method === "GET" || req.method === "HEAD"))
169
+ return metadataResponse();
170
+ const result = await verify(req);
171
+ return result.ok ? next(req, result.token) : result.response;
172
+ },
173
+ };
174
+ }
@@ -0,0 +1,4 @@
1
+ import type { EvupAuth, EvupAuthConfig, EvupUser } from "./types.js";
2
+ /** The app-facing user from id_token claims merged with userinfo. */
3
+ export declare function userFromClaims(claims: Record<string, unknown>): EvupUser;
4
+ export declare function createEvupAuth(config: EvupAuthConfig): EvupAuth;
@@ -0,0 +1,386 @@
1
+ import * as oauth from "oauth4webapi";
2
+ import { EvupAuthError } from "../errors.js";
3
+ import { checkStatic, normaliseBasePath, resolveSettings, TX_COOKIE, TX_TTL_SECONDS } from "./config.js";
4
+ import { readCookie, seal, SESSION_INFO, serializeCookie, TRANSACTION_INFO, unseal } from "./cookie.js";
5
+ import { loadIdp } from "./oidc.js";
6
+ import { accessDeniedPage, signInFailedPage } from "./pages.js";
7
+ import { safeReturnTo } from "./redirect.js";
8
+ /** A refresh starts once the access token has less than this many seconds left. */
9
+ const REFRESH_WINDOW_SECONDS = 60;
10
+ /** Browsers drop cookies near 4096 bytes (name and attributes included). */
11
+ const MAX_COOKIE_VALUE = 3800;
12
+ function asRecord(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
14
+ }
15
+ const str = (v) => (typeof v === "string" && v.length > 0 ? v : undefined);
16
+ /** The app-facing user from id_token claims merged with userinfo. */
17
+ export function userFromClaims(claims) {
18
+ return {
19
+ id: String(claims.sub ?? ""),
20
+ email: str(claims.email) ?? "",
21
+ emailVerified: claims.email_verified === true,
22
+ name: str(claims.name),
23
+ picture: str(claims.picture),
24
+ permissions: Array.isArray(claims.permissions) ? claims.permissions.filter((p) => typeof p === "string") : [],
25
+ claims,
26
+ };
27
+ }
28
+ /** Claims the slimmed-down cookie keeps: enough to rebuild the user. */
29
+ const CORE_CLAIMS = ["sub", "email", "email_verified", "name", "picture", "permissions"];
30
+ /** The user is rebuilt from `claims` on every read, so the cookie stores each value once. */
31
+ function readStored(payload) {
32
+ const claims = asRecord(payload.c);
33
+ if (typeof claims.sub !== "string" || !claims.sub)
34
+ return null;
35
+ if (typeof payload.at !== "string" || typeof payload.ea !== "number" || typeof payload.sc !== "string")
36
+ return null;
37
+ return {
38
+ user: userFromClaims(claims),
39
+ accessToken: payload.at,
40
+ refreshToken: str(payload.rt),
41
+ expiresAt: payload.ea,
42
+ scope: payload.sc,
43
+ idToken: str(payload.it),
44
+ };
45
+ }
46
+ const wantsJson = (req) => (req.headers.get("accept") ?? "").includes("application/json");
47
+ function toSession(s) {
48
+ return { user: s.user, accessToken: s.accessToken, expiresAt: s.expiresAt, scope: s.scope };
49
+ }
50
+ export function createEvupAuth(config) {
51
+ checkStatic(config);
52
+ const basePath = normaliseBasePath(config.basePath);
53
+ const callbackPath = new URL(config.redirectUri).pathname.replace(/\/+$/, "") || "/";
54
+ // Environment values (Workers bindings) may only exist once a request arrives: resolve lazily, fail early when the value is wrong
55
+ let resolved;
56
+ const first = resolveSettings(config);
57
+ if (first.ok)
58
+ resolved = first.settings;
59
+ else if (!first.missing)
60
+ throw first.error;
61
+ const settings = () => {
62
+ if (resolved)
63
+ return resolved;
64
+ const r = resolveSettings(config);
65
+ if (!r.ok)
66
+ throw r.error;
67
+ return (resolved = r.settings);
68
+ };
69
+ const idp = (s) => loadIdp(s, config.fetch);
70
+ const refreshing = new Map();
71
+ const cookieOptions = (s, maxAge) => ({ maxAge, path: s.cookie.path, domain: s.cookie.domain, sameSite: s.cookie.sameSite, secure: s.cookie.secure });
72
+ const clearSession = (s) => serializeCookie(s.cookie.name, "", cookieOptions(s, 0));
73
+ const clearTx = (s) => serializeCookie(TX_COOKIE, "", { maxAge: 0, path: "/", sameSite: "lax", secure: s.cookie.secure });
74
+ /** Encrypts the session; sheds the id_token, then the extra claims, when the cookie would be too big. */
75
+ async function sealSession(s, stored) {
76
+ const build = (st) => ({ c: st.user.claims, at: st.accessToken, rt: st.refreshToken, ea: st.expiresAt, sc: st.scope, it: st.idToken });
77
+ let value = await seal(build(stored), s.secret, SESSION_INFO, s.cookie.maxAge);
78
+ if (value.length > MAX_COOKIE_VALUE)
79
+ value = await seal(build({ ...stored, idToken: undefined }), s.secret, SESSION_INFO, s.cookie.maxAge);
80
+ if (value.length > MAX_COOKIE_VALUE) {
81
+ const claims = Object.fromEntries(CORE_CLAIMS.filter((k) => k in stored.user.claims).map((k) => [k, stored.user.claims[k]]));
82
+ const slim = { ...stored, idToken: undefined, user: { ...stored.user, claims } };
83
+ value = await seal(build(slim), s.secret, SESSION_INFO, s.cookie.maxAge);
84
+ }
85
+ if (value.length > MAX_COOKIE_VALUE)
86
+ throw new EvupAuthError("callback_failed", "The session is too large to store in a cookie");
87
+ return serializeCookie(s.cookie.name, value, cookieOptions(s, s.cookie.maxAge));
88
+ }
89
+ async function readSession(req, s) {
90
+ const raw = readCookie(req, s.cookie.name);
91
+ if (!raw)
92
+ return { stored: null, present: false };
93
+ const payload = await unseal(raw, s.secret, SESSION_INFO);
94
+ return { stored: payload ? readStored(payload) : null, present: true };
95
+ }
96
+ async function refresh(s, stored) {
97
+ const token = stored.refreshToken;
98
+ const running = refreshing.get(token);
99
+ if (running)
100
+ return running;
101
+ const job = (async () => {
102
+ try {
103
+ const { as, client, clientAuth, http } = await idp(s);
104
+ const res = await oauth.refreshTokenGrantRequest(as, client, clientAuth, token, http);
105
+ const result = await oauth.processRefreshTokenResponse(as, client, res);
106
+ const idClaims = result.id_token ? oauth.getValidatedIdTokenClaims(result) : undefined;
107
+ return {
108
+ user: idClaims ? userFromClaims({ ...stored.user.claims, ...idClaims }) : stored.user,
109
+ accessToken: result.access_token,
110
+ refreshToken: result.refresh_token ?? token,
111
+ expiresAt: Date.now() + (result.expires_in ?? 3600) * 1000,
112
+ scope: result.scope ?? stored.scope,
113
+ idToken: result.id_token ?? stored.idToken,
114
+ };
115
+ }
116
+ catch (err) {
117
+ // Any 4xx OAuth error (invalid_grant: revoked, banned, no longer allowed; invalid_client, invalid_scope, invalid_request...)
118
+ // means this refresh token will never work again. Only network failures, timeouts, 5xx and 408/429 are worth a retry.
119
+ if (err instanceof oauth.WWWAuthenticateChallengeError)
120
+ return "invalid";
121
+ if (err instanceof oauth.ResponseBodyError && err.status >= 400 && err.status < 500 && err.status !== 408 && err.status !== 429)
122
+ return "invalid";
123
+ return "error";
124
+ }
125
+ })().finally(() => refreshing.delete(token));
126
+ refreshing.set(token, job);
127
+ return job;
128
+ }
129
+ async function getSession(req, opts = {}) {
130
+ const s = settings();
131
+ const headers = new Headers();
132
+ const { stored, present } = await readSession(req, s);
133
+ if (!stored) {
134
+ if (present)
135
+ headers.append("set-cookie", clearSession(s));
136
+ return { session: null, headers };
137
+ }
138
+ const now = Date.now();
139
+ if (stored.expiresAt - now > (opts.refreshWindow ?? REFRESH_WINDOW_SECONDS) * 1000)
140
+ return { session: toSession(stored), headers };
141
+ if (opts.refresh === false && stored.refreshToken)
142
+ return { session: toSession(stored), headers };
143
+ if (!stored.refreshToken) {
144
+ if (stored.expiresAt > now)
145
+ return { session: toSession(stored), headers };
146
+ headers.append("set-cookie", clearSession(s));
147
+ return { session: null, headers };
148
+ }
149
+ const next = await refresh(s, stored);
150
+ if (next === "invalid") {
151
+ headers.append("set-cookie", clearSession(s));
152
+ return { session: null, headers };
153
+ }
154
+ if (next === "error") {
155
+ // The IdP could not be reached or answered with a server error: keep the cookie, retry on the next request
156
+ return { session: stored.expiresAt > now ? toSession(stored) : null, headers };
157
+ }
158
+ headers.append("set-cookie", await sealSession(s, next));
159
+ return { session: toSession(next), headers };
160
+ }
161
+ async function signIn(_req, opts = {}) {
162
+ const s = settings();
163
+ const { as } = await idp(s);
164
+ if (!as.authorization_endpoint)
165
+ throw new EvupAuthError("discovery_failed", "The IdP metadata has no authorization_endpoint");
166
+ const state = oauth.generateRandomState();
167
+ const nonce = oauth.generateRandomNonce();
168
+ const verifier = oauth.generateRandomCodeVerifier();
169
+ const url = new URL(as.authorization_endpoint);
170
+ url.searchParams.set("client_id", s.clientId);
171
+ url.searchParams.set("redirect_uri", s.redirectUri.href);
172
+ url.searchParams.set("response_type", "code");
173
+ url.searchParams.set("scope", s.scopes.join(" "));
174
+ url.searchParams.set("state", state);
175
+ url.searchParams.set("nonce", nonce);
176
+ url.searchParams.set("code_challenge", await oauth.calculatePKCECodeChallenge(verifier));
177
+ url.searchParams.set("code_challenge_method", "S256");
178
+ for (const r of s.resource)
179
+ url.searchParams.append("resource", r);
180
+ if (opts.prompt)
181
+ url.searchParams.set("prompt", opts.prompt);
182
+ if (opts.locale)
183
+ url.searchParams.set("ui_locales", opts.locale);
184
+ if (opts.loginHint)
185
+ url.searchParams.set("login_hint", opts.loginHint);
186
+ const tx = await seal({ state, nonce, verifier, returnTo: safeReturnTo(opts.returnTo) }, s.secret, TRANSACTION_INFO, TX_TTL_SECONDS);
187
+ const headers = new Headers({ location: url.href, "cache-control": "no-store" });
188
+ headers.append("set-cookie", serializeCookie(TX_COOKIE, tx, { maxAge: TX_TTL_SECONDS, path: "/", sameSite: "lax", secure: s.cookie.secure }));
189
+ return new Response(null, { status: 302, headers });
190
+ }
191
+ async function completeCallback(req, s) {
192
+ const txRaw = readCookie(req, TX_COOKIE);
193
+ const tx = txRaw ? await unseal(txRaw, s.secret, TRANSACTION_INFO) : null;
194
+ if (!tx || typeof tx.state !== "string" || typeof tx.nonce !== "string" || typeof tx.verifier !== "string") {
195
+ throw new EvupAuthError("invalid_state", "The sign-in transaction cookie is missing or expired");
196
+ }
197
+ const { as, client, clientAuth, http } = await idp(s);
198
+ let params;
199
+ try {
200
+ params = oauth.validateAuthResponse(as, client, new URL(req.url), tx.state);
201
+ }
202
+ catch (cause) {
203
+ if (cause instanceof oauth.AuthorizationResponseError) {
204
+ const code = cause.error === "access_denied" ? "access_denied" : "callback_failed";
205
+ throw new EvupAuthError(code, `The IdP returned error=${cause.error}`, { cause, description: cause.error_description });
206
+ }
207
+ throw new EvupAuthError("invalid_state", "The authorization response did not match the sign-in request (state or iss)", { cause });
208
+ }
209
+ let result;
210
+ try {
211
+ const res = await oauth.authorizationCodeGrantRequest(as, client, clientAuth, params, s.redirectUri.href, tx.verifier, http);
212
+ result = await oauth.processAuthorizationCodeResponse(as, client, res, { expectedNonce: tx.nonce, requireIdToken: true });
213
+ }
214
+ catch (cause) {
215
+ const description = cause instanceof oauth.ResponseBodyError ? cause.error_description : undefined;
216
+ throw new EvupAuthError("callback_failed", "The token exchange failed", { cause, description });
217
+ }
218
+ const idClaims = oauth.getValidatedIdTokenClaims(result);
219
+ if (!idClaims)
220
+ throw new EvupAuthError("callback_failed", "The IdP returned no id_token");
221
+ // The id_token carries the identity; profile claims (name, picture) only come from userinfo. A userinfo failure is not fatal.
222
+ let info = {};
223
+ try {
224
+ const res = await oauth.userInfoRequest(as, client, result.access_token, http);
225
+ info = { ...(await oauth.processUserInfoResponse(as, client, idClaims.sub, res)) };
226
+ }
227
+ catch {
228
+ info = {};
229
+ }
230
+ const stored = {
231
+ user: userFromClaims({ ...idClaims, ...info }),
232
+ accessToken: result.access_token,
233
+ refreshToken: result.refresh_token,
234
+ expiresAt: Date.now() + (result.expires_in ?? 3600) * 1000,
235
+ scope: result.scope ?? s.scopes.join(" "),
236
+ idToken: result.id_token,
237
+ };
238
+ const headers = new Headers({ location: safeReturnTo(tx.returnTo), "cache-control": "no-store" });
239
+ headers.append("set-cookie", await sealSession(s, stored));
240
+ headers.append("set-cookie", clearTx(s));
241
+ return new Response(null, { status: 302, headers });
242
+ }
243
+ async function reportError(req, error) {
244
+ try {
245
+ if (config.onError)
246
+ await config.onError(req, error);
247
+ else
248
+ console.error(`[evup-auth] ${error.code}: ${error.message}${error.cause instanceof Error ? ` (${error.cause.message})` : ""}`);
249
+ }
250
+ catch {
251
+ // a failing hook must not turn a handled failure into a 500
252
+ }
253
+ }
254
+ async function callback(req) {
255
+ const s = settings();
256
+ try {
257
+ return await completeCallback(req, s);
258
+ }
259
+ catch (err) {
260
+ const error = err instanceof EvupAuthError ? err : new EvupAuthError("callback_failed", "Unexpected sign-in failure", { cause: err });
261
+ if (error.code === "config")
262
+ throw error;
263
+ let res;
264
+ if (error.code === "access_denied")
265
+ res = config.onAccessDenied ? await config.onAccessDenied(req, error) : accessDeniedPage(basePath);
266
+ else {
267
+ res = signInFailedPage(basePath, error.code === "discovery_failed" ? 502 : 400);
268
+ await reportError(req, error);
269
+ }
270
+ const headers = new Headers(res.headers);
271
+ headers.append("set-cookie", clearTx(s));
272
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
273
+ }
274
+ }
275
+ async function signOut(req, opts = {}) {
276
+ const s = settings();
277
+ const { stored } = await readSession(req, s);
278
+ const headers = new Headers({ "cache-control": "no-store" });
279
+ headers.append("set-cookie", clearSession(s));
280
+ const local = safeReturnTo(opts.returnTo);
281
+ let location = local;
282
+ try {
283
+ const { as, client, clientAuth, http } = await idp(s);
284
+ // A public client cannot authenticate to /oauth2/revoke, so the IdP would refuse the call
285
+ if (stored?.refreshToken && s.clientSecret) {
286
+ try {
287
+ const res = await oauth.revocationRequest(as, client, clientAuth, stored.refreshToken, { ...http, additionalParameters: { token_type_hint: "refresh_token" } });
288
+ await oauth.processRevocationResponse(res);
289
+ }
290
+ catch {
291
+ // best effort: the refresh token also dies with the IdP session
292
+ }
293
+ }
294
+ if (as.end_session_endpoint) {
295
+ const url = new URL(as.end_session_endpoint);
296
+ if (stored?.idToken)
297
+ url.searchParams.set("id_token_hint", stored.idToken);
298
+ url.searchParams.set("client_id", s.clientId);
299
+ if (s.postLogoutRedirectUri)
300
+ url.searchParams.set("post_logout_redirect_uri", s.postLogoutRedirectUri);
301
+ location = url.href;
302
+ }
303
+ }
304
+ catch {
305
+ // IdP unreachable: the local session is gone, which is all that can be done
306
+ }
307
+ headers.set("location", location);
308
+ return new Response(null, { status: 302, headers });
309
+ }
310
+ function sameOrigin(req, s) {
311
+ if (req.headers.get("sec-fetch-site") === "cross-site")
312
+ return false;
313
+ const origin = req.headers.get("origin");
314
+ if (!origin)
315
+ return true;
316
+ return origin === new URL(req.url).origin || origin === s.redirectUri.origin;
317
+ }
318
+ const json = (body, extra) => {
319
+ const headers = new Headers({ "content-type": "application/json", "cache-control": "no-store" });
320
+ for (const [k, v] of extra?.entries() ?? [])
321
+ if (k !== "set-cookie")
322
+ headers.append(k, v);
323
+ for (const c of extra?.getSetCookie() ?? [])
324
+ headers.append("set-cookie", c);
325
+ return new Response(JSON.stringify(body), { status: 200, headers });
326
+ };
327
+ async function handler(req) {
328
+ const url = new URL(req.url);
329
+ const path = url.pathname.replace(/\/+$/, "") || "/";
330
+ const isCallback = path === `${basePath}/callback` || path === callbackPath;
331
+ if (path !== `${basePath}/sign-in` && !isCallback && path !== `${basePath}/sign-out` && path !== `${basePath}/session`)
332
+ return null;
333
+ const method = req.method.toUpperCase();
334
+ const notAllowed = (allow) => new Response("Method Not Allowed", { status: 405, headers: { allow } });
335
+ if (isCallback)
336
+ return method === "GET" ? callback(req) : notAllowed("GET");
337
+ if (path === `${basePath}/sign-in`) {
338
+ if (method !== "GET")
339
+ return notAllowed("GET");
340
+ return signIn(req, {
341
+ returnTo: url.searchParams.get("returnTo") ?? undefined,
342
+ prompt: url.searchParams.get("prompt") ?? undefined,
343
+ locale: url.searchParams.get("locale") ?? undefined,
344
+ loginHint: url.searchParams.get("loginHint") ?? undefined,
345
+ });
346
+ }
347
+ if (path === `${basePath}/session`) {
348
+ if (method !== "GET")
349
+ return notAllowed("GET");
350
+ const { session, headers } = await getSession(req);
351
+ return json({ user: session?.user ?? null }, headers);
352
+ }
353
+ // sign-out: POST only, so a cross-site link or image can never end a session
354
+ if (method !== "POST")
355
+ return notAllowed("POST");
356
+ const s = settings();
357
+ if (!sameOrigin(req, s))
358
+ return new Response("Forbidden", { status: 403 });
359
+ let returnTo = url.searchParams.get("returnTo") ?? undefined;
360
+ if (!returnTo && (req.headers.get("content-type") ?? "").includes("application/x-www-form-urlencoded")) {
361
+ const field = await req
362
+ .formData()
363
+ .then((form) => form.get("returnTo"))
364
+ .catch(() => null);
365
+ returnTo = typeof field === "string" ? field : undefined;
366
+ }
367
+ const res = await signOut(req, { returnTo });
368
+ if (!wantsJson(req))
369
+ return res;
370
+ const headers = new Headers(res.headers);
371
+ const redirectTo = headers.get("location");
372
+ headers.delete("location");
373
+ return json({ redirectTo }, headers);
374
+ }
375
+ return {
376
+ basePath,
377
+ handler,
378
+ signIn,
379
+ callback,
380
+ signOut,
381
+ getSession,
382
+ async getUser(req) {
383
+ return (await getSession(req, { refresh: false })).session?.user ?? null;
384
+ },
385
+ };
386
+ }
@@ -0,0 +1,42 @@
1
+ import { EvupAuthError } from "../errors.js";
2
+ import type { EvupAuthConfig } from "./types.js";
3
+ export declare const DEFAULT_ISSUER = "https://auth.evup.cloud/api/auth";
4
+ export declare const DEFAULT_SCOPES: string[];
5
+ export declare const TX_COOKIE = "evup_tx";
6
+ export declare const TX_TTL_SECONDS = 600;
7
+ export declare const MIN_SECRET_LENGTH = 32;
8
+ export type Settings = {
9
+ clientId: string;
10
+ clientSecret?: string;
11
+ secret: string;
12
+ redirectUri: URL;
13
+ issuer: string;
14
+ scopes: string[];
15
+ resource: string[];
16
+ postLogoutRedirectUri?: string;
17
+ basePath: string;
18
+ cookie: {
19
+ name: string;
20
+ maxAge: number;
21
+ sameSite: "lax" | "none";
22
+ secure: boolean;
23
+ domain?: string;
24
+ path: string;
25
+ };
26
+ /** The issuer is plain http on a loopback host (local development): oauth4webapi must be told to allow it. */
27
+ insecureIssuer: boolean;
28
+ };
29
+ export declare function processEnv(): object;
30
+ export declare function normaliseBasePath(value: string | undefined): string;
31
+ export declare function isLoopbackHost(hostname: string): boolean;
32
+ /** Checks that need no environment: run once when the instance is created. */
33
+ export declare function checkStatic(config: EvupAuthConfig): void;
34
+ /** Merges config with the environment. `missing` tells the caller the failure may fix itself once the environment is available. */
35
+ export declare function resolveSettings(config: EvupAuthConfig): {
36
+ ok: true;
37
+ settings: Settings;
38
+ } | {
39
+ ok: false;
40
+ error: EvupAuthError;
41
+ missing: boolean;
42
+ };