This commit is contained in:
seb
2026-10-06 11:19:33 +02:00
parent 1d1017e44b
commit b99e767c57
8 changed files with 301 additions and 2 deletions

View File

@@ -46,6 +46,8 @@ let httpsServer;
let starting;
let startedAt;
const PRIVATE_HOST_REGEX = /^(127\.0\.0\.1|localhost|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/;
function isAllowedOrigin(origin) {
if (!origin) return false;
if (env.corsOrigins.includes(origin)) return true;
@@ -54,6 +56,9 @@ function isAllowedOrigin(origin) {
if (u.hostname === 'quixpos.com' || u.hostname.endsWith('.quixpos.com')) {
return true;
}
if (PRIVATE_HOST_REGEX.test(u.hostname)) {
return true;
}
} catch {
// ignore invalid URL
}
@@ -73,6 +78,26 @@ function corsMiddleware(req, res, next) {
return next();
}
if (req.path.startsWith('/v1')) {
if (origin) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
res.setHeader('Access-Control-Allow-Credentials', 'true');
} else {
res.setHeader('Access-Control-Allow-Origin', '*');
}
const reqHeaders = req.headers['access-control-request-headers'];
res.setHeader(
'Access-Control-Allow-Headers',
reqHeaders || 'Content-Type, Authorization, x-auth-token, authtoken, auth-token, token, x-token'
);
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
return next();
}
if (origin && isAllowedOrigin(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');

View File

@@ -1,4 +1,4 @@
import { getStore } from './store.js';
import { getStore, getProvider } from './store.js';
export async function list(googleAuthId) {
const store = await getStore();
@@ -100,4 +100,79 @@ export async function setMaxKnownTombstoneId(id, maxknowntombstoneid) {
return store.posterminal.setMaxKnownTombstoneId(id, maxknowntombstoneid);
}
/**
* Retrieves an image buffer by hash for POS terminals.
* @param {string} hash - SHA-256 hash or thumbhash
* @param {object} [options]
* @param {number} [options.width=200]
* @param {number} [options.height=200]
* @returns {Promise<{buffer: Buffer, w: number, h: number, fullHash: string} | null>}
*/
export async function getPosImageByHash(hash, { width = 200, height = 200 } = {}) {
if (!hash || typeof hash !== 'string') return null;
const cleanHash = hash.trim();
if (!cleanHash) return null;
const dotIndex = cleanHash.lastIndexOf('.');
const baseHash = dotIndex > 0 ? cleanHash.slice(0, dotIndex) : cleanHash;
const provider = await getProvider();
const isSqlite = provider?.dialect === 'sqlite3';
if (isSqlite) {
const result = await provider.query(
'SELECT w, h, size, hash, thumbw, thumbh, thumbhash FROM pic WHERE hash = @hash OR thumbhash = @hash OR hash = @baseHash OR thumbhash = @baseHash LIMIT 1',
{ hash: cleanHash, baseHash }
);
const row = result.rows[0];
if (!row) return null;
const fullHash = row.hash;
const useThumb = width <= 200 && height <= 200;
let buffer = null;
if (useThumb) {
buffer = await provider.readPicThumb?.(fullHash);
}
if (!buffer) {
buffer = await provider.readPicFull?.(fullHash);
}
if (!buffer && !useThumb) {
buffer = await provider.readPicThumb?.(fullHash);
}
if (!buffer) return null;
return {
buffer: Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer),
w: row.w,
h: row.h,
fullHash,
};
}
const result = await provider.query(
'SELECT TOP 1 w, h, size, hash, thumbw, thumbh, thumbhash, fullbinary, thumbbinary FROM pic WHERE hash = @hash OR thumbhash = @hash OR hash = @baseHash OR thumbhash = @baseHash',
{ hash: cleanHash, baseHash }
);
const row = result.rows[0];
if (!row) return null;
const fullHash = row.hash;
const useThumb = width <= 200 && height <= 200;
const rawBuffer = useThumb
? (row.thumbbinary || row.fullbinary)
: (row.fullbinary || row.thumbbinary);
if (!rawBuffer) return null;
return {
buffer: Buffer.isBuffer(rawBuffer) ? rawBuffer : Buffer.from(rawBuffer),
w: row.w,
h: row.h,
fullHash,
};
}

View File

@@ -4,6 +4,7 @@ import { handleClient } from './routes/client.js';
import { handleInit } from './routes/init.js';
import { handleCategory } from './routes/category.js';
import { handleProduct } from './routes/product.js';
import { handlePimage } from './routes/pimage.js';
const router = Router();
@@ -17,5 +18,9 @@ router.get('/init', posAuthMiddleware, handleInit);
router.get('/category', posAuthMiddleware, handleCategory);
router.get('/product', posAuthMiddleware, handleProduct);
// POS image delivery
router.get('/pimage', handlePimage);
router.get('/cimage', handlePimage);
export default router;

156
src/v1/routes/pimage.js Normal file
View File

@@ -0,0 +1,156 @@
import sharp from 'sharp';
import * as db from '../../db/posterminal.js';
const MAX_DIMENSION = 200;
/**
* @openapi
* /v1/pimage:
* get:
* tags: [POS]
* summary: POS product image delivery
* description: |
* Returns product image by hash (`path` query param) scaled to preview size.
* x-markdown: pos/pimage.md
* parameters:
* - in: query
* name: path
* required: true
* schema:
* type: string
* description: SHA-256 hash of the product image
* example: "71de4085ce2b1a53317832421009d844eec0c36a3ec071a31661cc2a212e15e6"
* - in: query
* name: w
* required: false
* schema:
* type: integer
* default: 200
* description: Max width
* - in: query
* name: h
* required: false
* schema:
* type: integer
* default: 200
* description: Max height
* - in: query
* name: format
* required: false
* schema:
* type: string
* enum: [jpeg, png, webp, avif]
* description: Optional target format (defaults to jpeg/png or client Accept preference)
* responses:
* 200:
* description: Resized image binary
* content:
* image/jpeg:
* schema:
* type: string
* format: binary
* image/png:
* schema:
* type: string
* format: binary
* image/webp:
* schema:
* type: string
* format: binary
* image/avif:
* schema:
* type: string
* format: binary
* 304:
* description: Image not modified
* 400:
* description: Missing required query parameter 'path'
* content:
* application/json:
* schema:
* type: object
* properties:
* Message:
* type: string
* example: "Missing required query parameter 'path'."
* 404:
* description: Image not found
* content:
* application/json:
* schema:
* type: object
* properties:
* Message:
* type: string
* example: "No image was found for path 'abc'."
*/
export async function handlePimage(req, res) {
const rawPath = typeof req.query.path === 'string' ? req.query.path.trim() : '';
if (!rawPath) {
return res.status(400).json({ Message: "Missing required query parameter 'path'." });
}
const widthParam = req.query.w !== undefined ? Number(req.query.w) : MAX_DIMENSION;
const heightParam = req.query.h !== undefined ? Number(req.query.h) : MAX_DIMENSION;
const targetW = Number.isFinite(widthParam) && widthParam > 0 ? Math.min(Math.round(widthParam), 2000) : MAX_DIMENSION;
const targetH = Number.isFinite(heightParam) && heightParam > 0 ? Math.min(Math.round(heightParam), 2000) : MAX_DIMENSION;
try {
const image = await db.getPosImageByHash(rawPath, { width: targetW, height: targetH });
if (!image) {
return res.status(404).json({ Message: `No image was found for path '${rawPath}'.` });
}
const etag = `"${image.fullHash}-${targetW}x${targetH}"`;
const ifNoneMatch = req.headers['if-none-match'];
if (ifNoneMatch === etag || ifNoneMatch === image.fullHash || ifNoneMatch === `"${image.fullHash}"`) {
res.setHeader('ETag', etag);
res.setHeader('Cache-Control', 'public, max-age=86400');
return res.status(304).end();
}
let buffer = image.buffer;
let contentType = 'image/jpeg';
try {
const imageSharp = sharp(buffer);
const meta = await imageSharp.metadata();
let pipeline = imageSharp.resize(targetW, targetH, {
fit: 'inside',
withoutEnlargement: true,
});
const accept = String(req.headers.accept || '');
const formatParam = typeof req.query.format === 'string' ? req.query.format.toLowerCase() : '';
if (formatParam === 'avif' || (!formatParam && accept.includes('image/avif'))) {
pipeline = pipeline.avif({ effort: 2 });
contentType = 'image/avif';
} else if (formatParam === 'webp' || (!formatParam && accept.includes('image/webp'))) {
pipeline = pipeline.webp({ quality: 85 });
contentType = 'image/webp';
} else if (formatParam === 'png' || (!formatParam && meta.hasAlpha)) {
pipeline = pipeline.png();
contentType = 'image/png';
} else {
pipeline = pipeline.jpeg({ quality: 85 });
contentType = 'image/jpeg';
}
buffer = await pipeline.toBuffer();
} catch (resizeErr) {
console.warn(`[pimage] resize/convert fallback for ${rawPath}:`, resizeErr.message);
}
res.setHeader('Content-Type', contentType);
res.setHeader('Content-Length', String(buffer.length));
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('ETag', etag);
return res.status(200).send(buffer);
} catch (err) {
console.error('POS /v1/pimage error:', err);
return res.status(500).json({ Message: 'Internal server error' });
}
}