@cipherstash/nextjs
Version:
Nextjs package for use with @cipherstash/protect
283 lines (277 loc) • 9.15 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
CS_COOKIE_NAME: () => CS_COOKIE_NAME,
getCtsToken: () => getCtsToken,
protectMiddleware: () => protectMiddleware,
resetCtsToken: () => resetCtsToken
});
module.exports = __toCommonJS(index_exports);
var import_jose = require("jose");
var import_headers = require("next/headers");
var import_server2 = require("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
var import_server = require("next/server");
// ../utils/config/index.ts
var import_node_fs = __toESM(require("fs"));
var import_node_path = __toESM(require("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 = import_node_path.default.join(process.cwd(), "cipherstash.toml");
if (!import_node_fs.default.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 (!import_node_fs.default.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 = import_node_fs.default.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 ?? import_server.NextResponse.next();
}
const response = res ?? import_server.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 = (0, import_jose.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 (0, import_headers.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 = import_server2.NextResponse.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 ?? import_server2.NextResponse.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 import_server2.NextResponse.next();
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CS_COOKIE_NAME,
getCtsToken,
protectMiddleware,
resetCtsToken
});
//# sourceMappingURL=index.cjs.map
;