Extract @ipp/core npm workspace package

This commit is contained in:
Alan Grainger
2026-10-05 15:55:18 +13:00
parent 54c0f91c4e
commit d03a77f691
65 changed files with 1056 additions and 746 deletions
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@ipp/core",
"version": "3.4.1",
"private": true,
"description": "Read-side code shared by Immich Public Proxy and its upload service.",
"license": "AGPL-3.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -b",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"devDependencies": {
"@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21",
"@types/node": "^22",
"express": "^4.21.1",
"typescript": "^5.6.2",
"vitest": "^4"
}
}
+28
View File
@@ -0,0 +1,28 @@
import { getCurrentConfig } from './loader'
/**
* Read a configuration option using dotted notation. Returns `defaultOption`
* when the path doesn't resolve to a value.
*
* @example
* getConfigOption('ipp.gallery.singleImage', false)
*/
export function getConfigOption (path: string, defaultOption?: unknown) {
const value = path.split('.').reduce(
(obj: { [key: string]: unknown }, key) => (obj || {})[key] as { [key: string]: unknown },
getCurrentConfig() as { [key: string]: unknown }
)
if (value === undefined) {
return defaultOption
}
return value
}
/**
* Read a configuration option that must be a finite number. Non-numeric
* values fall back to `defaultOption` instead of propagating `NaN`.
*/
export function getNumericConfigOption (path: string, defaultOption: number): number {
const value = Number(getConfigOption(path, defaultOption))
return Number.isFinite(value) ? value : defaultOption
}
+62
View File
@@ -0,0 +1,62 @@
import { readFileSync } from 'fs'
import { resolve } from 'path'
export type Config = Record<string, unknown>
/** Where each app keeps its config file, and how it upgrades legacy config shapes. */
export interface LoadConfigOptions {
/** Absolute path of the bundled config file, used when `IPP_CONFIG` is unset. */
defaultPath?: string
/** Rewrites legacy keys in place before the config is cached. */
migrate?: (config: Config) => void
}
// Module-level cache populated by `loadConfig()`. Access through
// `getCurrentConfig()` rather than importing directly; that gives
// `config/access.ts` a stable read path even before `loadConfig()` has
// been called (returning an empty object so calls fall back to defaults).
let currentConfig: Config = {}
/**
* Read the runtime configuration from `process.env.CONFIG` (an inline JSON
* string, typically set in docker-compose) or from the config file. Applies
* the app's `migrate` hook, caches the result, and returns it.
*
* The default path comes from the app, not from this module's location:
* core is compiled into its own package, so a path relative to `__dirname`
* would point inside `@ipp/core` instead of at the app's bundled file.
*
* Called once from each app's `index.ts` at startup. Safe to call again in
* tests with a fresh env to reset state.
*/
export function loadConfig ({ defaultPath, migrate }: LoadConfigOptions = {}): Config {
let config: Config = {}
try {
if (process.env.CONFIG) {
// Attempt to parse docker-compose config string into JSON (if specified)
config = JSON.parse(process.env.CONFIG)
} else {
// IPP_CONFIG (if set) is taken as-is for absolute paths, or resolved
// against the current working directory for relative paths.
const configPath = process.env.IPP_CONFIG ? resolve(process.env.IPP_CONFIG) : defaultPath
if (configPath) {
const configJson = JSON.parse(readFileSync(configPath, 'utf8'))
if (typeof configJson === 'object') config = configJson
}
}
} catch (e) {
console.log(e)
}
migrate?.(config)
currentConfig = config
return config
}
/**
* Return the most recently loaded config, or an empty object if
* `loadConfig()` hasn't been called yet. Used by `getConfigOption`.
*/
export function getCurrentConfig (): Config {
return currentConfig
}
+44
View File
@@ -0,0 +1,44 @@
import crypto from 'crypto'
interface EncryptedPayload {
iv: string; // Initialization Vector (IV)
cr: string; // Encrypted data
}
// Generate a random 256-bit key on startup
const key = crypto.randomBytes(32)
const algorithm = 'aes-256-cbc'
/**
* Encrypt text data for storing in the session cookie
*/
export function encrypt (text: string): EncryptedPayload {
try {
const ivBuf = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), ivBuf)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return {
iv: ivBuf.toString('hex'),
cr: encrypted
}
} catch (e) { }
return {
cr: '',
iv: ''
}
}
/**
* Decrypt data which was stored in the session cookie
*/
export function decrypt (payload: EncryptedPayload): string {
try {
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), Buffer.from(payload.iv, 'hex'))
let decrypted = decipher.update(payload.cr, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
} catch (e) { }
return ''
}
+47
View File
@@ -0,0 +1,47 @@
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access'
import { respondToInvalidRequest } from './invalidRequest'
import { log } from './utils/log'
/**
* Apply the response headers configured under `ipp.responseHeaders` to the
* given Response. Used by route handlers to attach the default Cache-Control
* and CORS values from `config.json`.
*/
export function addResponseHeaders (res: Response): void {
Object.entries(getConfigOption('ipp.responseHeaders', {}) as { [key: string]: string })
.forEach(([header, value]) => {
res.set(header, value)
})
}
/** Stop browsers and shared caches storing a response from a password-protected share. */
export function addNoStoreHeaders (res: Response): void {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
res.set('Pragma', 'no-cache')
res.set('Expires', '0')
}
/**
* Wrap an async route handler so a rejected promise is passed to Express's
* error chain (and on to `errorHandler`).
*/
export function asyncHandler (fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>) {
return (req: Request, res: Response, next: NextFunction): void => {
fn(req, res, next).catch(next)
}
}
/**
* Terminal Express error middleware. Logs the error server-side, then applies the
* same privacy policy as any other invalid request.
*/
export function errorHandler (err: unknown, req: Request, res: Response, _next: NextFunction): void {
log.error('Error handling ' + req.method + ' ' + req.path + ' - ' +
(err instanceof Error ? (err.stack || err.message) : String(err)))
if (res.headersSent) {
res.end()
return
}
respondToInvalidRequest(res, 404, 'Unhandled error for ' + req.path)
}
+125
View File
@@ -0,0 +1,125 @@
import dayjs from 'dayjs'
import { ImmichVersion, KeyType } from '../types'
import { log } from '../utils/log'
/**
* Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app.
*/
export async function request (endpoint: string, init?: RequestInit) {
try {
const res = await fetch(apiUrl() + endpoint, init)
if (res.status === 200) {
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
return res.json()
} else {
return res
}
} else {
log('Immich API status ' + res.status)
console.log(await res.text())
}
} catch (e) {
log('Unable to reach Immich on ' + process.env.IMMICH_URL)
log(`From the container IPP is running in, run this and check you receive a JSON result: node -e "fetch('${apiUrl()}/server/ping').then(r => r.text()).then(console.log).catch(console.error)"`)
log('Avoid testing with curl - curl uses its own DNS resolver and can succeed even when the resolver Node/IPP uses (musl getaddrinfo) fails. See https://github.com/alangrainger/immich-public-proxy/issues/263')
}
}
export function apiUrl () {
return (process.env.IMMICH_URL || '').replace(/\/*$/, '') + '/api'
}
/**
* Build safely-encoded URL string.
*/
export function buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
// Remove empty properties
params = Object.fromEntries(Object.entries(params).filter(([_, value]) => !!value))
let query = ''
// Safely encode query parameters
if (Object.entries(params).length) {
query = '?' + (new URLSearchParams(params as {
[key: string]: string
})).toString()
}
return baseUrl + query
}
/**
* Check if a provided ID matches the Immich ID format
*/
export function isId (id: string) {
return !!id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
}
/**
* Check if a provided key matches the Immich shared-link key format.
* It appears that the key is always 67 chars long, but since I don't know that this
* will always be the case, I've left it open-ended.
*/
export function isKey (key: string) {
return !!key.match(/^[\w-]+$/)
}
/**
* Map the URL path prefix (`share` or `s`) to the corresponding `KeyType`.
*/
export function getKeyTypeFromShare (shareType: string) {
return shareType === 's' ? KeyType.slug : KeyType.key
}
/**
* Reachability ping for the `/share/healthcheck` route.
*/
export async function accessible () {
return !!(await request('/server/ping'))
}
// Minimum Immich server version IPP is compatible with
export const MIN_IMMICH_VERSION: ImmichVersion = { major: 2, minor: 0, patch: 0 }
const formatVersion = (v: ImmichVersion) => `${v.major}.${v.minor}.${v.patch}`
/**
* Fetch the Immich server version from the public `/server/version` endpoint
* (no auth required). Returns null if Immich is unreachable or the response
* isn't the expected `{ major, minor, patch }` shape.
*/
export async function getImmichVersion (): Promise<ImmichVersion | null> {
const res = await request('/server/version')
if (res && typeof res.major === 'number' && typeof res.minor === 'number' && typeof res.patch === 'number') {
return { major: res.major, minor: res.minor, patch: res.patch }
}
return null
}
/**
* True if `version` is at least MIN_IMMICH_VERSION. A prerelease of the
* minimum version (e.g. 3.0.0-beta) counts as supported.
*/
export function isImmichVersionSupported (version: ImmichVersion): boolean {
if (version.major !== MIN_IMMICH_VERSION.major) return version.major > MIN_IMMICH_VERSION.major
if (version.minor !== MIN_IMMICH_VERSION.minor) return version.minor > MIN_IMMICH_VERSION.minor
return version.patch >= MIN_IMMICH_VERSION.patch
}
/**
* Startup guard. If we can positively confirm the Immich server is older than
* IPP supports, log and exit rather than silently serving broken album shares.
* If the version can't be determined (Immich not yet reachable at boot, or an
* unexpected response), log a warning and continue - a transient blip must not
* crash-loop the container, and per-request handling still copes.
*/
export async function enforceMinimumImmichVersion (): Promise<void> {
const version = await getImmichVersion()
if (!version) {
log('Could not determine the Immich server version. Check that Immich is reachable and running ' + formatVersion(MIN_IMMICH_VERSION) + ' or newer.')
return
}
if (!isImmichVersionSupported(version)) {
console.error(dayjs().format() + ' FATAL: Immich server is version ' + formatVersion(version) + ', but IPP requires Immich ' + formatVersion(MIN_IMMICH_VERSION) + ' or newer.')
process.exit(1)
}
}
+138
View File
@@ -0,0 +1,138 @@
import dayjs from 'dayjs'
import { KeyType, SharedLink, SharedLinkResult } from '../types'
import { log } from '../utils/log'
import { cachedPromise, TtlLruCache } from '../utils/ttlLruCache'
import { apiUrl, buildUrl } from './client'
/*
Immich replaced the deprecated `?password=...` query-param auth for shared
links with `POST /shared-links/login`, which returns an
`immich_shared_link_token` cookie used on subsequent calls. This cache holds
one such token per (keyType, key, password) so the gallery's many asset
requests reuse a single login round-trip. Keying by password is load-bearing
for security: a request without the correct password produces a different
cache key (often empty) and falls through to a fresh login that Immich will
reject - IPP never serves cached tokens to unauthenticated visitors.
*/
const tokenCache = new TtlLruCache<Promise<string | null>>({ ttlMs: 120_000, max: 100 })
/**
* Display title for a shared link. Prefers the user-set link description,
* falls back to the album name (for album shares), or a generic placeholder.
*/
export function title (share: SharedLink): string {
return share.description || share?.album?.albumName || 'Gallery'
}
/**
* Fetch and interpret `GET /shared-links/me` for a key. Uncached: each app
* wraps this with its own cache.
*
* On success the link carries `keyType` and `password`, and whatever `assets`
* Immich sent - an empty array for album shares, which the caller enumerates
* if it needs them. An expired link, an invalid key or an unexpected response
* is `{ valid: false }`; a 401 for anything other than a bad key is
* `passwordRequired`.
*/
export async function fetchSharedLink (key: string, keyType: KeyType = KeyType.key, password?: string): Promise<SharedLinkResult> {
const url = buildUrl(apiUrl() + '/shared-links/me', {
[keyType]: key
})
const headers = await authHeaders(keyType, key, password)
const res = await fetch(url, { headers })
if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) {
const jsonBody = await res.json()
if (jsonBody) {
if (res.status === 200) {
const link = jsonBody as SharedLink
link.keyType = keyType
link.password = password
if (link.expiresAt && dayjs(link.expiresAt) < dayjs()) {
// This link has expired
log('Expired link ' + key)
} else {
return {
valid: true,
link
}
}
} else if (res.status === 401) {
// Immich returns 401 for both invalid keys and password-protected shares.
// Check the message to distinguish between the two cases.
if (jsonBody?.message === 'Invalid share key' || jsonBody?.message === 'Invalid share slug') {
// Known invalid key/slug - treat as invalid request
log('Invalid share key ' + key)
} else {
// Default: treat as password required (fail-safe)
return {
valid: true,
passwordRequired: true
}
}
} else {
console.log(JSON.stringify(jsonBody))
}
}
} else {
// Otherwise return failure
log('Immich response ' + res.status + ' for key ' + key)
try {
console.log(res.headers.get('Content-Type'))
console.log((await res.text()).slice(0, 500))
log('Unexpected response from Immich API at ' + apiUrl())
log('Please make sure the IPP container is able to reach this path.')
} catch (e) {
console.log(e)
}
}
return {
valid: false
}
}
/**
* Build the `Cookie` header that authenticates to Immich for a
* password-protected share. Returns `{}` (no Cookie header) when the share
* has no password or login failed; in those cases Immich will respond 401
* for protected resources, which the caller handles as "password required".
*/
export async function authHeaders (keyType: KeyType, key: string, password?: string): Promise<Record<string, string>> {
if (!password) return {}
const token = await getSharedLinkToken(key, password, keyType)
return token ? { Cookie: `immich_shared_link_token=${token}` } : {}
}
/**
* Cached login: fetch an `immich_shared_link_token` for the given password,
* or return null on failure. The cache is per (keyType, key, password) so
* that a request without the correct password can't reuse another visitor's
* authenticated session. See `tokenCache` doc-comment for the security
* argument.
*/
function getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
const cacheKey = `${keyType}:${key}:${password}`
// Default eviction (falsy is invalid) drops a null/empty token, so a failed
// login is never cached.
return cachedPromise(tokenCache, cacheKey, () => sharedLinkLogin(key, password, keyType))
}
/**
* `POST /shared-links/login`. Replaces the deprecated `?password=...` query
* param. Returns the cookie value on success, null on any failure.
*/
async function sharedLinkLogin (key: string, password: string, keyType: KeyType): Promise<string | null> {
const url = buildUrl(apiUrl() + '/shared-links/login', { [keyType]: key })
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password })
})
if (res.status !== 201) return null
const setCookie = res.headers.get('set-cookie') || ''
const match = setCookie.match(/immich_shared_link_token=([^;,]+)/)
return match ? match[1] : null
} catch (e) {
return null
}
}
+21
View File
@@ -0,0 +1,21 @@
/*
@ipp/core: the read-side code shared by IPP and its upload service. Nothing
here writes to Immich; the only POST is the shared-link password login.
*/
export * from './types'
export * from './immich/client'
export * from './immich/share'
export * from './config/loader'
export * from './config/access'
export * from './http'
export * from './invalidRequest'
export * from './session'
export * from './encrypt'
export * from './utils/log'
export * from './utils/webStream'
export * from './utils/sanitize'
export * from './utils/text'
export * from './utils/ttlLruCache'
export * from './view/render'
export * from './view/theme'
export * from './view/password'
+66
View File
@@ -0,0 +1,66 @@
import { Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access'
import { log } from './utils/log'
/** The public contract of a 404 handler, kept stable for operator replacements. */
export type InvalidRequestHandler = (res: Response, defaultResponse: number | string | null, logMessage?: string) => void
/**
* Respond to any request that the app would otherwise serve content for but
* cannot (bad share key, password failure, unknown asset, etc.). Behavior is
* driven by `ipp.customInvalidResponse` config; if unset, falls back to
* `defaultResponse` (typically 404).
*
* Accepted values for the configured response (and `defaultResponse`):
* - `number` - HTTP status code to send with an empty body.
* - `null` - drop the TCP connection without sending anything.
* - `string` starting with `http` - 302 redirect to that URL.
* - anything else - send an empty 404 (the ultimate fallback).
*
* IPP ships the same logic in `app/src/invalidRequestHandler.ts`, which
* operators may replace by a volume mount, and registers it at startup. Keep
* the two in step.
*/
export const defaultInvalidRequestHandler: InvalidRequestHandler = (res, defaultResponse, logMessage = '') => {
let method = getConfigOption('ipp.customInvalidResponse', false)
if (method === false) {
// No custom method specified, use the default
method = defaultResponse
}
logMessage = logMessage ? ' - ' + logMessage : ''
if (typeof method === 'number') {
// Respond with an HTTP status code
log('Return status ' + method + logMessage)
res.status(method).send()
} else if (method === null) {
// Drop the connection without responding
log('Dropping connection' + logMessage)
res.destroy()
} else if (typeof method === 'string' && method.startsWith('http')) {
// Redirect to another URL
res.redirect(method)
} else {
// Fallback to 404
log('Return status 404' + logMessage)
res.status(404).send()
}
}
let handler: InvalidRequestHandler = defaultInvalidRequestHandler
/**
* Replace the handler that `respondToInvalidRequest` calls. Each app calls
* this once at startup if it ships its own handler file.
*/
export function setInvalidRequestHandler (fn: InvalidRequestHandler): void {
handler = fn
}
/**
* Answer an invalid request through the registered handler. Every caller, in
* core and in the apps, goes through here so a replacement applies everywhere.
*/
export function respondToInvalidRequest (res: Response, defaultResponse: number | string | null, logMessage = ''): void {
handler(res, defaultResponse, logMessage)
}
+96
View File
@@ -0,0 +1,96 @@
import crypto from 'crypto'
import cookieSession from 'cookie-session'
import dayjs from 'dayjs'
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { decrypt, encrypt } from './encrypt'
import { log } from './utils/log'
import { toString } from './utils/text'
// Extend the Request type with a `password` property
declare module 'express-serve-static-core' {
interface Request {
password?: string;
}
}
/** Cookie name and path for one app's session. */
export interface SessionOptions {
/**
* Each app on a host needs its own name: the secret is random per process,
* so a shared name makes each app's failed signature check expire the
* other's cookie, which locks every share the visitor unlocked there.
*/
name: string
/** Defaults to `/`. Left unset, browsers would scope the cookie to the request's directory. */
path?: string
}
/**
* Cookie-session middleware holding the encrypted share passwords. The
* signing secret is random per process, so a restart signs every visitor out.
*/
export function sessionMiddleware ({ name, path = '/' }: SessionOptions) {
return cookieSession({
name,
path,
httpOnly: true,
sameSite: 'lax',
secret: crypto.randomBytes(32).toString('base64url')
})
}
/**
* Middleware to decode the encrypted data stored in the session cookie
*/
export function decodeCookie (req: Request, _res: Response, next: NextFunction) {
const shareKey = req.params.key
const session = req.session?.[shareKey]
if (shareKey && session?.iv && session?.cr) {
try {
const payload = JSON.parse(decrypt({
iv: toString(session.iv),
cr: toString(session.cr)
}))
if (payload?.expires && dayjs(payload.expires) > dayjs()) {
req.password = payload.password
}
} catch (e) { }
}
next()
}
/**
* Store a share password in the session cookie as an encrypted payload which
* expires in 1 hour. After that time, the visitor will need to provide the
* password again.
*
* The data is encrypted/decrypted on the server as a db-less way of
* managing user session data. The data is provided to the server by the
* user's browser in its encrypted state.
*/
export function storeUnlock (req: Request, key: string, password: string) {
if (!req.session) return
req.session[key] = encrypt(JSON.stringify({
password,
expires: dayjs().add(1, 'hour').format()
}))
}
/**
* Receive an unlock request from the password page (`POST <basePath>/share/unlock`).
*/
export function unlockHandler (req: Request, res: Response) {
if (req.body.key) storeUnlock(req, req.body.key, req.body.password)
res.send()
}
/**
* The visitor sent a password and Immich rejected it. Answer 401 and delete
* the session entry, so the page doesn't keep saying "Invalid password". The
* caller still renders the password page.
*/
export function invalidPasswordResponse (req: Request, res: Response, key: string) {
log('Invalid password for key ' + key)
res.status(401)
if (req.session) delete req.session[key]
}
+105
View File
@@ -0,0 +1,105 @@
export enum AssetType {
image = 'IMAGE',
video = 'VIDEO'
}
export enum KeyType {
key = 'key',
slug = 'slug'
}
export interface ExifInfo {
description?: string;
exifImageWidth?: number;
exifImageHeight?: number;
// EXIF orientation string ("1".."8") or null. Values 5-8 indicate the image
// is rotated 90°/270°, so the displayed aspect ratio swaps width/height.
orientation?: string | null;
// Additional EXIF fields surfaced by Immich for the metadata sidebar
// (gated server-side by ipp.showMetadata.exif.* and .location.* config).
dateTimeOriginal?: string | null;
timeZone?: string | null;
fileSizeInByte?: number | null;
make?: string | null;
model?: string | null;
lensModel?: string | null;
exposureTime?: string | null;
iso?: number | null;
fNumber?: number | null;
focalLength?: number | null;
city?: string | null;
state?: string | null;
country?: string | null;
latitude?: number | null;
longitude?: number | null;
}
export enum AlbumType {
album = 'ALBUM',
individual = 'INDIVIDUAL'
}
export interface Asset {
id: string;
key: string;
keyType: KeyType;
originalFileName?: string;
originalMimeType?: string;
password?: string;
fileCreatedAt?: string; // May not exist - see https://github.com/alangrainger/immich-public-proxy/issues/61
// Timezone-agnostic "taken" timestamp (photographer's local wall-clock).
// Immich groups its own timeline by this field. For individual shares it
// comes straight from the asset DTO; for album grid items it is synthesised
// from fileCreatedAt + localOffsetHours (see timelineBucketToAssets).
localDateTime?: string;
type: AssetType;
isTrashed: boolean;
exifInfo?: ExifInfo;
width?: number;
height?: number;
// Base64-encoded thumbhash for tasteful blur placeholders during lazy-load
thumbhash?: string;
// Motion photo (Live Photo) clip: a hidden asset authorised by the same key
livePhotoVideoId?: string;
// True for album assets enumerated via the timeline API, which give us only
// grid fields (id, type, ratio, thumbhash, isTrashed, fileCreatedAt). Their
// exif / originalFileName / description are fetched lazily when the asset is
// opened in the lightbox (see the `/meta/` route + client/metadata.ts).
needsDetail?: boolean;
}
/**
* Immich server version as returned by `GET /server/version`.
*/
export interface ImmichVersion {
major: number;
minor: number;
patch: number;
}
export interface SharedLink {
key: string;
keyType: KeyType;
type: string;
description?: string;
assets: Asset[];
allowDownload?: boolean;
showMetadata?: boolean;
password?: string;
album?: {
id: string;
albumName?: string;
order?: string;
description?: string;
albumThumbnailAssetId?: string;
assetCount?: number;
}
expiresAt: string | null;
}
export interface SharedLinkResult {
valid: boolean;
key?: string;
passwordRequired?: boolean;
link?: SharedLink;
}
+24
View File
@@ -0,0 +1,24 @@
import dayjs from 'dayjs'
/**
* Output a timestamped log message. Calling `log(...)` is equivalent to
* `log.info(...)` and stays available for existing call sites.
*
* log.info('...') informational, goes to stdout
* log.warn('...') non-fatal anomaly, goes to stderr with WARN prefix
* log.error('...') failure / unexpected error, goes to stderr with ERROR prefix
*/
const timestamp = () => dayjs().format()
type LogFn = ((message: string) => void) & {
info: (message: string) => void
warn: (message: string) => void
error: (message: string) => void
}
const logImpl: LogFn = ((message: string) => console.log(timestamp() + ' ' + message)) as LogFn
logImpl.info = (message: string) => console.log(timestamp() + ' ' + message)
logImpl.warn = (message: string) => console.warn(timestamp() + ' WARN ' + message)
logImpl.error = (message: string) => console.error(timestamp() + ' ERROR ' + message)
export const log = logImpl
+41
View File
@@ -0,0 +1,41 @@
/**
* Adapted from https://www.npmjs.com/package/sanitize-filename
*
* Replaces characters in strings that are illegal/unsafe for filenames.
* Unsafe characters are either removed or replaced by a substitute set
* in the optional second argument.
*
* Illegal Characters on Various Operating Systems
* / ? < > \ : * | "
* https://kb.acronis.com/content/39790
*
* Unicode Control codes
* C0 0x00-0x1f & C1 (0x80-0x9f)
* http://en.wikipedia.org/wiki/C0_and_C1_control_codes
*
* Reserved filenames on Unix-based systems (".", "..").
* Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1"-"COM9",
* "LPT1"-"LPT9") case-insensitively and with or without filename extensions.
*
* Capped at 254 characters in length.
*/
const illegalRe = /[/?<>\\:*|"]/g
// eslint-disable-next-line no-control-regex
const controlRe = /[\x00-\x1f\x80-\x9f]/g
const reservedRe = /^\.+$/
const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i
const windowsTrailingRe = /[. ]+$/
export function sanitize (input: string, replacement = ''): string {
if (typeof input !== 'string') {
throw new Error('Input must be string')
}
return input
.replace(illegalRe, replacement)
.replace(controlRe, replacement)
.replace(reservedRe, replacement)
.replace(windowsReservedRe, replacement)
.replace(windowsTrailingRe, replacement)
.slice(0, 254)
}
+35
View File
@@ -0,0 +1,35 @@
/**
* Escape the five HTML-significant characters so that user-controlled text
* can be embedded in HTML without injecting markup. Ampersand is escaped
* first so the other replacements aren't double-escaped.
*/
export function escapeHtml (str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}
/**
* Serialise a value as JSON that is safe to embed inside an inline `<script>`
* block. `JSON.stringify` does not escape `<`, so a string value containing
* `</script>` would terminate the script element early and inject markup into
* the page.
*/
export function jsonForInlineScript (value: unknown): string {
return JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/**
* Narrow an `unknown` to `string`, returning an empty string for any other
* type. Used at boundaries where the input shape isn't statically known
* (cookie session payloads, etc.).
*/
export function toString (value: unknown): string {
return typeof value === 'string' ? value : ''
}
+97
View File
@@ -0,0 +1,97 @@
/*
Time-to-live + size-bounded LRU cache. Used by the Immich share client to memoise
share-link lookups and `POST /shared-links/login` tokens, where:
- TTL gives us freshness without rebuilding share state on every asset
request.
- LRU + size cap keeps memory bounded under a wide key space (one entry
per `(keyType, key, password)` combination).
- Move-to-end on `get` makes "recently accessed" stay alive across
bursts and lets long-tail keys age out.
The cache is intentionally storage-only. Callers handle the "should this
value stay cached?" decision after the underlying fetch resolves (e.g.
delete on null result, delete on rejection). Keeping that policy at the
call site means we don't bake validation rules into a generic cache.
*/
interface Entry<V> {
value: V
expiresAt: number
}
export class TtlLruCache<V> {
private readonly entries = new Map<string, Entry<V>>()
private readonly ttlMs: number
private readonly max: number
constructor (opts: { ttlMs: number, max: number }) {
this.ttlMs = opts.ttlMs
this.max = opts.max
}
/**
* Get the value for `key`, refreshing its LRU position. Returns
* `undefined` if the entry is missing or expired (expired entries are
* dropped on access).
*/
get (key: string): V | undefined {
const entry = this.entries.get(key)
if (!entry) return undefined
if (entry.expiresAt <= Date.now()) {
this.entries.delete(key)
return undefined
}
// Move-to-end so LRU eviction drops the least recently accessed.
this.entries.delete(key)
this.entries.set(key, entry)
return entry.value
}
/**
* Insert or replace `key` with `value` and a fresh TTL. Evicts the
* oldest entry when the cache exceeds its size cap (unless the oldest
* is the entry we just wrote, which shouldn't happen but is guarded
* just in case).
*/
set (key: string, value: V): void {
this.entries.set(key, { value, expiresAt: Date.now() + this.ttlMs })
if (this.entries.size > this.max) {
const oldest = this.entries.keys().next().value
if (oldest !== undefined && oldest !== key) this.entries.delete(oldest)
}
}
delete (key: string): void {
this.entries.delete(key)
}
}
/**
* Memoise an in-flight Promise in `cache`, coalescing concurrent callers onto
* a single upstream call. The entry is evicted as soon as it resolves to an
* invalid value (per `isValid`, default "falsy is invalid") or rejects, so a
* transient Immich blip never poisons the cache with a negative result.
*
* This is the shared form of the "should this stay cached?" policy that
* TtlLruCache deliberately leaves to its callers (see its doc-comment): the
* cache stays storage-only; the eviction rule lives here, once, instead of
* being hand-copied at each call site.
*/
export function cachedPromise<T> (
cache: TtlLruCache<Promise<T>>,
key: string,
factory: () => Promise<T>,
isValid: (value: T) => boolean = (value) => !!value
): Promise<T> {
const cached = cache.get(key)
if (cached) return cached
const promise = factory()
cache.set(key, promise)
promise.then(
(value) => { if (!isValid(value)) cache.delete(key) },
() => { cache.delete(key) }
)
return promise
}
+14
View File
@@ -0,0 +1,14 @@
import { Readable } from 'stream'
/**
* Wrap a fetch `Response.body` as a Node Readable, for use with `pipeline`.
*
* `response.body` is the global/undici ReadableStream<Uint8Array>;
* Readable.fromWeb expects node:stream/web's ReadableStream<any>. The two
* are structurally compatible at runtime but TS sees them as distinct
* nominal types, so a cast is needed.
*/
export function readableFromWeb (body: ReadableStream<Uint8Array>): Readable {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Readable.fromWeb(body as any)
}
+76
View File
@@ -0,0 +1,76 @@
import { jsonForInlineScript } from '../utils/text'
interface PasswordProps {
shareKey: string
notifyInvalidPassword: boolean
/** Path prefix the app is mounted under, without a trailing slash. Empty at the root. */
basePath?: string
}
const submitScript = (unlockUrl: string) => `
async function submitForm (formElement) {
const formData = new FormData(formElement)
try {
const res = await fetch(${jsonForInlineScript(unlockUrl)}, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData.entries()))
})
if (res.status === 200) {
window.location.reload()
}
} catch (e) { }
}
document.getElementById('unlock')
.addEventListener('submit', function (e) {
e.preventDefault()
submitForm(this)
})
`
export function Password ({ shareKey, notifyInvalidPassword, basePath = '' }: PasswordProps) {
return (
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<title>Password required</title>
<link rel="icon" href={basePath + '/share/static/favicon.ico'} type="image/x-icon"/>
<link type="text/css" rel="stylesheet" href={basePath + '/share/static/pico.min.css'}/>
</head>
<body>
<header></header>
<main class="container">
<div class="grid">
<div></div>
<div>
<form id="unlock" method="post">
<input
type="password"
name="password"
placeholder="Password"
aria-label="Password"
required
autoFocus
/>
{notifyInvalidPassword && <small>Invalid password</small>}
<input type="hidden" name="key" value={shareKey}/>
<button type="submit">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="lucide lucide-lock-open">
<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 9.9-1"/>
</svg>
Unlock
</button>
</form>
</div>
<div></div>
</div>
</main>
<script dangerouslySetInnerHTML={{ __html: submitScript(basePath + '/share/unlock') }}/>
</body>
</html>
)
}
+10
View File
@@ -0,0 +1,10 @@
import { renderToString } from 'preact-render-to-string'
import { VNode } from 'preact'
/**
* Render a JSX component to a complete HTML response string.
* Prepends the doctype so the result is a valid HTML5 document.
*/
export function renderPage (component: VNode): string {
return '<!DOCTYPE html>' + renderToString(component)
}
+25
View File
@@ -0,0 +1,25 @@
// Mirrors Immich's FOUC-prevention pattern: read color-theme from localStorage
// (or fall back to OS preference), then add/remove .dark on <html> before paint.
// Source: immich-app/immich v2.7.5 web/src/app.html (2026-05-23).
const themeScript = `
const key = 'color-theme';
let theme = localStorage.getItem(key);
if (!theme) {
theme = { value: 'light', system: true };
} else if (theme === 'dark' || theme === 'light') {
theme = { value: theme, system: false };
localStorage.setItem(key, JSON.stringify(theme));
} else {
theme = JSON.parse(theme);
}
let v = theme.value;
if (theme.system) {
v = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
if (v === 'dark') document.documentElement.classList.add('dark');
else document.documentElement.classList.remove('dark');
`
export function ThemeScript () {
return <script dangerouslySetInnerHTML={{ __html: themeScript }}/>
}
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import express from 'express'
import type { Server } from 'http'
import type { AddressInfo } from 'net'
import { asyncHandler, errorHandler } from '../src/http'
/*
Regression tests for the per-request crash class: under Express 4 a rejected
promise in an async route became an unhandledRejection, and index.ts used to
respond to that with process.exit(1) - one bad request took down the whole
container. asyncHandler + errorHandler must instead turn any thrown/rejected
route error into a plain 404 (the privacy policy: no upstream detail) while
the server keeps serving.
*/
describe('asyncHandler + errorHandler', () => {
let server: Server
let base: string
beforeAll(async () => {
// Silence errorHandler's expected server-side logging during these tests
vi.spyOn(console, 'error').mockImplementation(() => {})
const app = express()
app.get('/ok', asyncHandler(async (_req, res) => { res.send('ok') }))
app.get('/boom', asyncHandler(async () => {
throw new TypeError("Cannot read properties of undefined (reading 'headers')")
}))
app.get('/mid-stream', asyncHandler(async (_req, res) => {
res.status(200)
res.write('partial')
throw new Error('upstream died mid-response')
}))
app.use(errorHandler)
await new Promise<void>(resolve => {
server = app.listen(0, resolve)
})
base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
})
afterAll(() => {
server?.close()
vi.restoreAllMocks()
})
it('turns a rejected route promise into a 404 with an empty body', async () => {
const res = await fetch(base + '/boom')
expect(res.status).toBe(404)
expect(await res.text()).toBe('')
})
it('keeps serving other requests after a route has thrown', async () => {
await fetch(base + '/boom')
const res = await fetch(base + '/ok')
expect(res.status).toBe(200)
expect(await res.text()).toBe('ok')
})
it('does not leak error detail to the client', async () => {
const res = await fetch(base + '/boom')
const body = await res.text()
expect(body).not.toContain('TypeError')
expect(body).not.toContain('headers')
})
it('ends the response when the error hits after headers were sent', async () => {
const res = await fetch(base + '/mid-stream')
// Status was already committed before the throw; the handler can only
// end the stream, not rewrite it to a 404.
expect(res.status).toBe(200)
expect(await res.text()).toBe('partial')
// And the server is still alive afterwards
const ok = await fetch(base + '/ok')
expect(ok.status).toBe(200)
})
})
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { getImmichVersion, isImmichVersionSupported, MIN_IMMICH_VERSION } from '../src/immich/client'
// The startup guard that refuses to run against an Immich server older than
// IPP supports. The floor is 2.0.0 - the columnar timeline API IPP relies on
// to enumerate album shares landed in Immich 2.0.
function jsonResponse (body: unknown, status = 200) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (h: string) => (h.toLowerCase() === 'content-type' ? 'application/json' : null) },
json: async () => body,
text: async () => JSON.stringify(body)
}
}
describe('isImmichVersionSupported', () => {
it('accepts exactly the minimum version', () => {
expect(isImmichVersionSupported(MIN_IMMICH_VERSION)).toBe(true)
})
it('accepts newer major/minor/patch across the 2.x and 3.x lines', () => {
expect(isImmichVersionSupported({ major: 2, minor: 7, patch: 5 })).toBe(true)
expect(isImmichVersionSupported({ major: 3, minor: 0, patch: 2 })).toBe(true)
expect(isImmichVersionSupported({ major: 4, minor: 0, patch: 0 })).toBe(true)
})
it('rejects 1.x, which predates the columnar timeline API', () => {
expect(isImmichVersionSupported({ major: 1, minor: 137, patch: 3 })).toBe(false)
expect(isImmichVersionSupported({ major: 1, minor: 125, patch: 7 })).toBe(false)
})
})
describe('getImmichVersion', () => {
beforeEach(() => {
process.env.IMMICH_URL = 'http://immich.test'
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('parses the /server/version response', async () => {
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
if (url.includes('/server/version')) return jsonResponse({ major: 3, minor: 0, patch: 2, prerelease: null })
throw new Error('Unexpected fetch to ' + url)
}))
expect(await getImmichVersion()).toEqual({ major: 3, minor: 0, patch: 2 })
})
it('returns null when Immich is unreachable', async () => {
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED') }))
expect(await getImmichVersion()).toBeNull()
})
it('returns null on an unexpected response shape', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ version: 'v3.0.2' })))
expect(await getImmichVersion()).toBeNull()
})
})
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect, afterEach } from 'vitest'
import { loadConfig } from '../src/config/loader'
import { getNumericConfigOption } from '../src/config/access'
/*
Regression tests for the non-numeric config bug: a non-numeric
`ipp.downloadFromImmichConcurrencyLimit` used to reach its consumer as NaN,
where `active >= NaN` is always false - so the download concurrency limit
never throttled and every asset in a zip download hit Immich at once.
*/
function loadConfigFrom (config: Record<string, unknown>) {
process.env.CONFIG = JSON.stringify(config)
loadConfig()
}
afterEach(() => {
delete process.env.CONFIG
loadConfig()
})
describe('getNumericConfigOption', () => {
it('returns a configured number', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 5 } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
})
it('coerces a numeric string (docker-compose env values arrive as strings)', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: '5' } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
})
it('falls back to the default for a non-numeric value instead of NaN', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
it('falls back to the default for non-scalar values', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: { max: 5 } } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
it('falls back to the default when the option is unset', () => {
loadConfigFrom({})
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
})
+53
View File
@@ -0,0 +1,53 @@
import { describe, it, expect } from 'vitest'
import { escapeHtml, jsonForInlineScript } from '../src/utils/text'
describe('escapeHtml', () => {
it('escapes the five HTML-significant characters', () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
'&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
)
})
it('escapes ampersand first so other escapes are not re-escaped', () => {
expect(escapeHtml('&amp;')).toBe('&amp;amp;')
})
it('escapes single quotes', () => {
expect(escapeHtml("it's")).toBe('it&#039;s')
})
it('returns empty string unchanged', () => {
expect(escapeHtml('')).toBe('')
})
it('passes through strings with no special characters', () => {
expect(escapeHtml('plain text 123')).toBe('plain text 123')
})
})
describe('jsonForInlineScript', () => {
it('escapes < so </script> cannot terminate an inline script block', () => {
const out = jsonForInlineScript({ name: '</script><script>alert(1)</script>' })
expect(out).not.toContain('<')
expect(out).toContain('\\u003c/script>')
})
it('round-trips through JSON.parse unchanged', () => {
const value = {
name: '</script> & <!-- tricky --> \u2028\u2029',
n: 3,
nested: { arr: [1, 'two'] }
}
expect(JSON.parse(jsonForInlineScript(value))).toEqual(value)
})
it('escapes the JS line separators U+2028 and U+2029', () => {
const out = jsonForInlineScript({ s: '\u2028\u2029' })
expect(out).toBe('{"s":"\\u2028\\u2029"}')
})
it('matches JSON.stringify for benign values', () => {
const value = { a: 1, b: 'plain text', c: null }
expect(jsonForInlineScript(value)).toBe(JSON.stringify(value))
})
})
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { TtlLruCache } from '../src/utils/ttlLruCache'
/*
All TTL-based assertions rely on Vitest's fake-timer system mocking
`Date.now()`. `vi.advanceTimersByTime` advances both the timer queue
and the system clock the cache reads from.
*/
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
describe('TtlLruCache', () => {
it('returns undefined for an unknown key', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
expect(cache.get('missing')).toBeUndefined()
})
it('returns the value after set', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
cache.set('a', 'apple')
expect(cache.get('a')).toBe('apple')
})
it('returns undefined exactly at the TTL boundary', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
cache.set('a', 'apple')
vi.advanceTimersByTime(999)
expect(cache.get('a')).toBe('apple')
vi.advanceTimersByTime(1)
expect(cache.get('a')).toBeUndefined()
})
it('drops expired entries on access so they do not count toward the size cap', () => {
const cache = new TtlLruCache<string>({ ttlMs: 100, max: 2 })
cache.set('a', '1')
vi.advanceTimersByTime(200)
// Read once so the expired entry is dropped from the internal map.
expect(cache.get('a')).toBeUndefined()
// The cache should now have capacity for two fresh entries with no
// collateral eviction of either.
cache.set('b', '2')
cache.set('c', '3')
expect(cache.get('b')).toBe('2')
expect(cache.get('c')).toBe('3')
})
})
describe('TtlLruCache delete', () => {
it('removes an existing entry', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
cache.set('a', '1')
cache.delete('a')
expect(cache.get('a')).toBeUndefined()
})
it('is a no-op for a missing key', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
expect(() => cache.delete('missing')).not.toThrow()
})
})
describe('TtlLruCache LRU eviction', () => {
it('evicts the oldest entry when set causes overflow', () => {
const cache = new TtlLruCache<string>({ ttlMs: 10_000, max: 2 })
cache.set('a', '1')
cache.set('b', '2')
cache.set('c', '3') // overflow - 'a' is the oldest, gets evicted
expect(cache.get('a')).toBeUndefined()
expect(cache.get('b')).toBe('2')
expect(cache.get('c')).toBe('3')
})
it('get refreshes LRU position so a recently-read entry survives eviction', () => {
const cache = new TtlLruCache<string>({ ttlMs: 10_000, max: 2 })
cache.set('a', '1')
cache.set('b', '2')
// Touch 'a' so it becomes the most-recently-used. 'b' is now oldest.
cache.get('a')
cache.set('c', '3') // overflow - 'b' should be evicted, not 'a'
expect(cache.get('a')).toBe('1')
expect(cache.get('b')).toBeUndefined()
expect(cache.get('c')).toBe('3')
})
})
describe('TtlLruCache re-set', () => {
it('replaces the value when set is called twice for the same key', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
cache.set('a', '1')
cache.set('a', '2')
expect(cache.get('a')).toBe('2')
})
it('resets the TTL on re-set', () => {
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
cache.set('a', '1')
vi.advanceTimersByTime(800)
cache.set('a', '2') // bumps expiry to 1000ms from now
vi.advanceTimersByTime(800)
// 800 + 800 = 1600ms past the original set, but only 800ms past the
// re-set, so the entry should still be live.
expect(cache.get('a')).toBe('2')
})
})
+33
View File
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"composite": true,
"declaration": true,
"rootDir": "src",
"outDir": "dist",
"tsBuildInfoFile": "dist/tsconfig.tsbuildinfo",
"inlineSourceMap": true,
"inlineSources": true,
"module": "CommonJS",
"target": "ES6",
"noImplicitAny": true,
"esModuleInterop": true,
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"strictNullChecks": true,
"lib": [
"DOM",
"ES5",
"ES6",
"ES7"
],
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"jsxImportSource": "preact"
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node'
}
})