UNPKG

@cipherstash/nextjs

Version:

Nextjs package for use with @cipherstash/protect

248 lines (242 loc) 7.24 kB
// src/index.ts import { decodeJwt } from "jose"; import { cookies } from "next/headers"; import { NextResponse as NextResponse2 } from "next/server"; // ../utils/logger/index.ts function getLevelValue(level) { switch (level) { case "debug": return 10; case "info": return 20; case "error": return 30; default: return 30; } } var envLogLevel = process.env.PROTECT_LOG_LEVEL || "info"; var currentLevel = getLevelValue(envLogLevel); function debug(...args) { if (currentLevel <= getLevelValue("debug")) { console.debug("[protect] DEBUG", ...args); } } function info(...args) { if (currentLevel <= getLevelValue("info")) { console.info("[protect] INFO", ...args); } } function error(...args) { if (currentLevel <= getLevelValue("error")) { console.error("[protect] ERROR", ...args); } } var logger = { debug, info, error }; // src/cts/index.ts import { NextResponse } from "next/server"; // ../utils/config/index.ts import fs from "node:fs"; import path from "node:path"; function getWorkspaceCrn(tomlString) { let currentSection = ""; let workspaceCrn; const lines = tomlString.split(/\r?\n/); for (const line of lines) { const trimmedLine = line.trim(); if (!trimmedLine || trimmedLine.startsWith("#")) { continue; } const sectionMatch = trimmedLine.match(/^\[([^\]]+)\]$/); if (sectionMatch) { currentSection = sectionMatch[1]; continue; } const kvMatch = trimmedLine.match(/^(\w+)\s*=\s*"([^"]+)"$/); if (kvMatch) { const [_, key, value] = kvMatch; if (currentSection === "auth" && key === "workspace_crn") { workspaceCrn = value; break; } } } return workspaceCrn; } function extractWorkspaceIdFromCrn(crn) { const match = crn.match(/crn:[^:]+:([^:]+)$/); if (!match) { throw new Error("Invalid CRN format"); } return match[1]; } function loadWorkSpaceId() { const configPath = path.join(process.cwd(), "cipherstash.toml"); if (!fs.existsSync(configPath) && !process.env.CS_WORKSPACE_CRN) { throw new Error( "You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable." ); } if (process.env.CS_WORKSPACE_CRN) { return extractWorkspaceIdFromCrn(process.env.CS_WORKSPACE_CRN); } if (!fs.existsSync(configPath)) { throw new Error( "You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable." ); } const tomlString = fs.readFileSync(configPath, "utf8"); const workspaceCrn = getWorkspaceCrn(tomlString); if (!workspaceCrn) { throw new Error( "You have not defined a workspace CRN in your config file, or the CS_WORKSPACE_CRN environment variable." ); } return extractWorkspaceIdFromCrn(workspaceCrn); } // src/cts/index.ts var fetchCtsToken = async (oidcToken) => { const workspaceId = loadWorkSpaceId(); if (!workspaceId) { logger.error( 'The "CS_WORKSPACE_ID" environment variable is not set, and is required by protectClerkMiddleware. No CipherStash session will be set.' ); return { success: false, error: 'The "CS_WORKSPACE_ID" environment variable is not set.' }; } const ctsEndoint = process.env.CS_CTS_ENDPOINT || "https://ap-southeast-2.aws.auth.viturhosted.net"; const ctsResponse = await fetch(`${ctsEndoint}/api/authorize`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ workspaceId, oidcToken }) }); if (!ctsResponse.ok) { logger.debug(`Failed to fetch CTS token: ${ctsResponse.statusText}`); logger.error( "There was an issue communicating with the CipherStash CTS API, the CipherStash session was not set. If the issue persists, please contact support." ); return { success: false, error: `Failed to fetch CTS token: ${ctsResponse.statusText}` }; } const cts_token = await ctsResponse.json(); return { success: true, ctsToken: cts_token }; }; var setCtsToken = async (oidcToken, res) => { const ctsResponse = await fetchCtsToken(oidcToken); const cts_token = ctsResponse.ctsToken; if (!cts_token) { logger.debug(`Failed to fetch CTS token: ${ctsResponse.error}`); logger.error( "There was an issue fetching the CipherStash session, the CipherStash session was not set. If the issue persists, please contact support." ); return res ?? NextResponse.next(); } const response = res ?? NextResponse.next(); response.cookies.set({ name: CS_COOKIE_NAME, value: JSON.stringify(cts_token), expires: new Date(cts_token.expiry * 1e3), sameSite: "lax", path: "/" }); return response; }; // src/index.ts function getSubjectFromToken(jwt) { const payload = decodeJwt(jwt); if (typeof payload?.sub === "string" && payload?.sub.startsWith("CS|")) { return payload.sub.slice(3); } return payload?.sub; } var CS_COOKIE_NAME = "__cipherstash_cts_session"; var getCtsToken = async (oidcToken) => { const cookieStore = await cookies(); const cookieData = cookieStore.get(CS_COOKIE_NAME)?.value; if (oidcToken && !cookieData) { logger.debug( "The CipherStash session cookie was not found in the request, but a JWT token was provided. The JWT token will be used to fetch a new CipherStash session." ); return await fetchCtsToken(oidcToken); } if (!cookieData) { logger.debug("No CipherStash session cookie found in the request."); return { success: false, error: "No CipherStash session cookie found in the request." }; } const cts_token = JSON.parse(cookieData); return { success: true, ctsToken: cts_token }; }; var resetCtsToken = (res) => { if (res) { res.cookies.delete(CS_COOKIE_NAME); return res; } const response = NextResponse2.next(); response.cookies.delete(CS_COOKIE_NAME); return response; }; var protectMiddleware = async (oidcToken, req, res) => { const ctsSession = req.cookies.get(CS_COOKIE_NAME)?.value; if (oidcToken && ctsSession) { const ctsToken = JSON.parse(ctsSession); const ctsTokenSubject = getSubjectFromToken(ctsToken.accessToken); const oidcTokenSubject = getSubjectFromToken(oidcToken); if (ctsTokenSubject === oidcTokenSubject) { logger.debug( "The JWT token and the CipherStash session are both valid for the same user." ); return res ?? NextResponse2.next(); } return await setCtsToken(oidcToken, res); } if (oidcToken && !ctsSession) { logger.debug( "The JWT token was defined, so the CipherStash session will be set." ); return await setCtsToken(oidcToken, res); } if (!oidcToken && ctsSession) { logger.debug( "The JWT token was undefined, so the CipherStash session was reset." ); return resetCtsToken(res); } logger.debug( "The JWT token was undefined, so the CipherStash session was not set." ); if (res) { return res; } return NextResponse2.next(); }; export { logger, setCtsToken, CS_COOKIE_NAME, getCtsToken, resetCtsToken, protectMiddleware }; //# sourceMappingURL=chunk-GVV2ST3S.js.map