@evup/auth 0.3.1 → 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.
@@ -1,8 +1,8 @@
1
1
  import type { AstroIntegration } from "astro";
2
2
  import type { EvupAuthConfig, EvupUser, Session } from "../server/types.js";
3
- export { createEvupMiddleware } from "./middleware.js";
4
- export type { AuthOrFactory } from "./middleware.js";
5
3
  export type { EvupAuth, EvupAuthConfig, EvupUser, Session } from "../server/types.js";
4
+ export type { AuthOrFactory } from "./middleware.js";
5
+ export { createEvupMiddleware } from "./middleware.js";
6
6
  /**
7
7
  * Options of the integration. They are baked into the server bundle, so the secrets (`secret`, `clientSecret`) and anything
8
8
  * that is not JSON (`onAccessDenied`, `fetch`, `env`) are left out: secrets come from the environment, and the manual form
@@ -11,7 +11,8 @@ export function createEvupMiddleware(authOrFactory) {
11
11
  return next();
12
12
  }
13
13
  // A rejected factory (missing binding, bad config) must not stick: the next request tries again
14
- const pending = (cached ??= (async () => authOrFactory(context))());
14
+ cached ??= (async () => authOrFactory(context))();
15
+ const pending = cached;
15
16
  const auth = await pending.catch((err) => {
16
17
  if (cached === pending)
17
18
  cached = undefined;
@@ -44,11 +44,12 @@ let instance;
44
44
  * then Workers bindings.
45
45
  */
