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
+3
View File
@@ -1,4 +1,7 @@
/node_modules/
/app/node_modules/ /app/node_modules/
/app/dist/ /app/dist/
/app/public/js/ /app/public/js/
/app/.env /app/.env
/shared/node_modules/
/shared/dist/
+1
View File
@@ -0,0 +1 @@
dist/
+1 -1
View File
@@ -25,7 +25,7 @@
}, },
"overrides": [ "overrides": [
{ {
"files": ["public/web.js"], "files": ["app/public/web.js"],
"env": { "browser": true, "node": false }, "env": { "browser": true, "node": false },
"rules": { "rules": {
"import/no-absolute-path": "off" "import/no-absolute-path": "off"
+1 -1
View File
@@ -53,7 +53,7 @@ jobs:
type=semver,pattern={{version}},value=v${{ env.PACKAGE_VERSION }} type=semver,pattern={{version}},value=v${{ env.PACKAGE_VERSION }}
type=semver,pattern={{major}}.{{minor}},value=v${{ env.PACKAGE_VERSION }} type=semver,pattern={{major}}.{{minor}},value=v${{ env.PACKAGE_VERSION }}
type=semver,pattern={{major}},value=v${{ env.PACKAGE_VERSION }} type=semver,pattern={{major}},value=v${{ env.PACKAGE_VERSION }}
type=raw,value=latest type=raw,value=latest,enable=${{ !contains(env.PACKAGE_VERSION, '-') }}
- name: Build and push Docker image - name: Build and push Docker image
id: build id: build
+1
View File
@@ -6,3 +6,4 @@ app/public/js/
.directory .directory
/app/config.dev.json /app/config.dev.json
.npm-cache/ .npm-cache/
*.tsbuildinfo
+55 -33
View File
@@ -19,33 +19,50 @@ Immich Public Proxy (IPP) exists to share Immich photos publicly without exposin
Request flow for a typical share URL like `https://proxy.example.com/share/<key>`: Request flow for a typical share URL like `https://proxy.example.com/share/<key>`:
1. Express routes in `app/src/index.ts` receive the request. 1. Express routes in `app/src/index.ts` receive the request.
2. `app/src/immich.ts` fetches the share metadata from Immich over the local network, validates it, and returns the asset list. 2. `app/src/immich.ts` fetches the share metadata from Immich over the local network (through `fetchSharedLink` in `@ipp/core`), validates it, and returns the asset list.
3. For a gallery, `app/src/gallery/builder.ts` builds the view-model and `app/src/view/gallery.tsx` renders it server-side with Preact. The page embeds a JSON init block consumed by the client. 3. For a gallery, `app/src/gallery/builder.ts` builds the view-model and `app/src/view/gallery.tsx` renders it server-side with Preact. The page embeds a JSON init block consumed by the client.
4. The client gallery lives in `app/src/client/` (TypeScript ES modules, compiled file-for-file by `tsc` into `app/public/js/`). It wires PhotoSwipe v5 with a virtualized justified-rows layout. There is no client-side framework hydration. 4. The client gallery lives in `app/src/client/` (TypeScript ES modules, compiled file-for-file by `tsc` into `app/public/js/`). It wires PhotoSwipe v5 with a virtualized justified-rows layout. There is no client-side framework hydration.
5. For individual assets (image, video, thumbnail, download, zip), Express streams bytes from Immich back to the client without touching disk via `app/src/stream/`. 5. For individual assets (image, video, thumbnail, download, zip), Express streams bytes from Immich back to the client without touching disk via `app/src/stream/`.
### Repository layout ### Repository layout
The repo is an npm workspace with two packages: `shared/` is `@ipp/core`, the read-side code that IPP shares with the planned upload service, and `app/` is IPP itself. Run `npm install` at the root; there is one lockfile.
``` ```
.github/workflows/ CI: builds and pushes Docker image on v* tags .github/workflows/ CI: builds and pushes Docker image on v* tags
package.json Workspace root: scripts that delegate to the workspaces; no dependencies
package-lock.json The one lockfile for every workspace
.eslintrc Lint config for both workspaces
shared/ @ipp/core - read-side only, knows nothing about galleries
src/
index.ts Barrel: everything the apps import comes from '@ipp/core'
types.ts Share-level types (SharedLink, Asset, KeyType, ...)
immich/client.ts Immich API request helper, URL building, key/id checks, version guard
immich/share.ts fetchSharedLink, password login + token cache, auth headers, title
config/loader.ts loadConfig() reads env / file; the app passes its default path and migrations
config/access.ts getConfigOption() reads the loaded config
http.ts Operator-configured response headers, asyncHandler, errorHandler
invalidRequest.ts The 404 policy, with setInvalidRequestHandler for the app's own handler file
session.ts Cookie session, decodeCookie, unlock handler, invalid-password response
encrypt.ts Cookie-session encryption for password-protected shares
utils/ log, sanitize (filenames), text (escaping), ttlLruCache, webStream
view/ Page renderer, theme script, password page
tests/ Vitest unit tests for core
app/ app/
config.json Runtime configuration, overrideable via volume or inline config.json Runtime configuration, overrideable via volume or inline
package.json Node project manifest package.json IPP's manifest; its version is the release version
tsconfig.json Server TypeScript config (compiles src/ to dist/) tsconfig.json Server TypeScript config (compiles src/ to dist/; references shared/)
tsconfig.client.json Client TypeScript config (compiles src/client/ + src/shared/ to public/js/) tsconfig.client.json Client TypeScript config (compiles src/client/ + src/shared/ to public/js/)
vitest.config.ts Unit-test runner config vitest.config.ts Unit-test runner config; aliases @ipp/core to its source
src/ src/
index.ts Express setup and routes index.ts Express setup and routes
immich.ts Upstream Immich API calls, share + token caches immich.ts Share lookup with album enumeration and cache, asset detail, IPP URLs
encrypt.ts Cookie-session encryption for password-protected shares invalidRequestHandler.ts IPP's 404 handler; operators may replace the compiled file by a mount
invalidRequestHandler.ts Centralised 404 / custom-response handling share.ts Share-level policy (canDownload, expiry date, motion photos)
http.ts Operator-configured HTTP response headers types.ts Gallery-only server types
share.ts Share-level info + policy (title, canDownload) version.ts Release version and the static-asset cache-busting segment
types.ts Server-only TypeScript types
config/ config/
loader.ts loadConfig() reads env / file, applies migrations
migrations.ts Backward-compat shims for legacy config-key shapes migrations.ts Backward-compat shims for legacy config-key shapes
access.ts getConfigOption() reads the loaded config
gallery/ gallery/
builder.ts Gallery view-model construction builder.ts Gallery view-model construction
exif.ts EXIF / location whitelisting for the sidebar exif.ts EXIF / location whitelisting for the sidebar
@@ -53,23 +70,21 @@ app/
stream/ stream/
asset.ts Single-asset stream (image / video / thumbnail) asset.ts Single-asset stream (image / video / thumbnail)
download.ts Zip pipeline (concurrency-bounded, retry, abort) download.ts Zip pipeline (concurrency-bounded, retry, abort)
utils/ view/ Gallery and home page Preact SSR templates (.tsx)
log.ts Timestamped log.info / log.warn / log.error
sanitize.ts Filename-character sanitization
text.ts escapeHtml + toString narrowing
view/ Preact SSR templates (.tsx)
shared/types.ts Types shared between server SSR and client (GalleryItem, etc.) shared/types.ts Types shared between server SSR and client (GalleryItem, etc.)
client/ Client gallery, virtualisation, lightbox, sidebar client/ Client gallery, virtualisation, lightbox, sidebar
public/ Static assets served as-is public/ Static assets served as-is
photoswipe/ Vendored PhotoSwipe v5 photoswipe/ Vendored PhotoSwipe v5
thumbhash/, fonts/, images/ thumbhash/, fonts/, images/
style.css, photoswipe-overrides.css style.css, photoswipe-overrides.css
tests/ Vitest unit tests for pure functions tests/ Vitest unit tests for IPP
docs/ User docs site (VitePress); docs/README.md explains its structure docs/ User docs site (VitePress); docs/README.md explains its structure
Dockerfile Multi-stage build, runs as the non-root `node` user Dockerfile Multi-stage build; IPP runs from /app as the non-root `node` user
docker-compose.yml Reference deployment docker-compose.yml Reference deployment
``` ```
**What goes in `@ipp/core`.** A module belongs in core when it is about Immich shares, HTTP plumbing, config, sessions, utilities or page rendering, and does not know what a gallery is. Core is read-side only: its one POST to Immich is the shared-link password login. The browser client shares no code with core; `app/src/shared/` is the separate server-and-client type folder.
The server tsconfig excludes `src/client/`; the client tsconfig only includes `src/client/` and `src/shared/`. Compiled client output (`app/public/js/`) is gitignored. The server tsconfig excludes `src/client/`; the client tsconfig only includes `src/client/` and `src/shared/`. Compiled client output (`app/public/js/`) is gitignored.
## Tech stack ## Tech stack
@@ -92,9 +107,8 @@ The server tsconfig excludes `src/client/`; the client tsconfig only includes `s
## Development setup ## Development setup
```bash ```bash
cd app npm install # at the repo root, for every workspace
npm install npm run dev # builds @ipp/core once, then watches core, server and client
npm run dev
``` ```
Required environment variables (set in `app/.env` or your shell): Required environment variables (set in `app/.env` or your shell):
@@ -110,17 +124,25 @@ Configuration overrides go in `app/config.json` or inline via env (see `docs/con
## Build, lint, test ## Build, lint, test
At the repo root:
```bash ```bash
npm run build # both server and client tsc; output to dist/ and public/js/ npm run build # core, then IPP's server and client; output to dist/ and app/public/js/
npm run build:server # server only npm test # vitest run in every workspace (unit tests on pure functions)
npm run build:client # client only npm run lint # ESLint over both workspaces
npm test # vitest run (unit tests on pure functions) npm run bump -- 4.0.1 # set the version in every workspace manifest and the lockfile
npm run test:watch # vitest in watch mode
npm run test:container # build a podman image and run it locally
npx eslint src/ # lint
``` ```
`npm test` runs the pure-function unit tests in `app/tests/`. Today the suite covers `escapeHtml` only; the other shipped pure-function areas (filename derivation, layout math, EXIF whitelisting) deserve coverage too. Add tests as you touch those areas, and for any new pure logic you introduce. Skip HTTP plumbing. In `app/`:
```bash
npm run build:server # core and IPP's server only
npm run build:client # client only
npm run test:watch # vitest in watch mode
npm run test:container # build a podman image and run it locally
```
`npm test` runs the pure-function unit tests in `shared/tests/` and `app/tests/`. IPP's tests import `@ipp/core` from its source, so they need no build. Today the suite covers `escapeHtml` only; the other shipped pure-function areas (filename derivation, layout math, EXIF whitelisting) deserve coverage too. Add tests as you touch those areas, and for any new pure logic you introduce. Skip HTTP plumbing.
Beyond unit tests, exercise the gallery end-to-end against a real Immich instance: happy path plus failure paths (expired share, trashed asset, password protection, very large albums, video range requests). Beyond unit tests, exercise the gallery end-to-end against a real Immich instance: happy path plus failure paths (expired share, trashed asset, password protection, very large albums, video range requests).
@@ -128,9 +150,9 @@ Beyond unit tests, exercise the gallery end-to-end against a real Immich instanc
**Configuration.** New options go in `app/config.json` under the appropriate `ipp.*` namespace, read via `getConfigOption`, and documented on the page for their group under `docs/config/` (see `docs/README.md` for the conventions). Prefer a group toggle plus per-field overrides over a single flat boolean when several related toggles cluster, following the `ipp.showMetadata` pattern. Existing keys keep working; if you rename one, add a backward-compat shim with a startup deprecation warning, as was done for the v2.0 gallery key rename. **Configuration.** New options go in `app/config.json` under the appropriate `ipp.*` namespace, read via `getConfigOption`, and documented on the page for their group under `docs/config/` (see `docs/README.md` for the conventions). Prefer a group toggle plus per-field overrides over a single flat boolean when several related toggles cluster, following the `ipp.showMetadata` pattern. Existing keys keep working; if you rename one, add a backward-compat shim with a startup deprecation warning, as was done for the v2.0 gallery key rename.
**Privacy of responses.** Always return 404 for invalid or upstream-failed requests. Use `invalidRequestHandler` rather than crafting ad-hoc error responses. Do not surface Immich status codes or error bodies to the client. **Privacy of responses.** Always return 404 for invalid or upstream-failed requests. Use `respondToInvalidRequest` from `@ipp/core` rather than crafting ad-hoc error responses; it calls IPP's `invalidRequestHandler`, which index.ts registers at startup. Do not surface Immich status codes or error bodies to the client.
**Escaping.** Any string that originates from Immich and is embedded into HTML by the SSR templates must be escaped (use `escapeHtml` from `utils/text.ts`). Strings that cross to the client via the init JSON block stay as plain text and are rendered with `textContent`, not `innerHTML` - that retired the "pre-escaped HTML over the wire" contract that the early gallery shipped with. **Escaping.** Any string that originates from Immich and is embedded into HTML by the SSR templates must be escaped (use `escapeHtml` from `@ipp/core`). Strings that cross to the client via the init JSON block stay as plain text and are rendered with `textContent`, not `innerHTML` - that retired the "pre-escaped HTML over the wire" contract that the early gallery shipped with.
**Third-party links.** Any anchor the client renders that points to a third-party origin (the "Open in OpenStreetMap" link is the current example) must set `rel="noopener noreferrer"`. The `noreferrer` part is the load-bearing one: without it, the browser sends the share URL as the `Referer` header, and the share URL *is* the capability token for the album - it ends up in the third party's webserver logs. `noopener` prevents the new tab from touching `window.opener`. Embedding a third-party widget (map tile, oEmbed, etc.) instead of a click-through link reintroduces the same leak silently on every render - that's a design decision that needs more than a code change. **Third-party links.** Any anchor the client renders that points to a third-party origin (the "Open in OpenStreetMap" link is the current example) must set `rel="noopener noreferrer"`. The `noreferrer` part is the load-bearing one: without it, the browser sends the share URL as the `Referer` header, and the share URL *is* the capability token for the album - it ends up in the third party's webserver logs. `noopener` prevents the new tab from touching `window.opener`. Embedding a third-party widget (map tile, oEmbed, etc.) instead of a click-through link reintroduces the same leak silently on every render - that's a design decision that needs more than a code change.
@@ -140,7 +162,7 @@ Beyond unit tests, exercise the gallery end-to-end against a real Immich instanc
**File organisation.** Group functions by cohesion, not by file count. A file deserves its own name when it carries a coherent concept worth a separate filename - "filename sanitization" or "config loader" pass; "narrow unknown to string" does not. When several small helpers share a theme, group them in one file (`utils/text.ts` for escaping + narrowing; `share.ts` for share-level info + policy). When a single concern is substantial enough to dominate a file on its own, give it its own name (`config/migrations.ts`, `stream/download.ts`). IPP optimises for audit reading rather than tree-shakeable reuse, so fewer cohesive files beat many one-export micro-modules. Same lens applies on the client (`app/src/client/`): each module is a viewport-of-code that earns its name. **File organisation.** Group functions by cohesion, not by file count. A file deserves its own name when it carries a coherent concept worth a separate filename - "filename sanitization" or "config loader" pass; "narrow unknown to string" does not. When several small helpers share a theme, group them in one file (`utils/text.ts` for escaping + narrowing; `share.ts` for share-level info + policy). When a single concern is substantial enough to dominate a file on its own, give it its own name (`config/migrations.ts`, `stream/download.ts`). IPP optimises for audit reading rather than tree-shakeable reuse, so fewer cohesive files beat many one-export micro-modules. Same lens applies on the client (`app/src/client/`): each module is a viewport-of-code that earns its name.
Where to put a new function: ask what category of thing it is, not where it gets called from. Share-level policy decisions and share-derived info go in `share.ts`. Per-asset view-model transforms (filename derivation, EXIF whitelisting) go alongside `gallery/builder.ts`. HTTP response setup driven by operator config goes in `http.ts`. Streaming pipelines go in `stream/`. If a new function doesn't fit any existing category, prefer adding to the closest existing file over creating a new single-function module - revisit when a real second member of the category appears. Where to put a new function: ask what category of thing it is, not where it gets called from. Share-level policy decisions and share-derived info go in `share.ts`. Per-asset view-model transforms (filename derivation, EXIF whitelisting) go alongside `gallery/builder.ts`. HTTP response setup driven by operator config goes in core's `http.ts`. Streaming pipelines go in `stream/`. If a new function doesn't fit any existing category, prefer adding to the closest existing file over creating a new single-function module - revisit when a real second member of the category appears.
**No client framework, no bundler.** The client is TypeScript compiled file-for-file by `tsc` into plain ES modules served by Express static. Do not introduce a frontend framework (React / Svelte / Vue / Solid) or a bundler (Webpack / Rollup / Vite / Parcel). PhotoSwipe is loaded as ESM directly. Inter-module imports inside `app/src/client/` use `.js` extensions in the source: with no bundler, the browser fetches the compiled `.js` files directly, so the extension has to be present in the import path at runtime. `moduleResolution: bundler` is permissive about extensions in TypeScript-land; the constraint comes from the browser, not the TS config. **No client framework, no bundler.** The client is TypeScript compiled file-for-file by `tsc` into plain ES modules served by Express static. Do not introduce a frontend framework (React / Svelte / Vue / Solid) or a bundler (Webpack / Rollup / Vite / Parcel). PhotoSwipe is loaded as ESM directly. Inter-module imports inside `app/src/client/` use `.js` extensions in the source: with no bundler, the browser fetches the compiled `.js` files directly, so the extension has to be present in the import path at runtime. `moduleResolution: bundler` is permissive about extensions in TypeScript-land; the constraint comes from the browser, not the TS config.
+30 -10
View File
@@ -1,26 +1,46 @@
FROM node:lts-alpine AS builder FROM node:lts-alpine AS builder
# /app must be node-owned for npm ci; WORKDIR leaves it root-owned on some builders # /ipp must be node-owned for npm ci; WORKDIR leaves it root-owned on some builders
RUN mkdir /app && chown node:node /app RUN mkdir /ipp && chown node:node /ipp
USER node USER node
WORKDIR /app WORKDIR /ipp
COPY --chown=node:node app/ ./
RUN npm ci \ # npm ci needs the manifest of every workspace in the root `workspaces` array
&& npx tsc \ COPY --chown=node:node package.json package-lock.json ./
&& npx tsc -p tsconfig.client.json COPY --chown=node:node shared/package.json shared/
COPY --chown=node:node app/package.json app/
RUN npm ci --workspace=app
COPY --chown=node:node shared/ shared/
COPY --chown=node:node app/ app/
RUN npm run build --workspace=shared --workspace=app
# Production tree with @ipp/core dereferenced from its workspace symlink into a
# real folder (cp -L), so the runner's /app is self-contained. IPP's own
# workspace link goes first: the runner has IPP at /app, not in node_modules.
RUN rm -rf node_modules \
&& npm ci --workspace=app --omit=dev \
&& rm -rf node_modules/immich-public-proxy node_modules/.bin/immich-public-proxy \
&& cp -rL node_modules /ipp/prod_modules \
&& cd /ipp/prod_modules/@ipp/core \
&& rm -rf src tests tsconfig.json vitest.config.ts dist/tsconfig.tsbuildinfo \
&& rm -f /ipp/app/dist/tsconfig.tsbuildinfo
FROM node:lts-alpine AS runner FROM node:lts-alpine AS runner
RUN apk --no-cache add curl \ RUN apk --no-cache add curl \
&& mkdir /app && chown node:node /app && mkdir /app && chown node:node /app
# IPP stays at /app so the documented mounts (/app/config.json,
# /app/dist/invalidRequestHandler.js) and the IPP_CONFIG default keep working
USER node USER node
WORKDIR /app WORKDIR /app
COPY --from=builder --chown=node:node app/ ./ COPY --from=builder --chown=node:node /ipp/app/package.json ./
COPY --from=builder --chown=node:node /ipp/prod_modules ./node_modules
RUN npm ci --omit=dev 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 ./
ARG PACKAGE_VERSION ARG PACKAGE_VERSION
ENV APP_VERSION=${PACKAGE_VERSION} ENV APP_VERSION=${PACKAGE_VERSION}
+5 -5
View File
@@ -2,9 +2,10 @@
"name": "immich-public-proxy", "name": "immich-public-proxy",
"version": "3.4.1", "version": "3.4.1",
"scripts": { "scripts": {
"dev": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"", "predev": "tsc -b ../shared",
"build": "tsc && tsc -p tsconfig.client.json", "dev": "concurrently -n core,server,client -c magenta,blue,green \"tsc -b -w --preserveWatchOutput ../shared\" \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
"build:server": "tsc", "build": "tsc -b && tsc -p tsconfig.client.json",
"build:server": "tsc -b",
"build:client": "tsc -p tsconfig.client.json", "build:client": "tsc -p tsconfig.client.json",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
@@ -21,13 +22,12 @@
"main": "dist/index.js", "main": "dist/index.js",
"bin": "dist/index.js", "bin": "dist/index.js",
"dependencies": { "dependencies": {
"@ipp/core": "*",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"preact": "^10.29.2", "preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1" "tslib": "^2.8.1"
}, },
"devDependencies": { "devDependencies": {
+4 -27
View File
@@ -1,28 +1,5 @@
import { getCurrentConfig } from './loader' /*
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.
* 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) { export { getConfigOption } from '@ipp/core'
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
}
+3 -5
View File
@@ -1,15 +1,13 @@
import { Asset, AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
import { import {
getVideoContentType, getVideoContentType,
photoUrl, photoUrl,
videoUrl videoUrl
} from '../immich' } from '../immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, SharedLink } from '../types' import { ImageSize } from '../types'
import { getConfigOption, getNumericConfigOption } from '../config/access' import { canDownload, expiryDate } from '../share'
import { canDownload, expiryDate, title } from '../share'
import { toString } from '../utils/text'
import { h } from 'preact' import { h } from 'preact'
import { renderPage } from '../view/render'
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery' import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
import type { GroupByDateMode } from '../shared/types' import type { GroupByDateMode } from '../shared/types'
import { downloadFilename } from './filename' 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 { GalleryExif } from '../shared/types'
import { getConfigOption } from '../config/access'
type Group = 'exif' | 'location' type Group = 'exif' | 'location'
+2 -3
View File
@@ -1,6 +1,5 @@
import { Asset, ImageSize } from '../types' import { Asset, getConfigOption, sanitize } from '@ipp/core'
import { getConfigOption } from '../config/access' import { ImageSize } from '../types'
import { sanitize } from '../utils/sanitize'
import { resolveImageEndpoint } from './sizing' 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 { AssetMetadata } from '../shared/types'
import { getConfigOption } from '../config/access'
import { pickExif } from './exif' import { pickExif } from './exif'
import { downloadFilename } from './filename' import { downloadFilename } from './filename'
+2 -2
View File
@@ -1,5 +1,5 @@
import { Asset, AssetType, ImageSize } from '../types' import { Asset, AssetType, getConfigOption } from '@ipp/core'
import { getConfigOption } from '../config/access' import { ImageSize } from '../types'
/* /*
Single source of truth for image-size policy: given a requested ImageSize Single source of truth for image-size policy: given a requested ImageSize
+26 -290
View File
@@ -2,30 +2,33 @@ import {
AlbumType, AlbumType,
Asset, Asset,
AssetType, AssetType,
ImageSize,
ImmichVersion,
IncomingShareRequest,
KeyType, KeyType,
SharedLink,
SharedLinkResult, SharedLinkResult,
TimelineBucket, addNoStoreHeaders,
TimelineBucketAssets addResponseHeaders,
} from './types' apiUrl,
import dayjs from 'dayjs' authHeaders,
import { getConfigOption } from './config/access' buildUrl,
import { addNoStoreHeaders, addResponseHeaders } from './http' 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 { canDownload } from './share'
import { log } from './utils/log'
import { assetBuffer } from './stream/asset' import { assetBuffer } from './stream/asset'
import { downloadAll } from './stream/download' import { downloadAll } from './stream/download'
import { gallery } from './gallery/builder' import { gallery } from './gallery/builder'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { h } from 'preact' 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. 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 }) 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 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 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 }) 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 * 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. * 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 // A password is required, but the visitor-provided one doesn't match
if (sharedLinkRes.passwordRequired && req.password) { if (sharedLinkRes.passwordRequired && req.password) {
log('Invalid password for key ' + req.key) invalidPasswordResponse(req.req, res, 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]
} }
// Don't cache password-protected albums // 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 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]) { if (req.password && req.req.session && !req.req.session[link.key]) {
req.req.session[link.key] = encrypt(JSON.stringify({ storeUnlock(req.req, link.key, req.password)
password: req.password,
expires: dayjs().add(1, 'hour').format()
}))
} }
// Everything is ok - output the shared link data // Everything is ok - output the shared link data
@@ -242,19 +169,9 @@ export function getShareByKey (key: string, password?: string, keyType: KeyType
* coalescing on cold misses. * coalescing on cold misses.
*/ */
async function fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> { async function fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
let link const result = await fetchSharedLink(key, keyType, password)
const url = buildUrl(apiUrl() + '/shared-links/me', { if (!result.link) return result
[keyType]: key const link = result.link
})
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
// For an album, `/shared-links/me` returns an empty `assets` array // For an album, `/shared-links/me` returns an empty `assets` array
// (Immich 3.0 dropped album assets from both that response and // (Immich 3.0 dropped album assets from both that response and
@@ -271,7 +188,7 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
valid: false valid: false
} }
} }
const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, headers) const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, await authHeaders(keyType, key, password))
if (albumAssets === null) { if (albumAssets === null) {
// Enumeration failed upstream. Return invalid (not cached) rather // Enumeration failed upstream. Return invalid (not cached) rather
// than caching an empty album for the next 120s on a transient blip. // than caching an empty album for the next 120s on a transient blip.
@@ -282,11 +199,6 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
link.assets = albumAssets 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)) { if (!Array.isArray(link.assets)) {
// Defensive guard: the returned album should always(?) populate this array // Defensive guard: the returned album should always(?) populate this array
log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')') log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')')
@@ -307,43 +219,7 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
} else if (sortOrder === 'desc') { } else if (sortOrder === 'desc') {
link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0) link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
} }
return { return result
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
}
} }
// Base resolution used to turn an Immich `ratio` (width/height) into concrete // 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 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 * `authHeaders` for an asset whose key/keyType/password are already stamped on
* it (the common case for share-scoped fetches). * 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 * 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}`) 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, * Coerce an unknown `size` parameter from a URL into a valid ImageSize,
* defaulting to preview when the input is missing or unrecognised. * defaulting to preview when the input is missing or unrecognised.
@@ -685,10 +428,3 @@ export function validateImageSize (size: unknown) {
return size as ImageSize 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 'dotenv/config'
import express from 'express' import express from 'express'
import cookieSession from 'cookie-session' import { resolve } from 'path'
import { import {
accessible, accessible,
addNoStoreHeaders,
addResponseHeaders,
Asset,
AssetType,
asyncHandler,
decodeCookie,
enforceMinimumImmichVersion, enforceMinimumImmichVersion,
fetchAssetDetail, errorHandler,
getConfigOption,
getKeyTypeFromShare, getKeyTypeFromShare,
getShareByKey,
handleShareRequest,
isId, isId,
isKey isKey,
} from './immich' KeyType,
loadConfig,
renderPage,
respondToInvalidRequest,
sessionMiddleware,
setInvalidRequestHandler,
SharedLink,
unlockHandler
} from '@ipp/core'
import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich'
import { buildAssetMetadata } from './gallery/metadata' import { buildAssetMetadata } from './gallery/metadata'
import crypto from 'crypto'
import { assetBuffer } from './stream/asset' import { assetBuffer } from './stream/asset'
import { downloadAssets } from './stream/download' import { downloadAssets } from './stream/download'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { NextFunction, Request, Response } from 'express-serve-static-core' import { Request } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, KeyType, SharedLink } from './types' import { ImageSize } from './types'
import { getConfigOption } from './config/access' import { applyMigrations } from './config/migrations'
import { loadConfig } from './config/loader'
import { addNoStoreHeaders, addResponseHeaders, asyncHandler, errorHandler } from './http'
import { canDownload, findMotionPhotoStill } from './share' import { canDownload, findMotionPhotoStill } from './share'
import { toString } from './utils/text' import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler'
import { decrypt, encrypt } from './encrypt'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { ASSET_VERSION } from './version' import { ASSET_VERSION } from './version'
import { h } from 'preact' import { h } from 'preact'
import { renderPage } from './view/render'
import { Home } from './view/home' 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 // Read config.json (or the inline CONFIG env var) and apply backward-compat
// migrations. Must run before any code that calls getConfigOption. // migrations. Must run before any code that calls getConfigOption. The
loadConfig() // 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() const app = express()
app.use(cookieSession({ app.use(sessionMiddleware({ name: 'session' }))
name: 'session',
httpOnly: true,
sameSite: 'lax',
secret: crypto.randomBytes(32).toString('base64url')
}))
// For parsing the password unlock form and POSTed JSON payloads // For parsing the password unlock form and POSTed JSON payloads
app.use(express.json()) app.use(express.json())
// For parsing the selective-download form POST (form-encoded body) // 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 // Remove the X-Powered-By ExpressJS header
app.disable('x-powered-by') 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 * Shared route guards. Several routes need the same "resolve a share, reject
* invalid / password-protected ones, optionally find the requested asset" * 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 * [ROUTE] Receive an unlock request from the password page
* Stores a cookie with an encrypted payload which expires in 1 hour. * 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) => { app.post('/share/unlock', unlockHandler)
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()
}))
/* /*
* [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those. * [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 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 function with their own custom one, by replacing the invalidRequestHandler.js file
through a Docker volume mount. 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 { Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access' import { getConfigOption, log } from '@ipp/core'
import { log } from './utils/log'
/** /**
* Respond to any request that IPP would otherwise serve content for but cannot * 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 { Asset, getConfigOption, SharedLink } from '@ipp/core'
import { getConfigOption } from './config/access' import { DownloadAll } from './types'
import dayjs from 'dayjs' 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 * 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 * 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 { import {
assetFetchUrl, assetFetchUrl,
authHeadersForAsset, authHeadersForAsset,
@@ -5,13 +6,10 @@ import {
validateImageSize validateImageSize
} from '../immich' } from '../immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, ImageSize, IncomingShareRequest, SharedLink } from '../types' import { ImageSize, IncomingShareRequest } from '../types'
import { respondToInvalidRequest } from '../invalidRequestHandler'
import { attachmentDisposition, getFilename, servedMimeFrom } from '../gallery/filename' import { attachmentDisposition, getFilename, servedMimeFrom } from '../gallery/filename'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
import { pipeline } from 'stream/promises' import { pipeline } from 'stream/promises'
import { readableFromWeb } from '../utils/webStream'
import { log } from '../utils/log'
/** /**
* Stream an asset from Immich back to the client. * 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 { assetFetchUrl, authHeadersForAsset } from '../immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, SharedLink } from '../types'
import { log } from '../utils/log'
import archiver, { Archiver } from 'archiver' import archiver, { Archiver } from 'archiver'
import { sanitize } from '../utils/sanitize'
import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing' import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing'
import { title } from '../share'
import { attachmentDisposition, getFilename, responseMime, servedMimeFrom } from '../gallery/filename' 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. */ /** Attempts to get response headers from Immich for one asset before giving up. */
const MAX_ATTEMPTS = 3 const MAX_ATTEMPTS = 3
+1 -106
View File
@@ -1,83 +1,5 @@
import { Request } from 'express-serve-static-core' import { Request } from 'express-serve-static-core'
import { KeyType } from '@ipp/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;
}
/** /**
* One entry of `GET /timeline/buckets` - a time bucket (month) and its count. * One entry of `GET /timeline/buckets` - a time bucket (month) and its count.
@@ -107,33 +29,6 @@ export interface TimelineBucketAssets {
livePhotoVideoId: (string | null)[]; 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 { export enum ImageSize {
thumbnail = 'thumbnail', thumbnail = 'thumbnail',
preview = 'preview', 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()
}
}
}
+4 -23
View File
@@ -1,24 +1,5 @@
import dayjs from 'dayjs' /*
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.
* 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() export { log } from '@ipp/core'
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
+1 -3
View File
@@ -1,8 +1,6 @@
import { AssetType } from '../types' import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core'
import { ThemeScript } from './theme'
import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
import { ASSET_VERSION } from '../version' import { ASSET_VERSION } from '../version'
import { jsonForInlineScript } from '../utils/text'
export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { KeyType } from '@ipp/core'
import { getShareByKey, utcBucketKey } from '../src/immich' import { getShareByKey, utcBucketKey } from '../src/immich'
import { KeyType } from '../src/types'
// 3.0-shaped responses: album `/shared-links/me` returns an empty assets[], // 3.0-shaped responses: album `/shared-links/me` returns an empty assets[],
// and the album's assets are enumerated from the timeline API. This exercises // and the album's assets are enumerated from the timeline API. This exercises
+1 -2
View File
@@ -1,7 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest' import { describe, it, expect, beforeEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { buildAssetMetadata } from '../src/gallery/metadata' import { buildAssetMetadata } from '../src/gallery/metadata'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
// buildAssetMetadata is the lazy-flow counterpart to the gallery builder's // buildAssetMetadata is the lazy-flow counterpart to the gallery builder's
// per-item baking; it must apply the same showMetadata kill-switch and // per-item baking; it must apply the same showMetadata kill-switch and
+2 -2
View File
@@ -1,9 +1,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest' import { describe, it, expect, vi, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig } from '@ipp/core'
import { Writable } from 'stream' import { Writable } from 'stream'
import type { Request, Response } from 'express-serve-static-core' import type { Request, Response } from 'express-serve-static-core'
import { assetBuffer } from '../src/stream/asset' import { assetBuffer } from '../src/stream/asset'
import { loadConfig } from '../src/config/loader' import { ImageSize, IncomingShareRequest } from '../src/types'
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../src/types'
afterEach(() => { afterEach(() => {
vi.unstubAllGlobals() vi.unstubAllGlobals()
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { Asset, AssetType, KeyType } from '@ipp/core'
import { dateSortComparator } from '../src/gallery/builder' import { dateSortComparator } from '../src/gallery/builder'
import { Asset, AssetType, KeyType } from '../src/types'
/* /*
The date-grouping sort must follow the album's own order while The date-grouping sort must follow the album's own order while
+1 -2
View File
@@ -1,10 +1,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest' import { describe, it, expect, vi, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { Writable } from 'stream' import { Writable } from 'stream'
import { once } from 'events' import { once } from 'events'
import type { Response } from 'express-serve-static-core' import type { Response } from 'express-serve-static-core'
import { downloadAssets } from '../src/stream/download' import { downloadAssets } from '../src/stream/download'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
/* /*
"Download all" streams each asset from Immich straight into the zip on the "Download all" streams each asset from Immich straight into the zip on the
+7 -5
View File
@@ -1,14 +1,16 @@
import { describe, it, expect, vi } from 'vitest' import { describe, it, expect, vi } from 'vitest'
import { AssetType, ImageSize, KeyType } from '../src/types' import { AssetType, KeyType } from '@ipp/core'
import type { Asset } from '../src/types' import type { Asset } from '@ipp/core'
import { ImageSize } from '../src/types'
import { getFilename } from '../src/gallery/filename' import { getFilename } from '../src/gallery/filename'
/* /*
getFilename reads `ipp.downloadedFilename` via getConfigOption; mock the getFilename reads `ipp.downloadedFilename` via getConfigOption; mock it in
config-access module so tests exercise the default (original filename) mode @ipp/core so tests exercise the default (original filename) mode
without loading a real config file. without loading a real config file.
*/ */
vi.mock('../src/config/access', () => ({ vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (_path: string, fallback?: unknown) => fallback getConfigOption: (_path: string, fallback?: unknown) => fallback
})) }))
+1 -2
View File
@@ -1,9 +1,8 @@
import { describe, it, expect, beforeEach } from 'vitest' import { describe, it, expect, beforeEach } from 'vitest'
import { KeyType, loadConfig, SharedLink } from '@ipp/core'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import 'dayjs/locale/de' // load German so the localised-format assertions are deterministic import 'dayjs/locale/de' // load German so the localised-format assertions are deterministic
import { expiryDate } from '../src/share' import { expiryDate } from '../src/share'
import { loadConfig } from '../src/config/loader'
import { KeyType, SharedLink } from '../src/types'
// expiryDate formats the share's Immich expiry for the gallery subtitle. It is // expiryDate formats the share's Immich expiry for the gallery subtitle. It is
// gated behind ipp.gallery.showExpiryDate (default off) and formatted with // gated behind ipp.gallery.showExpiryDate (default off) and formatted with
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { renderPage } from '@ipp/core'
import { h } from 'preact' import { h } from 'preact'
import { Gallery, GalleryProps, GalleryItem } from '../src/view/gallery' import { Gallery, GalleryProps, GalleryItem } from '../src/view/gallery'
import { renderPage } from '../src/view/render'
/* /*
Regression test for the init-JSON XSS: asset strings (originalFileName, EXIF Regression test for the init-JSON XSS: asset strings (originalFileName, EXIF
+4 -3
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, KeyType } from '../src/types' import { AssetType, KeyType } from '@ipp/core'
import type { Asset, SharedLink } from '../src/types' import type { Asset, SharedLink } from '@ipp/core'
import type { Response } from 'express-serve-static-core' import type { Response } from 'express-serve-static-core'
import { findMotionPhotoStill } from '../src/share' import { findMotionPhotoStill } from '../src/share'
import { gallery } from '../src/gallery/builder' import { gallery } from '../src/gallery/builder'
@@ -11,7 +11,8 @@ import { gallery } from '../src/gallery/builder'
is on. Config is mocked per test rather than loaded from a file. is on. Config is mocked per test rather than loaded from a file.
*/ */
const cfg: Record<string, unknown> = {} const cfg: Record<string, unknown> = {}
vi.mock('../src/config/access', () => ({ vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (path: string, fallback?: unknown) => (path in cfg ? cfg[path] : fallback), getConfigOption: (path: string, fallback?: unknown) => (path in cfg ? cfg[path] : fallback),
getNumericConfigOption: (path: string, fallback: number) => (path in cfg ? Number(cfg[path]) : fallback) getNumericConfigOption: (path: string, fallback: number) => (path in cfg ? Number(cfg[path]) : fallback)
})) }))
+7 -5
View File
@@ -1,16 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, ImageSize } from '../src/types' import { AssetType } from '@ipp/core'
import type { Asset } from '../src/types' import type { Asset } from '@ipp/core'
import { ImageSize } from '../src/types'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing'
/* /*
resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality` resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality`
via getConfigOption, so we mock the config-access module and set the tiers per via getConfigOption, so we mock it in @ipp/core and set the tiers per
test rather than loading a real config file. vitest hoists vi.mock above the test rather than loading a real config file. vitest hoists vi.mock above the
imports, so the mock is in place by the time sizing.ts resolves config/access. imports, so the mock is in place by the time sizing.ts resolves @ipp/core.
*/ */
const cfg: Record<string, unknown> = {} const cfg: Record<string, unknown> = {}
vi.mock('../src/config/access', () => ({ vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (path: string, fallback?: unknown) => getConfigOption: (path: string, fallback?: unknown) =>
path in cfg ? cfg[path] : fallback path in cfg ? cfg[path] : fallback
})) }))
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { Asset, AssetType, KeyType } from '@ipp/core'
import { getVideoContentType } from '../src/immich' import { getVideoContentType } from '../src/immich'
import { Asset, AssetType, KeyType } from '../src/types'
const video: Asset = { const video: Asset = {
id: 'v1', id: 'v1',
+3
View File
@@ -34,5 +34,8 @@
"tests", "tests",
"vitest.config.ts", "vitest.config.ts",
"src/client" "src/client"
],
"references": [
{ "path": "../shared" }
] ]
} }
+5
View File
@@ -1,6 +1,11 @@
import { resolve } from 'path'
import { defineConfig } from 'vitest/config' import { defineConfig } from 'vitest/config'
export default defineConfig({ export default defineConfig({
resolve: {
// Test against core's source, so `npm test` needs no build of shared/
alias: { '@ipp/core': resolve(__dirname, '../shared/src/index.ts') }
},
test: { test: {
include: ['tests/**/*.test.ts'], include: ['tests/**/*.test.ts'],
environment: 'node' environment: 'node'
+37 -3
View File
@@ -1,21 +1,27 @@
{ {
"name": "immich-public-proxy", "name": "immich-public-proxy-workspace",
"version": "3.4.1", "version": "3.4.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "immich-public-proxy-workspace",
"workspaces": [
"shared",
"app"
]
},
"app": {
"name": "immich-public-proxy", "name": "immich-public-proxy",
"version": "3.4.1", "version": "3.4.1",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"dependencies": { "dependencies": {
"@ipp/core": "*",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"preact": "^10.29.2", "preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1" "tslib": "^2.8.1"
}, },
"bin": { "bin": {
@@ -614,6 +620,10 @@
"dev": true, "dev": true,
"license": "BSD-3-Clause" "license": "BSD-3-Clause"
}, },
"node_modules/@ipp/core": {
"resolved": "shared",
"link": true
},
"node_modules/@isaacs/cliui": { "node_modules/@isaacs/cliui": {
"version": "8.0.2", "version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@@ -4101,6 +4111,10 @@
"node": ">= 4" "node": ">= 4"
} }
}, },
"node_modules/immich-public-proxy": {
"resolved": "app",
"link": true
},
"node_modules/import-fresh": { "node_modules/import-fresh": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",
@@ -7548,6 +7562,26 @@
"engines": { "engines": {
"node": ">= 14" "node": ">= 14"
} }
},
"shared": {
"name": "@ipp/core",
"version": "3.4.1",
"license": "AGPL-3.0",
"dependencies": {
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"devDependencies": {
"@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21",
"@types/node": "^22",
"express": "^4.21.1",
"typescript": "^5.6.2",
"vitest": "^4"
}
} }
} }
} }
+15
View File
@@ -0,0 +1,15 @@
{
"name": "immich-public-proxy-workspace",
"private": true,
"workspaces": [
"shared",
"app"
],
"scripts": {
"build": "npm run build --workspaces",
"test": "npm test --workspaces",
"lint": "eslint shared app --ext .ts,.tsx",
"dev": "npm run dev --workspace=app",
"bump": "npm version --no-git-tag-version --workspaces"
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@ipp/core",
"version": "3.4.1",
"private": true,
"description": "Read-side code shared by Immich Public Proxy and its upload service.",
"license": "AGPL-3.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -b",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"preact": "^10.29.2",
"preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"devDependencies": {
"@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21",
"@types/node": "^22",
"express": "^4.21.1",
"typescript": "^5.6.2",
"vitest": "^4"
}
}
+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
}
@@ -1,9 +1,16 @@
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import { resolve } from 'path' import { resolve } from 'path'
import { applyMigrations } from './migrations'
export type Config = Record<string, unknown> 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 // Module-level cache populated by `loadConfig()`. Access through
// `getCurrentConfig()` rather than importing directly; that gives // `getCurrentConfig()` rather than importing directly; that gives
// `config/access.ts` a stable read path even before `loadConfig()` has // `config/access.ts` a stable read path even before `loadConfig()` has
@@ -13,32 +20,35 @@ let currentConfig: Config = {}
/** /**
* Read the runtime configuration from `process.env.CONFIG` (an inline JSON * Read the runtime configuration from `process.env.CONFIG` (an inline JSON
* string, typically set in docker-compose) or from the config file. Applies * string, typically set in docker-compose) or from the config file. Applies
* backward-compatibility migrations, caches the result, and returns it. * the app's `migrate` hook, caches the result, and returns it.
* *
* Called once from `index.ts` at startup. Safe to call again in tests with * The default path comes from the app, not from this module's location:
* a fresh env to reset state. * 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 (): Config { export function loadConfig ({ defaultPath, migrate }: LoadConfigOptions = {}): Config {
let config: Config = {} let config: Config = {}
try { try {
if (process.env.CONFIG) { if (process.env.CONFIG) {
// Attempt to parse docker-compose config string into JSON (if specified) // Attempt to parse docker-compose config string into JSON (if specified)
config = JSON.parse(process.env.CONFIG) config = JSON.parse(process.env.CONFIG)
} else { } 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 // IPP_CONFIG (if set) is taken as-is for absolute paths, or resolved
// against the current working directory for relative paths. // against the current working directory for relative paths.
const configPath = process.env.IPP_CONFIG const configPath = process.env.IPP_CONFIG ? resolve(process.env.IPP_CONFIG) : defaultPath
? resolve(process.env.IPP_CONFIG) if (configPath) {
: resolve(__dirname, '../../config.json')
const configJson = JSON.parse(readFileSync(configPath, 'utf8')) const configJson = JSON.parse(readFileSync(configPath, 'utf8'))
if (typeof configJson === 'object') config = configJson if (typeof configJson === 'object') config = configJson
} }
}
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
applyMigrations(config) migrate?.(config)
currentConfig = config currentConfig = config
return config return config
} }
+1 -1
View File
@@ -1,6 +1,6 @@
import { NextFunction, Request, Response } from 'express-serve-static-core' import { NextFunction, Request, Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access' import { getConfigOption } from './config/access'
import { respondToInvalidRequest } from './invalidRequestHandler' import { respondToInvalidRequest } from './invalidRequest'
import { log } from './utils/log' import { log } from './utils/log'
/** /**
+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
@@ -1,5 +1,5 @@
/* /*
Time-to-live + size-bounded LRU cache. Used by `immich.ts` to memoise 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: share-link lookups and `POST /shared-links/login` tokens, where:
- TTL gives us freshness without rebuilding share state on every asset - TTL gives us freshness without rebuilding share state on every asset
@@ -66,3 +66,32 @@ export class TtlLruCache<V> {
this.entries.delete(key) 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
}
@@ -1,13 +1,17 @@
import { jsonForInlineScript } from '../utils/text'
interface PasswordProps { interface PasswordProps {
shareKey: string shareKey: string
notifyInvalidPassword: boolean notifyInvalidPassword: boolean
/** Path prefix the app is mounted under, without a trailing slash. Empty at the root. */
basePath?: string
} }
const submitScript = ` const submitScript = (unlockUrl: string) => `
async function submitForm (formElement) { async function submitForm (formElement) {
const formData = new FormData(formElement) const formData = new FormData(formElement)
try { try {
const res = await fetch('/share/unlock', { const res = await fetch(${jsonForInlineScript(unlockUrl)}, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData.entries())) body: JSON.stringify(Object.fromEntries(formData.entries()))
@@ -25,14 +29,14 @@ const submitScript = `
}) })
` `
export function Password ({ shareKey, notifyInvalidPassword }: PasswordProps) { export function Password ({ shareKey, notifyInvalidPassword, basePath = '' }: PasswordProps) {
return ( return (
<html lang="en"> <html lang="en">
<head> <head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<title>Password required</title> <title>Password required</title>
<link rel="icon" href="/share/static/favicon.ico" type="image/x-icon"/> <link rel="icon" href={basePath + '/share/static/favicon.ico'} type="image/x-icon"/>
<link type="text/css" rel="stylesheet" href="/share/static/pico.min.css"/> <link type="text/css" rel="stylesheet" href={basePath + '/share/static/pico.min.css'}/>
</head> </head>
<body> <body>
<header></header> <header></header>
@@ -65,7 +69,7 @@ export function Password ({ shareKey, notifyInvalidPassword }: PasswordProps) {
<div></div> <div></div>
</div> </div>
</main> </main>
<script dangerouslySetInnerHTML={{ __html: submitScript }}/> <script dangerouslySetInnerHTML={{ __html: submitScript(basePath + '/share/unlock') }}/>
</body> </body>
</html> </html>
) )
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { getImmichVersion, isImmichVersionSupported, MIN_IMMICH_VERSION } from '../src/immich' import { getImmichVersion, isImmichVersionSupported, MIN_IMMICH_VERSION } from '../src/immich/client'
// The startup guard that refuses to run against an Immich server older than // The startup guard that refuses to run against an Immich server older than
// IPP supports. The floor is 2.0.0 - the columnar timeline API IPP relies on // IPP supports. The floor is 2.0.0 - the columnar timeline API IPP relies on
@@ -1,13 +1,12 @@
import { describe, it, expect, afterEach } from 'vitest' import { describe, it, expect, afterEach } from 'vitest'
import { loadConfig } from '../src/config/loader' import { loadConfig } from '../src/config/loader'
import { getNumericConfigOption } from '../src/config/access' import { getNumericConfigOption } from '../src/config/access'
import { createLimiter } from '../src/utils/limiter'
/* /*
Regression tests for the non-numeric concurrency bug: a non-numeric Regression tests for the non-numeric config bug: a non-numeric
`ipp.downloadFromImmichConcurrencyLimit` used to reach createLimiter as NaN, `ipp.downloadFromImmichConcurrencyLimit` used to reach its consumer as NaN,
where `active >= NaN` is always false - so the limiter never throttled and where `active >= NaN` is always false - so the download concurrency limit
every asset in a zip download hit Immich at once. never throttled and every asset in a zip download hit Immich at once.
*/ */
function loadConfigFrom (config: Record<string, unknown>) { function loadConfigFrom (config: Record<string, unknown>) {
@@ -46,30 +45,3 @@ describe('getNumericConfigOption', () => {
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20) expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
}) })
}) })
describe('createLimiter with guarded config', () => {
/** Run `total` tasks through the limiter and report the concurrency peak */
async function peakConcurrency (limit: number, total: number): Promise<number> {
const run = createLimiter(limit)
let active = 0
let peak = 0
await Promise.all(Array.from({ length: total }, () => run(async () => {
active++
peak = Math.max(peak, active)
// Yield so other queued tasks get a chance to start while this one is "active"
await new Promise(resolve => setTimeout(resolve, 1))
active--
})))
return peak
}
it('a NaN limit disables throttling (the failure mode being guarded against)', async () => {
expect(await peakConcurrency(NaN, 10)).toBe(10)
})
it('the guarded value throttles as configured', async () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
const limit = Math.max(1, getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 3))
expect(await peakConcurrency(limit, 10)).toBe(3)
})
})
+33
View File
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"composite": true,
"declaration": true,
"rootDir": "src",
"outDir": "dist",
"tsBuildInfoFile": "dist/tsconfig.tsbuildinfo",
"inlineSourceMap": true,
"inlineSources": true,
"module": "CommonJS",
"target": "ES6",
"noImplicitAny": true,
"esModuleInterop": true,
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"strictNullChecks": true,
"lib": [
"DOM",
"ES5",
"ES6",
"ES7"
],
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"jsxImportSource": "preact"
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node'
}
})