@evup/auth 0.0.0-stage → 0.1.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/README.md +791 -2
- package/dist/astro/index.d.ts +22 -0
- package/dist/astro/index.js +34 -0
- package/dist/astro/integration-middleware.d.ts +1 -0
- package/dist/astro/integration-middleware.js +3 -0
- package/dist/astro/middleware.d.ts +9 -0
- package/dist/astro/middleware.js +36 -0
- package/dist/astro/route.d.ts +3 -0
- package/dist/astro/route.js +6 -0
- package/dist/astro/runtime.d.ts +8 -0
- package/dist/astro/runtime.js +58 -0
- package/dist/client/index.d.ts +15 -0
- package/dist/client/index.js +34 -0
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +12 -0
- package/dist/hono/index.d.ts +26 -0
- package/dist/hono/index.js +53 -0
- package/dist/next/index.d.ts +25 -0
- package/dist/next/index.js +84 -0
- package/dist/next/read.d.ts +7 -0
- package/dist/next/read.js +11 -0
- package/dist/resource/index.d.ts +48 -0
- package/dist/resource/index.js +174 -0
- package/dist/server/auth.d.ts +4 -0
- package/dist/server/auth.js +386 -0
- package/dist/server/config.d.ts +42 -0
- package/dist/server/config.js +103 -0
- package/dist/server/cookie.d.ts +30 -0
- package/dist/server/cookie.js +105 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +3 -0
- package/dist/server/oidc.d.ts +17 -0
- package/dist/server/oidc.js +44 -0
- package/dist/server/pages.d.ts +3 -0
- package/dist/server/pages.js +12 -0
- package/dist/server/redirect.d.ts +5 -0
- package/dist/server/redirect.js +28 -0
- package/dist/server/types.d.ts +109 -0
- package/dist/server/types.js +1 -0
- package/package.json +86 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AstroIntegration } from "astro";
|
|
2
|
+
import type { EvupAuthConfig, EvupUser, Session } from "../server/types.js";
|
|
3
|
+
export { createEvupMiddleware } from "./middleware.js";
|
|
4
|
+
export type { AuthOrFactory } from "./middleware.js";
|
|
5
|
+
export type { EvupAuth, EvupAuthConfig, EvupUser, Session } from "../server/types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Options of the integration. They are baked into the server bundle, so the secrets (`secret`, `clientSecret`) and anything
|
|
8
|
+
* that is not JSON (`onAccessDenied`, `fetch`, `env`) are left out: secrets come from the environment, and the manual form
|
|
9
|
+
* (`createEvupMiddleware(createEvupAuth({...}))`) covers the rest.
|
|
10
|
+
*/
|
|
11
|
+
export type EvupAstroConfig = Omit<EvupAuthConfig, "secret" | "clientSecret" | "onAccessDenied" | "env" | "fetch">;
|
|
12
|
+
declare global {
|
|
13
|
+
namespace App {
|
|
14
|
+
interface Locals {
|
|
15
|
+
user: EvupUser | null;
|
|
16
|
+
session: Session | null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Astro integration: injects the `${basePath}/[...evup]` route and the middleware that fills `Astro.locals`. */
|
|
21
|
+
export declare function evup(config: EvupAstroConfig): AstroIntegration;
|
|
22
|
+
export default evup;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { normaliseBasePath } from "../server/config.js";
|
|
2
|
+
export { createEvupMiddleware } from "./middleware.js";
|
|
3
|
+
const VIRTUAL_ID = "virtual:evup-auth/config";
|
|
4
|
+
/** Astro integration: injects the `${basePath}/[...evup]` route and the middleware that fills `Astro.locals`. */
|
|
5
|
+
export function evup(config) {
|
|
6
|
+
for (const key of ["secret", "clientSecret", "onAccessDenied", "env", "fetch"]) {
|
|
7
|
+
if (key in config)
|
|
8
|
+
throw new Error(`evup(): "${key}" cannot be set on the integration. Use env vars, or createEvupMiddleware(createEvupAuth({...})) for the manual setup.`);
|
|
9
|
+
}
|
|
10
|
+
const basePath = normaliseBasePath(config.basePath);
|
|
11
|
+
return {
|
|
12
|
+
name: "@evup/auth",
|
|
13
|
+
hooks: {
|
|
14
|
+
"astro:config:setup": ({ injectRoute, addMiddleware, updateConfig }) => {
|
|
15
|
+
updateConfig({
|
|
16
|
+
vite: {
|
|
17
|
+
// The injected files import a virtual module, so Vite has to process this package instead of externalising it
|
|
18
|
+
ssr: { noExternal: ["@evup/auth"] },
|
|
19
|
+
plugins: [
|
|
20
|
+
{
|
|
21
|
+
name: "evup-auth-config",
|
|
22
|
+
resolveId: (id) => (id === VIRTUAL_ID ? `\0${VIRTUAL_ID}` : undefined),
|
|
23
|
+
load: (id) => (id === `\0${VIRTUAL_ID}` ? `export default ${JSON.stringify(config)};` : undefined),
|
|
24
|
+
},
|
|
25
|
+
],
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
injectRoute({ pattern: `${basePath}/[...evup]`, entrypoint: new URL("./route.js", import.meta.url), prerender: false });
|
|
29
|
+
addMiddleware({ entrypoint: new URL("./integration-middleware.js", import.meta.url), order: "pre" });
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export default evup;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const onRequest: import("astro").MiddlewareHandler;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { APIContext, MiddlewareHandler } from "astro";
|
|
2
|
+
import type { EvupAuth } from "../server/types.js";
|
|
3
|
+
/** An instance, or a factory that gets the Astro context (and may be async). The factory runs once per isolate. */
|
|
4
|
+
export type AuthOrFactory = EvupAuth | ((ctx: APIContext) => EvupAuth | Promise<EvupAuth>);
|
|
5
|
+
/**
|
|
6
|
+
* Serves the sign-in, callback, sign-out and session routes, sets `Astro.locals.user` / `Astro.locals.session`
|
|
7
|
+
* and appends a refreshed or cleared session cookie to the response. Prerendered pages get `null` locals.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createEvupMiddleware(authOrFactory: AuthOrFactory): MiddlewareHandler;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serves the sign-in, callback, sign-out and session routes, sets `Astro.locals.user` / `Astro.locals.session`
|
|
3
|
+
* and appends a refreshed or cleared session cookie to the response. Prerendered pages get `null` locals.
|
|
4
|
+
*/
|
|
5
|
+
export function createEvupMiddleware(authOrFactory) {
|
|
6
|
+
let cached = typeof authOrFactory === "function" ? undefined : Promise.resolve(authOrFactory);
|
|
7
|
+
return async (context, next) => {
|
|
8
|
+
if (context.isPrerendered) {
|
|
9
|
+
context.locals.user = null;
|
|
10
|
+
context.locals.session = null;
|
|
11
|
+
return next();
|
|
12
|
+
}
|
|
13
|
+
// A rejected factory (missing binding, bad config) must not stick: the next request tries again
|
|
14
|
+
const pending = (cached ??= (async () => authOrFactory(context))());
|
|
15
|
+
const auth = await pending.catch((err) => {
|
|
16
|
+
if (cached === pending)
|
|
17
|
+
cached = undefined;
|
|
18
|
+
throw err;
|
|
19
|
+
});
|
|
20
|
+
const served = await auth.handler(context.request);
|
|
21
|
+
if (served)
|
|
22
|
+
return served;
|
|
23
|
+
const { session, headers } = await auth.getSession(context.request);
|
|
24
|
+
context.locals.session = session;
|
|
25
|
+
context.locals.user = session?.user ?? null;
|
|
26
|
+
const response = await next();
|
|
27
|
+
const cookies = headers.getSetCookie();
|
|
28
|
+
if (cookies.length === 0)
|
|
29
|
+
return response;
|
|
30
|
+
// Responses from redirects or fetch() have immutable headers: copy before appending
|
|
31
|
+
const out = new Response(response.body, response);
|
|
32
|
+
for (const cookie of cookies)
|
|
33
|
+
out.headers.append("set-cookie", cookie);
|
|
34
|
+
return out;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { APIContext } from "astro";
|
|
2
|
+
import type { EvupAuth } from "../server/types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The auth instance the integration's route and middleware share. Environment, lowest to highest priority: `import.meta.env`
|
|
5
|
+
* (dev only: a production build inlines private variables at build time or not at all, so it is never relied on), `process.env`,
|
|
6
|
+
* then Workers bindings.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getAuth(context: APIContext): Promise<EvupAuth>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import config from "virtual:evup-auth/config";
|
|
10
|
+
import { createEvupAuth } from "../server/auth.js";
|
|
11
|
+
const onlyStrings = (source) => {
|
|
12
|
+
const out = {};
|
|
13
|
+
if (source && typeof source === "object")
|
|
14
|
+
for (const [k, v] of Object.entries(source))
|
|
15
|
+
if (typeof v === "string")
|
|
16
|
+
out[k] = v;
|
|
17
|
+
return out;
|
|
18
|
+
};
|
|
19
|
+
/** Workers bindings: the adapter's `locals.runtime.env` (older adapters), else `import { env } from "cloudflare:workers"`. */
|
|
20
|
+
async function workersEnv(context) {
|
|
21
|
+
try {
|
|
22
|
+
// Astro 6+ adapters make this getter throw instead of returning the env
|
|
23
|
+
const fromLocals = context.locals.runtime?.env;
|
|
24
|
+
if (fromLocals)
|
|
25
|
+
return onlyStrings(fromLocals);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// fall through to cloudflare:workers
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
// The specifier is computed so that builds for other runtimes do not try to resolve it
|
|
32
|
+
const specifier = "cloudflare:workers";
|
|
33
|
+
const mod = (await import(__rewriteRelativeImportExtension(/* @vite-ignore */ specifier)));
|
|
34
|
+
return onlyStrings(mod.env);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
let instance;
|
|
41
|
+
/**
|
|
42
|
+
* The auth instance the integration's route and middleware share. Environment, lowest to highest priority: `import.meta.env`
|
|
43
|
+
* (dev only: a production build inlines private variables at build time or not at all, so it is never relied on), `process.env`,
|
|
44
|
+
* then Workers bindings.
|
|
45
|
+
*/
|
|
46
|
+
export function getAuth(context) {
|
|
47
|
+
const pending = (instance ??= (async () => {
|
|
48
|
+
const processEnv = globalThis.process?.env;
|
|
49
|
+
const env = { ...onlyStrings(import.meta.env), ...onlyStrings(processEnv), ...(await workersEnv(context)) };
|
|
50
|
+
return createEvupAuth({ ...config, env });
|
|
51
|
+
})());
|
|
52
|
+
// A rejected attempt (bad config, missing binding) must not stick: the next request tries again
|
|
53
|
+
pending.catch(() => {
|
|
54
|
+
if (instance === pending)
|
|
55
|
+
instance = undefined;
|
|
56
|
+
});
|
|
57
|
+
return pending;
|
|
58
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { EvupUser, SignInOptions, SignOutOptions } from "../server/types.js";
|
|
2
|
+
export type { EvupUser, SignInOptions, SignOutOptions };
|
|
3
|
+
export type EvupClientConfig = {
|
|
4
|
+
/** Where the server routes are mounted. Default "/auth". */
|
|
5
|
+
basePath?: string;
|
|
6
|
+
};
|
|
7
|
+
export interface EvupClient {
|
|
8
|
+
/** The signed-in user, or null. Asks `${basePath}/session`; tokens never reach the browser. */
|
|
9
|
+
getUser(): Promise<EvupUser | null>;
|
|
10
|
+
/** Navigates to the sign-in route (full page redirect). */
|
|
11
|
+
signIn(opts?: SignInOptions): void;
|
|
12
|
+
/** POSTs to the sign-out route, then follows the redirect it answers with. */
|
|
13
|
+
signOut(opts?: SignOutOptions): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare function createEvupClient(config?: EvupClientConfig): EvupClient;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export function createEvupClient(config = {}) {
|
|
2
|
+
const raw = (config.basePath ?? "/auth").trim();
|
|
3
|
+
const basePath = (raw.startsWith("/") ? raw : `/${raw}`).replace(/\/+$/, "");
|
|
4
|
+
return {
|
|
5
|
+
async getUser() {
|
|
6
|
+
const res = await fetch(`${basePath}/session`, { credentials: "same-origin", headers: { accept: "application/json" }, cache: "no-store" });
|
|
7
|
+
if (!res.ok)
|
|
8
|
+
return null;
|
|
9
|
+
const body = (await res.json());
|
|
10
|
+
return body.user ?? null;
|
|
11
|
+
},
|
|
12
|
+
signIn(opts = {}) {
|
|
13
|
+
const params = new URLSearchParams();
|
|
14
|
+
if (opts.returnTo)
|
|
15
|
+
params.set("returnTo", opts.returnTo);
|
|
16
|
+
if (opts.prompt)
|
|
17
|
+
params.set("prompt", opts.prompt);
|
|
18
|
+
if (opts.locale)
|
|
19
|
+
params.set("locale", opts.locale);
|
|
20
|
+
if (opts.loginHint)
|
|
21
|
+
params.set("loginHint", opts.loginHint);
|
|
22
|
+
const query = params.toString();
|
|
23
|
+
location.assign(`${basePath}/sign-in${query ? `?${query}` : ""}`);
|
|
24
|
+
},
|
|
25
|
+
async signOut(opts = {}) {
|
|
26
|
+
const query = opts.returnTo ? `?${new URLSearchParams({ returnTo: opts.returnTo })}` : "";
|
|
27
|
+
const res = await fetch(`${basePath}/sign-out${query}`, { method: "POST", credentials: "same-origin", headers: { accept: "application/json" } });
|
|
28
|
+
if (!res.ok)
|
|
29
|
+
throw new Error(`Sign-out failed (${res.status})`);
|
|
30
|
+
const body = (await res.json());
|
|
31
|
+
location.assign(body.redirectTo || "/");
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type EvupAuthErrorCode = "access_denied" | "invalid_state" | "callback_failed" | "config" | "discovery_failed";
|
|
2
|
+
/** Every failure the SDK reports on purpose. `code` is stable; `message` is for logs. */
|
|
3
|
+
export declare class EvupAuthError extends Error {
|
|
4
|
+
readonly code: EvupAuthErrorCode;
|
|
5
|
+
/** The OAuth `error_description` the IdP sent, when there was one. */
|
|
6
|
+
readonly description?: string;
|
|
7
|
+
constructor(code: EvupAuthErrorCode, message: string, options?: {
|
|
8
|
+
cause?: unknown;
|
|
9
|
+
description?: string;
|
|
10
|
+
});
|
|
11
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Every failure the SDK reports on purpose. `code` is stable; `message` is for logs. */
|
|
2
|
+
export class EvupAuthError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
/** The OAuth `error_description` the IdP sent, when there was one. */
|
|
5
|
+
description;
|
|
6
|
+
constructor(code, message, options) {
|
|
7
|
+
super(message, options?.cause === undefined ? undefined : { cause: options.cause });
|
|
8
|
+
this.name = "EvupAuthError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.description = options?.description;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { EvupAccessToken, EvupResource } from "../resource/index.js";
|
|
3
|
+
import type { EvupAuth, EvupUser, Session } from "../server/types.js";
|
|
4
|
+
export type { EvupAccessToken } from "../resource/index.js";
|
|
5
|
+
export type { EvupAuth, EvupUser, Session } from "../server/types.js";
|
|
6
|
+
/** Pass to `new Hono<{ Variables: EvupVariables }>()` to type `c.var.user` and friends. */
|
|
7
|
+
export type EvupVariables = {
|
|
8
|
+
user: EvupUser | null;
|
|
9
|
+
session: Session | null;
|
|
10
|
+
evupAuth: EvupAuth;
|
|
11
|
+
evupToken: EvupAccessToken;
|
|
12
|
+
};
|
|
13
|
+
/** An instance, or a factory that gets the Hono context (Workers: build it from `c.env`). The factory runs once per isolate. */
|
|
14
|
+
export type AuthOrFactory = EvupAuth | ((c: Context) => EvupAuth);
|
|
15
|
+
/**
|
|
16
|
+
* Serves the sign-in, callback, sign-out and session routes, and sets `c.var.user` / `c.var.session` for every other request.
|
|
17
|
+
* A refreshed or cleared session cookie is appended to the response.
|
|
18
|
+
*/
|
|
19
|
+
export declare function evupAuth(authOrFactory: AuthOrFactory): MiddlewareHandler;
|
|
20
|
+
/**
|
|
21
|
+
* Lets only signed-in users through. Browser navigations (Accept: text/html) go to the sign-in route and come back;
|
|
22
|
+
* anything else gets a 401 JSON error. Needs `evupAuth()` earlier in the chain.
|
|
23
|
+
*/
|
|
24
|
+
export declare function requireUser(): MiddlewareHandler;
|
|
25
|
+
/** Protects a route as an OAuth resource server: verifies the Bearer token, sets `c.var.evupToken`, serves the metadata path. */
|
|
26
|
+
export declare function evupResource(resource: EvupResource): MiddlewareHandler;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serves the sign-in, callback, sign-out and session routes, and sets `c.var.user` / `c.var.session` for every other request.
|
|
3
|
+
* A refreshed or cleared session cookie is appended to the response.
|
|
4
|
+
*/
|
|
5
|
+
export function evupAuth(authOrFactory) {
|
|
6
|
+
let cached = typeof authOrFactory === "function" ? undefined : authOrFactory;
|
|
7
|
+
return async (c, next) => {
|
|
8
|
+
const auth = (cached ??= authOrFactory(c));
|
|
9
|
+
const served = await auth.handler(c.req.raw);
|
|
10
|
+
if (served)
|
|
11
|
+
return served;
|
|
12
|
+
const { session, headers } = await auth.getSession(c.req.raw);
|
|
13
|
+
c.set("evupAuth", auth);
|
|
14
|
+
c.set("session", session);
|
|
15
|
+
c.set("user", session?.user ?? null);
|
|
16
|
+
await next();
|
|
17
|
+
for (const cookie of headers.getSetCookie())
|
|
18
|
+
c.header("Set-Cookie", cookie, { append: true });
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Lets only signed-in users through. Browser navigations (Accept: text/html) go to the sign-in route and come back;
|
|
23
|
+
* anything else gets a 401 JSON error. Needs `evupAuth()` earlier in the chain.
|
|
24
|
+
*/
|
|
25
|
+
export function requireUser() {
|
|
26
|
+
return async (c, next) => {
|
|
27
|
+
if (c.get("user"))
|
|
28
|
+
return next();
|
|
29
|
+
const auth = c.get("evupAuth");
|
|
30
|
+
if (!auth)
|
|
31
|
+
throw new Error("requireUser() needs the evupAuth() middleware before it");
|
|
32
|
+
if (c.req.method === "GET" && (c.req.header("accept") ?? "").includes("text/html")) {
|
|
33
|
+
const url = new URL(c.req.url);
|
|
34
|
+
return c.redirect(`${auth.basePath}/sign-in?${new URLSearchParams({ returnTo: url.pathname + url.search })}`, 302);
|
|
35
|
+
}
|
|
36
|
+
return c.json({ error: "unauthorized", error_description: "Sign in required" }, 401);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Protects a route as an OAuth resource server: verifies the Bearer token, sets `c.var.evupToken`, serves the metadata path. */
|
|
40
|
+
export function evupResource(resource) {
|
|
41
|
+
return async (c, next) => {
|
|
42
|
+
const req = c.req.raw;
|
|
43
|
+
if (req.method === "OPTIONS")
|
|
44
|
+
return resource.preflightResponse();
|
|
45
|
+
if (new URL(req.url).pathname.replace(/\/+$/, "") === resource.metadataPath && (req.method === "GET" || req.method === "HEAD"))
|
|
46
|
+
return resource.metadataResponse();
|
|
47
|
+
const result = await resource.verify(req);
|
|
48
|
+
if (!result.ok)
|
|
49
|
+
return result.response;
|
|
50
|
+
c.set("evupToken", result.token);
|
|
51
|
+
return next();
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { NextRequest } from "next/server.js";
|
|
2
|
+
import type { EvupAuth, EvupUser, Session } from "../server/types.js";
|
|
3
|
+
export type { EvupAuth, EvupUser, Session } from "../server/types.js";
|
|
4
|
+
/** Route handlers for `app/auth/[...evup]/route.ts`: `export const { GET, POST } = handlers(auth)`. */
|
|
5
|
+
export declare function handlers(auth: EvupAuth): {
|
|
6
|
+
GET: (req: Request) => Promise<Response>;
|
|
7
|
+
POST: (req: Request) => Promise<Response>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The session of the current request, for Server Components, Server Actions and route handlers.
|
|
11
|
+
* Read-only: it never refreshes (see `readSession`). `session.expiresAt` can already be in the past when `withEvupAuth` does not
|
|
12
|
+
* run for this path; with `withEvupAuth` in front, the access token has at least two minutes left when the render starts.
|
|
13
|
+
*/
|
|
14
|
+
export declare function getSession(auth: EvupAuth): Promise<Session | null>;
|
|
15
|
+
export declare function getUser(auth: EvupAuth): Promise<EvupUser | null>;
|
|
16
|
+
export type WithEvupAuthOptions = {
|
|
17
|
+
/** Path prefixes that need a signed-in user, e.g. ["/dashboard", "/settings"]. "/dashboard" covers "/dashboard/x". */
|
|
18
|
+
protect?: string[];
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* For `middleware.ts` (Next.js up to 15) or `proxy.ts` (Next.js 16): refreshes the session cookie (starting 120 s before expiry),
|
|
22
|
+
* sends visitors of protected paths to the sign-in route (page navigations) or answers 401 JSON (API calls),
|
|
23
|
+
* and hands the refreshed cookie to the page being rendered.
|
|
24
|
+
*/
|
|
25
|
+
export declare function withEvupAuth(auth: EvupAuth, options?: WithEvupAuthOptions): (req: NextRequest) => Promise<Response>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { headers } from "next/headers.js";
|
|
2
|
+
import { NextResponse } from "next/server.js";
|
|
3
|
+
import { parseSetCookie } from "../server/cookie.js";
|
|
4
|
+
import { readSession } from "./read.js";
|
|
5
|
+
/** Route handlers for `app/auth/[...evup]/route.ts`: `export const { GET, POST } = handlers(auth)`. */
|
|
6
|
+
export function handlers(auth) {
|
|
7
|
+
const run = async (req) => (await auth.handler(req)) ?? new Response("Not Found", { status: 404 });
|
|
8
|
+
return { GET: run, POST: run };
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The session of the current request, for Server Components, Server Actions and route handlers.
|
|
12
|
+
* Read-only: it never refreshes (see `readSession`). `session.expiresAt` can already be in the past when `withEvupAuth` does not
|
|
13
|
+
* run for this path; with `withEvupAuth` in front, the access token has at least two minutes left when the render starts.
|
|
14
|
+
*/
|
|
15
|
+
export async function getSession(auth) {
|
|
16
|
+
return readSession(auth, await headers());
|
|
17
|
+
}
|
|
18
|
+
export async function getUser(auth) {
|
|
19
|
+
return (await getSession(auth))?.user ?? null;
|
|
20
|
+
}
|
|
21
|
+
const covers = (prefix, path) => {
|
|
22
|
+
const p = prefix.replace(/\/+$/, "") || "/";
|
|
23
|
+
return p === "/" || path === p || path.startsWith(`${p}/`);
|
|
24
|
+
};
|
|
25
|
+
/** Seconds before expiry at which the middleware refreshes: larger than the default so Server Components (which never refresh) see a fresh token. */
|
|
26
|
+
const MIDDLEWARE_REFRESH_WINDOW = 120;
|
|
27
|
+
/** A page navigation (including Next.js client-side navigations, which fetch RSC payloads) as opposed to an API call. */
|
|
28
|
+
function isNavigation(req) {
|
|
29
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
30
|
+
return false;
|
|
31
|
+
return (req.headers.get("accept") ?? "").includes("text/html") || req.headers.has("rsc");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* For `middleware.ts` (Next.js up to 15) or `proxy.ts` (Next.js 16): refreshes the session cookie (starting 120 s before expiry),
|
|
35
|
+
* sends visitors of protected paths to the sign-in route (page navigations) or answers 401 JSON (API calls),
|
|
36
|
+
* and hands the refreshed cookie to the page being rendered.
|
|
37
|
+
*/
|
|
38
|
+
export function withEvupAuth(auth, options = {}) {
|
|
39
|
+
return async (req) => {
|
|
40
|
+
const served = await auth.handler(req);
|
|
41
|
+
if (served)
|
|
42
|
+
return served;
|
|
43
|
+
const { session, headers: out } = await auth.getSession(req, { refreshWindow: MIDDLEWARE_REFRESH_WINDOW });
|
|
44
|
+
const setCookies = out.getSetCookie();
|
|
45
|
+
const path = req.nextUrl.pathname;
|
|
46
|
+
const protectedPath = (options.protect ?? []).some((prefix) => covers(prefix, path));
|
|
47
|
+
let response;
|
|
48
|
+
if (!session && protectedPath && !isNavigation(req)) {
|
|
49
|
+
response = NextResponse.json({ error: "unauthorized", error_description: "Sign in required" }, { status: 401 });
|
|
50
|
+
}
|
|
51
|
+
else if (!session && protectedPath) {
|
|
52
|
+
const target = new URL(`${auth.basePath}/sign-in`, req.url);
|
|
53
|
+
target.searchParams.set("returnTo", path + req.nextUrl.search);
|
|
54
|
+
response = NextResponse.redirect(target);
|
|
55
|
+
}
|
|
56
|
+
else if (setCookies.length > 0) {
|
|
57
|
+
// Downstream (Server Components) must see the new cookie too, not only the browser
|
|
58
|
+
const requestHeaders = new Headers(req.headers);
|
|
59
|
+
const jar = new Map();
|
|
60
|
+
for (const part of (req.headers.get("cookie") ?? "").split(";")) {
|
|
61
|
+
const eq = part.indexOf("=");
|
|
62
|
+
if (eq > 0)
|
|
63
|
+
jar.set(part.slice(0, eq).trim(), part.slice(eq + 1).trim());
|
|
64
|
+
}
|
|
65
|
+
for (const raw of setCookies) {
|
|
66
|
+
const c = parseSetCookie(raw);
|
|
67
|
+
if (!c)
|
|
68
|
+
continue;
|
|
69
|
+
if (c.maxAge === 0)
|
|
70
|
+
jar.delete(c.name);
|
|
71
|
+
else
|
|
72
|
+
jar.set(c.name, c.value);
|
|
73
|
+
}
|
|
74
|
+
requestHeaders.set("cookie", [...jar].map(([k, v]) => `${k}=${v}`).join("; "));
|
|
75
|
+
response = NextResponse.next({ request: { headers: requestHeaders } });
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
response = NextResponse.next();
|
|
79
|
+
}
|
|
80
|
+
for (const cookie of setCookies)
|
|
81
|
+
response.headers.append("set-cookie", cookie);
|
|
82
|
+
return response;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { EvupAuth, Session } from "../server/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The session for a Server Component render, from the request headers alone. It never refreshes: Server Components cannot
|
|
4
|
+
* set cookies, and a refresh that the browser never hears about would spend the rotated refresh token and revoke the whole
|
|
5
|
+
* token family on the next request. Refreshing is left to `withEvupAuth` (and route handlers), which can set the cookie.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readSession(auth: EvupAuth, h: Headers): Promise<Session | null>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session for a Server Component render, from the request headers alone. It never refreshes: Server Components cannot
|
|
3
|
+
* set cookies, and a refresh that the browser never hears about would spend the rotated refresh token and revoke the whole
|
|
4
|
+
* token family on the next request. Refreshing is left to `withEvupAuth` (and route handlers), which can set the cookie.
|
|
5
|
+
*/
|
|
6
|
+
export async function readSession(auth, h) {
|
|
7
|
+
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost";
|
|
8
|
+
const proto = h.get("x-forwarded-proto") ?? "https";
|
|
9
|
+
const req = new Request(`${proto}://${host}${auth.basePath}/session`, { headers: { cookie: h.get("cookie") ?? "" } });
|
|
10
|
+
return (await auth.getSession(req, { refresh: false })).session;
|
|
11
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { JWTPayload } from "jose";
|
|
2
|
+
export { EvupAuthError } from "../errors.js";
|
|
3
|
+
export type EvupResourceConfig = {
|
|
4
|
+
/** The resource URL registered in the app's "API resources" card. It is the `aud` the token must carry. */
|
|
5
|
+
resource: string;
|
|
6
|
+
/** Default "https://auth.evup.cloud/api/auth". */
|
|
7
|
+
issuer?: string;
|
|
8
|
+
/** Advertised in the metadata and required on every token. */
|
|
9
|
+
scopes?: string[];
|
|
10
|
+
resourceName?: string;
|
|
11
|
+
/** Seconds of clock skew accepted on `exp` / `nbf`. Default 30. */
|
|
12
|
+
clockTolerance?: number;
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
};
|
|
15
|
+
export type EvupAccessToken = {
|
|
16
|
+
/** The user id. */
|
|
17
|
+
sub: string;
|
|
18
|
+
/** The OAuth client the token was issued to (`azp`). */
|
|
19
|
+
clientId: string;
|
|
20
|
+
scopes: string[];
|
|
21
|
+
permissions: string[];
|
|
22
|
+
/** Expiry, seconds since the epoch. */
|
|
23
|
+
exp: number;
|
|
24
|
+
/** All claims of the verified token. */
|
|
25
|
+
claims: JWTPayload;
|
|
26
|
+
};
|
|
27
|
+
export type VerifyResult = {
|
|
28
|
+
ok: true;
|
|
29
|
+
token: EvupAccessToken;
|
|
30
|
+
} | {
|
|
31
|
+
ok: false;
|
|
32
|
+
status: 401 | 403;
|
|
33
|
+
response: Response;
|
|
34
|
+
};
|
|
35
|
+
export interface EvupResource {
|
|
36
|
+
/** Path the protected resource metadata is served at: "/.well-known/oauth-protected-resource" + the resource path. */
|
|
37
|
+
readonly metadataPath: string;
|
|
38
|
+
/** The RFC 9728 document. */
|
|
39
|
+
metadata(): Record<string, unknown>;
|
|
40
|
+
metadataResponse(): Response;
|
|
41
|
+
/** Checks the Bearer token of a request (or a raw token / "Bearer ..." header value). */
|
|
42
|
+
verify(req: Request | string): Promise<VerifyResult>;
|
|
43
|
+
/** The answer to a CORS preflight (OPTIONS): 204 with the headers a browser-based MCP client needs. */
|
|
44
|
+
preflightResponse(): Response;
|
|
45
|
+
/** Answers OPTIONS preflights, serves the metadata path, otherwise verifies the token and calls `next`. */
|
|
46
|
+
handle(req: Request, next: (req: Request, token: EvupAccessToken) => Promise<Response>): Promise<Response>;
|
|
47
|
+
}
|
|
48
|
+
export declare function createEvupResource(config: EvupResourceConfig): EvupResource;
|