Files
immich-magic-proxy/app/src/server.ts
T

260 lines
9.2 KiB
TypeScript

import express, { Express } from 'express'
import {
addNoStoreHeaders,
addResponseHeaders,
Asset,
AssetType,
asyncHandler,
CORE_PUBLIC_DIR,
decodeCookie,
errorHandler,
getKeyTypeFromShare,
healthcheck,
isKey,
KeyType,
respondToInvalidRequest,
sessionMiddleware,
slugLinksDisabled,
unlockHandler
} from '@ipp/core'
import { fetchAssetDetail, handleShareRequest } from './immich'
import { buildAssetMetadata } from './gallery/metadata'
import { assetBuffer } from './stream/asset'
import { downloadAssets } from './stream/download'
import { ImageSize } from './types'
import { canDownload, uploadHealthcheck } from './share'
import { ASSET_VERSION } from './version'
import { resolveShare, resolveSharedAsset } from './resolve'
import { deny, loadRecipient, requireRecipient } from './magic/session'
import { allowShareView, canViewShare } from './magic/access'
import { registerRecipientRoutes, registerSignInRoutes } from './magic/routes'
import { registerAdminRoutes } from './magic/admin'
import { getStore } from './magic/store'
/**
* Build the Express app. Call `loadConfig` first: routes read config as they
* are registered.
*
* Every route that shows anything from Immich is gated. A share's gallery,
* photos and downloads open for a recipient given that share, or for anyone
* when the share is public (`allowShareView`); an Immich link not seen before
* is checked with Immich and recorded as a public share. Everything else,
* comments included, needs a magic-link session (`requireRecipient`) and,
* for comments, a grant of that share (`requireShareAccess`).
*/
export function createApp (): Express {
const app = express()
// Behind a reverse proxy, so req.ip and req.protocol reflect the visitor
app.set('trust proxy', process.env.TRUST_PROXY ?? 'loopback, linklocal, uniquelocal')
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)
app.use(express.urlencoded({ extended: false, limit: '1mb' }))
/** Serve IPP's own `public` folder, then core's, at `path`. */
function serveStatic (path: string, options: Parameters<typeof express.static>[1] = {}) {
for (const dir of ['public', CORE_PUBLIC_DIR]) {
app.use(path, express.static(dir, { ...options, setHeaders: addResponseHeaders }))
}
}
// Cache-busted, immutable static assets under a per-release version segment.
// These hold only the app's own code and styles, never anything from Immich.
const inProduction = process.env.NODE_ENV === 'production'
serveStatic('/share/static/' + ASSET_VERSION, { immutable: inProduction, maxAge: inProduction ? '365d' : 0 })
serveStatic('/share/static')
// The same assets on /, to allow for /robots.txt and /favicon.ico
serveStatic('/')
app.disable('x-powered-by')
/*
[ROUTE] Healthcheck, on /share/healthcheck and the legacy /healthcheck
*/
app.get(/^(|\/share)\/healthcheck$/, asyncHandler(healthcheck))
/*
[ROUTE] The upload service's healthcheck path, when the service is assumed
to be at a path on this hostname. Answers "nothing here" as a 204.
*/
const uploadProbe = uploadHealthcheck()
if (uploadProbe) {
app.get(uploadProbe, (_req, res) => {
addNoStoreHeaders(res)
res.status(204).end()
})
}
// Open the store now, so a bad DATA_DIR fails at startup rather than on the first visitor
getStore()
// ----- public: magic-link sign-in and the admin console ---------------------
app.use(loadRecipient)
registerSignInRoutes(app)
registerAdminRoutes(app)
// ----- shares: public ones for anyone, the rest for their recipients --------
/*
[ROUTE] The main URL a visitor opens from a shared link
*/
app.get('/:shareType(share|s)/:key/:mode(download)?', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType)
if (slugLinksDisabled(keyType)) {
respondToInvalidRequest(res, 404, 'Slug links are disabled in config.json')
} else {
await handleShareRequest({
req,
key: req.params.key,
keyType,
mode: req.params.mode,
password: req.password
}, res)
}
}))
/*
[ROUTE] Password unlock from the password page, for a visitor who may
view the share: a recipient of it (when no password is stored), or
anyone for a public share.
*/
app.post('/share/unlock', (req, res, next) => {
const key = req.body?.key
if (typeof key !== 'string' || !isKey(key) || !canViewShare(req, key)) {
deny(req, res, 'Unlock for a share this visitor may not view')
return
}
next()
}, unlockHandler)
/*
[ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
The list arrives as a single "assets" form field containing a JSON array.
Validates each ID against share.assets so the request can't pull anything
outside the share.
*/
app.post('/:shareType(share|s)/:key/download', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType)
let requestedIds: unknown
try {
requestedIds = JSON.parse(String(req.body?.assets ?? '[]'))
} catch (e) {
respondToInvalidRequest(res, 400, 'Malformed assets list')
return
}
if (!Array.isArray(requestedIds) || requestedIds.length === 0) {
respondToInvalidRequest(res, 400, 'No assets selected')
return
}
const resolved = await resolveShare(req, keyType)
if (!resolved.ok) {
respondToInvalidRequest(res, resolved.status, resolved.reason)
return
}
if (!canDownload(resolved.link)) {
respondToInvalidRequest(res, 403, 'Downloads disabled for this share')
return
}
const requested = new Set(requestedIds.map(String))
const validAssets = resolved.link.assets.filter(a => requested.has(a.id))
if (validAssets.length === 0) {
respondToInvalidRequest(res, 400, 'No valid assets in selection')
return
}
await downloadAssets(res, resolved.link, validAssets)
}))
/*
[ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
state issues) and force a clean GET redirect.
See https://github.com/alangrainger/immich-public-proxy/pull/205
*/
app.post('/:shareType(share|s)/:key/:mode(download)?', (req, res) => {
res.redirect(303, req.originalUrl)
})
/*
[ROUTE] Direct link to a photo or video asset
*/
app.get('/share/:type(photo|video)/:key/:id/:size?', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
addResponseHeaders(res)
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path)
return
}
// Always key auth: this route has no slug form
const resolved = await resolveSharedAsset(req, KeyType.key, req.params.type === 'video')
if (!resolved.ok) {
// Password-protected: redirect to the share page so the visitor gets the
// unlock prompt, rather than returning an error.
if (resolved.passwordRequired) {
res.redirect('/share/' + req.params.key)
return
}
respondToInvalidRequest(res, resolved.status, resolved.reason)
return
}
if (resolved.link.password) addNoStoreHeaders(res)
const asset: Asset = {
...resolved.asset,
type: req.params.type === 'video' ? AssetType.video : resolved.asset.type
}
const request = {
req,
key: req.params.key,
range: req.headers.range || ''
}
await assetBuffer(request, res, asset, req.params.size, resolved.link, req.params.type === 'video')
}))
/*
[ROUTE] On-demand per-asset metadata for lazy album items.
Album shares enumerate their assets from the timeline API, which yields
grid-only data (no exif / filename / description). When such an item opens
in the lightbox, the client fetches its detail from here. The id is
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', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
addResponseHeaders(res)
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
if (!resolved.ok) {
respondToInvalidRequest(res, resolved.status, resolved.reason)
return
}
if (resolved.link.password) addNoStoreHeaders(res)
const detail = await fetchAssetDetail(resolved.asset)
if (!detail) {
respondToInvalidRequest(res, 404, 'Asset detail unavailable for ' + req.params.id)
return
}
res.json(buildAssetMetadata(detail, resolved.link))
}))
// ----- everything below needs a magic-link session --------------------------
app.use(requireRecipient)
registerRecipientRoutes(app)
/*
[ROUTE] Send a 404 for all other routes and methods. `all`, so a POST or DELETE to an
unknown path gets the same policy instead of Express's own HTML error page.
*/
app.all('*', (req, res) => {
respondToInvalidRequest(res, 404, 'Invalid route ' + req.path)
})
app.use(errorHandler)
return app
}