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
-35
View File
@@ -1,35 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"env": { "node": true },
"plugins": [
"@typescript-eslint"
],
"extends": [
"standard",
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-new": 0,
"no-unused-vars": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
},
"overrides": [
{
"files": ["public/web.js"],
"env": { "browser": true, "node": false },
"rules": {
"import/no-absolute-path": "off"
}
}
]
}
-7553
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -2,9 +2,10 @@
"name": "immich-public-proxy",
"version": "3.4.1",
"scripts": {
"dev": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
"build": "tsc && tsc -p tsconfig.client.json",
"build:server": "tsc",
"predev": "tsc -b ../shared",
"dev": "concurrently -n core,server,client -c magenta,blue,green \"tsc -b -w --preserveWatchOutput ../shared\" \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
"build": "tsc -b && tsc -p tsconfig.client.json",
"build:server": "tsc -b",
"build:client": "tsc -p tsconfig.client.json",
"test": "vitest run",
"test:watch": "vitest",
@@ -21,13 +22,12 @@
"main": "dist/index.js",
"bin": "dist/index.js",
"dependencies": {
"@ipp/core": "*",
"archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"devDependencies": {
+5 -28
View File
@@ -1,28 +1,5 @@
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
}
/*
Kept for operators who mount a copy of invalidRequestHandler.js taken from
IPP 3.x, which requires './config/access'. Delete in 4.0 with an upgrade note.
*/
export { getConfigOption } from '@ipp/core'
-52
View File
@@ -1,52 +0,0 @@
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { applyMigrations } from './migrations'
export type Config = Record<string, unknown>
// 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
* backward-compatibility migrations, caches the result, and returns it.
*
* Called once from `index.ts` at startup. Safe to call again in tests with
* a fresh env to reset state.
*/
export function loadConfig (): 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 {
// Default config.json sits one level above the compiled dist/ output.
// 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)
: resolve(__dirname, '../../config.json')
const configJson = JSON.parse(readFileSync(configPath, 'utf8'))
if (typeof configJson === 'object') config = configJson
}
} catch (e) {
console.log(e)
}
applyMigrations(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
@@ -1,44 +0,0 @@
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 ''
}
+3 -5
View File
@@ -1,15 +1,13 @@
import { Asset, AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
import {
getVideoContentType,
photoUrl,
videoUrl
} from '../immich'
import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, SharedLink } from '../types'
import { getConfigOption, getNumericConfigOption } from '../config/access'
import { canDownload, expiryDate, title } from '../share'
import { toString } from '../utils/text'
import { ImageSize } from '../types'
import { canDownload, expiryDate } from '../share'
import { h } from 'preact'
import { renderPage } from '../view/render'
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
import type { GroupByDateMode } from '../shared/types'
import { downloadFilename } from './filename'
+1 -2
View File
@@ -1,6 +1,5 @@
import { Asset, ExifInfo } from '../types'
import { Asset, ExifInfo, getConfigOption } from '@ipp/core'
import { GalleryExif } from '../shared/types'
import { getConfigOption } from '../config/access'
type Group = 'exif' | 'location'
+2 -3
View File
@@ -1,6 +1,5 @@
import { Asset, ImageSize } from '../types'
import { getConfigOption } from '../config/access'
import { sanitize } from '../utils/sanitize'
import { Asset, getConfigOption, sanitize } from '@ipp/core'
import { ImageSize } from '../types'
import { resolveImageEndpoint } from './sizing'
/**
+1 -2
View File
@@ -1,6 +1,5 @@
import { Asset, SharedLink } from '../types'
import { Asset, getConfigOption, SharedLink } from '@ipp/core'
import { AssetMetadata } from '../shared/types'
import { getConfigOption } from '../config/access'
import { pickExif } from './exif'
import { downloadFilename } from './filename'
+2 -2
View File
@@ -1,5 +1,5 @@
import { Asset, AssetType, ImageSize } from '../types'
import { getConfigOption } from '../config/access'
import { Asset, AssetType, getConfigOption } from '@ipp/core'
import { ImageSize } from '../types'
/*
Single source of truth for image-size policy: given a requested ImageSize
-47
View File
@@ -1,47 +0,0 @@
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access'
import { respondToInvalidRequest } from './invalidRequestHandler'
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)
}
+66 -330
View File
@@ -2,30 +2,33 @@ import {
AlbumType,
Asset,
AssetType,
ImageSize,
ImmichVersion,
IncomingShareRequest,
KeyType,
SharedLink,
SharedLinkResult,
TimelineBucket,
TimelineBucketAssets
} from './types'
import dayjs from 'dayjs'
import { getConfigOption } from './config/access'
import { addNoStoreHeaders, addResponseHeaders } from './http'
addNoStoreHeaders,
addResponseHeaders,
apiUrl,
authHeaders,
buildUrl,
cachedPromise,
fetchSharedLink,
getConfigOption,
invalidPasswordResponse,
isKey,
log,
Password,
renderPage,
request,
respondToInvalidRequest,
storeUnlock,
TtlLruCache
} from '@ipp/core'
import { ImageSize, IncomingShareRequest, TimelineBucket, TimelineBucketAssets } from './types'
import { canDownload } from './share'
import { log } from './utils/log'
import { assetBuffer } from './stream/asset'
import { downloadAll } from './stream/download'
import { gallery } from './gallery/builder'
import { Response } from 'express-serve-static-core'
import { h } from 'preact'
import { renderPage } from './view/render'
import { Password } from './view/password'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { encrypt } from './encrypt'
import { TtlLruCache } from './utils/ttlLruCache'
/*
In-process cache for share-link lookups. Each direct-asset request (e.g.
@@ -46,18 +49,6 @@ import { TtlLruCache } from './utils/ttlLruCache'
*/
const shareCache = new TtlLruCache<Promise<SharedLinkResult>>({ ttlMs: 120_000, max: 100 })
/*
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 })
/*
Per-asset detail cache for the lazy album flow. When a `needsDetail` album
item opens in the lightbox, the `/meta/` route fetches the full asset from
@@ -68,64 +59,6 @@ const tokenCache = new TtlLruCache<Promise<string | null>>({ ttlMs: 120_000, max
*/
const assetDetailCache = new TtlLruCache<Promise<Asset | undefined>>({ ttlMs: 120_000, max: 500 })
/**
* 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.
*/
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
}
/**
* 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'
}
/**
* Handle an incoming request for a shared link `key`. This is the main function which
* communicates with Immich and returns the output back to the visitor.
@@ -155,10 +88,7 @@ export async function handleShareRequest (req: IncomingShareRequest, res: Respon
// A password is required, but the visitor-provided one doesn't match
if (sharedLinkRes.passwordRequired && req.password) {
log('Invalid password for key ' + req.key)
res.status(401)
// Delete the cookie-session data, so that it doesn't keep saying "Invalid password"
if (req.req?.session) delete req.req.session[req.key]
invalidPasswordResponse(req.req, res, req.key)
}
// Don't cache password-protected albums
@@ -183,10 +113,7 @@ export async function handleShareRequest (req: IncomingShareRequest, res: Respon
// If this was a password-protected slug link, we need to also store session information for the ID-based key
if (req.password && req.req.session && !req.req.session[link.key]) {
req.req.session[link.key] = encrypt(JSON.stringify({
password: req.password,
expires: dayjs().add(1, 'hour').format()
}))
storeUnlock(req.req, link.key, req.password)
}
// Everything is ok - output the shared link data
@@ -242,108 +169,57 @@ export function getShareByKey (key: string, password?: string, keyType: KeyType
* coalescing on cold misses.
*/
async function fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
let link
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) {
// Normal response - get the shared assets
link = jsonBody as SharedLink
link.keyType = keyType
const result = await fetchSharedLink(key, keyType, password)
if (!result.link) return result
const link = result.link
// For an album, `/shared-links/me` returns an empty `assets` array
// (Immich 3.0 dropped album assets from both that response and
// `AlbumResponseDto`). We enumerate the album's assets from the
// timeline API instead - the same approach Immich's own web client
// uses for shared albums. This yields grid-only assets; their full
// detail (exif, filename) is fetched lazily on lightbox open. The
// album cover id we need for og:image is already on `link.album`
// (mapAlbum still returns albumThumbnailAssetId).
if (link.type === AlbumType.album) {
if (!link.album?.id) {
log('Album share missing album id for key ' + key)
return {
valid: false
}
}
const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, headers)
if (albumAssets === null) {
// Enumeration failed upstream. Return invalid (not cached) rather
// than caching an empty album for the next 120s on a transient blip.
return {
valid: false
}
}
link.assets = albumAssets
}
link.password = password
if (link.expiresAt && dayjs(link.expiresAt) < dayjs()) {
// This link has expired
log('Expired link ' + key)
} else {
if (!Array.isArray(link.assets)) {
// Defensive guard: the returned album should always(?) populate this array
log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')')
link.assets = []
}
// Filter assets to exclude trashed assets
link.assets = link.assets.filter(asset => !asset.isTrashed)
// Populate the shared assets with the public key/password
link.assets.forEach(asset => {
asset.key = key
asset.keyType = keyType
asset.password = password
})
// Sort album if there is a sort order specified
const sortOrder = link.album?.order
if (sortOrder === 'asc') {
link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0)
} else if (sortOrder === 'desc') {
link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
}
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))
// For an album, `/shared-links/me` returns an empty `assets` array
// (Immich 3.0 dropped album assets from both that response and
// `AlbumResponseDto`). We enumerate the album's assets from the
// timeline API instead - the same approach Immich's own web client
// uses for shared albums. This yields grid-only assets; their full
// detail (exif, filename) is fetched lazily on lightbox open. The
// album cover id we need for og:image is already on `link.album`
// (mapAlbum still returns albumThumbnailAssetId).
if (link.type === AlbumType.album) {
if (!link.album?.id) {
log('Album share missing album id for key ' + key)
return {
valid: false
}
}
} 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)
const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, await authHeaders(keyType, key, password))
if (albumAssets === null) {
// Enumeration failed upstream. Return invalid (not cached) rather
// than caching an empty album for the next 120s on a transient blip.
return {
valid: false
}
}
link.assets = albumAssets
}
return {
valid: false
if (!Array.isArray(link.assets)) {
// Defensive guard: the returned album should always(?) populate this array
log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')')
link.assets = []
}
// Filter assets to exclude trashed assets
link.assets = link.assets.filter(asset => !asset.isTrashed)
// Populate the shared assets with the public key/password
link.assets.forEach(asset => {
asset.key = key
asset.keyType = keyType
asset.password = password
})
// Sort album if there is a sort order specified
const sortOrder = link.album?.order
if (sortOrder === 'asc') {
link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0)
} else if (sortOrder === 'desc') {
link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
}
return result
}
// Base resolution used to turn an Immich `ratio` (width/height) into concrete
@@ -505,18 +381,6 @@ export async function getVideoContentType (asset: Asset): Promise<string | undef
return data.headers.get('Content-Type') || undefined
}
/**
* 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}` } : {}
}
/**
* `authHeaders` for an asset whose key/keyType/password are already stamped on
* it (the common case for share-scoped fetches).
@@ -537,57 +401,6 @@ export function assetFetchUrl (asset: Asset, subpath: string, sizeQueryParam?: s
})
}
/**
* 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
}
}
/**
* 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
}
/**
* Return the image data URL for a photo
*/
@@ -604,76 +417,6 @@ export function videoUrl (key: string, id: string) {
return buildUrl(`/share/video/${key}/${id}`)
}
/**
* 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-]+$/)
}
/**
* 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)
}
}
/**
* Coerce an unknown `size` parameter from a URL into a valid ImageSize,
* defaulting to preview when the input is missing or unrecognised.
@@ -685,10 +428,3 @@ export function validateImageSize (size: unknown) {
return size as ImageSize
}
}
/**
* Map the URL path prefix (`share` or `s`) to the corresponding `KeyType`.
*/
export function getKeyTypeFromShare (shareType: string) {
return shareType === 's' ? KeyType.slug : KeyType.key
}
+34 -65
View File
@@ -2,54 +2,56 @@
import 'dotenv/config'
import express from 'express'
import cookieSession from 'cookie-session'
import { resolve } from 'path'
import {
accessible,
addNoStoreHeaders,
addResponseHeaders,
Asset,
AssetType,
asyncHandler,
decodeCookie,
enforceMinimumImmichVersion,
fetchAssetDetail,
errorHandler,
getConfigOption,
getKeyTypeFromShare,
getShareByKey,
handleShareRequest,
isId,
isKey
} from './immich'
isKey,
KeyType,
loadConfig,
renderPage,
respondToInvalidRequest,
sessionMiddleware,
setInvalidRequestHandler,
SharedLink,
unlockHandler
} from '@ipp/core'
import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich'
import { buildAssetMetadata } from './gallery/metadata'
import crypto from 'crypto'
import { assetBuffer } from './stream/asset'
import { downloadAssets } from './stream/download'
import dayjs from 'dayjs'
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, KeyType, SharedLink } from './types'
import { getConfigOption } from './config/access'
import { loadConfig } from './config/loader'
import { addNoStoreHeaders, addResponseHeaders, asyncHandler, errorHandler } from './http'
import { Request } from 'express-serve-static-core'
import { ImageSize } from './types'
import { applyMigrations } from './config/migrations'
import { canDownload, findMotionPhotoStill } from './share'
import { toString } from './utils/text'
import { decrypt, encrypt } from './encrypt'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler'
import { ASSET_VERSION } from './version'
import { h } from 'preact'
import { renderPage } from './view/render'
import { Home } from './view/home'
// Extend the Request type with a `password` property
declare module 'express-serve-static-core' {
interface Request {
password?: string;
}
}
// Read config.json (or the inline CONFIG env var) and apply backward-compat
// migrations. Must run before any code that calls getConfigOption.
loadConfig()
// migrations. Must run before any code that calls getConfigOption. The
// bundled config.json sits one level above this file (src/ in dev, dist/ in
// the image), which is /app/config.json in the image.
loadConfig({ defaultPath: resolve(__dirname, '../config.json'), migrate: applyMigrations })
// Route every invalid response, including core's, through IPP's handler file,
// so an operator's mounted replacement applies everywhere.
setInvalidRequestHandler(ippInvalidRequestHandler)
const app = express()
app.use(cookieSession({
name: 'session',
httpOnly: true,
sameSite: 'lax',
secret: crypto.randomBytes(32).toString('base64url')
}))
app.use(sessionMiddleware({ name: 'session' }))
// For parsing the password unlock form and POSTed JSON payloads
app.use(express.json())
// For parsing the selective-download form POST (form-encoded body)
@@ -68,26 +70,6 @@ app.use(express.static('public', { setHeaders: addResponseHeaders }))
// Remove the X-Powered-By ExpressJS header
app.disable('x-powered-by')
/**
* Middleware to decode the encrypted data stored in the session cookie
*/
const 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()
}
/*
* Shared route guards. Several routes need the same "resolve a share, reject
* invalid / password-protected ones, optionally find the requested asset"
@@ -189,21 +171,8 @@ app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, asyncHandler
/*
* [ROUTE] Receive an unlock request from the password page
* Stores a cookie with 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.
*/
app.post('/share/unlock', asyncHandler(async (req, res) => {
if (req.session && req.body.key) {
req.session[req.body.key] = encrypt(JSON.stringify({
password: req.body.password,
expires: dayjs().add(1, 'hour').format()
}))
}
res.send()
}))
app.post('/share/unlock', unlockHandler)
/*
* [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
+5 -2
View File
@@ -2,11 +2,14 @@
This function is in its own file so that *if desired* someone can replace the entire
function with their own custom one, by replacing the invalidRequestHandler.js file
through a Docker volume mount.
index.ts registers it with @ipp/core at startup, so a replacement also applies to
the invalid responses that core sends. Core keeps a copy of this logic as its
default (shared/src/invalidRequest.ts); keep the two in step.
*/
import { Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access'
import { log } from './utils/log'
import { getConfigOption, log } from '@ipp/core'
/**
* Respond to any request that IPP would otherwise serve content for but cannot
+2 -12
View File
@@ -1,17 +1,7 @@
import { Asset, DownloadAll, SharedLink } from './types'
import { getConfigOption } from './config/access'
import { Asset, getConfigOption, SharedLink } from '@ipp/core'
import { DownloadAll } from './types'
import dayjs from 'dayjs'
/**
* 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.
* Used by the gallery view-model and as the zip filename in the download
* pipeline.
*/
export function title (share: SharedLink): string {
return share.description || share?.album?.albumName || 'Gallery'
}
/**
* Decide whether the given shared link's download UI is shown (the "download
* all" zip, multi-select download, and the per-asset lightbox button). The
+2 -4
View File
@@ -1,3 +1,4 @@
import { Asset, log, readableFromWeb, respondToInvalidRequest, SharedLink } from '@ipp/core'
import {
assetFetchUrl,
authHeadersForAsset,
@@ -5,13 +6,10 @@ import {
validateImageSize
} from '../immich'
import { Response } from 'express-serve-static-core'
import { Asset, ImageSize, IncomingShareRequest, SharedLink } from '../types'
import { respondToInvalidRequest } from '../invalidRequestHandler'
import { ImageSize, IncomingShareRequest } from '../types'
import { attachmentDisposition, getFilename, servedMimeFrom } from '../gallery/filename'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
import { pipeline } from 'stream/promises'
import { readableFromWeb } from '../utils/webStream'
import { log } from '../utils/log'
/**
* Stream an asset from Immich back to the client.
+1 -6
View File
@@ -1,14 +1,9 @@
import { Asset, log, readableFromWeb, respondToInvalidRequest, sanitize, SharedLink, title } from '@ipp/core'
import { assetFetchUrl, authHeadersForAsset } from '../immich'
import { Response } from 'express-serve-static-core'
import { Asset, SharedLink } from '../types'
import { log } from '../utils/log'
import archiver, { Archiver } from 'archiver'
import { sanitize } from '../utils/sanitize'
import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing'
import { title } from '../share'
import { attachmentDisposition, getFilename, responseMime, servedMimeFrom } from '../gallery/filename'
import { readableFromWeb } from '../utils/webStream'
import { respondToInvalidRequest } from '../invalidRequestHandler'
/** Attempts to get response headers from Immich for one asset before giving up. */
const MAX_ATTEMPTS = 3
+1 -106
View File
@@ -1,83 +1,5 @@
import { Request } from 'express-serve-static-core'
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;
}
import { KeyType } from '@ipp/core'
/**
* One entry of `GET /timeline/buckets` - a time bucket (month) and its count.
@@ -107,33 +29,6 @@ export interface TimelineBucketAssets {
livePhotoVideoId: (string | null)[];
}
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;
}
export enum ImageSize {
thumbnail = 'thumbnail',
preview = 'preview',
-21
View File
@@ -1,21 +0,0 @@
/**
* Returns a function that runs at most `limit` async tasks concurrently.
* Tasks queue when the limit is reached and resume in FIFO order.
*/
export function createLimiter (limit: number) {
let active = 0
const queue: Array<() => void> = []
return async function run<T> (fn: () => Promise<T>): Promise<T> {
if (active >= limit) {
await new Promise<void>(resolve => queue.push(resolve))
}
active++
try {
return await fn()
} finally {
active--
const next = queue.shift()
if (next) next()
}
}
}
+5 -24
View File
@@ -1,24 +1,5 @@
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
/*
Kept for operators who mount a copy of invalidRequestHandler.js taken from
IPP 3.x, which requires './utils/log'. Delete in 4.0 with an upgrade note.
*/
export { log } from '@ipp/core'
-41
View File
@@ -1,41 +0,0 @@
/**
* 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
@@ -1,35 +0,0 @@
/**
* 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 : ''
}
-68
View File
@@ -1,68 +0,0 @@
/*
Time-to-live + size-bounded LRU cache. Used by `immich.ts` 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)
}
}
-14
View File
@@ -1,14 +0,0 @@
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)
}
+1 -3
View File
@@ -1,8 +1,6 @@
import { AssetType } from '../types'
import { ThemeScript } from './theme'
import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core'
import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
import { ASSET_VERSION } from '../version'
import { jsonForInlineScript } from '../utils/text'
export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
-72
View File
@@ -1,72 +0,0 @@
interface PasswordProps {
shareKey: string
notifyInvalidPassword: boolean
}
const submitScript = `
async function submitForm (formElement) {
const formData = new FormData(formElement)
try {
const res = await fetch('/share/unlock', {
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 }: 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="/share/static/favicon.ico" type="image/x-icon"/>
<link type="text/css" rel="stylesheet" href="/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 }}/>
</body>
</html>
)
}
-10
View File
@@ -1,10 +0,0 @@
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
@@ -1,25 +0,0 @@
// 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 }}/>
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { KeyType } from '@ipp/core'
import { getShareByKey, utcBucketKey } from '../src/immich'
import { KeyType } from '../src/types'
// 3.0-shaped responses: album `/shared-links/me` returns an empty assets[],
// and the album's assets are enumerated from the timeline API. This exercises
+1 -2
View File
@@ -1,7 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { buildAssetMetadata } from '../src/gallery/metadata'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
// buildAssetMetadata is the lazy-flow counterpart to the gallery builder's
// per-item baking; it must apply the same showMetadata kill-switch and
+2 -2
View File
@@ -1,9 +1,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig } from '@ipp/core'
import { Writable } from 'stream'
import type { Request, Response } from 'express-serve-static-core'
import { assetBuffer } from '../src/stream/asset'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../src/types'
import { ImageSize, IncomingShareRequest } from '../src/types'
afterEach(() => {
vi.unstubAllGlobals()
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import { Asset, AssetType, KeyType } from '@ipp/core'
import { dateSortComparator } from '../src/gallery/builder'
import { Asset, AssetType, KeyType } from '../src/types'
/*
The date-grouping sort must follow the album's own order while
+1 -2
View File
@@ -1,10 +1,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { Writable } from 'stream'
import { once } from 'events'
import type { Response } from 'express-serve-static-core'
import { downloadAssets } from '../src/stream/download'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
/*
"Download all" streams each asset from Immich straight into the zip on the
+7 -5
View File
@@ -1,14 +1,16 @@
import { describe, it, expect, vi } from 'vitest'
import { AssetType, ImageSize, KeyType } from '../src/types'
import type { Asset } from '../src/types'
import { AssetType, KeyType } from '@ipp/core'
import type { Asset } from '@ipp/core'
import { ImageSize } from '../src/types'
import { getFilename } from '../src/gallery/filename'
/*
getFilename reads `ipp.downloadedFilename` via getConfigOption; mock the
config-access module so tests exercise the default (original filename) mode
getFilename reads `ipp.downloadedFilename` via getConfigOption; mock it in
@ipp/core so tests exercise the default (original filename) mode
without loading a real config file.
*/
vi.mock('../src/config/access', () => ({
vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (_path: string, fallback?: unknown) => fallback
}))
-77
View File
@@ -1,77 +0,0 @@
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)
})
})
+1 -2
View File
@@ -1,9 +1,8 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { KeyType, loadConfig, SharedLink } from '@ipp/core'
import dayjs from 'dayjs'
import 'dayjs/locale/de' // load German so the localised-format assertions are deterministic
import { expiryDate } from '../src/share'
import { loadConfig } from '../src/config/loader'
import { KeyType, SharedLink } from '../src/types'
// expiryDate formats the share's Immich expiry for the gallery subtitle. It is
// gated behind ipp.gallery.showExpiryDate (default off) and formatted with
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import { renderPage } from '@ipp/core'
import { h } from 'preact'
import { Gallery, GalleryProps, GalleryItem } from '../src/view/gallery'
import { renderPage } from '../src/view/render'
/*
Regression test for the init-JSON XSS: asset strings (originalFileName, EXIF
-60
View File
@@ -1,60 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { getImmichVersion, isImmichVersionSupported, MIN_IMMICH_VERSION } from '../src/immich'
// 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()
})
})
+4 -3
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, KeyType } from '../src/types'
import type { Asset, SharedLink } from '../src/types'
import { AssetType, KeyType } from '@ipp/core'
import type { Asset, SharedLink } from '@ipp/core'
import type { Response } from 'express-serve-static-core'
import { findMotionPhotoStill } from '../src/share'
import { gallery } from '../src/gallery/builder'
@@ -11,7 +11,8 @@ import { gallery } from '../src/gallery/builder'
is on. Config is mocked per test rather than loaded from a file.
*/
const cfg: Record<string, unknown> = {}
vi.mock('../src/config/access', () => ({
vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (path: string, fallback?: unknown) => (path in cfg ? cfg[path] : fallback),
getNumericConfigOption: (path: string, fallback: number) => (path in cfg ? Number(cfg[path]) : fallback)
}))
-75
View File
@@ -1,75 +0,0 @@
import { describe, it, expect, afterEach } from 'vitest'
import { loadConfig } from '../src/config/loader'
import { getNumericConfigOption } from '../src/config/access'
import { createLimiter } from '../src/utils/limiter'
/*
Regression tests for the non-numeric concurrency bug: a non-numeric
`ipp.downloadFromImmichConcurrencyLimit` used to reach createLimiter as NaN,
where `active >= NaN` is always false - so the limiter 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)
})
})
describe('createLimiter with guarded config', () => {
/** Run `total` tasks through the limiter and report the concurrency peak */
async function peakConcurrency (limit: number, total: number): Promise<number> {
const run = createLimiter(limit)
let active = 0
let peak = 0
await Promise.all(Array.from({ length: total }, () => run(async () => {
active++
peak = Math.max(peak, active)
// Yield so other queued tasks get a chance to start while this one is "active"
await new Promise(resolve => setTimeout(resolve, 1))
active--
})))
return peak
}
it('a NaN limit disables throttling (the failure mode being guarded against)', async () => {
expect(await peakConcurrency(NaN, 10)).toBe(10)
})
it('the guarded value throttles as configured', async () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
const limit = Math.max(1, getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 3))
expect(await peakConcurrency(limit, 10)).toBe(3)
})
})
+7 -5
View File
@@ -1,16 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, ImageSize } from '../src/types'
import type { Asset } from '../src/types'
import { AssetType } from '@ipp/core'
import type { Asset } from '@ipp/core'
import { ImageSize } from '../src/types'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing'
/*
resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality`
via getConfigOption, so we mock the config-access module and set the tiers per
via getConfigOption, so we mock it in @ipp/core and set the tiers per
test rather than loading a real config file. vitest hoists vi.mock above the
imports, so the mock is in place by the time sizing.ts resolves config/access.
imports, so the mock is in place by the time sizing.ts resolves @ipp/core.
*/
const cfg: Record<string, unknown> = {}
vi.mock('../src/config/access', () => ({
vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (path: string, fallback?: unknown) =>
path in cfg ? cfg[path] : fallback
}))
-53
View File
@@ -1,53 +0,0 @@
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
@@ -1,110 +0,0 @@
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')
})
})
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { Asset, AssetType, KeyType } from '@ipp/core'
import { getVideoContentType } from '../src/immich'
import { Asset, AssetType, KeyType } from '../src/types'
const video: Asset = {
id: 'v1',
+3
View File
@@ -34,5 +34,8 @@
"tests",
"vitest.config.ts",
"src/client"
],
"references": [
{ "path": "../shared" }
]
}
+5
View File
@@ -1,6 +1,11 @@
import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
// Test against core's source, so `npm test` needs no build of shared/
alias: { '@ipp/core': resolve(__dirname, '../shared/src/index.ts') }
},
test: {
include: ['tests/**/*.test.ts'],
environment: 'node'