Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
/**
* App icon serving + detection.
*
* GET /:id/icon → image bytes (ETag / CSP-guarded SVG)
* POST /:id/detect-icon → { success, detected, appIconPath } (single app)
*/
import { Router } from 'express';
import { readFile, stat } from 'fs/promises';
import { extname } from 'path';
import sharp from 'sharp';
import * as appsService from '../../services/apps.js';
import { notifyAppsChanged } from '../../services/apps.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import { detectAppIcon, getIconContentType, isUsableSvg, resolveContainedIcon } from '../../services/appIconDetect.js';
import { loadApp, pathExists } from './shared.js';
const router = Router();
const rasterIconCache = new Map();
const getRasterIcon = (appId, iconPath, iconStat, size, iconData) => {
const variant = 'png';
const key = `${iconPath}:${iconStat.mtimeMs}:${size}:${variant}`;
for (const [cachedKey, value] of rasterIconCache) {
if (value.appId === appId && value.size === size && cachedKey !== key) rasterIconCache.delete(cachedKey);
}
if (!rasterIconCache.has(key)) {
const rendered = sharp(iconData).resize(size, size, { fit: 'cover', withoutEnlargement: true }).png().toBuffer()
.catch((error) => {
rasterIconCache.delete(key);
throw error;
});
rasterIconCache.set(key, { appId, size, rendered });
}
return rasterIconCache.get(key).rendered;
};
// GET /api/apps/:id/icon - Serve the app's detected icon image
router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
const { appIconQuerySchema, validateRequest } = await import('../../lib/validation.js');
const { size } = validateRequest(appIconQuerySchema, req.query);
// Use a stored path only when it still resolves to an icon inside the
// repo. Re-detect when it is missing, escapes through `..` or a symlink,
// or is an SVG that embeds an external <image href="..."> (those render
// blank under this route's CSP — PortOS's own favicon.svg is the example).
// Containment is checked before ETag so a symlink swapped onto a host file
// cannot answer 304 with the escaped file's metadata.
let iconPath = await resolveContainedIcon(app.repoPath, app.appIconPath);
if (!iconPath || (extname(iconPath).toLowerCase() === '.svg' && !await isUsableSvg(iconPath))) {
const detected = await detectAppIcon(app.repoPath, app.type);
if (detected && detected !== app.appIconPath) {
await appsService.updateApp(app.id, { appIconPath: detected });
}
iconPath = detected;
}
if (!iconPath) {
throw new ServerError('No app icon found', { status: 404 });
}
const contentType = getIconContentType(iconPath);
const iconStat = await stat(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));
if (!iconStat) throw new ServerError('No app icon found', { status: 404 });
const extension = extname(iconPath).toLowerCase();
const isRaster = ['.png', '.jpg', '.jpeg', '.webp'].includes(extension);
const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}${isRaster ? `-${size}` : ''}"`;
res.set('Content-Type', isRaster ? 'image/png' : contentType);
res.set('Cache-Control', 'public, max-age=3600');
res.set('ETag', etag);
res.set('X-Content-Type-Options', 'nosniff');
if (contentType === 'image/svg+xml') {
res.set('Content-Disposition', 'inline; filename="icon.svg"');
res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");
}
const ifNoneMatch = req.headers['if-none-match'];
if (ifNoneMatch) {
const tags = ifNoneMatch.split(',').map(v => v.trim());
if (tags.includes('*') || tags.includes(etag)) {
return res.status(304).end();
}
}
const iconData = await readFile(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));
if (!iconData) throw new ServerError('No app icon found', { status: 404 });
res.send(isRaster ? await getRasterIcon(app.id, iconPath, iconStat, size, iconData) : iconData);
}));
// POST /api/apps/:id/detect-icon - Detect and persist app icon for a single app
router.post('/:id/detect-icon', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
if (!app.repoPath || !await pathExists(app.repoPath)) {
throw new ServerError('App repoPath is missing or inaccessible', { status: 400, code: 'INVALID_REPO_PATH' });
}
const iconPath = await detectAppIcon(app.repoPath, app.type);
if (!iconPath) {
console.log(`🎨 No icon detected for ${app.name}`);
res.json({ success: true, detected: false, appIconPath: null });
return;
}
await appsService.updateApp(app.id, { appIconPath: iconPath });
notifyAppsChanged('detect-icon');
console.log(`🎨 Detected icon for ${app.name}: ${iconPath.split('/').pop()}`);
res.json({ success: true, detected: true, appIconPath: iconPath });
}));
export default router;