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
+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 }}/>
}