Add the optional Immich integration and manual gallery push
Immich connections stay server-side with an encrypted API key, albums can be imported, and photos are only sent back when an event's push button is pressed: originals upload once, edited photos re-render, and edits hashes plus checksums skip anything already in Immich. This also lands the accompanying editor, cloud and administration work that was still uncommitted. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
+21
-4
@@ -1,23 +1,40 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import { SESSION_DAYS } from './config.mjs';
|
||||
import { sessions, users } from './db.mjs';
|
||||
|
||||
const KEYLEN = 64;
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
|
||||
export function hashPassword(password) {
|
||||
export async function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const hash = crypto.scryptSync(password, salt, KEYLEN);
|
||||
const hash = await scrypt(password, salt, KEYLEN);
|
||||
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
export async function verifyPassword(password, stored) {
|
||||
const [scheme, saltHex, hashHex] = String(stored).split('$');
|
||||
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
|
||||
const expected = Buffer.from(hashHex, 'hex');
|
||||
const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
|
||||
const actual = await scrypt(password, Buffer.from(saltHex, 'hex'), expected.length);
|
||||
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
}
|
||||
|
||||
/**
|
||||
* A fixed hash for addresses that do not exist, so a failed login costs the
|
||||
* same scrypt work as a real one and does not reveal registration by timing.
|
||||
* Built synchronously once at boot; this is not on a request path.
|
||||
*/
|
||||
const DUMMY_HASH = (() => {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const hash = crypto.scryptSync('luminary-timing-equalizer', salt, KEYLEN);
|
||||
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
|
||||
})();
|
||||
|
||||
export async function spendPasswordCheck(password) {
|
||||
await verifyPassword(password, DUMMY_HASH);
|
||||
}
|
||||
|
||||
export function createSession(userId) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
|
||||
|
||||
+10
-2
@@ -11,6 +11,7 @@ import crypto from 'node:crypto';
|
||||
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
||||
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
||||
import { removeAsset } from './storage.mjs';
|
||||
import { open, seal } from './secrets.mjs';
|
||||
|
||||
const VERSION = 'g1';
|
||||
|
||||
@@ -119,7 +120,14 @@ export function bridgePhotoId(sourcePhotoId) {
|
||||
}
|
||||
|
||||
export function bridgeForEvent(eventId) {
|
||||
return bridgeGet.get(eventId) ?? null;
|
||||
const row = bridgeGet.get(eventId);
|
||||
if (!row) return null;
|
||||
try {
|
||||
return { ...row, token: open(row.token) };
|
||||
} catch (err) {
|
||||
console.error(`[luminary] could not decrypt the bridge token for ${eventId}: ${err.message}`);
|
||||
return { ...row, token: '' };
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
|
||||
@@ -208,7 +216,7 @@ export async function importBridgeEvent({ serviceToken, sessionId, ownerId = ''
|
||||
bridgeInsert.run(
|
||||
eventId,
|
||||
sessionId,
|
||||
serviceToken,
|
||||
seal(serviceToken),
|
||||
GLENLOCH_URL,
|
||||
listing.event.id,
|
||||
returnUrl,
|
||||
|
||||
@@ -33,6 +33,13 @@ export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '')
|
||||
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
|
||||
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
|
||||
|
||||
|
||||
/** Optional key for encrypting saved SMTP and bridge credentials at rest. */
|
||||
export const SECRET_KEY = setting('SECRET_KEY');
|
||||
|
||||
/** Trust X-Forwarded-For for rate limits; only behind a proxy that sets it. */
|
||||
export const TRUST_PROXY = setting('TRUST_PROXY') === '1';
|
||||
|
||||
/** How long an imported bridge event survives without being reopened. */
|
||||
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
|
||||
|
||||
|
||||
+446
@@ -114,6 +114,76 @@ db.exec(`
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS immich_albums (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL,
|
||||
server_url TEXT NOT NULL,
|
||||
album_id TEXT NOT NULL,
|
||||
album_name TEXT NOT NULL DEFAULT '',
|
||||
asset_count INTEGER NOT NULL DEFAULT 0,
|
||||
kind TEXT NOT NULL DEFAULT 'import',
|
||||
last_sync_at INTEGER,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS immich_albums_key
|
||||
ON immich_albums(owner_id, server_url, album_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS immich_assets (
|
||||
event_id TEXT NOT NULL,
|
||||
asset_id TEXT NOT NULL,
|
||||
photo_id TEXT NOT NULL,
|
||||
owner_id TEXT NOT NULL,
|
||||
album_id TEXT NOT NULL,
|
||||
checksum TEXT NOT NULL DEFAULT '',
|
||||
file_name TEXT NOT NULL DEFAULT '',
|
||||
imported_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (event_id, asset_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS immich_assets_photo ON immich_assets(photo_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS immich_settings (
|
||||
owner_id TEXT PRIMARY KEY,
|
||||
server_url TEXT NOT NULL DEFAULT '',
|
||||
api_key TEXT NOT NULL DEFAULT '',
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
auto_sync INTEGER NOT NULL DEFAULT 0,
|
||||
sync_minutes INTEGER NOT NULL DEFAULT 60,
|
||||
trash_original INTEGER NOT NULL DEFAULT 0,
|
||||
sync_metadata INTEGER NOT NULL DEFAULT 1,
|
||||
last_sync_at INTEGER,
|
||||
last_error TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS immich_pushes (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL,
|
||||
photo_id TEXT NOT NULL,
|
||||
source_asset_id TEXT NOT NULL,
|
||||
new_asset_id TEXT,
|
||||
checksum TEXT NOT NULL,
|
||||
edits_hash TEXT NOT NULL DEFAULT '',
|
||||
state TEXT NOT NULL,
|
||||
trashed_source INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS immich_pushes_photo ON immich_pushes(photo_id, checksum);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS immich_meta (
|
||||
photo_id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL,
|
||||
asset_id TEXT NOT NULL,
|
||||
local_fingerprint TEXT NOT NULL DEFAULT '',
|
||||
remote_fingerprint TEXT NOT NULL DEFAULT '',
|
||||
remote_updated_at INTEGER,
|
||||
last_synced_at INTEGER,
|
||||
last_error TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_quota (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
bytes_limit INTEGER NOT NULL DEFAULT (100 * 1024 * 1024 * 1024),
|
||||
@@ -162,6 +232,24 @@ if (!eventColumns.includes('share_token')) {
|
||||
}
|
||||
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS events_share_token ON events(share_token)');
|
||||
|
||||
/* Metadata round-tripping arrived after the first Immich release. */
|
||||
const immichSettingsColumns = db.prepare('PRAGMA table_info(immich_settings)').all().map((c) => c.name);
|
||||
if (!immichSettingsColumns.includes('sync_metadata')) {
|
||||
db.exec('ALTER TABLE immich_settings ADD COLUMN sync_metadata INTEGER NOT NULL DEFAULT 1');
|
||||
}
|
||||
|
||||
/* Manual pushes remember which edit version reached Immich. */
|
||||
const immichPushColumns = db.prepare('PRAGMA table_info(immich_pushes)').all().map((c) => c.name);
|
||||
if (!immichPushColumns.includes('edits_hash')) {
|
||||
db.exec("ALTER TABLE immich_pushes ADD COLUMN edits_hash TEXT NOT NULL DEFAULT ''");
|
||||
}
|
||||
|
||||
/* Galleries created from an event are destinations, not import sources. */
|
||||
const immichAlbumColumns = db.prepare('PRAGMA table_info(immich_albums)').all().map((c) => c.name);
|
||||
if (!immichAlbumColumns.includes('kind')) {
|
||||
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
|
||||
}
|
||||
|
||||
const q = {
|
||||
upsertEvent: db.prepare(`
|
||||
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
||||
@@ -255,6 +343,115 @@ const q = {
|
||||
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
|
||||
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
|
||||
|
||||
event: db.prepare('SELECT data FROM events WHERE id = ?'),
|
||||
immichAlbum: db.prepare(
|
||||
'SELECT * FROM immich_albums WHERE owner_id = ? AND server_url = ? AND album_id = ?',
|
||||
),
|
||||
immichAlbumForEvent: db.prepare('SELECT * FROM immich_albums WHERE event_id = ?'),
|
||||
immichAlbumByAlbum: db.prepare(
|
||||
'SELECT * FROM immich_albums WHERE owner_id = ? AND album_id = ? LIMIT 1',
|
||||
),
|
||||
immichAlbumsByOwner: db.prepare(
|
||||
'SELECT * FROM immich_albums WHERE owner_id = ? ORDER BY last_sync_at DESC, created_at DESC',
|
||||
),
|
||||
upsertImmichAlbum: db.prepare(`
|
||||
INSERT INTO immich_albums (event_id, owner_id, server_url, album_id, album_name, asset_count, kind, last_sync_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(event_id) DO UPDATE SET
|
||||
server_url = excluded.server_url,
|
||||
album_id = excluded.album_id,
|
||||
album_name = excluded.album_name,
|
||||
asset_count = excluded.asset_count,
|
||||
kind = excluded.kind,
|
||||
last_sync_at = excluded.last_sync_at
|
||||
`),
|
||||
deleteImmichAlbum: db.prepare('DELETE FROM immich_albums WHERE event_id = ?'),
|
||||
immichAssetsByEvent: db.prepare('SELECT * FROM immich_assets WHERE event_id = ?'),
|
||||
upsertImmichAsset: db.prepare(`
|
||||
INSERT INTO immich_assets (event_id, asset_id, photo_id, owner_id, album_id, checksum, file_name, imported_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(event_id, asset_id) DO UPDATE SET
|
||||
photo_id = excluded.photo_id,
|
||||
checksum = excluded.checksum,
|
||||
file_name = excluded.file_name,
|
||||
imported_at = excluded.imported_at
|
||||
`),
|
||||
deleteImmichAsset: db.prepare('DELETE FROM immich_assets WHERE event_id = ? AND asset_id = ?'),
|
||||
deleteImmichAssetsForPhoto: db.prepare('DELETE FROM immich_assets WHERE photo_id = ?'),
|
||||
immichAssetForPhoto: db.prepare('SELECT * FROM immich_assets WHERE photo_id = ? LIMIT 1'),
|
||||
immichSettings: db.prepare('SELECT * FROM immich_settings WHERE owner_id = ?'),
|
||||
allImmichSettings: db.prepare('SELECT * FROM immich_settings'),
|
||||
upsertImmichSettings: db.prepare(`
|
||||
INSERT INTO immich_settings (owner_id, server_url, api_key, enabled, auto_sync, sync_minutes, trash_original, sync_metadata, last_sync_at, last_error, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(owner_id) DO UPDATE SET
|
||||
server_url = excluded.server_url,
|
||||
api_key = excluded.api_key,
|
||||
enabled = excluded.enabled,
|
||||
auto_sync = excluded.auto_sync,
|
||||
sync_minutes = excluded.sync_minutes,
|
||||
trash_original = excluded.trash_original,
|
||||
sync_metadata = excluded.sync_metadata,
|
||||
last_sync_at = excluded.last_sync_at,
|
||||
last_error = excluded.last_error
|
||||
`),
|
||||
deleteImmichSettings: db.prepare('DELETE FROM immich_settings WHERE owner_id = ?'),
|
||||
setImmichSyncState: db.prepare(
|
||||
'UPDATE immich_settings SET last_sync_at = ?, last_error = ? WHERE owner_id = ?',
|
||||
),
|
||||
immichPush: db.prepare(
|
||||
'SELECT * FROM immich_pushes WHERE photo_id = ? AND checksum = ? ORDER BY created_at DESC LIMIT 1',
|
||||
),
|
||||
immichPushedForPhoto: db.prepare(
|
||||
"SELECT * FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL ORDER BY created_at DESC LIMIT 1",
|
||||
),
|
||||
immichPhotoIdsByEvent: db.prepare(
|
||||
'SELECT id FROM photos WHERE event_id = ? AND owner_id = ? ORDER BY sort_index ASC, updated_at ASC',
|
||||
),
|
||||
immichPendingByEvent: db.prepare(`
|
||||
SELECT p.data FROM photos p
|
||||
WHERE p.event_id = ? AND p.owner_id = ?
|
||||
AND NOT EXISTS (SELECT 1 FROM immich_assets a WHERE a.photo_id = p.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM immich_pushes u
|
||||
WHERE u.photo_id = p.id AND u.state = 'done' AND u.new_asset_id IS NOT NULL
|
||||
)
|
||||
ORDER BY p.sort_index ASC, p.updated_at ASC
|
||||
`),
|
||||
upsertImmichPush: db.prepare(`
|
||||
INSERT INTO immich_pushes (id, owner_id, photo_id, source_asset_id, new_asset_id, checksum, edits_hash, state, trashed_source, error, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
new_asset_id = excluded.new_asset_id,
|
||||
edits_hash = excluded.edits_hash,
|
||||
state = excluded.state,
|
||||
trashed_source = excluded.trashed_source,
|
||||
error = excluded.error
|
||||
`),
|
||||
deleteImmichPushesForPhoto: db.prepare('DELETE FROM immich_pushes WHERE photo_id = ?'),
|
||||
immichMeta: db.prepare('SELECT * FROM immich_meta WHERE photo_id = ?'),
|
||||
upsertImmichMeta: db.prepare(`
|
||||
INSERT INTO immich_meta (photo_id, owner_id, asset_id, local_fingerprint, remote_fingerprint, remote_updated_at, last_synced_at, last_error)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(photo_id) DO UPDATE SET
|
||||
owner_id = excluded.owner_id,
|
||||
asset_id = excluded.asset_id,
|
||||
local_fingerprint = excluded.local_fingerprint,
|
||||
remote_fingerprint = excluded.remote_fingerprint,
|
||||
remote_updated_at = excluded.remote_updated_at,
|
||||
last_synced_at = excluded.last_synced_at,
|
||||
last_error = excluded.last_error
|
||||
`),
|
||||
deleteImmichMeta: db.prepare('DELETE FROM immich_meta WHERE photo_id = ?'),
|
||||
immichPushAssets: db.prepare(
|
||||
"SELECT DISTINCT new_asset_id FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL",
|
||||
),
|
||||
patchPhotoMeta: db.prepare(`
|
||||
UPDATE photos
|
||||
SET data = json_set(data, '$.rating', ?, '$.flag', ?, '$.keywords', json(?)), updated_at = ?
|
||||
WHERE id = ?
|
||||
`),
|
||||
|
||||
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
|
||||
insertUser: db.prepare(
|
||||
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
@@ -361,6 +558,8 @@ export function saveEvent(record, sortIndex = 0, ownerId = '') {
|
||||
|
||||
export function removeEvent(id) {
|
||||
q.deleteEvent.run(id);
|
||||
// An album link must not outlive the event it points at.
|
||||
q.deleteImmichAlbum.run(id);
|
||||
}
|
||||
|
||||
export function shareTokenFor(id) {
|
||||
@@ -479,6 +678,250 @@ export function getPhoto(id) {
|
||||
return row ? parse(row.data) : null;
|
||||
}
|
||||
|
||||
export function getEvent(id) {
|
||||
const row = q.event.get(id);
|
||||
return row ? parse(row.data) : null;
|
||||
}
|
||||
|
||||
/** The Luminary event already linked to an Immich album, if any. */
|
||||
export function immichAlbumFor(ownerId, serverUrl, albumId) {
|
||||
const row = q.immichAlbum.get(ownerId, serverUrl, albumId);
|
||||
return row ? albumLinkFromRow(row) : null;
|
||||
}
|
||||
|
||||
export function immichAlbumLinks(ownerId) {
|
||||
return q.immichAlbumsByOwner.all(ownerId).map(albumLinkFromRow);
|
||||
}
|
||||
|
||||
export function immichAlbumForEvent(eventId) {
|
||||
const row = q.immichAlbumForEvent.get(eventId);
|
||||
return row ? albumLinkFromRow(row) : null;
|
||||
}
|
||||
|
||||
export function immichAlbumByAlbum(ownerId, albumId) {
|
||||
const row = q.immichAlbumByAlbum.get(ownerId, albumId);
|
||||
return row ? albumLinkFromRow(row) : null;
|
||||
}
|
||||
|
||||
function albumLinkFromRow(row) {
|
||||
return {
|
||||
eventId: row.event_id,
|
||||
ownerId: row.owner_id,
|
||||
serverUrl: row.server_url,
|
||||
albumId: row.album_id,
|
||||
albumName: row.album_name,
|
||||
assetCount: Number(row.asset_count ?? 0),
|
||||
kind: row.kind ?? 'import',
|
||||
lastSyncAt: row.last_sync_at ?? null,
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
export function saveImmichAlbum(link) {
|
||||
q.upsertImmichAlbum.run(
|
||||
link.eventId,
|
||||
link.ownerId,
|
||||
link.serverUrl,
|
||||
link.albumId,
|
||||
link.albumName ?? '',
|
||||
Number(link.assetCount ?? 0),
|
||||
link.kind === 'gallery' ? 'gallery' : 'import',
|
||||
link.lastSyncAt ?? Date.now(),
|
||||
link.createdAt ?? Date.now(),
|
||||
);
|
||||
}
|
||||
|
||||
export function immichAssetsForEvent(eventId) {
|
||||
return q.immichAssetsByEvent.all(eventId).map((row) => ({
|
||||
eventId: row.event_id,
|
||||
assetId: row.asset_id,
|
||||
photoId: row.photo_id,
|
||||
ownerId: row.owner_id,
|
||||
albumId: row.album_id,
|
||||
checksum: row.checksum,
|
||||
fileName: row.file_name,
|
||||
importedAt: row.imported_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function saveImmichAsset(asset) {
|
||||
q.upsertImmichAsset.run(
|
||||
asset.eventId,
|
||||
asset.assetId,
|
||||
asset.photoId,
|
||||
asset.ownerId,
|
||||
asset.albumId,
|
||||
asset.checksum ?? '',
|
||||
asset.fileName ?? '',
|
||||
asset.importedAt ?? Date.now(),
|
||||
);
|
||||
}
|
||||
|
||||
export function removeImmichAsset(eventId, assetId) {
|
||||
q.deleteImmichAsset.run(eventId, assetId);
|
||||
}
|
||||
|
||||
/** The Immich source row for a photo, used when sending an edit back. */
|
||||
export function immichAssetForPhoto(photoId) {
|
||||
const row = q.immichAssetForPhoto.get(photoId);
|
||||
if (!row) return null;
|
||||
return {
|
||||
eventId: row.event_id,
|
||||
assetId: row.asset_id,
|
||||
photoId: row.photo_id,
|
||||
ownerId: row.owner_id,
|
||||
albumId: row.album_id,
|
||||
checksum: row.checksum,
|
||||
fileName: row.file_name,
|
||||
importedAt: row.imported_at,
|
||||
};
|
||||
}
|
||||
|
||||
function immichSettingsFromRow(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
ownerId: row.owner_id,
|
||||
serverUrl: row.server_url,
|
||||
apiKey: row.api_key,
|
||||
enabled: Boolean(row.enabled),
|
||||
autoSync: Boolean(row.auto_sync),
|
||||
syncMinutes: Number(row.sync_minutes ?? 60),
|
||||
trashOriginal: Boolean(row.trash_original),
|
||||
syncMetadata: Boolean(row.sync_metadata ?? 1),
|
||||
lastSyncAt: row.last_sync_at ?? null,
|
||||
lastError: row.last_error ?? null,
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
export function immichSettingsFor(ownerId) {
|
||||
return immichSettingsFromRow(q.immichSettings.get(ownerId));
|
||||
}
|
||||
|
||||
export function allImmichSettings() {
|
||||
return q.allImmichSettings.all().map(immichSettingsFromRow);
|
||||
}
|
||||
|
||||
export function saveImmichSettingsRecord(record) {
|
||||
q.upsertImmichSettings.run(
|
||||
record.ownerId,
|
||||
record.serverUrl ?? '',
|
||||
record.apiKey ?? '',
|
||||
record.enabled ? 1 : 0,
|
||||
record.autoSync ? 1 : 0,
|
||||
Math.max(15, Math.min(1440, Number(record.syncMinutes) || 60)),
|
||||
record.trashOriginal ? 1 : 0,
|
||||
record.syncMetadata === false ? 0 : 1,
|
||||
record.lastSyncAt ?? null,
|
||||
record.lastError ?? null,
|
||||
record.createdAt ?? Date.now(),
|
||||
);
|
||||
}
|
||||
|
||||
export function deleteImmichSettingsRecord(ownerId) {
|
||||
q.deleteImmichSettings.run(ownerId);
|
||||
}
|
||||
|
||||
export function setImmichSyncState(ownerId, lastSyncAt, lastError) {
|
||||
q.setImmichSyncState.run(lastSyncAt ?? null, lastError ?? null, ownerId);
|
||||
}
|
||||
|
||||
export function immichPushFor(photoId, checksum) {
|
||||
const row = q.immichPush.get(photoId, checksum);
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
ownerId: row.owner_id,
|
||||
photoId: row.photo_id,
|
||||
sourceAssetId: row.source_asset_id,
|
||||
newAssetId: row.new_asset_id ?? null,
|
||||
checksum: row.checksum,
|
||||
state: row.state,
|
||||
trashedSource: Boolean(row.trashed_source),
|
||||
error: row.error ?? null,
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
export function saveImmichPush(record) {
|
||||
q.upsertImmichPush.run(
|
||||
record.id,
|
||||
record.ownerId,
|
||||
record.photoId,
|
||||
record.sourceAssetId,
|
||||
record.newAssetId ?? null,
|
||||
record.checksum,
|
||||
record.editsHash ?? '',
|
||||
record.state,
|
||||
record.trashedSource ? 1 : 0,
|
||||
record.error ?? null,
|
||||
record.createdAt ?? Date.now(),
|
||||
);
|
||||
}
|
||||
|
||||
export function immichMetaFor(photoId) {
|
||||
const row = q.immichMeta.get(photoId);
|
||||
if (!row) return null;
|
||||
return {
|
||||
photoId: row.photo_id,
|
||||
ownerId: row.owner_id,
|
||||
assetId: row.asset_id,
|
||||
localFingerprint: row.local_fingerprint,
|
||||
remoteFingerprint: row.remote_fingerprint,
|
||||
remoteUpdatedAt: row.remote_updated_at ?? null,
|
||||
lastSyncedAt: row.last_synced_at ?? null,
|
||||
lastError: row.last_error ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function saveImmichMeta(record) {
|
||||
q.upsertImmichMeta.run(
|
||||
record.photoId,
|
||||
record.ownerId,
|
||||
record.assetId,
|
||||
record.localFingerprint,
|
||||
record.remoteFingerprint,
|
||||
record.remoteUpdatedAt ?? null,
|
||||
record.lastSyncedAt ?? Date.now(),
|
||||
record.lastError ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function immichPushAssetsForPhoto(photoId) {
|
||||
return q.immichPushAssets.all(photoId).map((row) => row.new_asset_id);
|
||||
}
|
||||
|
||||
/** The first successful upload for a photo, whatever checksum produced it. */
|
||||
export function immichPushDoneForPhoto(photoId) {
|
||||
return q.immichPushedForPhoto.get(photoId) ?? null;
|
||||
}
|
||||
|
||||
/** Every photo id in an event, in the order it is shown. */
|
||||
export function photoIdsForEvent(eventId, ownerId) {
|
||||
return q.immichPhotoIdsByEvent.all(eventId, ownerId).map((row) => row.id);
|
||||
}
|
||||
|
||||
/** Live photo ids in an event that still need to reach its Immich gallery. */
|
||||
export function immichPendingForEvent(eventId, ownerId) {
|
||||
return q.immichPendingByEvent
|
||||
.all(eventId, ownerId)
|
||||
.map((row) => parse(row.data))
|
||||
.filter((photo) => photo && !photo.deletedAt)
|
||||
.map((photo) => photo.id);
|
||||
}
|
||||
|
||||
/** Updates only metadata fields in the stored record, preserving sort order. */
|
||||
export function patchPhotoMeta(photoId, patch, updatedAt = Date.now()) {
|
||||
q.patchPhotoMeta.run(
|
||||
Math.max(0, Math.min(5, Number(patch.rating) || 0)),
|
||||
patch.flag ?? 'none',
|
||||
JSON.stringify(Array.isArray(patch.keywords) ? patch.keywords : []),
|
||||
updatedAt,
|
||||
photoId,
|
||||
);
|
||||
return getPhoto(photoId);
|
||||
}
|
||||
|
||||
export function photoOwner(id) {
|
||||
return q.photoOwner.get(id)?.owner_id ?? null;
|
||||
}
|
||||
@@ -501,6 +944,9 @@ export function removePhoto(id) {
|
||||
q.deletePicksForPhoto.run(id);
|
||||
q.deleteCommentsForPhoto.run(id);
|
||||
q.deleteReviewsForPhoto.run(id);
|
||||
q.deleteImmichAssetsForPhoto.run(id);
|
||||
q.deleteImmichPushesForPhoto.run(id);
|
||||
q.deleteImmichMeta.run(id);
|
||||
}
|
||||
|
||||
export function countPhotos() {
|
||||
|
||||
+1540
File diff suppressed because it is too large
Load Diff
+683
-67
@@ -11,6 +11,7 @@ import {
|
||||
MAX_UPLOAD,
|
||||
PORT,
|
||||
RAW_PREVIEW_EDGE,
|
||||
TRUST_PROXY,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
authenticate,
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
hashPassword,
|
||||
normalizeEmail,
|
||||
publicUser,
|
||||
spendPasswordCheck,
|
||||
validEmail,
|
||||
verifyPassword,
|
||||
} from './auth.mjs';
|
||||
@@ -58,11 +60,11 @@ import {
|
||||
findProofThumb,
|
||||
findThumb,
|
||||
isCustomRoot,
|
||||
originalTarget,
|
||||
removeAsset,
|
||||
setStorageRoot,
|
||||
storageBytes,
|
||||
storageRoot,
|
||||
writeOriginal,
|
||||
writePreview,
|
||||
writeProof,
|
||||
writeProofThumb,
|
||||
@@ -91,10 +93,47 @@ import {
|
||||
warnUser,
|
||||
} from './quota.mjs';
|
||||
import { mailStatus, saveMailSettings, sendTestMail } from './mail.mjs';
|
||||
import {
|
||||
createImmichAlbumForEvent,
|
||||
disconnectImmich,
|
||||
disconnectImmichAdmin,
|
||||
immichAdminPing,
|
||||
immichAdminStatus,
|
||||
immichConfigured,
|
||||
immichEventQueue,
|
||||
immichJobFor,
|
||||
immichLinksForOwner,
|
||||
immichPendingPhotos,
|
||||
immichPing,
|
||||
immichStatusFor,
|
||||
listImmichAlbums,
|
||||
publishImmichOriginal,
|
||||
pushImmichPhoto,
|
||||
pushImmichPhotoMetadata,
|
||||
saveImmichAdminSettings,
|
||||
saveImmichUserSettings,
|
||||
startImmichImport,
|
||||
} from './immich.mjs';
|
||||
|
||||
const VERSION = '1.0.0';
|
||||
const COOKIE = 'lumen_session';
|
||||
|
||||
/** Self-only policy; must allow the wasm engines and React inline styles. */
|
||||
const CSP = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
"media-src 'self' blob:",
|
||||
"worker-src 'self' blob:",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'self'",
|
||||
].join('; ');
|
||||
|
||||
/* ------------------------------------------------------------------ helpers */
|
||||
|
||||
function json(res, status, payload, extraHeaders = {}) {
|
||||
@@ -108,8 +147,95 @@ function json(res, status, payload, extraHeaders = {}) {
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function error(res, status, message) {
|
||||
json(res, status, { error: message });
|
||||
class PayloadTooLarge extends Error {}
|
||||
|
||||
function error(res, status, message, extraHeaders = {}) {
|
||||
json(res, status, { error: message }, extraHeaders);
|
||||
}
|
||||
|
||||
/** Failed sign-ins are bucketed per socket address and per account. */
|
||||
const AUTH_WINDOW_MS = 15 * 60 * 1000;
|
||||
const authBuckets = new Map();
|
||||
|
||||
function clientIp(req) {
|
||||
// X-Forwarded-For is spoofable unless a proxy overwrites it, so it is only
|
||||
// consulted when the operator opts in with LUMINARY_TRUST_PROXY=1.
|
||||
if (TRUST_PROXY) {
|
||||
const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
|
||||
if (forwarded) return forwarded;
|
||||
}
|
||||
return String(req.socket?.remoteAddress ?? 'unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-address cap. Behind a proxy without TRUST_PROXY every client shares the
|
||||
* proxy address, so the cap is higher to avoid turning noise into a lock-out;
|
||||
* the per-account limit is the real brute-force bound.
|
||||
*/
|
||||
const LOGIN_IP_LIMIT = TRUST_PROXY ? 50 : 500;
|
||||
|
||||
function authFailures(key) {
|
||||
const bucket = authBuckets.get(key);
|
||||
if (!bucket || Date.now() - bucket.start >= AUTH_WINDOW_MS) return 0;
|
||||
return bucket.count;
|
||||
}
|
||||
|
||||
function recordAuthFailure(key) {
|
||||
const now = Date.now();
|
||||
const bucket = authBuckets.get(key);
|
||||
if (!bucket || now - bucket.start >= AUTH_WINDOW_MS) {
|
||||
authBuckets.set(key, { start: now, count: 1 });
|
||||
} else {
|
||||
bucket.count += 1;
|
||||
}
|
||||
if (authBuckets.size > 10_000) {
|
||||
for (const [name, value] of authBuckets) {
|
||||
if (now - value.start >= AUTH_WINDOW_MS) authBuckets.delete(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function clearAuthFailures(key) {
|
||||
authBuckets.delete(key);
|
||||
}
|
||||
|
||||
/** Coarse fixed-window limiter for public gallery writes. */
|
||||
const galleryBuckets = new Map();
|
||||
function allowGalleryWrite(req, token) {
|
||||
const key = `${clientIp(req)}:${token}`;
|
||||
const now = Date.now();
|
||||
const bucket = galleryBuckets.get(key);
|
||||
if (!bucket || now - bucket.start >= 60_000) {
|
||||
galleryBuckets.set(key, { start: now, count: 1 });
|
||||
if (galleryBuckets.size > 5_000) {
|
||||
for (const [name, value] of galleryBuckets) {
|
||||
if (now - value.start >= 60_000) galleryBuckets.delete(name);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bucket.count += 1;
|
||||
return bucket.count <= 120;
|
||||
}
|
||||
|
||||
const PHOTO_MIME_BY_EXT = {
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
gif: 'image/gif',
|
||||
avif: 'image/avif',
|
||||
tif: 'image/tiff',
|
||||
tiff: 'image/tiff',
|
||||
};
|
||||
const PHOTO_MIMES = new Set(Object.values(PHOTO_MIME_BY_EXT));
|
||||
|
||||
/** Only raster types the browser cannot turn into script are served inline. */
|
||||
function normalizePhotoMime(value, name = '') {
|
||||
const mime = String(value ?? '').split(';')[0].trim().toLowerCase();
|
||||
if (PHOTO_MIMES.has(mime)) return mime;
|
||||
const ext = String(name).split('.').pop()?.toLowerCase() ?? '';
|
||||
return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream';
|
||||
}
|
||||
|
||||
function parseCookies(req) {
|
||||
@@ -117,7 +243,11 @@ function parseCookies(req) {
|
||||
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
||||
const idx = part.indexOf('=');
|
||||
if (idx < 0) continue;
|
||||
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
|
||||
try {
|
||||
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
|
||||
} catch {
|
||||
/* ignore malformed percent-encoding in a cookie */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -152,9 +282,14 @@ function requireAdmin(req, res) {
|
||||
return user;
|
||||
}
|
||||
|
||||
/** An ownerless row predates workspaces; anyone signed in may finish it. */
|
||||
/**
|
||||
* A null owner means the row does not exist yet (new records are allowed).
|
||||
* An empty owner is a legacy row from before workspaces; only an admin may
|
||||
* touch it. Everyone else may only reach their own rows.
|
||||
*/
|
||||
function ownedBy(owner, user) {
|
||||
return !owner || owner === user.id;
|
||||
if (owner === null || owner === undefined) return true;
|
||||
return owner === user.id || (owner === '' && user.role === 'admin');
|
||||
}
|
||||
|
||||
function adminUser(row) {
|
||||
@@ -204,11 +339,16 @@ function readBody(req, limit = MAX_UPLOAD) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
let tooLarge = false;
|
||||
req.on('data', (chunk) => {
|
||||
if (tooLarge) return;
|
||||
size += chunk.length;
|
||||
if (size > limit) {
|
||||
reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
|
||||
req.destroy();
|
||||
tooLarge = true;
|
||||
chunks.length = 0;
|
||||
// Keep draining instead of destroying the socket so the 413 can flush.
|
||||
req.resume();
|
||||
reject(new PayloadTooLarge(`Request exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
@@ -228,6 +368,51 @@ async function readJson(req, limit = 8 * 1024 * 1024) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams an upload straight to disk. Buffering the body would let one request
|
||||
* hold hundreds of megabytes of RAM.
|
||||
*/
|
||||
async function receiveUpload(req, target, limit) {
|
||||
const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`;
|
||||
let size = 0;
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const out = fs.createWriteStream(temp, { flags: 'wx' });
|
||||
let settled = false;
|
||||
const fail = (err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
req.unpipe(out);
|
||||
out.destroy();
|
||||
req.resume();
|
||||
fs.rm(temp, { force: true }, () => reject(err));
|
||||
};
|
||||
req.on('data', (chunk) => {
|
||||
if (settled) return;
|
||||
size += chunk.length;
|
||||
if (size > limit) fail(new PayloadTooLarge('Upload exceeds the size limit'));
|
||||
});
|
||||
req.on('error', fail);
|
||||
out.on('error', fail);
|
||||
out.on('finish', () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve();
|
||||
});
|
||||
req.pipe(out);
|
||||
});
|
||||
if (!size) {
|
||||
await fsp.rm(temp, { force: true });
|
||||
return 0;
|
||||
}
|
||||
await fsp.rename(temp, target);
|
||||
return size;
|
||||
} catch (err) {
|
||||
await fsp.rm(temp, { force: true }).catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function match(pathname, pattern) {
|
||||
const p = pattern.split('/');
|
||||
const a = pathname.split('/');
|
||||
@@ -248,7 +433,7 @@ function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
|
||||
'Content-Type': type,
|
||||
'Content-Length': data.length,
|
||||
'Cache-Control': cache,
|
||||
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
res.end(data);
|
||||
}
|
||||
@@ -271,7 +456,7 @@ async function sendFile(req, res, filePath, type, cache = 'private, max-age=8640
|
||||
'Content-Type': type,
|
||||
'Content-Length': stat.size,
|
||||
'Cache-Control': cache,
|
||||
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
...extraHeaders,
|
||||
});
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
@@ -288,6 +473,35 @@ function decodeDataUrl(value) {
|
||||
return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') };
|
||||
}
|
||||
|
||||
/** Health totals walk the filesystem, so cache them instead of scanning per hit. */
|
||||
let healthCache = { at: 0, photos: 0, bytes: 0, root: '', custom: false };
|
||||
function healthStats() {
|
||||
if (Date.now() - healthCache.at < 30_000) return healthCache;
|
||||
healthCache = {
|
||||
at: Date.now(),
|
||||
photos: countPhotos(),
|
||||
bytes: storageBytes(),
|
||||
root: storageRoot(),
|
||||
custom: isCustomRoot(),
|
||||
};
|
||||
return healthCache;
|
||||
}
|
||||
|
||||
const MAX_ARCHIVE_FILES = 400;
|
||||
const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
|
||||
let archiveBuilding = false;
|
||||
|
||||
/** Uploads accepted for an id that does not have a photo row yet. */
|
||||
const recentUploads = new Map();
|
||||
|
||||
function pendingBytes(ownerId) {
|
||||
let total = 0;
|
||||
for (const upload of recentUploads.values()) {
|
||||
if (upload.pending && upload.ownerId === ownerId) total += upload.bytes;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------- api */
|
||||
|
||||
import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs';
|
||||
@@ -297,17 +511,20 @@ function route(method, pattern, handler) {
|
||||
routes.push({ method, pattern, handler });
|
||||
}
|
||||
|
||||
route('GET', '/api/health', async ({ res }) => {
|
||||
route('GET', '/api/health', async ({ req, res }) => {
|
||||
const raw = await rawSupport();
|
||||
const user = currentUser(req);
|
||||
const stats = healthStats();
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
app: 'luminary',
|
||||
version: VERSION,
|
||||
needsSetup: users.count() === 0,
|
||||
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
||||
photos: countPhotos(),
|
||||
bytes: storageBytes(),
|
||||
storage: { root: storageRoot(), custom: isCustomRoot() },
|
||||
photos: stats.photos,
|
||||
bytes: stats.bytes,
|
||||
// The absolute data path is only for signed-in team members.
|
||||
...(user ? { storage: { root: stats.root, custom: stats.custom } } : {}),
|
||||
raw,
|
||||
});
|
||||
});
|
||||
@@ -351,7 +568,7 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
|
||||
id,
|
||||
email,
|
||||
name: name || email.split('@')[0],
|
||||
passHash: hashPassword(password),
|
||||
passHash: await hashPassword(password),
|
||||
role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member',
|
||||
});
|
||||
if (inviteRow && !invites.accept(token, id)) {
|
||||
@@ -368,11 +585,38 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
|
||||
});
|
||||
|
||||
route('POST', '/api/auth/login', async ({ req, res }) => {
|
||||
const ipKey = `login:ip:${clientIp(req)}`;
|
||||
if (authFailures(ipKey) >= LOGIN_IP_LIMIT) {
|
||||
return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' });
|
||||
}
|
||||
|
||||
const body = await readJson(req, 64 * 1024);
|
||||
const email = normalizeEmail(body.email);
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
const accountKey = `login:acct:${clientIp(req)}:${email}`;
|
||||
if (authFailures(accountKey) >= 8) {
|
||||
return error(res, 429, 'Too many sign-in attempts for this account. Try again later.', {
|
||||
'Retry-After': '900',
|
||||
});
|
||||
}
|
||||
|
||||
const row = users.byEmail(email);
|
||||
if (!row || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct');
|
||||
if (!row) {
|
||||
// Spend the same scrypt work as a real account so response timing does not
|
||||
// reveal which addresses are registered.
|
||||
await spendPasswordCheck(password);
|
||||
recordAuthFailure(ipKey);
|
||||
recordAuthFailure(accountKey);
|
||||
return error(res, 401, 'Email or password is not correct');
|
||||
}
|
||||
|
||||
const valid = await verifyPassword(password, row.pass_hash);
|
||||
if (!valid) {
|
||||
recordAuthFailure(ipKey);
|
||||
recordAuthFailure(accountKey);
|
||||
return error(res, 401, 'Email or password is not correct');
|
||||
}
|
||||
clearAuthFailures(accountKey);
|
||||
if (row.disabled) return error(res, 403, 'This account has been disabled by an administrator');
|
||||
const token = createSession(row.id);
|
||||
json(
|
||||
@@ -445,6 +689,7 @@ route('GET', '/api/admin/overview', async ({ req, res }) => {
|
||||
},
|
||||
quotas: quotasForAdmin(),
|
||||
mail: mailStatus(),
|
||||
immich: immichAdminStatus(),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -464,7 +709,7 @@ route('POST', '/api/admin/users', async ({ req, res }) => {
|
||||
id,
|
||||
email,
|
||||
name: name || email.split('@')[0],
|
||||
passHash: hashPassword(password),
|
||||
passHash: await hashPassword(password),
|
||||
role,
|
||||
});
|
||||
json(res, 201, { user: adminUser(users.byId(id)) });
|
||||
@@ -482,7 +727,7 @@ route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => {
|
||||
|
||||
if (typeof body.password === 'string' && body.password) {
|
||||
if (body.password.length < 8) return error(res, 400, 'Use at least 8 characters for the password');
|
||||
patch.passHash = hashPassword(body.password);
|
||||
patch.passHash = await hashPassword(body.password);
|
||||
}
|
||||
|
||||
if (typeof body.role === 'string') {
|
||||
@@ -718,6 +963,208 @@ route('POST', '/api/admin/mail/test', async ({ req, res }) => {
|
||||
}
|
||||
});
|
||||
|
||||
route('GET', '/api/admin/immich', async ({ req, res }) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
json(res, 200, { immich: immichAdminStatus() });
|
||||
});
|
||||
|
||||
route('PUT', '/api/admin/immich', async ({ req, res }) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const body = await readJson(req, 16 * 1024);
|
||||
try {
|
||||
json(res, 200, { immich: saveImmichAdminSettings(body) });
|
||||
} catch (err) {
|
||||
return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection');
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/admin/immich/test', async ({ req, res }) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
try {
|
||||
json(res, 200, await immichAdminPing());
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
||||
}
|
||||
});
|
||||
|
||||
route('DELETE', '/api/admin/immich', async ({ req, res }) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
json(res, 200, { immich: disconnectImmichAdmin() });
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ immich */
|
||||
|
||||
route('GET', '/api/immich', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
json(res, 200, { immich: immichStatusFor(user.id) });
|
||||
});
|
||||
|
||||
route('PUT', '/api/immich', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const body = await readJson(req, 16 * 1024);
|
||||
try {
|
||||
json(res, 200, { immich: saveImmichUserSettings(user.id, body) });
|
||||
} catch (err) {
|
||||
return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection');
|
||||
}
|
||||
});
|
||||
|
||||
route('DELETE', '/api/immich', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
json(res, 200, { immich: disconnectImmich(user.id) });
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/test', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
try {
|
||||
json(res, 200, await immichPing(user.id));
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
||||
}
|
||||
});
|
||||
|
||||
/** Albums are listed for any signed-in user; the API key still stays server-side. */
|
||||
route('GET', '/api/immich/albums', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!immichConfigured(user.id)) return error(res, 503, 'Immich is not configured yet');
|
||||
try {
|
||||
const links = new Map(immichLinksForOwner(user.id).map((link) => [link.albumId, link]));
|
||||
const albums = await listImmichAlbums(user.id);
|
||||
json(res, 200, {
|
||||
albums: albums.map((album) => ({
|
||||
...album,
|
||||
eventId: links.get(album.id)?.eventId ?? null,
|
||||
lastSyncAt: links.get(album.id)?.lastSyncAt ?? null,
|
||||
kind: links.get(album.id)?.kind ?? 'import',
|
||||
})),
|
||||
});
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/albums', async ({ req, res }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const body = await readJson(req, 16 * 1024);
|
||||
if (typeof body.eventId !== 'string' || !body.eventId) {
|
||||
return error(res, 400, 'Choose the event for the gallery');
|
||||
}
|
||||
if (!ownedBy(eventOwner(body.eventId), user)) return error(res, 404, 'No such event');
|
||||
try {
|
||||
json(res, 201, await createImmichAlbumForEvent({
|
||||
ownerId: user.id,
|
||||
eventId: body.eventId,
|
||||
name: body.name,
|
||||
}));
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not create the Immich gallery');
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/albums/:id/import', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
try {
|
||||
json(res, 202, { job: startImmichImport({ albumId: params.id, ownerId: user.id }) });
|
||||
} catch (err) {
|
||||
return error(res, 400, err instanceof Error ? err.message : 'Could not start the import');
|
||||
}
|
||||
});
|
||||
|
||||
route('GET', '/api/immich/jobs/:id', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
const job = immichJobFor(params.id, user);
|
||||
if (!job) return error(res, 404, 'Import job not found');
|
||||
json(res, 200, { job });
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/photos/:id/metadata', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
|
||||
const body = await readJson(req, 64 * 1024);
|
||||
const rating = Math.max(0, Math.min(5, Math.trunc(Number(body.rating) || 0)));
|
||||
const flag = body.flag === 'pick' || body.flag === 'reject' ? body.flag : 'none';
|
||||
const keywords = Array.isArray(body.keywords)
|
||||
? body.keywords.filter((word) => typeof word === 'string').slice(0, 100)
|
||||
: [];
|
||||
try {
|
||||
json(res, 200, await pushImmichPhotoMetadata({
|
||||
photoId: params.id,
|
||||
ownerId: user.id,
|
||||
local: { rating, flag, keywords },
|
||||
}));
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not sync Immich metadata');
|
||||
}
|
||||
});
|
||||
|
||||
/** Photo ids still missing from an event's gallery, for a backfill run. */
|
||||
route('GET', '/api/immich/events/:id/pending', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
try {
|
||||
json(res, 200, immichPendingPhotos({ eventId: params.id, ownerId: user.id }));
|
||||
} catch (err) {
|
||||
return error(res, 400, err instanceof Error ? err.message : 'Could not read the Immich queue');
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The manual push plan for an event: originals Immich has never seen plus the
|
||||
* edits that changed since the last push. Nothing uploads from this route.
|
||||
*/
|
||||
route('GET', '/api/immich/events/:id/queue', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
try {
|
||||
json(res, 200, immichEventQueue({ eventId: params.id, ownerId: user.id }));
|
||||
} catch (err) {
|
||||
return error(res, 400, err instanceof Error ? err.message : 'Could not plan the Immich push');
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/photos/:id/publish', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
try {
|
||||
json(res, 200, await publishImmichOriginal({ photoId: params.id, ownerId: user.id }));
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not publish the photo');
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/immich/photos/:id/push', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
|
||||
const body = await readJson(req, 96 * 1024 * 1024);
|
||||
if (typeof body.jpeg !== 'string' || !body.jpeg) {
|
||||
return error(res, 400, 'A rendered JPEG is required');
|
||||
}
|
||||
const jpeg = Buffer.from(body.jpeg, 'base64');
|
||||
if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
|
||||
return error(res, 400, 'The edited file is not a JPEG image');
|
||||
}
|
||||
try {
|
||||
json(res, 200, await pushImmichPhoto({ photoId: params.id, ownerId: user.id, jpeg }));
|
||||
} catch (err) {
|
||||
return error(res, 502, err instanceof Error ? err.message : 'Could not send the edit to Immich');
|
||||
}
|
||||
});
|
||||
|
||||
route('GET', '/api/bridge/login', async ({ req, res, url }) => {
|
||||
if (!bridgeConfigured()) {
|
||||
return error(res, 503, 'The advanced editor bridge is not configured');
|
||||
@@ -742,7 +1189,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => {
|
||||
id,
|
||||
email,
|
||||
name: payload.name || email.split('@')[0],
|
||||
passHash: hashPassword(crypto.randomBytes(24).toString('hex')),
|
||||
passHash: await hashPassword(crypto.randomBytes(24).toString('hex')),
|
||||
role: 'member',
|
||||
});
|
||||
row = users.byId(id);
|
||||
@@ -962,7 +1409,16 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para
|
||||
if (!hit) return error(res, 404, 'Not found');
|
||||
const proof = findProof(params.id);
|
||||
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
||||
return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', 'private, max-age=3600');
|
||||
if (!file) return error(res, 404, 'Not found');
|
||||
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
||||
return sendFile(
|
||||
req,
|
||||
res,
|
||||
file,
|
||||
mime,
|
||||
'private, max-age=3600',
|
||||
mime === 'application/octet-stream' ? { 'Content-Disposition': 'attachment' } : {},
|
||||
);
|
||||
});
|
||||
|
||||
/** Client download of the edited proof, named like the delivered file. */
|
||||
@@ -973,7 +1429,8 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
|
||||
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
||||
const originalName = String(hit.photo.name || 'photo.jpg');
|
||||
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
||||
return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', 'private, max-age=3600', {
|
||||
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
||||
return sendFile(req, res, file, mime, 'private, max-age=3600', {
|
||||
'Content-Disposition': `attachment; filename="${safe}"`,
|
||||
});
|
||||
});
|
||||
@@ -987,44 +1444,68 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
|
||||
(pick) => pick.picked && (!clientId || pick.clientId === clientId),
|
||||
);
|
||||
if (!picks.length) return error(res, 404, 'There are no favourites to download yet');
|
||||
|
||||
const entries = [];
|
||||
const seen = new Set();
|
||||
for (const pick of picks) {
|
||||
if (seen.has(pick.photoId)) continue;
|
||||
seen.add(pick.photoId);
|
||||
const photo = getPhoto(pick.photoId);
|
||||
if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue;
|
||||
const proof = findProof(photo.id);
|
||||
const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id);
|
||||
if (!file) continue;
|
||||
try {
|
||||
const data = await fsp.readFile(file);
|
||||
const originalName = String(photo.name || 'photo.jpg');
|
||||
const name = proof
|
||||
? originalName.replace(/\.[^.]+$/, '.jpg')
|
||||
: originalName;
|
||||
entries.push({ name, data });
|
||||
} catch {
|
||||
/* skip an unreadable file rather than losing the whole archive */
|
||||
}
|
||||
if (archiveBuilding) {
|
||||
return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', {
|
||||
'Retry-After': '30',
|
||||
});
|
||||
}
|
||||
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
|
||||
|
||||
const archive = createZip(entries);
|
||||
const eventName = String(shared.event.name || 'proofing')
|
||||
.replace(/[^a-z0-9._ -]+/gi, '-')
|
||||
.trim() || 'proofing';
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Length': archive.length,
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`,
|
||||
});
|
||||
res.end(archive);
|
||||
archiveBuilding = true;
|
||||
try {
|
||||
const entries = [];
|
||||
const seen = new Set();
|
||||
let totalBytes = 0;
|
||||
for (const pick of picks) {
|
||||
if (seen.has(pick.photoId)) continue;
|
||||
seen.add(pick.photoId);
|
||||
const photo = getPhoto(pick.photoId);
|
||||
if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue;
|
||||
const proof = findProof(photo.id);
|
||||
const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id);
|
||||
if (!file) continue;
|
||||
if (entries.length >= MAX_ARCHIVE_FILES) {
|
||||
return error(res, 413, 'Too many favourites for one archive. Download in smaller batches.');
|
||||
}
|
||||
try {
|
||||
const stat = await fsp.stat(file);
|
||||
if (totalBytes + stat.size > MAX_ARCHIVE_BYTES) {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
'This selection is too large for one archive. Download in smaller batches.',
|
||||
);
|
||||
}
|
||||
const data = await fsp.readFile(file);
|
||||
totalBytes += data.length;
|
||||
const originalName = String(photo.name || 'photo.jpg');
|
||||
const name = proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName;
|
||||
entries.push({ name, data });
|
||||
} catch {
|
||||
/* skip an unreadable file rather than losing the whole archive */
|
||||
}
|
||||
}
|
||||
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
|
||||
|
||||
const archive = createZip(entries);
|
||||
const eventName = String(shared.event.name || 'proofing')
|
||||
.replace(/[^a-z0-9._ -]+/gi, '-')
|
||||
.trim() || 'proofing';
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Length': archive.length,
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`,
|
||||
});
|
||||
res.end(archive);
|
||||
} finally {
|
||||
archiveBuilding = false;
|
||||
}
|
||||
});
|
||||
|
||||
route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
@@ -1048,6 +1529,9 @@ route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) =>
|
||||
});
|
||||
|
||||
route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
@@ -1068,6 +1552,9 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => {
|
||||
});
|
||||
|
||||
route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
@@ -1118,19 +1605,82 @@ route('PUT', '/api/presets', async ({ req, res }) => {
|
||||
route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
const owner = photoOwner(params.id);
|
||||
if (owner !== null && !ownedBy(owner, user)) return error(res, 404, 'No such photo');
|
||||
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const name = url.searchParams.get('name') || 'upload';
|
||||
const mime = url.searchParams.get('mime') || 'application/octet-stream';
|
||||
const drop = url.searchParams.get('drop') === '1';
|
||||
const data = await readBody(req);
|
||||
if (!data.length) return error(res, 400, 'Empty upload');
|
||||
|
||||
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
||||
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
||||
await writeOriginal(params.id, ext, data);
|
||||
const raw = isRawName(name) || drop;
|
||||
|
||||
if (isRawName(name) || drop) {
|
||||
// New ids are part of the normal import flow: the client uploads bytes first
|
||||
// and PUTs the record afterwards. Until that row exists the bytes are charged
|
||||
// to this user's quota, so nobody can fill the disk with unclaimed files.
|
||||
const limit = owner
|
||||
? MAX_UPLOAD
|
||||
: Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id)));
|
||||
if (limit < 1) {
|
||||
return error(res, 413, 'This account has no storage quota left for a new upload');
|
||||
}
|
||||
const announced = Number(req.headers['content-length']);
|
||||
if (Number.isFinite(announced) && announced > limit) {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
}
|
||||
|
||||
// Reserve the announced size synchronously: otherwise two parallel uploads
|
||||
// could each pass the same remaining-quota check before either writes.
|
||||
if (owner === null) {
|
||||
recentUploads.set(params.id, {
|
||||
ownerId: user.id,
|
||||
bytes: Number.isFinite(announced) && announced > 0 ? announced : limit,
|
||||
at: Date.now(),
|
||||
pending: true,
|
||||
});
|
||||
}
|
||||
|
||||
const target = originalTarget(params.id, ext);
|
||||
const previous = findOriginal(params.id);
|
||||
if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined);
|
||||
|
||||
let size = 0;
|
||||
try {
|
||||
size = await receiveUpload(req, target, limit);
|
||||
} catch (err) {
|
||||
if (owner === null) recentUploads.delete(params.id);
|
||||
if (err instanceof PayloadTooLarge) {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!size) {
|
||||
if (owner === null) recentUploads.delete(params.id);
|
||||
return error(res, 400, 'Empty upload');
|
||||
}
|
||||
|
||||
recentUploads.set(params.id, {
|
||||
ownerId: user.id,
|
||||
bytes: size,
|
||||
at: Date.now(),
|
||||
pending: owner === null,
|
||||
});
|
||||
|
||||
if (raw) {
|
||||
try {
|
||||
const data = await fsp.readFile(target);
|
||||
const decoded = await decodeRaw(data);
|
||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||
const info = await jpegInfo(decoded.jpeg);
|
||||
@@ -1146,11 +1696,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
maxEdge: RAW_PREVIEW_EDGE,
|
||||
});
|
||||
} catch (err) {
|
||||
recentUploads.delete(params.id);
|
||||
await removeAsset(params.id).catch(() => undefined);
|
||||
return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file');
|
||||
}
|
||||
}
|
||||
|
||||
return json(res, 201, { raw: false, mime, size: data.length });
|
||||
return json(res, 201, { raw: false, mime, size });
|
||||
});
|
||||
|
||||
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
|
||||
@@ -1292,7 +1844,7 @@ route('GET', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original');
|
||||
if (!upstream.ok) return error(res, 404, 'Original unavailable');
|
||||
const data = Buffer.from(await upstream.arrayBuffer());
|
||||
return sendBuffer(res, data, linked.photo.mime || 'application/octet-stream');
|
||||
return sendBuffer(res, data, normalizePhotoMime(linked.photo.mime, linked.photo.name));
|
||||
});
|
||||
|
||||
route('POST', '/api/bridge/export', async ({ req, res }) => {
|
||||
@@ -1326,6 +1878,15 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
|
||||
const record = { ...body, id: params.id };
|
||||
|
||||
// Quota accounting uses bytes the server actually received, not the client's
|
||||
// claim, for an upload that just finished.
|
||||
const upload = recentUploads.get(params.id);
|
||||
if (upload && upload.ownerId === user.id) {
|
||||
record.size = upload.bytes;
|
||||
recentUploads.delete(params.id);
|
||||
}
|
||||
record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name);
|
||||
|
||||
const thumb = decodeDataUrl(record.thumb);
|
||||
if (thumb) {
|
||||
await writeThumb(params.id, thumb.data);
|
||||
@@ -1353,6 +1914,7 @@ route('DELETE', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
recentUploads.delete(params.id);
|
||||
removePhoto(params.id);
|
||||
clearDenoised(params.id);
|
||||
await removeAsset(params.id);
|
||||
@@ -1378,9 +1940,18 @@ const MIME = {
|
||||
};
|
||||
|
||||
async function serveStatic(req, res, url) {
|
||||
const pathname = decodeURIComponent(url.pathname);
|
||||
const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname);
|
||||
if (candidate.startsWith(DIST_DIR)) {
|
||||
let pathname;
|
||||
try {
|
||||
pathname = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
return error(res, 400, 'Bad request');
|
||||
}
|
||||
if (pathname.includes('\0')) return error(res, 400, 'Bad request');
|
||||
// path.relative, not startsWith: a sibling such as /srv/dist-private shares
|
||||
// the dist prefix and would otherwise pass a bare prefix check.
|
||||
const candidate = path.resolve(path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname));
|
||||
const relative = path.relative(DIST_DIR, candidate);
|
||||
if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
|
||||
try {
|
||||
const stat = await fsp.stat(candidate);
|
||||
if (stat.isFile()) {
|
||||
@@ -1413,8 +1984,15 @@ async function serveStatic(req, res, url) {
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
|
||||
res.setHeader('Content-Security-Policy', CSP);
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
||||
res.setHeader('Referrer-Policy', 'same-origin');
|
||||
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');
|
||||
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
||||
if (String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() === 'https') {
|
||||
res.setHeader('Strict-Transport-Security', 'max-age=15552000');
|
||||
}
|
||||
try {
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
for (const r of routes) {
|
||||
@@ -1429,11 +2007,39 @@ const server = http.createServer(async (req, res) => {
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Unexpected error';
|
||||
console.error(`[luminary] ${req.method} ${url.pathname} → ${message}`);
|
||||
if (!res.headersSent) return error(res, 500, message);
|
||||
if (!res.headersSent) {
|
||||
if (err instanceof PayloadTooLarge) return error(res, 413, message);
|
||||
// Do not leak internals from an unexpected failure.
|
||||
return error(res, 500, 'Unexpected server error');
|
||||
}
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
/** Drop uploads that were streamed to disk but never became a photo record. */
|
||||
async function sweepStaleUploads() {
|
||||
const cutoff = Date.now() - 60 * 60 * 1000;
|
||||
for (const [id, upload] of recentUploads) {
|
||||
if (upload.at > cutoff) continue;
|
||||
recentUploads.delete(id);
|
||||
if (!getPhoto(id)) await removeAsset(id).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove pre-upgrade orphans: originals with no catalog row, older than a day. */
|
||||
async function sweepOrphanOriginals() {
|
||||
const dir = path.join(storageRoot(), 'originals');
|
||||
const names = await fsp.readdir(dir).catch(() => []);
|
||||
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
||||
for (const name of names) {
|
||||
const id = name.replace(/\.[^.]+$/, '');
|
||||
if (/^[A-Za-z0-9_-]{1,80}$/.test(id) && getPhoto(id)) continue;
|
||||
const file = path.join(dir, name);
|
||||
const stat = await fsp.stat(file).catch(() => null);
|
||||
if (stat && stat.mtimeMs < cutoff) await fsp.rm(file, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
server.listen(PORT, HOST, async () => {
|
||||
startQuotaWorker();
|
||||
const raw = await rawSupport();
|
||||
@@ -1446,6 +2052,16 @@ server.listen(PORT, HOST, async () => {
|
||||
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
void sweepStaleUploads().catch((err) =>
|
||||
console.error(`[luminary] upload sweep: ${err.message}`),
|
||||
);
|
||||
}, 10 * 60 * 1000).unref?.();
|
||||
|
||||
void sweepOrphanOriginals().catch((err) =>
|
||||
console.error(`[luminary] orphan sweep: ${err.message}`),
|
||||
);
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||||
process.on(signal, () => {
|
||||
server.close(() => process.exit(0));
|
||||
|
||||
+12
-2
@@ -1,5 +1,6 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import { kv } from './db.mjs';
|
||||
import { open, seal } from './secrets.mjs';
|
||||
import {
|
||||
SMTP_APP_PASSWORD,
|
||||
SMTP_FROM,
|
||||
@@ -13,7 +14,16 @@ const SETTINGS_KEY = 'mailSettings';
|
||||
|
||||
function savedSettings() {
|
||||
const value = kv.get(SETTINGS_KEY);
|
||||
return value && typeof value === 'object' ? value : {};
|
||||
if (!value || typeof value !== 'object') return {};
|
||||
if (typeof value.appPassword === 'string' && value.appPassword) {
|
||||
try {
|
||||
return { ...value, appPassword: open(value.appPassword) };
|
||||
} catch (err) {
|
||||
console.error('[luminary] could not decrypt the saved SMTP password:', err.message);
|
||||
return { ...value, appPassword: '' };
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Never returns the app password; `hasPassword` is enough for the admin UI. */
|
||||
@@ -70,7 +80,7 @@ function validateSettings(input) {
|
||||
|
||||
export function saveMailSettings(input) {
|
||||
const next = validateSettings(input ?? {});
|
||||
kv.set(SETTINGS_KEY, next);
|
||||
kv.set(SETTINGS_KEY, { ...next, appPassword: seal(next.appPassword) });
|
||||
return mailStatus();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Small AES-256-GCM helper for credentials stored in SQLite (SMTP app password,
|
||||
* bridge service tokens). Values written before this file existed are plain
|
||||
* strings and are still readable; they are sealed the next time they are saved.
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DATA_DIR, SECRET_KEY } from './config.mjs';
|
||||
|
||||
const PREFIX = 'enc:v1:';
|
||||
let cachedKey = null;
|
||||
|
||||
function loadKey() {
|
||||
if (cachedKey) return cachedKey;
|
||||
|
||||
if (SECRET_KEY) {
|
||||
cachedKey = crypto.createHash('sha256').update(SECRET_KEY).digest();
|
||||
return cachedKey;
|
||||
}
|
||||
|
||||
// Without an explicit key, keep one beside the database. It protects copies
|
||||
// of the database (backups, dumps) but not an attacker who has the whole
|
||||
// data directory.
|
||||
const file = path.join(DATA_DIR, 'secret.key');
|
||||
const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : '';
|
||||
if (existing) {
|
||||
cachedKey = crypto.createHash('sha256').update(existing).digest();
|
||||
return cachedKey;
|
||||
}
|
||||
|
||||
const generated = crypto.randomBytes(32).toString('hex');
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
try {
|
||||
fs.writeFileSync(file, generated, { mode: 0o600, flag: 'wx' });
|
||||
cachedKey = crypto.createHash('sha256').update(generated).digest();
|
||||
} catch {
|
||||
cachedKey = crypto
|
||||
.createHash('sha256')
|
||||
.update(fs.readFileSync(file, 'utf8').trim())
|
||||
.digest();
|
||||
}
|
||||
return cachedKey;
|
||||
}
|
||||
|
||||
export function isSealed(value) {
|
||||
return typeof value === 'string' && value.startsWith(PREFIX);
|
||||
}
|
||||
|
||||
export function seal(value) {
|
||||
if (typeof value !== 'string' || !value) return value;
|
||||
if (isSealed(value)) return value;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', loadKey(), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||
return `${PREFIX}${iv.toString('base64url')}.${cipher.getAuthTag().toString('base64url')}.${ciphertext.toString('base64url')}`;
|
||||
}
|
||||
|
||||
export function open(value) {
|
||||
if (!isSealed(value)) return value;
|
||||
const [iv, tag, ciphertext] = String(value).slice(PREFIX.length).split('.');
|
||||
const decipher = crypto.createDecipheriv(
|
||||
'aes-256-gcm',
|
||||
loadKey(),
|
||||
Buffer.from(iv, 'base64url'),
|
||||
);
|
||||
decipher.setAuthTag(Buffer.from(tag, 'base64url'));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(ciphertext, 'base64url')),
|
||||
decipher.final(),
|
||||
]).toString('utf8');
|
||||
}
|
||||
@@ -83,6 +83,11 @@ export async function writeOriginal(id, ext, data) {
|
||||
return target;
|
||||
}
|
||||
|
||||
/** Final path for a streamed upload; the caller writes it without buffering. */
|
||||
export function originalTarget(id, ext = 'bin') {
|
||||
return originalPath(id, ext);
|
||||
}
|
||||
|
||||
export function findOriginal(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
|
||||
Reference in New Issue
Block a user