mirror of
https://github.com/hanzoai/chat.git
synced 2026-09-30 20:51:17 +00:00
Five things answered outside /v1/chat/. Four of them are chat's; they move.
/health -> /v1/chat/health
POST /oauth/iam/session-> POST /v1/chat/auth/iam/session (it is auth)
GET /oauth/openid[/callback], /oauth/error
-> /v1/chat/auth/openid[/callback], /v1/chat/auth/error
/images/ -> /v1/chat/images/
The fifth — the built assets at / and the SPA catch-all — is the SPA's, and
stays. Every caller moved in the same commit: api-endpoints (health, iamSession),
the metrics + telemetry health filter, the helm probes, the PR-preview workflow,
the PWA nav-fallback denylist. `ErrorController` matched a failed OIDC callback
by the substring '/oauth/', which the move would have silently broken; it now
matches the route.
Images are the one persisted case: a conversation stores the served path, and
history is immutable. New writes emit /v1/chat/images/…; /images/* answers one
permanent redirect; `isServedImage` (data-provider, the one place that knows the
namespace) recognises both. Local deletion maps the served path back to disk.
Two routers were written, tested, advertised to the browser — and never mounted,
so both were a guaranteed 404: skills (types say /v1/chat/skills) and the RUM
OTLP proxy (`rum/proxy` advertises /v1/chat/rum). Mounted where they said.
Deleted, with zero callers: server/experimental.js — a drifted second copy of
the whole mount table, still referencing a router that no longer exists, that
would have silently absorbed this move and diverged again; and nginx.hanzo.conf,
referenced by no compose/Dockerfile/chart, whose own /health shadowed chat's.
Gates collapsed to their one behavior, and the env deleted:
ALLOW_SOCIAL_LOGIN IAM is the one identity provider; false produced a
server with no way to sign in. socialLogins.js is now
iamLogin.js — one name for one thing.
CONTINUE_ON_UNCAUGHT_EXCEPTION keeps a process alive in an unknown state
instead of letting the kubelet replace it.
CONFIG_BYPASS_VALIDATION boots on invalid config, on request.
MCP_SKIP_CODE_CHALLENGE_CHECK turns off PKCE verification.
OPENID_JWKS_URL_CACHE_ENABLED read as `isEnabled(x) || true` — never off.
A second, differently-defaulted read lived in
remoteAgentAuth; both are now just on.
NO_INDEX a third boolean idiom for a header we always want.
DISABLE_COMPRESSION, ENABLE_IMAGE_OUTPUT_GZIP_SCAN — we write these images
ourselves, as PNG/GIF; none is gzipped on disk.
Tests fail without the change: the auth router spec (6 of 7) against the old
router, the static spec against the old env-gated one, the config spec now sets
CONFIG_BYPASS_VALIDATION=true and still expects the exit, the error spec against
the '/oauth/' matcher, and index.spec asserts the top level serves HTML — so a
probe or caller left behind fails loudly instead of looking green.
161 lines
6.2 KiB
JavaScript
161 lines
6.2 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const sharp = require('sharp');
|
|
const { imagesRoute } = require('@hanzochat/data-provider');
|
|
const { resizeImageBuffer } = require('../images/resize');
|
|
const { updateUser, updateFile } = require('~/models');
|
|
|
|
/**
|
|
* Converts an image file to the target format. The function first resizes the image based on the specified
|
|
* resolution.
|
|
*
|
|
* If the original image is already in target format, it writes the resized image back. Otherwise,
|
|
* it converts the image to target format before saving.
|
|
*
|
|
* The original image is deleted after conversion.
|
|
* @param {Object} params - The params object.
|
|
* @param {Object} params.req - The request object from Express. It should have a `user` property with an `id` representing the user
|
|
* @param {Express.Multer.File} params.file - The file object, which is part of the request. The file object should
|
|
* have a `path` property that points to the location of the uploaded file.
|
|
* @param {string} params.file_id - The file ID.
|
|
* @param {EModelEndpoint} params.endpoint - The params object.
|
|
* @param {string} [params.resolution='high'] - Optional. The desired resolution for the image resizing. Default is 'high'.
|
|
*
|
|
* @returns {Promise<{ filepath: string, bytes: number, width: number, height: number}>}
|
|
* A promise that resolves to an object containing:
|
|
* - filepath: The path where the converted image is saved.
|
|
* - bytes: The size of the converted image in bytes.
|
|
* - width: The width of the converted image.
|
|
* - height: The height of the converted image.
|
|
*/
|
|
async function uploadLocalImage({ req, file, file_id, endpoint, resolution = 'high' }) {
|
|
const appConfig = req.config;
|
|
const inputFilePath = file.path;
|
|
const inputBuffer = await fs.promises.readFile(inputFilePath);
|
|
const {
|
|
buffer: resizedBuffer,
|
|
width,
|
|
height,
|
|
} = await resizeImageBuffer(inputBuffer, resolution, endpoint);
|
|
const extension = path.extname(inputFilePath);
|
|
|
|
const { imageOutput } = appConfig.paths;
|
|
const userPath = path.join(imageOutput, req.user.id);
|
|
|
|
if (!fs.existsSync(userPath)) {
|
|
fs.mkdirSync(userPath, { recursive: true });
|
|
}
|
|
|
|
const fileName = `${file_id}__${path.basename(inputFilePath)}`;
|
|
const newPath = path.join(userPath, fileName);
|
|
const targetExtension = `.${appConfig.imageOutputType}`;
|
|
|
|
if (extension.toLowerCase() === targetExtension) {
|
|
const bytes = Buffer.byteLength(resizedBuffer);
|
|
await fs.promises.writeFile(newPath, resizedBuffer);
|
|
const filepath = path.posix.join('/', 'images', req.user.id, path.basename(newPath));
|
|
return { filepath, bytes, width, height };
|
|
}
|
|
|
|
const outputFilePath = newPath.replace(extension, targetExtension);
|
|
const data = await sharp(resizedBuffer).toFormat(appConfig.imageOutputType).toBuffer();
|
|
await fs.promises.writeFile(outputFilePath, data);
|
|
const bytes = Buffer.byteLength(data);
|
|
const filepath = path.posix.join('/', 'images', req.user.id, path.basename(outputFilePath));
|
|
await fs.promises.unlink(inputFilePath);
|
|
return { filepath, bytes, width, height };
|
|
}
|
|
|
|
/**
|
|
* Encodes an image file to base64.
|
|
* @param {string} imagePath - The path to the image file.
|
|
* @returns {Promise<string>} A promise that resolves with the base64 encoded image data.
|
|
*/
|
|
function encodeImage(imagePath) {
|
|
return new Promise((resolve, reject) => {
|
|
fs.readFile(imagePath, (err, data) => {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve(data.toString('base64'));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Local: Updates the file and encodes the image to base64,
|
|
* for image payload handling: tuple order of [filepath, base64].
|
|
* @param {Object} req - The request object.
|
|
* @param {MongoFile} file - The file object.
|
|
* @returns {Promise<[MongoFile, string]>} - A promise that resolves to an array of results from updateFile and encodeImage.
|
|
*/
|
|
async function prepareImagesLocal(req, file) {
|
|
const appConfig = req.config;
|
|
const { publicPath, imageOutput } = appConfig.paths;
|
|
const userPath = path.join(imageOutput, req.user.id);
|
|
|
|
if (!fs.existsSync(userPath)) {
|
|
fs.mkdirSync(userPath, { recursive: true });
|
|
}
|
|
const filepath = path.join(publicPath, file.filepath);
|
|
|
|
const promises = [];
|
|
promises.push(updateFile({ file_id: file.file_id }));
|
|
promises.push(encodeImage(filepath));
|
|
return await Promise.all(promises);
|
|
}
|
|
|
|
/**
|
|
* Uploads a user's avatar to local server storage and returns the URL.
|
|
* If the 'manual' flag is set to 'true', it also updates the user's avatar URL in the database.
|
|
*
|
|
* @param {object} params - The parameters object.
|
|
* @param {Buffer} params.buffer - The Buffer containing the avatar image.
|
|
* @param {string} params.userId - The user ID.
|
|
* @param {string} params.manual - A string flag indicating whether the update is manual ('true' or 'false').
|
|
* @param {string} [params.agentId] - Optional agent ID if this is an agent avatar.
|
|
* @returns {Promise<string>} - A promise that resolves with the URL of the uploaded avatar.
|
|
* @throws {Error} - Throws an error if Firebase is not initialized or if there is an error in uploading.
|
|
*/
|
|
async function processLocalAvatar({ buffer, userId, manual, agentId }) {
|
|
const userDir = path.resolve(
|
|
__dirname,
|
|
'..',
|
|
'..',
|
|
'..',
|
|
'..',
|
|
'..',
|
|
'client',
|
|
'public',
|
|
'images',
|
|
userId,
|
|
);
|
|
|
|
const metadata = await sharp(buffer).metadata();
|
|
const extension = metadata.format === 'gif' ? 'gif' : 'png';
|
|
|
|
const timestamp = new Date().getTime();
|
|
/** Unique filename with timestamp and optional agent ID */
|
|
const fileName = agentId
|
|
? `agent-${agentId}-avatar-${timestamp}.${extension}`
|
|
: `avatar-${timestamp}.${extension}`;
|
|
const urlRoute = `${imagesRoute}/${userId}/${fileName}`;
|
|
const avatarPath = path.join(userDir, fileName);
|
|
|
|
await fs.promises.mkdir(userDir, { recursive: true });
|
|
await fs.promises.writeFile(avatarPath, buffer);
|
|
|
|
const isManual = manual === 'true';
|
|
let url = `${urlRoute}?manual=${isManual}`;
|
|
|
|
// Only update user record if this is a user avatar (manual === 'true')
|
|
if (isManual && !agentId) {
|
|
await updateUser(userId, { avatar: url });
|
|
}
|
|
|
|
return url;
|
|
}
|
|
|
|
module.exports = { uploadLocalImage, encodeImage, prepareImagesLocal, processLocalAvatar };
|