Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 33 additions & 13 deletions server/api/projectfiles.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logger from "../logger.js";
import logger, { childLogger } from "../logger.js";
import { NextFunction, Request, Response } from "express";
import conductorErrors from "../conductor-errors.js";
import ProjectFile, {
Expand All @@ -22,8 +22,10 @@ import { isObjectIdOrHexString } from "mongoose";
import async from "async";
import {
assembleUrl,
getCommonsCanonicalURL,
getPaginationOffset,
getRandomOffset,
isCanonicalCommonsInstance,
} from "../util/helpers.js";
import {
CopyObjectCommand,
Expand Down Expand Up @@ -75,6 +77,7 @@ import { generateVideoStreamURL } from "../util/videoutils.js";
import axios from "axios";
import mime from "mime";

const permalinkLog = childLogger("permalink");
const filesStorage = multer.memoryStorage();
const MAX_UPLOAD_FILES = 20;
const MAX_UPLOAD_FILE_SIZE = 100000000; // 100mb
Expand Down Expand Up @@ -634,14 +637,6 @@ async function getPermanentLink(
});
}

const { orgID } = project;
const organization = await Organization.findOne({ orgID }).lean();
if (!organization) {
return res.status(404).send({
err: true,
errMsg: conductorErrors.err11,
});
}
const projectFile = await ProjectFile.findOne({
projectID,
fileID,
Expand All @@ -659,8 +654,7 @@ async function getPermanentLink(
errMsg: conductorErrors.err29
});
}
const domain = organization.domain;
const permanentLink = `${domain}/permalink/${projectID}/${fileID}`;
const permanentLink = `${getCommonsCanonicalURL()}/permalink/${projectID}/${fileID}`;
return res.status(200).send({
error: false,
url: permanentLink,
Expand All @@ -675,13 +669,39 @@ async function getPermanentLink(
}
}

function receivingHost(req: Request) {
return (req.get("host") || "").toLowerCase();
}

async function redirectPermanentLink(
req: ZodReqWithOptionalUser<z.infer<typeof getProjectFileDownloadURLSchema>>,
req: Request &
ZodReqWithOptionalUser<z.infer<typeof getProjectFileDownloadURLSchema>>,
res: Response
) {
try {
const { projectID, fileID } = req.params;
const { direct } = req.query;

if (!isCanonicalCommonsInstance()) {
const queryIndex = req.originalUrl.indexOf("?");
const query = queryIndex === -1 ? "" : req.originalUrl.slice(queryIndex);
const target = `${getCommonsCanonicalURL()}/permalink/${projectID}/${fileID}${query}`;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add

if (target.endsWith(req.originalUrl)) {
  permalinkLog.warn({ host: receivingHost(req) }, "canonical host check rejected its own origin");
} else {
 [rest of current code]
}

here. This is a cheap guard that will help us see if a mismatch on the canonical instance itself is happening

if (target.endsWith(req.originalUrl)) {
permalinkLog.warn(
{ host: receivingHost(req) },
"canonical host check rejected its own origin; skipping redirect"
);
} else {
permalinkLog.debug(
{ host: receivingHost(req) },
"redirecting permalink to canonical host"
);
return res
.setHeader("Cache-Control", "no-store")
.redirect(302, target);
}
}

const project = await Project.findOne({ projectID }).lean();

if (!project) {
Expand All @@ -692,7 +712,7 @@ async function redirectPermanentLink(
}

if (!direct) {
return res.redirect('https://commons.libretexts.org/download/' + projectID + '/' + fileID);
return res.redirect(`${getCommonsCanonicalURL()}/download/${projectID}/${fileID}`);
}

const downloadURLs = await downloadProjectFiles(
Expand Down
42 changes: 42 additions & 0 deletions server/util/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,48 @@ export const getProductionURL = () => {
return process.env.CONDUCTOR_DOMAIN || '';
};

const DEFAULT_COMMONS_CANONICAL_URL = "https://commons.libretexts.org";

/**
* Origin of the permanent Commons host. Asset permalinks are generated and
* resolved against this origin, not the instance's own CONDUCTOR_DOMAIN.
* Set COMMONS_CANONICAL_DOMAIN (host or absolute URL) so staging points at
* the staging commons host.
*
* @returns {string} Origin with no trailing slash.
*/
export const getCommonsCanonicalURL = () => {
const configured = (process.env.COMMONS_CANONICAL_DOMAIN || "").trim();
const raw = configured || DEFAULT_COMMONS_CANONICAL_URL;
const withProtocol = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
try {
return new URL(withProtocol).origin;
} catch {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add logger.warn({ configured }, "Invalid COMMONS_CANONICAL_DOMAIN, falling back to default"); for extra visbility

logger.warn(
{ configured },
"Invalid COMMONS_CANONICAL_DOMAIN, falling back to default"
);
return DEFAULT_COMMONS_CANONICAL_URL;
}
};

/**
* Whether this Conductor instance is the permanent Commons host.
* Compares CONDUCTOR_DOMAIN (this instance) to getCommonsCanonicalURL().
*
* @returns {boolean}
*/
export const isCanonicalCommonsInstance = () => {
const self = (process.env.CONDUCTOR_DOMAIN || "").trim();
if (!self) return false;
const withProtocol = /^https?:\/\//i.test(self) ? self : `https://${self}`;
try {
return new URL(withProtocol).origin === getCommonsCanonicalURL();
} catch {
return false;
}
};

/**
* Removes a leading slash, if any, from a string.
*
Expand Down
Loading