@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,103 @@
1
+ import { EvupAuthError } from "../errors.js";
2
+ export const DEFAULT_ISSUER = "https://auth.evup.cloud/api/auth";
3
+ export const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
4
+ export const TX_COOKIE = "evup_tx";
5
+ export const TX_TTL_SECONDS = 600;
6
+ export const MIN_SECRET_LENGTH = 32;
7
+ export function processEnv() {
8
+ return globalThis.process?.env ?? {};
9
+ }
10
+ const fromEnv = (env, key) => {
11
+ const value = env[key];
12
+ return typeof value === "string" && value.length > 0 ? value : undefined;
13
+ };
14
+ export function normaliseBasePath(value) {
15
+ const raw = (value ?? "/auth").trim();
16
+ const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
17
+ return withSlash.replace(/\/+$/, "");
18
+ }
19
+ export function isLoopbackHost(hostname) {
20
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname.endsWith(".localhost");
21
+ }
22
+ function parseAbsolute(name, value) {
23
+ let url;
24
+ try {
25
+ url = new URL(value);
26
+ }
27
+ catch {
28
+ throw new EvupAuthError("config", `${name} must be an absolute URL, got "${value}"`);
29
+ }
30
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) {
31
+ throw new EvupAuthError("config", `${name} must use https (http is allowed for localhost only)`);
32
+ }
33
+ return url;
34
+ }
35
+ /** Checks that need no environment: run once when the instance is created. */
36
+ export function checkStatic(config) {
37
+ if (!config.redirectUri)
38
+ throw new EvupAuthError("config", "redirectUri is required");
39
+ parseAbsolute("redirectUri", config.redirectUri);
40
+ if (config.issuer)
41
+ parseAbsolute("issuer", config.issuer);
42
+ if (config.postLogoutRedirectUri)
43
+ parseAbsolute("postLogoutRedirectUri", config.postLogoutRedirectUri);
44
+ const sameSite = config.cookie?.sameSite;
45
+ if (sameSite !== undefined && sameSite !== "lax" && sameSite !== "none") {
46
+ 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
+ }
48
+ if (sameSite === "none" && config.cookie?.secure === false)
49
+ throw new EvupAuthError("config", 'cookie.sameSite "none" requires a Secure cookie');
50
+ if (config.secret !== undefined && config.secret.length < MIN_SECRET_LENGTH) {
51
+ throw new EvupAuthError("config", `secret must be at least ${MIN_SECRET_LENGTH} characters`);
52
+ }
53
+ }
54
+ /** Merges config with the environment. `missing` tells the caller the failure may fix itself once the environment is available. */
55
+ export function resolveSettings(config) {
56
+ const env = config.env ?? processEnv();
57
+ const clientId = config.clientId ?? fromEnv(env, "EVUP_CLIENT_ID");
58
+ const secret = config.secret ?? fromEnv(env, "EVUP_SESSION_SECRET");
59
+ try {
60
+ checkStatic(config);
61
+ if (!clientId)
62
+ return { ok: false, missing: true, error: new EvupAuthError("config", "clientId is missing: pass it or set EVUP_CLIENT_ID") };
63
+ if (!secret)
64
+ 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`);
67
+ const redirectUri = parseAbsolute("redirectUri", config.redirectUri);
68
+ const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
69
+ const issuerUrl = parseAbsolute("issuer", issuer);
70
+ const scopes = config.scopes?.length ? config.scopes : DEFAULT_SCOPES;
71
+ if (!scopes.includes("openid"))
72
+ throw new EvupAuthError("config", 'scopes must include "openid"');
73
+ const resource = config.resource === undefined ? [] : Array.isArray(config.resource) ? config.resource : [config.resource];
74
+ return {
75
+ ok: true,
76
+ settings: {
77
+ clientId,
78
+ clientSecret: config.clientSecret ?? fromEnv(env, "EVUP_CLIENT_SECRET"),
79
+ secret,
80
+ redirectUri,
81
+ issuer,
82
+ scopes,
83
+ resource,
84
+ postLogoutRedirectUri: config.postLogoutRedirectUri,
85
+ basePath: normaliseBasePath(config.basePath),
86
+ cookie: {
87
+ name: config.cookie?.name ?? "evup_session",
88
+ maxAge: config.cookie?.maxAge ?? 30 * 24 * 60 * 60,
89
+ sameSite: config.cookie?.sameSite ?? "lax",
90
+ secure: config.cookie?.secure ?? (redirectUri.protocol === "https:" || config.cookie?.sameSite === "none"),
91
+ domain: config.cookie?.domain,
92
+ path: config.cookie?.path ?? "/",
93
+ },
94
+ insecureIssuer: issuerUrl.protocol === "http:",
95
+ },
96
+ };
97
+ }
98
+ catch (err) {
99
+ if (err instanceof EvupAuthError)
100
+ return { ok: false, missing: false, error: err };
101
+ throw err;
102
+ }
103
+ }
@@ -0,0 +1,30 @@
1
+ /** HKDF `info` values of the two cookies. */
2
+ export declare const SESSION_INFO = "evup-auth session";
3
+ export declare const TRANSACTION_INFO = "evup-auth transaction";
4
+ /** Encrypts `payload` into a compact JWE (`dir` + `A256GCM`) that expires after `ttlSeconds`. */
5
+ export declare function seal(payload: Record<string, unknown>, secret: string, info: string, ttlSeconds: number): Promise<string>;
6
+ /** Decrypts and checks expiry. Any failure (tamper, wrong secret, expired, malformed) is null. */
7
+ export declare function unseal(token: string, secret: string, info: string): Promise<Record<string, unknown> | null>;
8
+ /** Reads one cookie from a `Cookie` request header. */
9
+ export declare function readCookie(req: Request, name: string): string | null;
10
+ export type SerializeOptions = {
11
+ maxAge: number;
12
+ path: string;
13
+ domain?: string;
14
+ sameSite: "lax" | "strict" | "none";
15
+ secure: boolean;
16
+ };
17
+ /** A `Set-Cookie` value. Always HttpOnly. `maxAge` 0 deletes the cookie. */
18
+ export declare function serializeCookie(name: string, value: string, o: SerializeOptions): string;
19
+ /** Parses one `Set-Cookie` value back into parts (used by the Next.js adapter, which sets cookies through its own API). */
20
+ export declare function parseSetCookie(value: string): {
21
+ name: string;
22
+ value: string;
23
+ path?: string;
24
+ domain?: string;
25
+ maxAge?: number;
26
+ sameSite?: "lax" | "strict" | "none";
27
+ secure: boolean;
28
+ httpOnly: boolean;
29
+ expires?: Date;
30
+ } | null;
@@ -0,0 +1,105 @@
1
+ import { EncryptJWT, jwtDecrypt } from "jose";
2
+ const encoder = new TextEncoder();
3
+ const keyCache = new Map();
4
+ /** HKDF-SHA256(secret, info) -> 32 bytes, so the session and transaction cookies never share a key. */
5
+ function deriveKey(secret, info) {
6
+ const id = `${info}\n${secret}`;
7
+ let key = keyCache.get(id);
8
+ if (!key) {
9
+ if (keyCache.size > 16)
10
+ keyCache.clear();
11
+ key = (async () => {
12
+ const base = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, ["deriveBits"]);
13
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: encoder.encode("evup-auth"), info: encoder.encode(info) }, base, 256);
14
+ return new Uint8Array(bits);
15
+ })();
16
+ keyCache.set(id, key);
17
+ }
18
+ return key;
19
+ }
20
+ /** HKDF `info` values of the two cookies. */
21
+ export const SESSION_INFO = "evup-auth session";
22
+ export const TRANSACTION_INFO = "evup-auth transaction";
23
+ /** Encrypts `payload` into a compact JWE (`dir` + `A256GCM`) that expires after `ttlSeconds`. */
24
+ export async function seal(payload, secret, info, ttlSeconds) {
25
+ const key = await deriveKey(secret, info);
26
+ return new EncryptJWT(payload)
27
+ .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
28
+ .setIssuedAt()
29
+ .setExpirationTime(`${ttlSeconds}s`)
30
+ .encrypt(key);
31
+ }
32
+ /** Decrypts and checks expiry. Any failure (tamper, wrong secret, expired, malformed) is null. */
33
+ export async function unseal(token, secret, info) {
34
+ try {
35
+ const key = await deriveKey(secret, info);
36
+ const { payload } = await jwtDecrypt(token, key, { keyManagementAlgorithms: ["dir"], contentEncryptionAlgorithms: ["A256GCM"], currentDate: new Date(Date.now()) });
37
+ return payload;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** Reads one cookie from a `Cookie` request header. */
44
+ export function readCookie(req, name) {
45
+ const header = req.headers.get("cookie");
46
+ if (!header)
47
+ return null;
48
+ for (const part of header.split(";")) {
49
+ const eq = part.indexOf("=");
50
+ if (eq === -1)
51
+ continue;
52
+ if (part.slice(0, eq).trim() === name)
53
+ return part.slice(eq + 1).trim();
54
+ }
55
+ return null;
56
+ }
57
+ /** A `Set-Cookie` value. Always HttpOnly. `maxAge` 0 deletes the cookie. */
58
+ 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)}`];
60
+ if (o.domain)
61
+ parts.push(`Domain=${o.domain}`);
62
+ if (o.secure)
63
+ parts.push("Secure");
64
+ if (o.maxAge <= 0)
65
+ parts.push("Expires=Thu, 01 Jan 1970 00:00:00 GMT");
66
+ return parts.join("; ");
67
+ }
68
+ /** Parses one `Set-Cookie` value back into parts (used by the Next.js adapter, which sets cookies through its own API). */
69
+ export function parseSetCookie(value) {
70
+ const [pair, ...attrs] = value.split(";").map((s) => s.trim());
71
+ if (!pair)
72
+ return null;
73
+ const eq = pair.indexOf("=");
74
+ if (eq < 1)
75
+ return null;
76
+ const out = { name: pair.slice(0, eq), value: pair.slice(eq + 1), secure: false, httpOnly: false };
77
+ for (const attr of attrs) {
78
+ const [k = "", v = ""] = attr.split("=");
79
+ switch (k.toLowerCase()) {
80
+ case "path":
81
+ out.path = v;
82
+ break;
83
+ case "domain":
84
+ out.domain = v;
85
+ break;
86
+ case "max-age":
87
+ out.maxAge = Number(v);
88
+ break;
89
+ case "expires":
90
+ out.expires = new Date(v);
91
+ break;
92
+ case "samesite":
93
+ if (["lax", "strict", "none"].includes(v.toLowerCase()))
94
+ out.sameSite = v.toLowerCase();
95
+ break;
96
+ case "secure":
97
+ out.secure = true;
98
+ break;
99
+ case "httponly":
100
+ out.httpOnly = true;
101
+ break;
102
+ }
103
+ }
104
+ return out;
105
+ }
@@ -0,0 +1,5 @@
1
+ export { createEvupAuth } from "./auth.js";
2
+ export { safeReturnTo } from "./redirect.js";
3
+ export { EvupAuthError } from "../errors.js";
4
+ export type { EvupAuthErrorCode } from "../errors.js";
5
+ export type { CookieOptions, EvupAuth, EvupAuthConfig, EvupUser, GetSessionOptions, Session, SignInOptions, SignOutOptions } from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { createEvupAuth } from "./auth.js";
2
+ export { safeReturnTo } from "./redirect.js";
3
+ export { EvupAuthError } from "../errors.js";
@@ -0,0 +1,17 @@
1
+ import * as oauth from "oauth4webapi";
2
+ import type { Settings } from "./config.js";
3
+ export type HttpOptions = {
4
+ signal: () => AbortSignal;
5
+ [oauth.customFetch]: (url: string, init: RequestInit) => Promise<Response>;
6
+ [oauth.allowInsecureRequests]?: boolean;
7
+ };
8
+ export type Idp = {
9
+ as: oauth.AuthorizationServer;
10
+ client: oauth.Client;
11
+ clientAuth: oauth.ClientAuth;
12
+ http: HttpOptions;
13
+ };
14
+ export declare function httpOptions(insecure: boolean, fetchImpl: typeof fetch | undefined): HttpOptions;
15
+ /** Discovery document of `issuer`, cached for an hour per isolate. A failed fetch is never cached. */
16
+ export declare function discover(issuer: string, http: HttpOptions, cacheKey: object): Promise<oauth.AuthorizationServer>;
17
+ export declare function loadIdp(s: Settings, fetchImpl: typeof fetch | undefined): Promise<Idp>;
@@ -0,0 +1,44 @@
1
+ import * as oauth from "oauth4webapi";
2
+ import { EvupAuthError } from "../errors.js";
3
+ const DISCOVERY_TTL_MS = 60 * 60 * 1000;
4
+ const HTTP_TIMEOUT_MS = 10_000;
5
+ /** Per fetch implementation, so a test stub never sees another test's metadata. */
6
+ const caches = new WeakMap();
7
+ export function httpOptions(insecure, fetchImpl) {
8
+ const http = {
9
+ signal: () => AbortSignal.timeout(HTTP_TIMEOUT_MS),
10
+ [oauth.customFetch]: (url, init) => (fetchImpl ?? fetch)(url, init),
11
+ };
12
+ if (insecure)
13
+ http[oauth.allowInsecureRequests] = true;
14
+ return http;
15
+ }
16
+ /** Discovery document of `issuer`, cached for an hour per isolate. A failed fetch is never cached. */
17
+ export async function discover(issuer, http, cacheKey) {
18
+ let cache = caches.get(cacheKey);
19
+ if (!cache)
20
+ caches.set(cacheKey, (cache = new Map()));
21
+ const hit = cache.get(issuer);
22
+ if (hit && hit.until > Date.now())
23
+ return hit.as;
24
+ try {
25
+ const issuerUrl = new URL(issuer);
26
+ const res = await oauth.discoveryRequest(issuerUrl, { ...http, algorithm: "oidc" });
27
+ const as = await oauth.processDiscoveryResponse(issuerUrl, res);
28
+ cache.set(issuer, { as, until: Date.now() + DISCOVERY_TTL_MS });
29
+ return as;
30
+ }
31
+ catch (cause) {
32
+ throw new EvupAuthError("discovery_failed", `Could not load the OpenID configuration of ${issuer}`, { cause });
33
+ }
34
+ }
35
+ export async function loadIdp(s, fetchImpl) {
36
+ const http = httpOptions(s.insecureIssuer, fetchImpl);
37
+ const as = await discover(s.issuer, http, fetchImpl ?? globalThis);
38
+ return {
39
+ as,
40
+ http,
41
+ client: { client_id: s.clientId },
42
+ clientAuth: s.clientSecret ? oauth.ClientSecretBasic(s.clientSecret) : oauth.None(),
43
+ };
44
+ }
@@ -0,0 +1,3 @@
1
+ /** Default 403 page when the IdP refuses the user (not allowed in this app, or on its waitlist). */
2
+ export declare const accessDeniedPage: (basePath: string) => Response;
3
+ export declare const signInFailedPage: (basePath: string, status: number) => Response;
@@ -0,0 +1,12 @@
1
+ const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
2
+ function page(status, title, message, action) {
3
+ const link = action ? `<p><a href="${escapeHtml(action.href)}">${escapeHtml(action.label)}</a></p>` : "";
4
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;color:#1a1a1a}a{color:#0b57d0}</style></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>${link}</body></html>`;
5
+ return new Response(html, {
6
+ status,
7
+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" },
8
+ });
9
+ }
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" });
12
+ 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" });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Accepts only a same-origin relative path. Anything that could leave the origin once a browser resolves it
3
+ * ("//host", "/\host", control characters, dot-segment tricks) falls back to `fallback`.
4
+ */
5
+ export declare function safeReturnTo(value: unknown, fallback?: string): string;
@@ -0,0 +1,28 @@
1
+ const PROBE_ORIGIN = "http://evup.invalid";
2
+ /**
3
+ * Accepts only a same-origin relative path. Anything that could leave the origin once a browser resolves it
4
+ * ("//host", "/\host", control characters, dot-segment tricks) falls back to `fallback`.
5
+ */
6
+ export function safeReturnTo(value, fallback = "/") {
7
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048)
8
+ return fallback;
9
+ if (value[0] !== "/" || value[1] === "/" || value[1] === "\\")
10
+ return fallback;
11
+ // eslint-disable-next-line no-control-regex
12
+ if (/[\u0000-\u001f\u007f\\]/.test(value))
13
+ return fallback;
14
+ let url;
15
+ try {
16
+ url = new URL(value, PROBE_ORIGIN);
17
+ }
18
+ catch {
19
+ return fallback;
20
+ }
21
+ if (url.origin !== PROBE_ORIGIN)
22
+ return fallback;
23
+ const normalised = url.pathname + url.search + url.hash;
24
+ // "/..//host" normalises to "//host", which a browser reads as protocol-relative
25
+ if (normalised[0] !== "/" || normalised[1] === "/" || normalised[1] === "\\")
26
+ return fallback;
27
+ return normalised;
28
+ }
@@ -0,0 +1,109 @@
1
+ import type { EvupAuthError } from "../errors.js";
2
+ export type EvupUser = {
3
+ /** The IdP user id (`sub`). */
4
+ id: string;
5
+ email: string;
6
+ emailVerified: boolean;
7
+ name?: string;
8
+ picture?: string;
9
+ /** RBAC permissions of the user in this app (the `permissions` claim). */
10
+ permissions: string[];
11
+ /** Every claim the IdP returned (id_token merged with userinfo). */
12
+ claims: Record<string, unknown>;
13
+ };
14
+ export type Session = {
15
+ user: EvupUser;
16
+ /** The OAuth access token. Opaque unless `resource` was requested, then a JWT. */
17
+ accessToken: string;
18
+ /** Access token expiry, milliseconds since the epoch. */
19
+ expiresAt: number;
20
+ /** Space-delimited scopes the IdP granted. */
21
+ scope: string;
22
+ };
23
+ export type SignInOptions = {
24
+ /** Same-origin relative path to return to after sign-in. Anything else becomes "/". */
25
+ returnTo?: string;
26
+ /** OIDC `prompt`, e.g. "select_account", "login", "consent", "none". */
27
+ prompt?: string;
28
+ /** UI locale hint (`ui_locales`). */
29
+ locale?: string;
30
+ /** `login_hint`: pre-fills the email on the sign-in page. */
31
+ loginHint?: string;
32
+ };
33
+ export type SignOutOptions = {
34
+ /** Same-origin relative path used when the user is not sent through the IdP sign-out page. */
35
+ returnTo?: string;
36
+ };
37
+ export type CookieOptions = {
38
+ /** Default "evup_session". */
39
+ name?: string;
40
+ /** Seconds. Default 30 days. */
41
+ maxAge?: number;
42
+ /**
43
+ * Default "lax". "none" needs `secure`. "strict" is rejected: the browser would not send the cookie on the redirect that
44
+ * follows the IdP callback, so the user would land signed out.
45
+ */
46
+ sameSite?: "lax" | "none";
47
+ /** Default true when `redirectUri` is https, false for http (local development). */
48
+ secure?: boolean;
49
+ domain?: string;
50
+ /** Default "/". */
51
+ path?: string;
52
+ };
53
+ export type EvupAuthConfig = {
54
+ /** Default: env `EVUP_CLIENT_ID`. */
55
+ clientId?: string;
56
+ /** Default: env `EVUP_CLIENT_SECRET`. Absent: public client (token_endpoint_auth_method none). */
57
+ clientSecret?: string;
58
+ /** Cookie encryption secret, at least 32 characters. Default: env `EVUP_SESSION_SECRET`. */
59
+ secret?: string;
60
+ /** Absolute URL of the callback route, registered as a redirect URI of the app. */
61
+ redirectUri: string;
62
+ /** Default "https://auth.evup.cloud/api/auth". */
63
+ issuer?: string;
64
+ /** Default ["openid", "profile", "email", "offline_access"]. */
65
+ scopes?: string[];
66
+ /** RFC 8707 resource indicator(s). Makes the access token a JWT for that API. */
67
+ resource?: string | string[];
68
+ /** Exact post-logout redirect URI registered for the app. */
69
+ postLogoutRedirectUri?: string;
70
+ cookie?: CookieOptions;
71
+ /** Default "/auth": routes `sign-in`, `callback`, `sign-out` and `session` live under it. */
72
+ basePath?: string;
73
+ /** Replaces the default 403 page when the IdP refuses the user. */
74
+ onAccessDenied?: (req: Request, err: EvupAuthError) => Response | Promise<Response>;
75
+ /**
76
+ * Called for every other sign-in callback failure (invalid_state, callback_failed, discovery_failed) after the error page is chosen.
77
+ * Default: `console.error` with the code, the message and the cause's message (never tokens). Errors thrown here are ignored.
78
+ */
79
+ onError?: (req: Request, err: EvupAuthError) => void | Promise<void>;
80
+ /** Where to read EVUP_* variables from. Workers: pass the env binding object (only string values are read). Default: `process.env` when it exists. */
81
+ env?: object;
82
+ /** Custom fetch for every request to the IdP. Default: global fetch. */
83
+ fetch?: typeof fetch;
84
+ };
85
+ export type GetSessionOptions = {
86
+ /** Default true. false: read the cookie only, never call the IdP (the session may then be past `expiresAt`). */
87
+ refresh?: boolean;
88
+ /** Seconds before expiry at which a refresh starts. Default 60. */
89
+ refreshWindow?: number;
90
+ };
91
+ export interface EvupAuth {
92
+ /** The configured `basePath` (normalised, no trailing slash). */
93
+ readonly basePath: string;
94
+ /** Serves the sign-in, callback, sign-out and session routes. Returns null for any other request. */
95
+ handler(req: Request): Promise<Response | null>;
96
+ signIn(req: Request, opts?: SignInOptions): Promise<Response>;
97
+ callback(req: Request): Promise<Response>;
98
+ signOut(req: Request, opts?: SignOutOptions): Promise<Response>;
99
+ /** `headers` carries Set-Cookie when the session was refreshed or cleared: adapters must send them. */
100
+ getSession(req: Request, opts?: GetSessionOptions): Promise<{
101
+ session: Session | null;
102
+ headers: Headers;
103
+ }>;
104
+ /**
105
+ * The user from the cookie only: it never refreshes, so it never touches the IdP and never needs a Set-Cookie.
106
+ * The session behind it may be expired (an expired access token is refreshed by `getSession`); the identity is what the last sign-in or refresh saw.
107
+ */
108
+ getUser(req: Request): Promise<EvupUser | null>;
109
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@evup/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "SDK for apps and resource servers that sign in with EvUp Account (OIDC authorization code + PKCE, RFC 9728 resource servers).",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/tamnt1707/evup-auth.git",
9
+ "directory": "packages/auth"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "main": "./dist/server/index.js",
23
+ "types": "./dist/server/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/server/index.d.ts",
27
+ "default": "./dist/server/index.js"
28
+ },
29
+ "./server": {
30
+ "types": "./dist/server/index.d.ts",
31
+ "default": "./dist/server/index.js"
32
+ },
33
+ "./client": {
34
+ "types": "./dist/client/index.d.ts",
35
+ "default": "./dist/client/index.js"
36
+ },
37
+ "./hono": {
38
+ "types": "./dist/hono/index.d.ts",
39
+ "default": "./dist/hono/index.js"
40
+ },
41
+ "./astro": {
42
+ "types": "./dist/astro/index.d.ts",
43
+ "default": "./dist/astro/index.js"
44
+ },
45
+ "./next": {
46
+ "types": "./dist/next/index.d.ts",
47
+ "default": "./dist/next/index.js"
48
+ },
49
+ "./resource": {
50
+ "types": "./dist/resource/index.d.ts",
51
+ "default": "./dist/resource/index.js"
52
+ },
53
+ "./package.json": "./package.json"
54
+ },
55
+ "scripts": {
56
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/fix-dts.mjs",
57
+ "typecheck": "tsc -p tsconfig.json --noEmit",
58
+ "test": "node --test \"test/**/*.test.ts\""
59
+ },
60
+ "dependencies": {
61
+ "jose": "^6.2.17",
62
+ "oauth4webapi": "^3.8.9"
63
+ },
64
+ "peerDependencies": {
65
+ "astro": ">=5",
66
+ "hono": ">=4",
67
+ "next": ">=14"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "astro": {
71
+ "optional": true
72
+ },
73
+ "hono": {
74
+ "optional": true
75
+ },
76
+ "next": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "devDependencies": {
81
+ "@types/node": "^22.0.0",
82
+ "next": "^16.4.6",
83
+ "typescript": "^6.0.3"
84
+ },
85
+ "publishConfig": {
86
+ "access": "public"
87
+ }
88
+ }