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

ReusableDevAuth.ts

31 lines1.3 KB

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