Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReusableDevAuth.ts

33 lines1.4 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Digest is effectful; this resolves the dev token synchronously at startup.
2import * as NodeCrypto from "node:crypto";
3import { AuthSessionId } from "@t3tools/contracts";
4import * as Mac from "effect/crypto/Mac";
5import * as DateTime from "effect/DateTime";
6import * as Redacted from "effect/Redacted";
7​
8import type { ServerConfig } from "../config.ts";
9​
10export const REUSABLE_DEV_SESSION_PREFIX = "dev-auth-";
11// The database schema requires an expiry for a configured token with no normal session TTL.
12export const REUSABLE_DEV_SESSION_EXPIRES_AT = DateTime.makeUnsafe("9999-12-31T23:59:59.999Z");
13​
14export function resolveReusableDevAuth(
15 config: Pick<ServerConfig["Service"], "mode" | "devUrl" | "devAuthToken">,
16) {
17 if (config.mode !== "web" || config.devUrl === undefined || config.devAuthToken === undefined) {
18 return undefined;
19 }
20 const token = config.devAuthToken;
21 if (Redacted.value(token).length === 0) {
22 return undefined;
23 }
24 const hash = NodeCrypto.createHash("sha256").update(Redacted.value(token)).digest();
25 const tokenId = hash.toString("hex");
26 return {
27 credential: Redacted.value(token),
28 sessionId: AuthSessionId.make(`${REUSABLE_DEV_SESSION_PREFIX}${tokenId}`),
29 cookieName: `t3_dev_session_${tokenId}`,
30 matches: (credential: string) =>
31 Mac.timingSafeEqual(hash, NodeCrypto.createHash("sha256").update(credential).digest()),
32 };