Some checks failed
Node.js CI - Dockge / ${{ matrix.os }} (22, ubuntu-latest) (push) Successful in 1m47s
json-yaml-validate / json-yaml-validate (push) Successful in 12s
Nightly Release / release-nightly (push) Failing after 44s
Node.js CI - Dockge / ${{ matrix.os }} (22, macos-latest) (push) Has been cancelled
Node.js CI - Dockge / ${{ matrix.os }} (22, windows-latest) (push) Has been cancelled
88 lines
3.1 KiB
TypeScript
88 lines
3.1 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
import jwt from "jsonwebtoken";
|
|
import type { Knex } from "knex";
|
|
import { R } from "redbean-node";
|
|
import { shake256, SHAKE256_LENGTH } from "./password-hash";
|
|
|
|
const maxTokenAge = 30 * 24 * 60 * 60;
|
|
const pending = new Map<string, Promise<void>>();
|
|
|
|
export interface AuthSession {
|
|
fingerprint: string;
|
|
expiresAt: number;
|
|
}
|
|
|
|
function sessionFor(token: string, expiresAt: number): AuthSession {
|
|
const signedContent = token.slice(0, token.lastIndexOf("."));
|
|
return {
|
|
fingerprint: createHash("sha256").update(signedContent).digest("hex"),
|
|
expiresAt,
|
|
};
|
|
}
|
|
|
|
/** Issue a distinct token for each credential login. */
|
|
export function issueSession(username: string, passwordHash: string, secret: string) {
|
|
const iat = Math.floor(Date.now() / 1000);
|
|
const token = jwt.sign({
|
|
username,
|
|
h: shake256(passwordHash, SHAKE256_LENGTH),
|
|
iat,
|
|
}, secret, {
|
|
algorithm: "HS256",
|
|
expiresIn: maxTokenAge,
|
|
jwtid: randomUUID(),
|
|
});
|
|
return {
|
|
token,
|
|
session: sessionFor(token, iat + maxTokenAge),
|
|
};
|
|
}
|
|
|
|
/** Verify signed claims before deriving the identity of a new or legacy token. */
|
|
export function verifySession(token: string, secret: string) {
|
|
const decoded = jwt.verify(token, secret, {
|
|
algorithms: [ "HS256" ],
|
|
maxAge: maxTokenAge,
|
|
});
|
|
if (typeof decoded === "string" || typeof decoded.username !== "string" || typeof decoded.h !== "string"
|
|
|| typeof decoded.iat !== "number") {
|
|
throw new Error("Invalid session claims");
|
|
}
|
|
const expiresAt = Math.min(decoded.exp ?? Infinity, decoded.iat + maxTokenAge);
|
|
return {
|
|
username: decoded.username,
|
|
passwordFingerprint: decoded.h,
|
|
session: sessionFor(token, expiresAt),
|
|
};
|
|
}
|
|
|
|
/** Serialize token login and revocation so that a concurrent login cannot survive logout. */
|
|
export async function withSession<T>(session: AuthSession, action: () => Promise<T>): Promise<T> {
|
|
const operation = (pending.get(session.fingerprint) ?? Promise.resolve()).then(action);
|
|
const tail = operation.then(() => {}, () => {});
|
|
pending.set(session.fingerprint, tail);
|
|
try {
|
|
return await operation;
|
|
} finally {
|
|
if (pending.get(session.fingerprint) === tail) {
|
|
pending.delete(session.fingerprint);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Check the persisted revocation before accepting a token. */
|
|
export async function isSessionRevoked(session: AuthSession): Promise<boolean> {
|
|
return Boolean(await R.knex("revoked_token").where("fingerprint", session.fingerprint).first());
|
|
}
|
|
|
|
/** Persist a revocation and remove records for tokens past their acceptance window. */
|
|
export async function revokeSession(session: AuthSession): Promise<void> {
|
|
await R.knex.transaction(async (trx: Knex.Transaction) => {
|
|
await trx("revoked_token").insert({
|
|
fingerprint: session.fingerprint,
|
|
expires_at: session.expiresAt,
|
|
}).onConflict("fingerprint").ignore();
|
|
await trx("revoked_token").where("expires_at", "<=", Math.floor(Date.now() / 1000)).delete();
|
|
});
|
|
}
|