Better error handling, and handling of numeric config options
This commit is contained in:
@@ -17,3 +17,12 @@ export function getConfigOption (path: string, defaultOption?: unknown) {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
} from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { AssetType, ImageSize, SharedLink } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { getConfigOption, getNumericConfigOption } from '../config/access'
|
||||
import { canDownload, expiryDate, title } from '../share'
|
||||
import { toString } from '../utils/text'
|
||||
import { h } from 'preact'
|
||||
@@ -164,8 +164,7 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
}
|
||||
|
||||
// HTML gallery page cache time
|
||||
const configured = Number(getConfigOption('ipp.gallery.cacheTime', 300))
|
||||
const cacheTime = Number.isFinite(configured) ? Math.max(0, configured) : 300
|
||||
const cacheTime = Math.max(0, getNumericConfigOption('ipp.gallery.cacheTime', 300))
|
||||
res.header('Cache-Control', 'public, max-age=' + cacheTime)
|
||||
res.send(renderPage(h(Gallery, props)))
|
||||
}
|
||||
|
||||
+27
-1
@@ -1,5 +1,7 @@
|
||||
import { Response } from 'express-serve-static-core'
|
||||
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
|
||||
@@ -12,3 +14,27 @@ export function addResponseHeaders (res: Response): void {
|
||||
res.set(header, value)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
}
|
||||
|
||||
+24
-16
@@ -22,7 +22,7 @@ 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 { addResponseHeaders } from './http'
|
||||
import { addResponseHeaders, asyncHandler, errorHandler } from './http'
|
||||
import { canDownload } from './share'
|
||||
import { toString } from './utils/text'
|
||||
import { decrypt, encrypt } from './encrypt'
|
||||
@@ -140,18 +140,18 @@ async function resolveSharedAsset (req: Request, keyType: KeyType): Promise<Shar
|
||||
* [ROUTE] Healthcheck
|
||||
* The path matches for /share/healthcheck, and also the legacy /healthcheck
|
||||
*/
|
||||
app.get(/^(|\/share)\/healthcheck$/, async (_req, res) => {
|
||||
app.get(/^(|\/share)\/healthcheck$/, asyncHandler(async (_req, res) => {
|
||||
if (await accessible()) {
|
||||
res.send('ok')
|
||||
} else {
|
||||
res.status(503).send()
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] This is the main URL that someone would visit if they are opening a shared link
|
||||
*/
|
||||
app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, async (req, res) => {
|
||||
app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
|
||||
if (keyType === KeyType.slug && !getConfigOption('ipp.allowSlugLinks', true)) {
|
||||
@@ -166,7 +166,7 @@ app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, async (req,
|
||||
password: req.password
|
||||
}, res)
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] Receive an unlock request from the password page
|
||||
@@ -177,7 +177,7 @@ app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, async (req,
|
||||
* managing user session data. The data is provided to the server by the
|
||||
* user's browser in its encrypted state.
|
||||
*/
|
||||
app.post('/share/unlock', async (req, res) => {
|
||||
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,
|
||||
@@ -185,7 +185,7 @@ app.post('/share/unlock', async (req, res) => {
|
||||
}))
|
||||
}
|
||||
res.send()
|
||||
})
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
|
||||
@@ -193,7 +193,7 @@ app.post('/share/unlock', async (req, res) => {
|
||||
* Validates each ID against share.assets so the request can't pull anything
|
||||
* outside the share.
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) => {
|
||||
app.post('/:shareType(share|s)/:key/download', decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
let requestedIds: unknown
|
||||
try {
|
||||
@@ -225,7 +225,7 @@ app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) =>
|
||||
}
|
||||
|
||||
await downloadAssets(res, resolved.link, validAssets)
|
||||
})
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
|
||||
@@ -239,7 +239,7 @@ app.post('/:shareType(share|s)/:key/:mode(download)?', (req, res) => {
|
||||
/*
|
||||
* [ROUTE] This is the direct link to a photo or video asset
|
||||
*/
|
||||
app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, res) => {
|
||||
app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(async (req, res) => {
|
||||
// Add the headers configured in config.json (most likely `cache-control`)
|
||||
addResponseHeaders(res)
|
||||
|
||||
@@ -274,8 +274,8 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
key: req.params.key,
|
||||
range: req.headers.range || ''
|
||||
}
|
||||
assetBuffer(request, res, asset, req.params.size).then()
|
||||
})
|
||||
await assetBuffer(request, res, asset, req.params.size)
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] On-demand per-asset metadata for lazy album items.
|
||||
@@ -286,7 +286,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
* validated against the share's asset set (defence in depth - Immich also
|
||||
* enforces this via the share key) before we fetch `GET /assets/:id`.
|
||||
*/
|
||||
app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, async (req, res) => {
|
||||
app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, asyncHandler(async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
|
||||
@@ -302,7 +302,7 @@ app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, async (req, res) =>
|
||||
}
|
||||
|
||||
res.json(buildAssetMetadata(detail, resolved.link))
|
||||
})
|
||||
}))
|
||||
|
||||
/*
|
||||
* [ROUTE] Home page
|
||||
@@ -327,6 +327,13 @@ app.get('*', (req, res) => {
|
||||
respondToInvalidRequest(res, 404, 'Invalid route ' + req.path)
|
||||
})
|
||||
|
||||
/*
|
||||
* Terminal error middleware: any throw/rejection inside a route (routed here
|
||||
* by asyncHandler) is logged and answered per the 404 privacy policy, instead
|
||||
* of escaping to process level.
|
||||
*/
|
||||
app.use(errorHandler)
|
||||
|
||||
// Send the correct process error code for any uncaught exceptions
|
||||
// so that Docker can gracefully restart the container
|
||||
process.on('uncaughtException', (err) => {
|
||||
@@ -334,10 +341,11 @@ process.on('uncaughtException', (err) => {
|
||||
server.close()
|
||||
process.exit(1)
|
||||
})
|
||||
// Log-only: with asyncHandler routing request errors into errorHandler, a
|
||||
// stray rejection from a background task (version check, staging-dir sweep,
|
||||
// etc.) is not worth killing every in-flight request for.
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('Unhandled Rejection at:', promise, 'reason:', reason)
|
||||
server.close()
|
||||
process.exit(1)
|
||||
})
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('Received SIGTERM. Gracefully shutting down...')
|
||||
|
||||
@@ -96,8 +96,8 @@ export interface MetadataConfig {
|
||||
|
||||
/**
|
||||
* Shape of the JSON init block embedded in `gallery.tsx` and consumed by
|
||||
* `client/init.ts`. The server writes it via `JSON.stringify`; the client
|
||||
* reads it via `readInitParams()`.
|
||||
* `client/init.ts`. The server writes it via `jsonForInlineScript`; the
|
||||
* client reads it via `readInitParams()`.
|
||||
*/
|
||||
export interface InitParams {
|
||||
items?: GalleryItem[]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { assetFetchUrl, authHeadersForAsset } from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { Asset, ImageSize, SharedLink } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { getNumericConfigOption } from '../config/access'
|
||||
import { log } from '../utils/log'
|
||||
import archiver, { Archiver } from 'archiver'
|
||||
import { sanitize } from '../utils/sanitize'
|
||||
@@ -96,7 +96,7 @@ export async function downloadAssets (res: Response, share: SharedLink, assets:
|
||||
|
||||
const options: StagingOptions = {
|
||||
stagingDir: await fs.mkdtemp(join(tmpdir(), STAGING_DIR_PREFIX)),
|
||||
concurrency: Math.max(1, getConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20) as number),
|
||||
concurrency: Math.max(1, getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)),
|
||||
maxAttempts: 3,
|
||||
headerTimeoutMs: 20_000,
|
||||
idleTimeoutMs: 20_000
|
||||
|
||||
@@ -12,6 +12,19 @@ export function escapeHtml (str: string): string {
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AssetType } from '../types'
|
||||
import { ThemeScript } from './theme'
|
||||
import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
|
||||
import { ASSET_VERSION } from '../version'
|
||||
import { jsonForInlineScript } from '../utils/text'
|
||||
|
||||
export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
|
||||
|
||||
@@ -25,7 +26,7 @@ export interface GalleryProps {
|
||||
}
|
||||
|
||||
export function Gallery (props: GalleryProps) {
|
||||
const initJson = JSON.stringify({
|
||||
const initJson = jsonForInlineScript({
|
||||
items: props.items,
|
||||
openItem: props.openItem,
|
||||
lightboxConfig: props.lightboxConfig,
|
||||
|
||||
Reference in New Issue
Block a user