46
46
  export function getAuth(context) {
47
- const pending = (instance ??= (async () => {
47
+ instance ??= (async () => {
48
48
  const processEnv = globalThis.process?.env;
49
49
  const env = { ...onlyStrings(import.meta.env), ...onlyStrings(processEnv), ...(await workersEnv(context)) };
50
50
  return createEvupAuth({ ...config, env });
51
- })());
51
+ })();
52
+ const pending = instance;
52
53
  // A rejected attempt (bad config, missing binding) must not stick: the next request tries again
53
54
  pending.catch(() => {
54
55
  if (instance === pending)
@@ -5,7 +5,8 @@
5
5
  export function evupAuth(authOrFactory) {
6
6
  let cached = typeof authOrFactory === "function" ? undefined : authOrFactory;
7
7
  return async (c, next) => {
8
- const auth = (cached ??= authOrFactory(c));
8
+ cached ??= authOrFactory(c);
9
+ const auth = cached;
9
10
  const served = await auth.handler(c.req.raw);
10
11
  if (served)
11
12
  return served;
package/dist/m2m/index.js CHANGED
@@ -68,7 +68,10 @@ export function createEvupClientCredentials(config) {
68
68
  if (discovery && discovery.until > now())
69
69
  return discovery.tokenEndpoint;
70
70
  try {
71
- const res = await doFetch(`${issuer}/.well-known/openid-configuration`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) });
71
+ const res = await doFetch(`${issuer}/.well-known/openid-configuration`, {
72
+ headers: { accept: "application/json" },
73
+ signal: AbortSignal.timeout(TIMEOUT_MS),
74
+ });
72
75
  if (!res.ok)
73
76
  throw new Error(`discovery answered ${res.status}`);
74
77
  const doc = (await res.json());
@@ -107,7 +110,12 @@ export function createEvupClientCredentials(config) {
107
110
  throw new EvupAuthError("token_request_failed", `token request failed: ${res.status}${oauthError ? ` ${oauthError}` : ""}`, { oauthError, description });
108
111
  }
109
112
  const lifetime = out?.expires_in;
110
- if (typeof out?.access_token !== "string" || !out.access_token || typeof out.token_type !== "string" || out.token_type.toLowerCase() !== "bearer" || typeof lifetime !== "number" || !(lifetime > 0)) {
113
+ if (typeof out?.access_token !== "string" ||
114
+ !out.access_token ||
115
+ typeof out.token_type !== "string" ||
116
+ out.token_type.toLowerCase() !== "bearer" ||
117
+ typeof lifetime !== "number" ||
118
+ !(lifetime > 0)) {
111
119
  throw new EvupAuthError("token_request_failed", "token request failed: invalid token response");
112
120
  }
113
121
  const issuedAt = now();
@@ -74,8 +74,10 @@ export function createEvupResource(config) {
74
74
  const cacheKey = config.fetch ?? globalThis;
75
75
  async function keys() {
76
76
  let perFetch = state.get(cacheKey);
77
- if (!perFetch)
78
- state.set(cacheKey, (perFetch = new Map()));
77
+ if (!perFetch) {
78
+ perFetch = new Map();
79
+ state.set(cacheKey, perFetch);
80
+ }
79
81
  const hit = perFetch.get(issuer);
80
82
  if (hit && hit.discovery.until > Date.now())
81
83
  return hit;
@@ -83,7 +85,10 @@ export function createEvupResource(config) {
83
85
  const issuerUrl = new URL(issuer);
84
86
  if (issuerUrl.protocol !== "https:" && !isLoopbackHost(issuerUrl.hostname))
85
87
  throw new Error("issuer must use https");
86
- const res = await fetchImpl(`${issuer}/.well-known/openid-configuration`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
88
+ const res = await fetchImpl(`${issuer}/.well-known/openid-configuration`, {
89
+ headers: { accept: "application/json" },
90
+ signal: AbortSignal.timeout(10_000),
91
+ });
87
92
  if (!res.ok)
88
93
  throw new Error(`discovery answered ${res.status}`);
89
94
  const doc = (await res.json());
@@ -91,7 +96,9 @@ export function createEvupResource(config) {
91
96
  throw new Error("the discovery issuer does not match the configured issuer");
92
97
  if (typeof doc.jwks_uri !== "string")
93
98
  throw new Error("discovery has no jwks_uri");
94
- 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") : [];
99
+ const algs = Array.isArray(doc.id_token_signing_alg_values_supported)
100
+ ? doc.id_token_signing_alg_values_supported.filter((a) => typeof a === "string" && a !== "none")
101
+ : [];
95
102
  const discovery = { jwksUri: doc.jwks_uri, algorithms: algs.length ? algs : ["EdDSA"], until: Date.now() + DISCOVERY_TTL_MS };
96
103
  const entry = { discovery, keys: createRemoteJWKSet(new URL(doc.jwks_uri), { [customFetch]: fetchImpl }) };
97
104
  perFetch.set(issuer, entry);
@@ -109,7 +116,10 @@ export function createEvupResource(config) {
109
116
  ...(config.resourceName ? { resource_name: config.resourceName } : {}),
110
117
  });
111
118
  function metadataResponse() {
112
- return new Response(JSON.stringify(metadata()), { status: 200, headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", ...CORS } });
119
+ return new Response(JSON.stringify(metadata()), {
120
+ status: 200,
121
+ headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", ...CORS },
122
+ });
113
123
  }
114
124
  function failure(status, error, description, www) {
115
125
  const response = new Response(JSON.stringify({ error, error_description: description }), {
@@ -1,4 +1,15 @@
1
1
  import type { EvupAuth, EvupAuthConfig, EvupUser } from "./types.js";
2
+ /** What the session cookie holds. */
3
+ export type Stored = {
4
+ user: EvupUser;
5
+ accessToken: string;
6
+ refreshToken?: string;
7
+ expiresAt: number;
8
+ scope: string;
9
+ idToken?: string;
10
+ };
2
11
  /** The app-facing user from id_token claims merged with userinfo. */
3
12
  export declare function userFromClaims(claims: Record<string, unknown>): EvupUser;
13
+ /** The session cookie value: a JWE of `stored` that lives `maxAge` seconds; sheds the id_token, then the extra claims, when it would be too big. */
14
+ export declare function sealStored(secret: string, maxAge: number, stored: Stored): Promise<string>;
4
15
  export declare function createEvupAuth(config: EvupAuthConfig): EvupAuth;
@@ -1,7 +1,7 @@
1
1
  import * as oauth from "oauth4webapi";
2
2
  import { EvupAuthError } from "../errors.js";
3
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";
4
+ import { readCookie, SESSION_INFO, seal, serializeCookie, TRANSACTION_INFO, unseal } from "./cookie.js";
5
5
  import { loadIdp } from "./oidc.js";
6
6
  import { accessDeniedPage, signInFailedPage } from "./pages.js";
7
7
  import { safeReturnTo } from "./redirect.js";
@@ -43,6 +43,21 @@ function readStored(payload) {
43
43
  idToken: str(payload.it),
44
44
  };
45
45
  }
46
+ /** The session cookie value: a JWE of `stored` that lives `maxAge` seconds; sheds the id_token, then the extra claims, when it would be too big. */
47
+ export async function sealStored(secret, maxAge, stored) {
48
+ const build = (st) => ({ c: st.user.claims, at: st.accessToken, rt: st.refreshToken, ea: st.expiresAt, sc: st.scope, it: st.idToken });
49
+ let value = await seal(build(stored), secret, SESSION_INFO, maxAge);
50
+ if (value.length > MAX_COOKIE_VALUE)
51
+ value = await seal(build({ ...stored, idToken: undefined }), secret, SESSION_INFO, maxAge);
52
+ if (value.length > MAX_COOKIE_VALUE) {
53
+ const claims = Object.fromEntries(CORE_CLAIMS.filter((k) => k in stored.user.claims).map((k) => [k, stored.user.claims[k]]));
54
+ const slim = { ...stored, idToken: undefined, user: { ...stored.user, claims } };
55
+ value = await seal(build(slim), secret, SESSION_INFO, maxAge);
56
+ }
57
+ if (value.length > MAX_COOKIE_VALUE)
58
+ throw new EvupAuthError("callback_failed", "The session is too large to store in a cookie");
59
+ return value;
60
+ }
46
61
  const wantsJson = (req) => (req.headers.get("accept") ?? "").includes("application/json");
47
62
  function toSession(s) {
48
63
  return { user: s.user, accessToken: s.accessToken, expiresAt: s.expiresAt, scope: s.scope };
@@ -64,27 +79,23 @@ export function createEvupAuth(config) {
64
79
  const r = resolveSettings(config);
65
80
  if (!r.ok)
66
81
  throw r.error;
67
- return (resolved = r.settings);
82
+ resolved = r.settings;
83
+ return resolved;
68
84
  };
69
85
  const idp = (s) => loadIdp(s, config.fetch);
70
86
  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 });
87
+ const cookieOptions = (s, maxAge) => ({
88
+ maxAge,
89
+ path: s.cookie.path,
90
+ domain: s.cookie.domain,
91
+ sameSite: s.cookie.sameSite,
92
+ secure: s.cookie.secure,
93
+ });
72
94
  const clearSession = (s) => serializeCookie(s.cookie.name, "", cookieOptions(s, 0));
73
95
  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. */
96
+ /** Encrypts the session into its Set-Cookie value. */
75
97
  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));
98
+ return serializeCookie(s.cookie.name, await sealStored(s.secret, s.cookie.maxAge, stored), cookieOptions(s, s.cookie.maxAge));
88
99
  }
89
100
  async function readSession(req, s) {
90
101
  const raw = readCookie(req, s.cookie.name);
@@ -284,7 +295,10 @@ export function createEvupAuth(config) {
284
295
  // A public client cannot authenticate to /oauth2/revoke, so the IdP would refuse the call
285
296
  if (stored?.refreshToken && s.clientSecret) {
286
297
  try {
287
- const res = await oauth.revocationRequest(as, client, clientAuth, stored.refreshToken, { ...http, additionalParameters: { token_type_hint: "refresh_token" } });
298
+ const res = await oauth.revocationRequest(as, client, clientAuth, stored.refreshToken, {
299
+ ...http,
300
+ additionalParameters: { token_type_hint: "refresh_token" },
301
+ });
288
302
  await oauth.processRevocationResponse(res);
289
303
  }
290
304
  catch {
@@ -1,7 +1,8 @@
1
1
  import { EvupAuthError } from "../errors.js";
2
- import type { EvupAuthConfig } from "./types.js";
2
+ import type { CookieOptions, EvupAuthConfig } from "./types.js";
3
3
  export declare const DEFAULT_ISSUER = "https://auth.evup.cloud/api/auth";
4
4
  export declare const DEFAULT_SCOPES: string[];
5
+ export declare const DEFAULT_COOKIE_NAME = "evup_session";
5
6
  export declare const TX_COOKIE = "evup_tx";
6
7
  export declare const TX_TTL_SECONDS = 600;
7
8
  export declare const MIN_SECRET_LENGTH = 32;
@@ -31,6 +32,8 @@ export declare function normaliseBasePath(value: string | undefined): string;
31
32
  export declare function isLoopbackHost(hostname: string): boolean;
32
33
  /** Checks that need no environment: run once when the instance is created. */
33
34
  export declare function checkStatic(config: EvupAuthConfig): void;
35
+ export declare function checkCookieOptions(cookie: CookieOptions | undefined): void;
36
+ export declare function checkSecret(secret: string): void;
34
37
  /** Merges config with the environment. `missing` tells the caller the failure may fix itself once the environment is available. */
35
38
  export declare function resolveSettings(config: EvupAuthConfig): {
36
39
  ok: true;
@@ -1,6 +1,7 @@
1
1
  import { EvupAuthError } from "../errors.js";
2
2
  export const DEFAULT_ISSUER = "https://auth.evup.cloud/api/auth";
3
3
  export const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
4
+ export const DEFAULT_COOKIE_NAME = "evup_session";
4
5
  export const TX_COOKIE = "evup_tx";
5
6
  export const TX_TTL_SECONDS = 600;
6
7
  export const MIN_SECRET_LENGTH = 32;
@@ -41,15 +42,21 @@ export function checkStatic(config) {
41
42
  parseAbsolute("issuer", config.issuer);
42
43
  if (config.postLogoutRedirectUri)
43
44
  parseAbsolute("postLogoutRedirectUri", config.postLogoutRedirectUri);
44
- const sameSite = config.cookie?.sameSite;
45
+ checkCookieOptions(config.cookie);
46
+ if (config.secret !== undefined)
47
+ checkSecret(config.secret);
48
+ }
49
+ export function checkCookieOptions(cookie) {
50
+ const sameSite = cookie?.sameSite;
45
51
  if (sameSite !== undefined && sameSite !== "lax" && sameSite !== "none") {
46
52
  throw new EvupAuthError("config", 'cookie.sameSite must be "lax" or "none": "strict" would hide the cookie on the redirect that follows the IdP callback');
47
53
  }
48
- if (sameSite === "none" && config.cookie?.secure === false)
54
+ if (sameSite === "none" && cookie?.secure === false)
49
55
  throw new EvupAuthError("config", 'cookie.sameSite "none" requires a Secure cookie');
50
- if (config.secret !== undefined && config.secret.length < MIN_SECRET_LENGTH) {
56
+ }
57
+ export function checkSecret(secret) {
58
+ if (secret.length < MIN_SECRET_LENGTH)
51
59
  throw new EvupAuthError("config", `secret must be at least ${MIN_SECRET_LENGTH} characters`);
52
- }
53
60
  }
54
61
  /** Merges config with the environment. `missing` tells the caller the failure may fix itself once the environment is available. */
55
62
  export function resolveSettings(config) {
@@ -62,8 +69,7 @@ export function resolveSettings(config) {
62
69
  return { ok: false, missing: true, error: new EvupAuthError("config", "clientId is missing: pass it or set EVUP_CLIENT_ID") };
63
70
  if (!secret)
64
71
  return { ok: false, missing: true, error: new EvupAuthError("config", "secret is missing: pass it or set EVUP_SESSION_SECRET") };
65
- if (secret.length < MIN_SECRET_LENGTH)
66
- throw new EvupAuthError("config", `secret must be at least ${MIN_SECRET_LENGTH} characters`);
72
+ checkSecret(secret);
67
73
  const redirectUri = parseAbsolute("redirectUri", config.redirectUri);
68
74
  const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
69
75
  const issuerUrl = parseAbsolute("issuer", issuer);
@@ -84,7 +90,7 @@ export function resolveSettings(config) {
84
90
  postLogoutRedirectUri: config.postLogoutRedirectUri,
85
91
  basePath: normaliseBasePath(config.basePath),
86
92
  cookie: {
87
- name: config.cookie?.name ?? "evup_session",
93
+ name: config.cookie?.name ?? DEFAULT_COOKIE_NAME,
88
94
  maxAge: config.cookie?.maxAge ?? 30 * 24 * 60 * 60,
89
95
  sameSite: config.cookie?.sameSite ?? "lax",
90
96
  secure: config.cookie?.secure ?? (redirectUri.protocol === "https:" || config.cookie?.sameSite === "none"),
@@ -33,7 +33,11 @@ export async function seal(payload, secret, info, ttlSeconds) {
33
33
  export async function unseal(token, secret, info) {
34
34
  try {
35
35
  const key = await deriveKey(secret, info);
36
- const { payload } = await jwtDecrypt(token, key, { keyManagementAlgorithms: ["dir"], contentEncryptionAlgorithms: ["A256GCM"], currentDate: new Date(Date.now()) });
36
+ const { payload } = await jwtDecrypt(token, key, {
37
+ keyManagementAlgorithms: ["dir"],
38
+ contentEncryptionAlgorithms: ["A256GCM"],
39
+ currentDate: new Date(Date.now()),
40
+ });
37
41
  return payload;
38
42
  }
39
43
  catch {
@@ -56,7 +60,13 @@ export function readCookie(req, name) {
56
60
  }
57
61
  /** A `Set-Cookie` value. Always HttpOnly. `maxAge` 0 deletes the cookie. */
58
62
  export function serializeCookie(name, value, o) {
59
- const parts = [`${name}=${value}`, `Path=${o.path}`, `Max-Age=${Math.max(0, Math.floor(o.maxAge))}`, "HttpOnly", `SameSite=${o.sameSite[0].toUpperCase()}${o.sameSite.slice(1)}`];
63
+ const parts = [
64
+ `${name}=${value}`,
65
+ `Path=${o.path}`,
66
+ `Max-Age=${Math.max(0, Math.floor(o.maxAge))}`,
67
+ "HttpOnly",
68
+ `SameSite=${o.sameSite[0].toUpperCase()}${o.sameSite.slice(1)}`,
69
+ ];
60
70
  if (o.domain)
61
71
  parts.push(`Domain=${o.domain}`);
62
72
  if (o.secure)
@@ -1,5 +1,5 @@
1
+ export type { EvupAuthErrorCode } from "../errors.js";
2
+ export { EvupAuthError } from "../errors.js";
1
3
  export { createEvupAuth } from "./auth.js";
2
4
  export { safeReturnTo } from "./redirect.js";
3
- export { EvupAuthError } from "../errors.js";
4
- export type { EvupAuthErrorCode } from "../errors.js";
5
5
  export type { CookieOptions, EvupAuth, EvupAuthConfig, EvupUser, GetSessionOptions, Session, SignInOptions, SignOutOptions } from "./types.js";
@@ -1,3 +1,3 @@
1
+ export { EvupAuthError } from "../errors.js";
1
2
  export { createEvupAuth } from "./auth.js";
2
3
  export { safeReturnTo } from "./redirect.js";
3
- export { EvupAuthError } from "../errors.js";
@@ -16,8 +16,10 @@ export function httpOptions(insecure, fetchImpl) {
16
16
  /** Discovery document of `issuer`, cached for an hour per isolate. A failed fetch is never cached. */
17
17
  export async function discover(issuer, http, cacheKey) {
18
18
  let cache = caches.get(cacheKey);
19
- if (!cache)
20
- caches.set(cacheKey, (cache = new Map()));
19
+ if (!cache) {
20
+ cache = new Map();
21
+ caches.set(cacheKey, cache);
22
+ }
21
23
  const hit = cache.get(issuer);
22
24
  if (hit && hit.until > Date.now())
23
25
  return hit.as;
@@ -8,5 +8,8 @@ function page(status, title, message, action) {
8
8
  });
9
9
  }
10
10
  /** Default 403 page when the IdP refuses the user (not allowed in this app, or on its waitlist). */
11
- export const accessDeniedPage = (basePath) => page(403, "Access denied", "Your account is not allowed to use this application.", { href: `${basePath}/sign-in?prompt=select_account`, label: "Sign in with another account" });
11
+ export const accessDeniedPage = (basePath) => page(403, "Access denied", "Your account is not allowed to use this application.", {
12
+ href: `${basePath}/sign-in?prompt=select_account`,
13
+ label: "Sign in with another account",
14
+ });
12
15
  export const signInFailedPage = (basePath, status) => page(status, "Sign-in failed", "We could not complete the sign-in. Please try again.", { href: `${basePath}/sign-in`, label: "Try again" });
@@ -8,7 +8,7 @@ export function safeReturnTo(value, fallback = "/") {
8
8
  return fallback;
9
9
  if (value[0] !== "/" || value[1] === "/" || value[1] === "\\")
10
10
  return fallback;
11
- // eslint-disable-next-line no-control-regex
11
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters in redirect targets is the point
12
12
  if (/[\u0000-\u001f\u007f\\]/.test(value))
13
13
  return fallback;
14
14
  let url;
@@ -0,0 +1,70 @@
1
+ import type { CookieOptions } from "../server/types.js";
2
+ /** The access token inside every test session. Any API that checks it with the IdP rejects it. */
3
+ export declare const TEST_ACCESS_TOKEN = "evup-test-access-token";
4
+ export type TestSessionUser = {
5
+ /** The user id (`sub`). */
6
+ id: string;
7
+ email: string;
8
+ /** Default true. */
9
+ emailVerified?: boolean;
10
+ name?: string;
11
+ picture?: string;
12
+ /** RBAC permissions of the user in the app (the `permissions` claim). */
13
+ permissions?: string[];
14
+ /** Extra claims, as the IdP would return them. `sub`, `email`, `email_verified`, `name`, `picture` and `permissions` come from the fields above. */
15
+ claims?: Record<string, unknown>;
16
+ };
17
+ export type TestSessionCookieOptions = {
18
+ /** The app's test `EVUP_SESSION_SECRET` (at least 32 characters, same rule as `createEvupAuth`). */
19
+ secret: string;
20
+ user: TestSessionUser;
21
+ /** Merged into `user.permissions` (duplicates removed). */
22
+ permissions?: string[];
23
+ /** Lifetime of the fake access token, seconds. Default 3600, well past the SDK's 60 s refresh window. */
24
+ expiresIn?: number;
25
+ /** Granted scopes, space-delimited. Default the SDK's default scopes. */
26
+ scope?: string;
27
+ /** Must match the app's `createEvupAuth({ cookie })`. `maxAge` defaults to `expiresIn`. */
28
+ cookie?: CookieOptions;
29
+ /**
30
+ * The app's URL (e.g. its `redirectUri`). When `cookie.secure` is unset, `attributes.secure` / `header` are Secure when it is
31
+ * https, like `createEvupAuth` derives it from `redirectUri`. Without it (and without `cookie.secure`), `header` is not Secure.
32
+ */
33
+ url?: string;
34
+ };
35
+ export type TestSessionCookieAttributes = {
36
+ path: string;
37
+ domain?: string;
38
+ /** Seconds. */
39
+ maxAge: number;
40
+ httpOnly: true;
41
+ sameSite: "lax" | "none";
42
+ /** `cookie.secure`, else true for an https `url` option or `sameSite` "none". `playwright(url)` decides it from its own URL. */
43
+ secure: boolean;
44
+ };
45
+ /** The shape of Playwright's `BrowserContext.addCookies()` entries. */
46
+ export type PlaywrightCookie = {
47
+ name: string;
48
+ value: string;
49
+ domain: string;
50
+ path: string;
51
+ httpOnly: boolean;
52
+ secure: boolean;
53
+ sameSite: "Lax" | "None";
54
+ /** Seconds since the epoch. */
55
+ expires: number;
56
+ };
57
+ export type TestSessionCookie = {
58
+ name: string;
59
+ value: string;
60
+ attributes: TestSessionCookieAttributes;
61
+ /** A Set-Cookie value, e.g. `evup_session=…; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax`. */
62
+ header: string;
63
+ /**
64
+ * The cookie for `context.addCookies()`: host-only on the host of `url`, or `.domain` (the domain and its subdomains) when
65
+ * `cookie.domain` is set; `secure` follows the URL's scheme unless `cookie.secure` is set.
66
+ */
67
+ playwright(url: string): PlaywrightCookie;
68
+ };
69
+ /** Mints a valid SDK session cookie for `user`, sealed with `secret`. Never calls the IdP. */
70
+ export declare function createTestSessionCookie(options: TestSessionCookieOptions): Promise<TestSessionCookie>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Test helpers for apps that sign in with EvUp Account. For end-to-end tests only: never import this in app code.
3
+ *
4
+ * `createTestSessionCookie` mints the same encrypted session cookie the SDK sets after a real sign-in, with the app's
5
+ * test `EVUP_SESSION_SECRET`, so a browser test can start signed in without a sign-in bypass in the app. It never talks to
6
+ * the IdP. The session holds an obviously fake access token and no refresh token: when the access token expires, the
7
+ * SDK cannot refresh it and `getSession` clears the cookie (the user is signed out), it never calls the IdP.
8
+ */
9
+ import { EvupAuthError } from "../errors.js";
10
+ import { sealStored, userFromClaims } from "../server/auth.js";
11
+ import { checkCookieOptions, checkSecret, DEFAULT_COOKIE_NAME, DEFAULT_SCOPES } from "../server/config.js";
12
+ import { serializeCookie } from "../server/cookie.js";
13
+ /** The access token inside every test session. Any API that checks it with the IdP rejects it. */
14
+ export const TEST_ACCESS_TOKEN = "evup-test-access-token";
15
+ /** Mints a valid SDK session cookie for `user`, sealed with `secret`. Never calls the IdP. */
16
+ export async function createTestSessionCookie(options) {
17
+ const { secret, user, cookie } = options;
18
+ if (typeof secret !== "string")
19
+ throw new EvupAuthError("config", "secret is required");
20
+ checkSecret(secret);
21
+ checkCookieOptions(cookie);
22
+ if (!user?.id)
23
+ throw new EvupAuthError("config", "user.id is required");
24
+ if (typeof user.email !== "string" || user.email.length === 0)
25
+ throw new EvupAuthError("config", "user.email is required");
26
+ let appUrl;
27
+ if (options.url !== undefined) {
28
+ try {
29
+ appUrl = new URL(options.url);
30
+ }
31
+ catch {
32
+ throw new EvupAuthError("config", `url must be an absolute URL, got "${options.url}"`);
33
+ }
34
+ }
35
+ const expiresIn = options.expiresIn ?? 3600;
36
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0)
37
+ throw new EvupAuthError("config", "expiresIn must be a positive number of seconds");
38
+ const permissions = [...new Set([...(user.permissions ?? []), ...(options.permissions ?? [])])];
39
+ const claims = {
40
+ ...user.claims,
41
+ sub: user.id,
42
+ email: user.email,
43
+ email_verified: user.emailVerified ?? true,
44
+ permissions,
45
+ };
46
+ if (user.name !== undefined)
47
+ claims.name = user.name;
48
+ if (user.picture !== undefined)
49
+ claims.picture = user.picture;
50
+ const now = Date.now();
51
+ const stored = {
52
+ user: userFromClaims(claims),
53
+ accessToken: TEST_ACCESS_TOKEN,
54
+ // No refresh token: the SDK can never refresh this session, so it fails closed once the access token expires
55
+ refreshToken: undefined,
56
+ expiresAt: now + expiresIn * 1000,
57
+ scope: options.scope ?? DEFAULT_SCOPES.join(" "),
58
+ };
59
+ const name = cookie?.name ?? DEFAULT_COOKIE_NAME;
60
+ const maxAge = cookie?.maxAge ?? expiresIn;
61
+ const sameSite = cookie?.sameSite ?? "lax";
62
+ const secure = cookie?.secure ?? (sameSite === "none" || appUrl?.protocol === "https:");
63
+ const value = await sealStored(secret, maxAge, stored);
64
+ const attributes = { path: cookie?.path ?? "/", domain: cookie?.domain, maxAge, httpOnly: true, sameSite, secure };
65
+ return {
66
+ name,
67
+ value,
68
+ attributes,
69
+ header: serializeCookie(name, value, { maxAge, path: attributes.path, domain: attributes.domain, sameSite, secure }),
70
+ playwright(url) {
71
+ const target = new URL(url);
72
+ return {
73
+ name,
74
+ value,
75
+ // A leading dot is how Playwright spells a Domain cookie (sent to subdomains too), like the browser stores Domain=
76
+ domain: attributes.domain ? `.${attributes.domain.replace(/^\./, "")}` : target.hostname,
77
+ path: attributes.path,
78
+ httpOnly: true,
79
+ secure: cookie?.secure ?? (sameSite === "none" || target.protocol === "https:"),
80
+ sameSite: sameSite === "none" ? "None" : "Lax",
81
+ expires: Math.floor(now / 1000) + maxAge,
82
+ };
83
+ },
84
+ };
85
+ }