Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions middleware/aiblock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ import type { Middleware, NextHandler } from "./main.ts";
import { UserAgent } from "@std/http";
import { STATUS_CODE, STATUS_TEXT } from "@std/http/status";

interface Options {}

export async function aiblock(options?: Options): Promise<Middleware> {
/**
* Creates a middleware that responds with `403 Forbidden` to requests from
* known AI crawlers. The blocklist is fetched once, when this is called.
*/
export async function aiblock(): Promise<Middleware> {
const fetchBlocklist = await fetch(
"https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/refs/heads/main/haproxy-block-ai-bots.txt",
);
const blocklist: string[] = (await fetchBlocklist.text()).split("\n");
// Drop empty lines: `"".includes()` matches every user agent and would block all requests.
const blocklist: string[] = (await fetchBlocklist.text())
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
return function aiblockMiddleware(
request: Request,
next: NextHandler,
Expand Down
29 changes: 18 additions & 11 deletions middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import type { Middleware, NextHandler } from "./main.ts";
import { getCookies } from "@std/http/cookie";
import { STATUS_TEXT, STATUS_CODE } from "@std/http/status";
import { STATUS_CODE, STATUS_TEXT } from "@std/http/status";

interface Options {
only: Array<Record<string, string>>
except: Record<string, string>
signin: string | null
/** Options for the {@linkcode auth} middleware. */
export interface Options {
/** Path of the sign-in page. Requests to it are never redirected. Defaults to `/signin`. */
signin?: string;
}

/**
* Redirects requests without an `authenticated` cookie to the sign-in page.
*
* This only checks that the cookie is present, not that its value was issued by
* the server, so it must not be relied on as real authentication.
*/
export default function auth(options?: Options): Middleware {
const only = options?.only;
const except = options?.except;
const signin = '/signin';
return async function authMiddleware(request: Request, next: NextHandler): Promise<Response> {
const signin = options?.signin ?? "/signin";
return async function authMiddleware(
request: Request,
next: NextHandler,
): Promise<Response> {
const url = new URL(request.url);
const cookies = getCookies(request.headers);
const allowed = cookies?.authenticated || url.pathname === signin;
Expand All @@ -24,10 +31,10 @@ export default function auth(options?: Options): Middleware {
const status = STATUS_CODE.Found;
const text = STATUS_TEXT[status];
const headers = new Headers(request.headers);
headers.set('location', signin);
headers.set("location", signin);
return new Response(text, {
status,
headers
headers,
});
};
}
Expand Down
4 changes: 2 additions & 2 deletions middleware/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ export default function csrf(): Middleware {

if (
contentType &&
contentType.includes("application/x-www-form-urlencoded") ||
contentType.includes("application/x-www-form-urlencoded") ||
contentType &&
contentType.includes("multipart/form-data")
contentType.includes("multipart/form-data")
) {
try {
const cloned = request.clone();
Expand Down
2 changes: 1 addition & 1 deletion middleware/example/serve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetch from "./main.ts";

export default {
fetch
fetch,
} satisfies Deno.ServeDefaultExport;
13 changes: 8 additions & 5 deletions middleware/logger.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { NextHandler } from "./main.ts";

export async function logger(req: Request, next: NextHandler): Promise<Response> {
console.log(`--> ${req.method} ${req.url}`);
const res = await next();
console.log(`<-- ${res.status}`);
return res;
export async function logger(
req: Request,
next: NextHandler,
): Promise<Response> {
console.log(`--> ${req.method} ${req.url}`);
const res = await next();
console.log(`<-- ${res.status}`);
return res;
}

export default logger;
36 changes: 18 additions & 18 deletions middleware/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import { assertEquals } from "jsr:@std/assert";
import { assertEquals } from "@std/assert";
import { compose, type Middleware } from "./main.ts";

Deno.test("middleware runs in order", async () => {
const trace: string[] = [];
const trace: string[] = [];

const mw1: Middleware = async (req, next) => {
trace.push("mw1-start");
const res = await next();
trace.push("mw1-end");
return res;
};
const mw1: Middleware = async (_req, next) => {
trace.push("mw1-start");
const res = await next();
trace.push("mw1-end");
return res;
};

const mw2: Middleware = async (req, next) => {
trace.push("mw2-start");
const res = await next();
trace.push("mw2-end");
return res;
};
const mw2: Middleware = async (_req, next) => {
trace.push("mw2-start");
const res = await next();
trace.push("mw2-end");
return res;
};

const handler = () => new Response("OK");
const composed = compose([mw1, mw2], handler);
const handler = () => new Response("OK");
const composed = compose([mw1, mw2], handler);

await composed(new Request("http://localhost"));
assertEquals(trace, ["mw1-start", "mw2-start", "mw2-end", "mw1-end"]);
await composed(new Request("http://localhost"));
assertEquals(trace, ["mw1-start", "mw2-start", "mw2-end", "mw1-end"]);
});
30 changes: 15 additions & 15 deletions middleware/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@ import loggerMiddleware from "./logger.ts";
import serveStaticMiddleware from "./static.ts";

/**
* This modules defines types used for middleware. It exports `compose()` and some helpers like: `insert()` & `replace()` for manipulating a stack of middleware.
* This module defines the types used for middleware. It exports `compose()` and
* some helpers like `insert()`, `replace()` and `remove()` for manipulating a
* stack of middleware.
*
* @example
* ```ts

import { compose, Middleware } from "jsr:@stewpot/middleware";

const logger: Middleware = async (request, next) => {
console.log(`${request.method} ${request.url}`);
return await next();
};

const handler = compose([logger], () => {
return new Response("Hello from final handler!");
});

Deno.serve(handler);
```
* import { compose, type Middleware } from "jsr:@stewpot/middleware";
*
* const logger: Middleware = async (request, next) => {
* console.log(`${request.method} ${request.url}`);
* return await next();
* };
*
* const handler = compose([logger], () => {
* return new Response("Hello from final handler!");
* });
*
* Deno.serve(handler);
* ```
*
* @module
*/
Expand Down
114 changes: 34 additions & 80 deletions middleware/session.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { getCookies, setCookie } from "@std/http/cookie";
import { ulid } from "jsr:@std/ulid/ulid";
import type { Middleware, NextHandler } from "./main.ts";

const SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes

/** Options for the {@linkcode session} middleware. */
export interface Options {
url?: string | null,
kv?: Deno.Kv,
key?: string
/** Deno KV store that sessions are persisted in. */
kv?: Deno.Kv;
}

type Session = {
Expand All @@ -34,7 +31,9 @@ async function createSession(kv: Deno.Kv, userId?: string): Promise<Session> {
expiresAt: now.add(SESSION_TTL).toString(),
userId,
};
await kv.set(["session", id], sess, { expireIn: SESSION_TTL.total("milliseconds") });
await kv.set(["session", id], sess, {
expireIn: SESSION_TTL.total("milliseconds"),
});
return sess;
}

Expand All @@ -47,44 +46,53 @@ async function touchSession(kv: Deno.Kv, session: Session): Promise<void> {
const now = Temporal.Now.instant();
session.lastSeen = now.toString();
session.expiresAt = now.add(SESSION_TTL).toString();
await kv.set(["session", session.id], session, { expireIn: SESSION_TTL.total("milliseconds") });
await kv.set(["session", session.id], session, {
expireIn: SESSION_TTL.total("milliseconds"),
});
}

/**
*
* Rotate session when user authenticates.
*
* Rotate the session when a user authenticates: the previous session is
* deleted and a new one is created for the given user.
*
* @example
*
* ```ts
* const url = new URL(req.url);
* if (url.pathname === "/login" && req.method === "POST") {
* const userId = "user123";
* session = await rotateSession(session, userId);
* session = await rotateSession(kv, session, userId);
* }
* ```
*
*
* @param kv Deno.Kv instance
* @param prevSession Previous session to rotate
* @param userId Id for current user
* @returns
* @returns The newly created session
*/
async function rotateSession(kv: Deno.Kv, prevSession: Session, userId?: string): Promise<Session> {
export async function rotateSession(
kv: Deno.Kv,
prevSession: Session,
userId?: string,
): Promise<Session> {
await kv.delete(["session", prevSession.id]);
return await createSession(kv, userId);
}

export default function session(options?: Options): Middleware {
const kv = options?.kv || null;
const kvKey = options?.key || 'sessions';
if (!kv) {
throw new Error(
'No access to any KV Store for sessions!'
)
"No access to any KV Store for sessions!",
);
}
return async function sessionMiddleware(request: Request, next: NextHandler): Promise<Response> {
return async function sessionMiddleware(
request: Request,
next: NextHandler,
): Promise<Response> {
const cookies = getCookies(request.headers);
let session: Session | null = cookies[COOKIE_NAME] ? await getSession(kv, cookies[COOKIE_NAME]) : null;
let session: Session | null = cookies[COOKIE_NAME]
? await getSession(kv, cookies[COOKIE_NAME])
: null;

if (!session) {
session = await createSession(kv);
Expand All @@ -102,69 +110,15 @@ export default function session(options?: Options): Middleware {
httpOnly: true,
secure: true,
sameSite: "Lax",
expires: new Date(Temporal.Instant.from(session.expiresAt).epochMilliseconds),
expires: new Date(
Temporal.Instant.from(session.expiresAt).epochMilliseconds,
),
});

/*
const url = new URL(request.url);
const https = url.protocol === 'https:';
const cookies = getCookies(request.headers);
const timestamp = Temporal.Now.instant();

let sessionId: string | null = cookies["session_id"];
let kvTimestamp: Temporal.Instant | null = null;
let isNew = false;

if (sessionId) {
const key = [kvKey, sessionId];
const session = await kv.get<{ timestamp: string }>(key);
if (session?.value?.timestamp) {
kvTimestamp = Temporal.Instant.from(session.value.timestamp);
const diff = timestamp.epochMilliseconds - kvTimestamp.epochMilliseconds;
if (diff > SESSION_TTL_MS) {
sessionId = null;
}
} else {
sessionId = null;
}
}

if (!sessionId) {
sessionId = ulid();
const key = [kvKey, sessionId];
const data = {
timestamp: timestamp.toString(),
ip: request.headers.get('host'),
userAgent: request.headers.get('user-agent')
};
const options = { expireIn: SESSION_TTL_MS };
const entry = await kv.set(key, data, options);
if (entry.ok) {
console.log({ message: "[INFO] Successfully created session entry in kv store." });
}
isNew = true;
}

const response = await next();
const headers = new Headers(response.headers);

if (isNew) {
setCookie(headers, {
name: "session_id",
value: sessionId,
path: "/",
httpOnly: true,
secure: url.hostname !== 'localhost' && https,
sameSite: "Strict",
maxAge: SESSION_TTL_MS / 1000,
});
}
// */

if (!request.headers.get('upgrade')) {
if (!request.headers.get("upgrade")) {
return new Response(response.body, {
status: response.status,
headers
headers,
});
}

Expand Down
Loading