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