Harden the containers

This commit is contained in:
Alan Grainger
2026-10-07 20:33:45 +13:00
parent cd14066a15
commit 69d600af08
8 changed files with 208 additions and 160 deletions
+11 -8
View File
@@ -35,18 +35,21 @@ RUN rm -rf node_modules \
FROM node:lts-alpine AS runner
RUN apk --no-cache add curl tini \
&& mkdir /app && chown node:node /app
RUN apk --no-cache add curl tini
# IPP stays at /app so the documented mounts (/app/config.json,
# /app/dist/invalidRequestHandler.js) and the IPP_CONFIG default keep working
USER node
WORKDIR /app
COPY --from=builder --chown=node:node /ipp/app/package.json ./
COPY --from=builder --chown=node:node /ipp/prod_modules ./node_modules
COPY --from=builder --chown=node:node /ipp/app/dist ./dist
COPY --from=builder --chown=node:node /ipp/app/public ./public
COPY --from=builder --chown=node:node /ipp/app/config.json ./
COPY --from=builder --chown=root:root /ipp/app/package.json ./
COPY --from=builder --chown=root:root /ipp/prod_modules ./node_modules
COPY --from=builder --chown=root:root /ipp/app/dist ./dist
COPY --from=builder --chown=root:root /ipp/app/public ./public
COPY --from=builder --chown=root:root /ipp/app/config.json ./
# The code is root-owned and the app runs as node, so a compromised process
# cannot rewrite it; nothing writes to disk at runtime. The explicit --chown
# is for buildah, which keeps the builder's owner on COPY --from.
USER node
ARG PACKAGE_VERSION
ENV APP_VERSION=${PACKAGE_VERSION}
+11 -8
View File
@@ -35,17 +35,20 @@ RUN rm -rf node_modules \
FROM node:lts-alpine AS runner
RUN apk --no-cache add curl tini \
&& mkdir /app && chown node:node /app
RUN apk --no-cache add curl tini
# At /app, as IPP, so a config.json mounts at the same path in both images
USER node
WORKDIR /app
COPY --from=builder --chown=node:node /ipp/upload-app/package.json ./
COPY --from=builder --chown=node:node /ipp/prod_modules ./node_modules
COPY --from=builder --chown=node:node /ipp/upload-app/dist ./dist
COPY --from=builder --chown=node:node /ipp/upload-app/public ./public
COPY --from=builder --chown=node:node /ipp/upload-app/config.json ./
COPY --from=builder --chown=root:root /ipp/upload-app/package.json ./
COPY --from=builder --chown=root:root /ipp/prod_modules ./node_modules
COPY --from=builder --chown=root:root /ipp/upload-app/dist ./dist
COPY --from=builder --chown=root:root /ipp/upload-app/public ./public
COPY --from=builder --chown=root:root /ipp/upload-app/config.json ./
# The code is root-owned and the app runs as node, so a compromised process
# cannot rewrite it; nothing writes to disk at runtime. The explicit --chown
# is for buildah, which keeps the builder's owner on COPY --from.
USER node
ARG PACKAGE_VERSION
ENV APP_VERSION=${PACKAGE_VERSION}
+53 -68
View File
@@ -42,10 +42,11 @@ import { ASSET_VERSION } from './version'
import { h } from 'preact'
import { Home } from './view/home'
// Read config.json (or the inline CONFIG env var). 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.
/*
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') })
const removedSwitches = removedMetadataSwitches()
@@ -57,8 +58,10 @@ if (removedSwitches.length) {
process.exit(1)
}
// Route every invalid response, including core's, through IPP's handler file,
// so an operator's mounted replacement applies everywhere.
/*
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()
@@ -67,28 +70,29 @@ app.use(sessionMiddleware({ name: 'session' }))
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.
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('/')
// Remove the X-Powered-By ExpressJS header
app.disable('x-powered-by')
/*
* Shared route guards. Several routes need the same "resolve a share, reject
* invalid / password-protected ones, optionally find the requested asset"
* preamble. These return a discriminated result so each route keeps control of
* its own response (e.g. the photo route redirects on password where the meta
* and download routes return 401), while the validation order and the
* `valid`/`link`/`passwordRequired` checks live in one place.
Shared route guards. Several routes need the same "resolve a share, reject
invalid / password-protected ones, optionally find the requested asset"
preamble. These return a discriminated result so each route keeps control of
its own response (e.g. the photo route redirects on password where the meta
and download routes return 401), while the validation order and the
`valid`/`link`/`passwordRequired` checks live in one place.
*/
type ShareResolution =
| { ok: true, link: SharedLink }
@@ -145,18 +149,17 @@ async function resolveSharedAsset (req: Request, keyType: KeyType, allowMotion =
}
/*
* [ROUTE] Healthcheck
* The path matches for /share/healthcheck, and also the legacy /healthcheck
[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. The gallery page probes it before showing
* the "Add photos" button. With the upload service routed in front of IPP the
* probe never gets here; without it, this answers "nothing here" as a 204
* rather than a 404, so the probe is neither a console error in the browser
* nor a hit on the 404 policy.
[ROUTE] The upload service's healthcheck path, when the service is assumed
to be at a path on this hostname. The gallery page probes it before showing
the "Add photos" button. With the upload service routed in front of IPP the
probe never gets here; without it, this answers "nothing here" as a 204
rather than a 404, so the probe is neither a console error in the browser
nor a hit on the 404 policy.
*/
const uploadProbe = uploadHealthcheck()
if (uploadProbe) {
@@ -167,7 +170,7 @@ if (uploadProbe) {
}
/*
* [ROUTE] This is the main URL that someone would visit if they are opening a shared link
[ROUTE] The main URL a visitor opens from a shared link
*/
app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType)
@@ -186,16 +189,15 @@ 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.
[ROUTE] Password unlock from the password page
*/
app.post('/share/unlock', 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.
[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', decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType)
@@ -232,31 +234,26 @@ app.post('/:shareType(share|s)/:key/download', decodeCookie, asyncHandler(async
}))
/*
* [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
[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] This is the direct link to a photo or video asset
[ROUTE] Direct link to a photo or video asset
*/
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)
// Validate the size parameter
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path)
return
}
// Resolve the share + asset (this is a `/share/...` route, always key auth).
// The resolved asset gives assetBuffer access to originalMimeType and
// originalFileName (needed for Content-Disposition and for requiresOriginal
// to recognise videos/animated images and bypass the preview downgrade).
// 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
@@ -283,13 +280,13 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(
}))
/*
* [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`.
[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', decodeCookie, asyncHandler(async (req, res) => {
addResponseHeaders(res)
@@ -312,13 +309,9 @@ app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, asyncHandler(async (
}))
/*
* [ROUTE] Home page
*
* It was requested here to have *something* on the home page:
* https://github.com/alangrainger/immich-public-proxy/discussions/19
*
* If you don't want to see this, set showHomePage as false in your config.json:
* https://github.com/alangrainger/immich-public-proxy?tab=readme-ov-file#immich-public-proxy-options
[ROUTE] Home page, so the root shows *something*, as requested in
https://github.com/alangrainger/immich-public-proxy/discussions/19.
Turned off by https://docs.ipp.nz/config/ipp-options#showhomepage
*/
if (getConfigOption('ipp.showHomePage', true)) {
app.get(/^\/(|share)\/*$/, (_req, res) => {
@@ -328,30 +321,26 @@ if (getConfigOption('ipp.showHomePage', true)) {
}
/*
* 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.
[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)
})
/*
* 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
// Exit non-zero on an uncaught exception, so Docker restarts the container
process.on('uncaughtException', (err) => {
console.error('There was an uncaught error', err)
server.close()
process.exit(1)
})
// Log-only: with asyncHandler routing request errors into errorHandler, a
// stray rejection from a background task (the version check, etc.) is not
// worth killing every in-flight request for.
/*
Log only: with asyncHandler routing request errors into errorHandler, a
stray rejection from a background task (the version check, etc.) is not
worth killing every in-flight request for.
*/
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason)
})
@@ -361,12 +350,8 @@ process.on('SIGTERM', () => {
process.exit(0)
})
// Start the ExpressJS server
const port = Number(process.env.IPP_PORT) || 3000
const server = app.listen(port, () => {
console.log(dayjs().format() + ' Server started on port ' + port)
// Bail out early if the Immich server is older than IPP supports, rather
// than silently serving broken album shares. Unknown/unreachable is
// tolerated (logs a warning and continues) - see enforceMinimumImmichVersion.
enforceMinimumImmichVersion().catch(e => console.error('Immich version check failed:', e))
})
+10
View File
@@ -5,6 +5,11 @@ services:
restart: always
ports:
- "3000:3000"
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges
environment:
PUBLIC_BASE_URL: https://your-proxy-url.com
IMMICH_URL: http://your-internal-immich-server:2283
@@ -22,6 +27,11 @@ services:
# restart: always
# ports:
# - "3001:3000"
# read_only: true
# cap_drop:
# - ALL
# security_opt:
# - no-new-privileges
# environment:
# IMMICH_URL: http://your-internal-immich-server:2283
# PUBLIC_BASE_URL: https://your-proxy-url.com
+7
View File
@@ -70,6 +70,11 @@ services:
restart: always
ports:
- "3001:3000"
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges
environment:
IMMICH_URL: http://your-internal-immich-server:2283
PUBLIC_BASE_URL: https://photos.example.com
@@ -81,6 +86,8 @@ services:
- `IMMICH_URL` and `PUBLIC_BASE_URL` mean the same as on the IPP container, so you can copy the `environment` block
across. `PUBLIC_BASE_URL` is IPP's public URL; it gives the upload page a back button to the gallery.
- `read_only`, `cap_drop` and `security_opt` lock the container down. They are optional: the service writes
nothing to disk and needs no extra privileges, so it runs the same with or without them.
The service has no setting for its own public URL. Your reverse proxy decides that in the next step.
+45 -40
View File
@@ -1393,9 +1393,9 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1926,9 +1926,9 @@
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.6",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz",
"integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==",
"version": "1.20.8",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",
"integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
@@ -1939,7 +1939,7 @@
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.15.1",
"qs": "~6.16.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
@@ -1994,9 +1994,9 @@
}
},
"node_modules/brace-expansion": {
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3399,9 +3399,9 @@
}
},
"node_modules/express": {
"version": "4.22.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"version": "4.22.3",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
"integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
@@ -3423,9 +3423,9 @@
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"path-to-regexp": "~0.1.13",
"proxy-addr": "~2.0.7",
"qs": "~6.15.1",
"qs": "~6.16.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
@@ -3858,9 +3858,9 @@
}
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -5288,9 +5288,9 @@
}
},
"node_modules/object-inspect": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz",
"integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==",
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -5696,9 +5696,9 @@
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
@@ -5706,6 +5706,10 @@
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/punycode": {
@@ -5719,12 +5723,13 @@
}
},
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
"integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
@@ -5839,9 +5844,9 @@
}
},
"node_modules/readdir-glob/node_modules/brace-expansion": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -6278,14 +6283,14 @@
}
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
@@ -6297,13 +6302,13 @@
}
},
"node_modules/side-channel-list": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3"
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
+53 -17
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import 'dotenv/config'
import express, { Router } from 'express'
import express, { RequestHandler, Router } from 'express'
import { Request } from 'express-serve-static-core'
import { resolve } from 'path'
import dayjs from 'dayjs'
@@ -35,9 +35,11 @@ import { getShare } from './share'
import { ASSET_VERSION } from './version'
import { UploadPage } from './view/upload'
// Must run before any code that calls getConfigOption. The bundled
// config.json sits one level above this file, which is /app/config.json in
// the image.
/*
Must run before any code that calls getConfigOption. The bundled
config.json sits one level above this file, which is /app/config.json in
the image.
*/
loadConfig({ defaultPath: resolve(__dirname, '../config.json') })
const receiveUpload = createUploadReceiver()
@@ -46,7 +48,35 @@ const inProduction = process.env.NODE_ENV === 'production'
const app = express()
app.disable('x-powered-by')
// Reachable at the root whatever the mount prefix, so one compose healthcheck fits both routing shapes
/*
The server has no whole-request timeout (see `requestTimeout` at the end),
so nothing else stops a sender trickling a body to a route that has already
answered. A request that carries a body closes its connection once the
response is sent, read or not. Each upload is its own request, so no
visitor loses a connection worth keeping.
*/
app.use((req, res, next) => {
if (req.headers['content-length'] || req.headers['transfer-encoding']) res.set('Connection', 'close')
next()
})
/**
* Drop a request that has no response within `ms`. For a route that reads
* its body before answering: with no whole-request timeout, a slow sender
* would otherwise hold it open forever.
*/
function bodyDeadline (ms: number): RequestHandler {
return (req, res, next) => {
const timer = setTimeout(() => req.destroy(), ms)
res.once('close', () => clearTimeout(timer))
next()
}
}
/*
[ROUTE] Healthcheck, reachable at the root whatever the mount prefix, so one
compose healthcheck fits both routing shapes
*/
app.get(['/healthcheck', '/share/healthcheck'], asyncHandler(healthcheck))
const router = Router()
@@ -65,7 +95,10 @@ router.use((_req, res, next) => {
})
router.use(sessionMiddleware({ name: 'upload-session' }))
// Before the share routes, which would otherwise read "healthcheck" as a key
/*
[ROUTE] Healthcheck under the mount prefix. Before the share routes, which
would otherwise read "healthcheck" as a key
*/
router.get(['/healthcheck', '/share/healthcheck'], asyncHandler(healthcheck))
type ShareResolution =
@@ -84,7 +117,7 @@ async function resolveShare (req: Request): Promise<ShareResolution> {
}
/*
* [ROUTE] Upload page, or the password page for a locked share
[ROUTE] Upload page, or the password page for a locked share
*/
router.get('/:shareType(share|s)/:key', decodeCookie, asyncHandler(async (req, res) => {
const key = req.params.key
@@ -111,17 +144,16 @@ router.get('/:shareType(share|s)/:key', decodeCookie, asyncHandler(async (req, r
}))
/*
* [ROUTE] Password unlock from the password page
[ROUTE] Password unlock from the password page
*/
router.post('/share/unlock', express.json({ limit: '10kb' }), unlockHandler)
router.post('/share/unlock', bodyDeadline(10_000), express.json({ limit: '10kb' }), unlockHandler)
/*
* [ROUTE] One file from a visitor, streamed to Immich
[ROUTE] One file from a visitor, streamed to Immich
*/
router.post('/:shareType(share|s)/:key/upload', decodeCookie, asyncHandler(async (req, res) => {
const resolved = await resolveShare(req)
if (!resolved.ok) {
res.set('Connection', 'close')
respondToInvalidRequest(res, 404, resolved.reason)
return
}
@@ -129,16 +161,16 @@ router.post('/:shareType(share|s)/:key/upload', decodeCookie, asyncHandler(async
}))
/*
* The same routes under `/upload` and at the root, so either reverse proxy
* shape works with no URL configuration: a hostname of its own forwards
* `/share/<key>`, a path on the IPP hostname forwards `/upload/share/<key>`.
* Handlers read the prefix they were reached by from `req.baseUrl`.
The same routes under `/upload` and at the root, so either reverse proxy
shape works with no URL configuration: a hostname of its own forwards
`/share/<key>`, a path on the IPP hostname forwards `/upload/share/<key>`.
Handlers read the prefix they were reached by from `req.baseUrl`.
*/
app.use('/upload', router)
app.use('/', router)
/*
* Everything else, including `/`, gets the 404 policy
[ROUTE] Everything else, including `/`, gets the 404 policy
*/
app.all('*', (req, res) => {
addNoStoreHeaders(res)
@@ -166,5 +198,9 @@ const server = app.listen(port, () => {
console.log(dayjs().format() + ' Upload service started on port ' + port)
enforceMinimumImmichVersion().catch(() => {})
})
// A large video on a phone uplink outlasts any whole-request limit; the body has an idle timeout instead
/*
A large video on a phone uplink outlasts any whole-request limit; the body
has an idle timeout instead, and the connection rules at the top of this
file cover every other route
*/
server.requestTimeout = 0
+2 -3
View File
@@ -32,10 +32,10 @@ const BODY_MIN_BYTES_PER_INTERVAL = 8 * 1024 * BODY_IDLE_MS / 1000
/**
* Answer an upload the server will not take, in the shape the page reads.
* `Connection: close` stops a body still in flight costing its full bandwidth.
* The connection closes after it (see `index.ts`), so a body still in flight
* stops costing its full bandwidth.
*/
function refuse (res: Response, status: number, reason: string): void {
res.set('Connection', 'close')
res.status(status).json({ error: reason })
}
@@ -71,7 +71,6 @@ export function createUploadReceiver () {
const key = req.params.key
const permit = authoriseUpload(link, key, keyType, req.password)
if (!permit) {
res.set('Connection', 'close')
respondToInvalidRequest(res, 404, 'Share does not accept uploads')
return
}