diff --git a/.dockerignore b/.dockerignore index d2045bf..14dd9db 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,7 @@ +/node_modules/ /app/node_modules/ /app/dist/ /app/public/js/ /app/.env +/shared/node_modules/ +/shared/dist/ diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..849ddff --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +dist/ diff --git a/app/.eslintrc b/.eslintrc similarity index 95% rename from app/.eslintrc rename to .eslintrc index c9943d2..eb096a2 100644 --- a/app/.eslintrc +++ b/.eslintrc @@ -25,7 +25,7 @@ }, "overrides": [ { - "files": ["public/web.js"], + "files": ["app/public/web.js"], "env": { "browser": true, "node": false }, "rules": { "import/no-absolute-path": "off" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 1b8bc26..f6fafa7 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -53,7 +53,7 @@ jobs: type=semver,pattern={{version}},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=raw,value=latest + type=raw,value=latest,enable=${{ !contains(env.PACKAGE_VERSION, '-') }} - name: Build and push Docker image id: build diff --git a/.gitignore b/.gitignore index 5cd136c..d88609c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ app/public/js/ .directory /app/config.dev.json .npm-cache/ +*.tsbuildinfo diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 110bfe9..0a765d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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/`: 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. 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/`. ### 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 +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/ config.json Runtime configuration, overrideable via volume or inline - package.json Node project manifest - tsconfig.json Server TypeScript config (compiles src/ to dist/) + package.json IPP's manifest; its version is the release version + 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/) - vitest.config.ts Unit-test runner config + vitest.config.ts Unit-test runner config; aliases @ipp/core to its source src/ index.ts Express setup and routes - immich.ts Upstream Immich API calls, share + token caches - encrypt.ts Cookie-session encryption for password-protected shares - invalidRequestHandler.ts Centralised 404 / custom-response handling - http.ts Operator-configured HTTP response headers - share.ts Share-level info + policy (title, canDownload) - types.ts Server-only TypeScript types + immich.ts Share lookup with album enumeration and cache, asset detail, IPP URLs + invalidRequestHandler.ts IPP's 404 handler; operators may replace the compiled file by a mount + share.ts Share-level policy (canDownload, expiry date, motion photos) + types.ts Gallery-only server types + version.ts Release version and the static-asset cache-busting segment config/ - loader.ts loadConfig() reads env / file, applies migrations migrations.ts Backward-compat shims for legacy config-key shapes - access.ts getConfigOption() reads the loaded config gallery/ builder.ts Gallery view-model construction exif.ts EXIF / location whitelisting for the sidebar @@ -53,23 +70,21 @@ app/ stream/ asset.ts Single-asset stream (image / video / thumbnail) download.ts Zip pipeline (concurrency-bounded, retry, abort) - utils/ - log.ts Timestamped log.info / log.warn / log.error - sanitize.ts Filename-character sanitization - text.ts escapeHtml + toString narrowing - view/ Preact SSR templates (.tsx) + view/ Gallery and home page Preact SSR templates (.tsx) shared/types.ts Types shared between server SSR and client (GalleryItem, etc.) client/ Client gallery, virtualisation, lightbox, sidebar public/ Static assets served as-is photoswipe/ Vendored PhotoSwipe v5 thumbhash/, fonts/, images/ 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 -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 ``` +**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. ## Tech stack @@ -92,9 +107,8 @@ The server tsconfig excludes `src/client/`; the client tsconfig only includes `s ## Development setup ```bash -cd app -npm install -npm run dev +npm install # at the repo root, for every workspace +npm run dev # builds @ipp/core once, then watches core, server and client ``` 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 +At the repo root: + ```bash -npm run build # both server and client tsc; output to dist/ and public/js/ -npm run build:server # server only -npm run build:client # client only -npm test # vitest run (unit tests on pure functions) -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 run build # core, then IPP's server and client; output to dist/ and app/public/js/ +npm test # vitest run in every workspace (unit tests on pure functions) +npm run lint # ESLint over both workspaces +npm run bump -- 4.0.1 # set the version in every workspace manifest and the lockfile ``` -`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). @@ -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. -**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. @@ -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. -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. diff --git a/Dockerfile b/Dockerfile index 74c0883..1a1e992 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,46 @@ FROM node:lts-alpine AS builder -# /app must be node-owned for npm ci; WORKDIR leaves it root-owned on some builders -RUN mkdir /app && chown node:node /app +# /ipp must be node-owned for npm ci; WORKDIR leaves it root-owned on some builders +RUN mkdir /ipp && chown node:node /ipp USER node -WORKDIR /app -COPY --chown=node:node app/ ./ +WORKDIR /ipp -RUN npm ci \ - && npx tsc \ - && npx tsc -p tsconfig.client.json +# npm ci needs the manifest of every workspace in the root `workspaces` array +COPY --chown=node:node package.json package-lock.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 RUN apk --no-cache add curl \ && 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 WORKDIR /app -COPY --from=builder --chown=node:node app/ ./ - -RUN npm ci --omit=dev +COPY --from=builder --chown=node:node /ipp/app/package.json ./ +COPY --from=builder --chown=node:node /ipp/prod_modules ./node_modules +COPY --from=builder --chown=node:node /ipp/app/dist ./dist +COPY --from=builder --chown=node:node /ipp/app/public ./public +COPY --from=builder --chown=node:node /ipp/app/config.json ./ ARG PACKAGE_VERSION ENV APP_VERSION=${PACKAGE_VERSION} diff --git a/app/package.json b/app/package.json index 6d43690..e9aa336 100644 --- a/app/package.json +++ b/app/package.json @@ -2,9 +2,10 @@ "name": "immich-public-proxy", "version": "3.4.1", "scripts": { - "dev": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"", - "build": "tsc && tsc -p tsconfig.client.json", - "build:server": "tsc", + "predev": "tsc -b ../shared", + "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": "tsc -b && tsc -p tsconfig.client.json", + "build:server": "tsc -b", "build:client": "tsc -p tsconfig.client.json", "test": "vitest run", "test:watch": "vitest", @@ -21,13 +22,12 @@ "main": "dist/index.js", "bin": "dist/index.js", "dependencies": { + "@ipp/core": "*", "archiver": "^7.0.1", - "cookie-session": "^2.1.0", "dayjs": "^1.11.13", "dotenv": "^16.4.5", "express": "^4.21.1", "preact": "^10.29.2", - "preact-render-to-string": "^6.7.0", "tslib": "^2.8.1" }, "devDependencies": { diff --git a/app/src/config/access.ts b/app/src/config/access.ts index 57d0fb6..87a4504 100644 --- a/app/src/config/access.ts +++ b/app/src/config/access.ts @@ -1,28 +1,5 @@ -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 -} +/* + 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. +*/ +export { getConfigOption } from '@ipp/core' diff --git a/app/src/gallery/builder.ts b/app/src/gallery/builder.ts index 2a7045b..d12977d 100644 --- a/app/src/gallery/builder.ts +++ b/app/src/gallery/builder.ts @@ -1,15 +1,13 @@ +import { Asset, AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core' import { getVideoContentType, photoUrl, videoUrl } from '../immich' import { Response } from 'express-serve-static-core' -import { Asset, AssetType, ImageSize, SharedLink } from '../types' -import { getConfigOption, getNumericConfigOption } from '../config/access' -import { canDownload, expiryDate, title } from '../share' -import { toString } from '../utils/text' +import { ImageSize } from '../types' +import { canDownload, expiryDate } from '../share' import { h } from 'preact' -import { renderPage } from '../view/render' import { Gallery, GalleryItem, GalleryProps } from '../view/gallery' import type { GroupByDateMode } from '../shared/types' import { downloadFilename } from './filename' diff --git a/app/src/gallery/exif.ts b/app/src/gallery/exif.ts index bb69799..6121d8e 100644 --- a/app/src/gallery/exif.ts +++ b/app/src/gallery/exif.ts @@ -1,6 +1,5 @@ -import { Asset, ExifInfo } from '../types' +import { Asset, ExifInfo, getConfigOption } from '@ipp/core' import { GalleryExif } from '../shared/types' -import { getConfigOption } from '../config/access' type Group = 'exif' | 'location' diff --git a/app/src/gallery/filename.ts b/app/src/gallery/filename.ts index f05df26..8eb4b47 100644 --- a/app/src/gallery/filename.ts +++ b/app/src/gallery/filename.ts @@ -1,6 +1,5 @@ -import { Asset, ImageSize } from '../types' -import { getConfigOption } from '../config/access' -import { sanitize } from '../utils/sanitize' +import { Asset, getConfigOption, sanitize } from '@ipp/core' +import { ImageSize } from '../types' import { resolveImageEndpoint } from './sizing' /** diff --git a/app/src/gallery/metadata.ts b/app/src/gallery/metadata.ts index 6102cbb..eee7053 100644 --- a/app/src/gallery/metadata.ts +++ b/app/src/gallery/metadata.ts @@ -1,6 +1,5 @@ -import { Asset, SharedLink } from '../types' +import { Asset, getConfigOption, SharedLink } from '@ipp/core' import { AssetMetadata } from '../shared/types' -import { getConfigOption } from '../config/access' import { pickExif } from './exif' import { downloadFilename } from './filename' diff --git a/app/src/gallery/sizing.ts b/app/src/gallery/sizing.ts index 6ef2f29..4857571 100644 --- a/app/src/gallery/sizing.ts +++ b/app/src/gallery/sizing.ts @@ -1,5 +1,5 @@ -import { Asset, AssetType, ImageSize } from '../types' -import { getConfigOption } from '../config/access' +import { Asset, AssetType, getConfigOption } from '@ipp/core' +import { ImageSize } from '../types' /* Single source of truth for image-size policy: given a requested ImageSize diff --git a/app/src/immich.ts b/app/src/immich.ts index 2e0012c..a4d7b13 100644 --- a/app/src/immich.ts +++ b/app/src/immich.ts @@ -2,30 +2,33 @@ import { AlbumType, Asset, AssetType, - ImageSize, - ImmichVersion, - IncomingShareRequest, KeyType, - SharedLink, SharedLinkResult, - TimelineBucket, - TimelineBucketAssets -} from './types' -import dayjs from 'dayjs' -import { getConfigOption } from './config/access' -import { addNoStoreHeaders, addResponseHeaders } from './http' + addNoStoreHeaders, + addResponseHeaders, + apiUrl, + authHeaders, + buildUrl, + 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 { log } from './utils/log' import { assetBuffer } from './stream/asset' import { downloadAll } from './stream/download' import { gallery } from './gallery/builder' import { Response } from 'express-serve-static-core' 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. @@ -46,18 +49,6 @@ import { TtlLruCache } from './utils/ttlLruCache' */ const shareCache = new TtlLruCache>({ 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>({ ttlMs: 120_000, max: 100 }) - /* 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 @@ -68,64 +59,6 @@ const tokenCache = new TtlLruCache>({ ttlMs: 120_000, max */ const assetDetailCache = new TtlLruCache>({ 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 ( - cache: TtlLruCache>, - key: string, - factory: () => Promise, - isValid: (value: T) => boolean = (value) => !!value -): Promise { - 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 * 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 if (sharedLinkRes.passwordRequired && req.password) { - log('Invalid password for key ' + 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] + invalidPasswordResponse(req.req, res, req.key) } // 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 (req.password && req.req.session && !req.req.session[link.key]) { - req.req.session[link.key] = encrypt(JSON.stringify({ - password: req.password, - expires: dayjs().add(1, 'hour').format() - })) + storeUnlock(req.req, link.key, req.password) } // Everything is ok - output the shared link data @@ -242,108 +169,57 @@ export function getShareByKey (key: string, password?: string, keyType: KeyType * coalescing on cold misses. */ async function fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise { - let link - 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) { - // Normal response - get the shared assets - link = jsonBody as SharedLink - link.keyType = keyType + const result = await fetchSharedLink(key, keyType, password) + if (!result.link) return result + const link = result.link - // For an album, `/shared-links/me` returns an empty `assets` array - // (Immich 3.0 dropped album assets from both that response and - // `AlbumResponseDto`). We enumerate the album's assets from the - // timeline API instead - the same approach Immich's own web client - // uses for shared albums. This yields grid-only assets; their full - // detail (exif, filename) is fetched lazily on lightbox open. The - // album cover id we need for og:image is already on `link.album` - // (mapAlbum still returns albumThumbnailAssetId). - if (link.type === AlbumType.album) { - if (!link.album?.id) { - log('Album share missing album id for key ' + key) - return { - valid: false - } - } - const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, headers) - if (albumAssets === null) { - // Enumeration failed upstream. Return invalid (not cached) rather - // than caching an empty album for the next 120s on a transient blip. - return { - valid: false - } - } - 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)) { - // Defensive guard: the returned album should always(?) populate this array - log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')') - link.assets = [] - } - // Filter assets to exclude trashed assets - link.assets = link.assets.filter(asset => !asset.isTrashed) - // Populate the shared assets with the public key/password - link.assets.forEach(asset => { - asset.key = key - asset.keyType = keyType - asset.password = password - }) - // Sort album if there is a sort order specified - const sortOrder = link.album?.order - if (sortOrder === 'asc') { - link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0) - } else if (sortOrder === 'desc') { - link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0) - } - 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)) + // For an album, `/shared-links/me` returns an empty `assets` array + // (Immich 3.0 dropped album assets from both that response and + // `AlbumResponseDto`). We enumerate the album's assets from the + // timeline API instead - the same approach Immich's own web client + // uses for shared albums. This yields grid-only assets; their full + // detail (exif, filename) is fetched lazily on lightbox open. The + // album cover id we need for og:image is already on `link.album` + // (mapAlbum still returns albumThumbnailAssetId). + if (link.type === AlbumType.album) { + if (!link.album?.id) { + log('Album share missing album id for key ' + key) + return { + valid: false } } - } 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) + const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, await authHeaders(keyType, key, password)) + if (albumAssets === null) { + // Enumeration failed upstream. Return invalid (not cached) rather + // than caching an empty album for the next 120s on a transient blip. + return { + valid: false + } } + link.assets = albumAssets } - return { - valid: false + + if (!Array.isArray(link.assets)) { + // Defensive guard: the returned album should always(?) populate this array + log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')') + link.assets = [] } + // Filter assets to exclude trashed assets + link.assets = link.assets.filter(asset => !asset.isTrashed) + // Populate the shared assets with the public key/password + link.assets.forEach(asset => { + asset.key = key + asset.keyType = keyType + asset.password = password + }) + // Sort album if there is a sort order specified + const sortOrder = link.album?.order + if (sortOrder === 'asc') { + link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0) + } else if (sortOrder === 'desc') { + link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0) + } + return result } // Base resolution used to turn an Immich `ratio` (width/height) into concrete @@ -505,18 +381,6 @@ export async function getVideoContentType (asset: Asset): Promise> { - 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 * 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 { - 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 { - 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 */ @@ -604,76 +417,6 @@ export function videoUrl (key: string, id: string) { 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 { - 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 { - 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, * defaulting to preview when the input is missing or unrecognised. @@ -685,10 +428,3 @@ export function validateImageSize (size: unknown) { 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 -} diff --git a/app/src/index.ts b/app/src/index.ts index c85d111..2232860 100644 --- a/app/src/index.ts +++ b/app/src/index.ts @@ -2,54 +2,56 @@ import 'dotenv/config' import express from 'express' -import cookieSession from 'cookie-session' +import { resolve } from 'path' import { accessible, + addNoStoreHeaders, + addResponseHeaders, + Asset, + AssetType, + asyncHandler, + decodeCookie, enforceMinimumImmichVersion, - fetchAssetDetail, + errorHandler, + getConfigOption, getKeyTypeFromShare, - getShareByKey, - handleShareRequest, isId, - isKey -} from './immich' + isKey, + KeyType, + loadConfig, + renderPage, + respondToInvalidRequest, + sessionMiddleware, + setInvalidRequestHandler, + SharedLink, + unlockHandler +} from '@ipp/core' +import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich' import { buildAssetMetadata } from './gallery/metadata' -import crypto from 'crypto' import { assetBuffer } from './stream/asset' import { downloadAssets } from './stream/download' import dayjs from 'dayjs' -import { NextFunction, Request, Response } from 'express-serve-static-core' -import { Asset, AssetType, ImageSize, KeyType, SharedLink } from './types' -import { getConfigOption } from './config/access' -import { loadConfig } from './config/loader' -import { addNoStoreHeaders, addResponseHeaders, asyncHandler, errorHandler } from './http' +import { Request } from 'express-serve-static-core' +import { ImageSize } from './types' +import { applyMigrations } from './config/migrations' import { canDownload, findMotionPhotoStill } from './share' -import { toString } from './utils/text' -import { decrypt, encrypt } from './encrypt' -import { respondToInvalidRequest } from './invalidRequestHandler' +import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler' import { ASSET_VERSION } from './version' import { h } from 'preact' -import { renderPage } from './view/render' 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 -// migrations. Must run before any code that calls getConfigOption. -loadConfig() +// migrations. Must run before any code that calls getConfigOption. The +// bundled config.json sits one level above this file (src/ in dev, dist/ in +// the image), which is /app/config.json in the image. +loadConfig({ defaultPath: resolve(__dirname, '../config.json'), 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() -app.use(cookieSession({ - name: 'session', - httpOnly: true, - sameSite: 'lax', - secret: crypto.randomBytes(32).toString('base64url') -})) +app.use(sessionMiddleware({ name: 'session' })) // For parsing the password unlock form and POSTed JSON payloads app.use(express.json()) // For parsing the selective-download form POST (form-encoded body) @@ -68,26 +70,6 @@ app.use(express.static('public', { setHeaders: addResponseHeaders })) // Remove the X-Powered-By ExpressJS header 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 * 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 * 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) => { - 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() -})) +app.post('/share/unlock', unlockHandler) /* * [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those. diff --git a/app/src/invalidRequestHandler.ts b/app/src/invalidRequestHandler.ts index 577bd9a..9065de7 100644 --- a/app/src/invalidRequestHandler.ts +++ b/app/src/invalidRequestHandler.ts @@ -2,11 +2,14 @@ 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 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 { getConfigOption } from './config/access' -import { log } from './utils/log' +import { getConfigOption, log } from '@ipp/core' /** * Respond to any request that IPP would otherwise serve content for but cannot diff --git a/app/src/share.ts b/app/src/share.ts index cdc68ba..96eff7b 100644 --- a/app/src/share.ts +++ b/app/src/share.ts @@ -1,17 +1,7 @@ -import { Asset, DownloadAll, SharedLink } from './types' -import { getConfigOption } from './config/access' +import { Asset, getConfigOption, SharedLink } from '@ipp/core' +import { DownloadAll } from './types' 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 * all" zip, multi-select download, and the per-asset lightbox button). The diff --git a/app/src/stream/asset.ts b/app/src/stream/asset.ts index c03f8c8..6e4931b 100644 --- a/app/src/stream/asset.ts +++ b/app/src/stream/asset.ts @@ -1,3 +1,4 @@ +import { Asset, log, readableFromWeb, respondToInvalidRequest, SharedLink } from '@ipp/core' import { assetFetchUrl, authHeadersForAsset, @@ -5,13 +6,10 @@ import { validateImageSize } from '../immich' import { Response } from 'express-serve-static-core' -import { Asset, ImageSize, IncomingShareRequest, SharedLink } from '../types' -import { respondToInvalidRequest } from '../invalidRequestHandler' +import { ImageSize, IncomingShareRequest } from '../types' import { attachmentDisposition, getFilename, servedMimeFrom } from '../gallery/filename' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing' import { pipeline } from 'stream/promises' -import { readableFromWeb } from '../utils/webStream' -import { log } from '../utils/log' /** * Stream an asset from Immich back to the client. diff --git a/app/src/stream/download.ts b/app/src/stream/download.ts index acc9b0a..c129924 100644 --- a/app/src/stream/download.ts +++ b/app/src/stream/download.ts @@ -1,14 +1,9 @@ +import { Asset, log, readableFromWeb, respondToInvalidRequest, sanitize, SharedLink, title } from '@ipp/core' import { assetFetchUrl, authHeadersForAsset } from '../immich' import { Response } from 'express-serve-static-core' -import { Asset, SharedLink } from '../types' -import { log } from '../utils/log' import archiver, { Archiver } from 'archiver' -import { sanitize } from '../utils/sanitize' import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing' -import { title } from '../share' 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. */ const MAX_ATTEMPTS = 3 diff --git a/app/src/types.ts b/app/src/types.ts index 1256cc9..5d2fc4f 100644 --- a/app/src/types.ts +++ b/app/src/types.ts @@ -1,83 +1,5 @@ import { Request } from 'express-serve-static-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; -} +import { KeyType } from '@ipp/core' /** * One entry of `GET /timeline/buckets` - a time bucket (month) and its count. @@ -107,33 +29,6 @@ export interface TimelineBucketAssets { 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 { thumbnail = 'thumbnail', preview = 'preview', diff --git a/app/src/utils/limiter.ts b/app/src/utils/limiter.ts deleted file mode 100644 index 267f903..0000000 --- a/app/src/utils/limiter.ts +++ /dev/null @@ -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 (fn: () => Promise): Promise { - if (active >= limit) { - await new Promise(resolve => queue.push(resolve)) - } - active++ - try { - return await fn() - } finally { - active-- - const next = queue.shift() - if (next) next() - } - } -} diff --git a/app/src/utils/log.ts b/app/src/utils/log.ts index bdb13d5..f097f96 100644 --- a/app/src/utils/log.ts +++ b/app/src/utils/log.ts @@ -1,24 +1,5 @@ -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 +/* + 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. +*/ +export { log } from '@ipp/core' diff --git a/app/src/view/gallery.tsx b/app/src/view/gallery.tsx index 8a55457..9dc298f 100644 --- a/app/src/view/gallery.tsx +++ b/app/src/view/gallery.tsx @@ -1,8 +1,6 @@ -import { AssetType } from '../types' -import { ThemeScript } from './theme' +import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core' import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' import { ASSET_VERSION } from '../version' -import { jsonForInlineScript } from '../utils/text' export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } diff --git a/app/tests/albumTimeline.test.ts b/app/tests/albumTimeline.test.ts index ea287cd..63673ce 100644 --- a/app/tests/albumTimeline.test.ts +++ b/app/tests/albumTimeline.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { KeyType } from '@ipp/core' import { getShareByKey, utcBucketKey } from '../src/immich' -import { KeyType } from '../src/types' // 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 diff --git a/app/tests/assetMetadata.test.ts b/app/tests/assetMetadata.test.ts index acda187..ddd753c 100644 --- a/app/tests/assetMetadata.test.ts +++ b/app/tests/assetMetadata.test.ts @@ -1,7 +1,6 @@ import { describe, it, expect, beforeEach } from 'vitest' +import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core' 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 // per-item baking; it must apply the same showMetadata kill-switch and diff --git a/app/tests/assetStream.test.ts b/app/tests/assetStream.test.ts index 7a8e736..02f2bda 100644 --- a/app/tests/assetStream.test.ts +++ b/app/tests/assetStream.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, vi, afterEach } from 'vitest' +import { Asset, AssetType, KeyType, loadConfig } from '@ipp/core' import { Writable } from 'stream' import type { Request, Response } from 'express-serve-static-core' import { assetBuffer } from '../src/stream/asset' -import { loadConfig } from '../src/config/loader' -import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../src/types' +import { ImageSize, IncomingShareRequest } from '../src/types' afterEach(() => { vi.unstubAllGlobals() diff --git a/app/tests/dateSort.test.ts b/app/tests/dateSort.test.ts index af84473..4fbc276 100644 --- a/app/tests/dateSort.test.ts +++ b/app/tests/dateSort.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest' +import { Asset, AssetType, KeyType } from '@ipp/core' 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 diff --git a/app/tests/downloadAssets.test.ts b/app/tests/downloadAssets.test.ts index 3bd24ff..c3b6be0 100644 --- a/app/tests/downloadAssets.test.ts +++ b/app/tests/downloadAssets.test.ts @@ -1,10 +1,9 @@ import { describe, it, expect, vi, afterEach } from 'vitest' +import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core' import { Writable } from 'stream' import { once } from 'events' import type { Response } from 'express-serve-static-core' 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 diff --git a/app/tests/downloadFilename.test.ts b/app/tests/downloadFilename.test.ts index 59594df..8c6a263 100644 --- a/app/tests/downloadFilename.test.ts +++ b/app/tests/downloadFilename.test.ts @@ -1,14 +1,16 @@ import { describe, it, expect, vi } from 'vitest' -import { AssetType, ImageSize, KeyType } from '../src/types' -import type { Asset } from '../src/types' +import { AssetType, KeyType } from '@ipp/core' +import type { Asset } from '@ipp/core' +import { ImageSize } from '../src/types' import { getFilename } from '../src/gallery/filename' /* -getFilename reads `ipp.downloadedFilename` via getConfigOption; mock the -config-access module so tests exercise the default (original filename) mode +getFilename reads `ipp.downloadedFilename` via getConfigOption; mock it in +@ipp/core so tests exercise the default (original filename) mode without loading a real config file. */ -vi.mock('../src/config/access', () => ({ +vi.mock('@ipp/core', async (importOriginal) => ({ + ...await importOriginal(), getConfigOption: (_path: string, fallback?: unknown) => fallback })) diff --git a/app/tests/expiryDate.test.ts b/app/tests/expiryDate.test.ts index 7045bae..8e36149 100644 --- a/app/tests/expiryDate.test.ts +++ b/app/tests/expiryDate.test.ts @@ -1,9 +1,8 @@ import { describe, it, expect, beforeEach } from 'vitest' +import { KeyType, loadConfig, SharedLink } from '@ipp/core' import dayjs from 'dayjs' import 'dayjs/locale/de' // load German so the localised-format assertions are deterministic 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 // gated behind ipp.gallery.showExpiryDate (default off) and formatted with diff --git a/app/tests/galleryInitJson.test.ts b/app/tests/galleryInitJson.test.ts index 4f08552..41c11ec 100644 --- a/app/tests/galleryInitJson.test.ts +++ b/app/tests/galleryInitJson.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest' +import { renderPage } from '@ipp/core' import { h } from 'preact' 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 diff --git a/app/tests/motionPhoto.test.ts b/app/tests/motionPhoto.test.ts index f0fa584..5393997 100644 --- a/app/tests/motionPhoto.test.ts +++ b/app/tests/motionPhoto.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { AssetType, KeyType } from '../src/types' -import type { Asset, SharedLink } from '../src/types' +import { AssetType, KeyType } from '@ipp/core' +import type { Asset, SharedLink } from '@ipp/core' import type { Response } from 'express-serve-static-core' import { findMotionPhotoStill } from '../src/share' 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. */ const cfg: Record = {} -vi.mock('../src/config/access', () => ({ +vi.mock('@ipp/core', async (importOriginal) => ({ + ...await importOriginal(), getConfigOption: (path: string, fallback?: unknown) => (path in cfg ? cfg[path] : fallback), getNumericConfigOption: (path: string, fallback: number) => (path in cfg ? Number(cfg[path]) : fallback) })) diff --git a/app/tests/sizing.test.ts b/app/tests/sizing.test.ts index 206f59e..15489e0 100644 --- a/app/tests/sizing.test.ts +++ b/app/tests/sizing.test.ts @@ -1,16 +1,18 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { AssetType, ImageSize } from '../src/types' -import type { Asset } from '../src/types' +import { AssetType } from '@ipp/core' +import type { Asset } from '@ipp/core' +import { ImageSize } from '../src/types' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing' /* 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 - 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 = {} -vi.mock('../src/config/access', () => ({ +vi.mock('@ipp/core', async (importOriginal) => ({ + ...await importOriginal(), getConfigOption: (path: string, fallback?: unknown) => path in cfg ? cfg[path] : fallback })) diff --git a/app/tests/videoContentType.test.ts b/app/tests/videoContentType.test.ts index e6b38e2..7c010c8 100644 --- a/app/tests/videoContentType.test.ts +++ b/app/tests/videoContentType.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { Asset, AssetType, KeyType } from '@ipp/core' import { getVideoContentType } from '../src/immich' -import { Asset, AssetType, KeyType } from '../src/types' const video: Asset = { id: 'v1', diff --git a/app/tsconfig.json b/app/tsconfig.json index 49e3ea1..6b1cb2d 100644 --- a/app/tsconfig.json +++ b/app/tsconfig.json @@ -34,5 +34,8 @@ "tests", "vitest.config.ts", "src/client" + ], + "references": [ + { "path": "../shared" } ] } diff --git a/app/vitest.config.ts b/app/vitest.config.ts index ec9809a..c064754 100644 --- a/app/vitest.config.ts +++ b/app/vitest.config.ts @@ -1,6 +1,11 @@ +import { resolve } from 'path' import { defineConfig } from 'vitest/config' 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: { include: ['tests/**/*.test.ts'], environment: 'node' diff --git a/app/package-lock.json b/package-lock.json similarity index 99% rename from app/package-lock.json rename to package-lock.json index 6014375..cb58443 100644 --- a/app/package-lock.json +++ b/package-lock.json @@ -1,21 +1,27 @@ { - "name": "immich-public-proxy", + "name": "immich-public-proxy-workspace", "version": "3.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { + "name": "immich-public-proxy-workspace", + "workspaces": [ + "shared", + "app" + ] + }, + "app": { "name": "immich-public-proxy", "version": "3.4.1", "license": "AGPL-3.0", "dependencies": { + "@ipp/core": "*", "archiver": "^7.0.1", - "cookie-session": "^2.1.0", "dayjs": "^1.11.13", "dotenv": "^16.4.5", "express": "^4.21.1", "preact": "^10.29.2", - "preact-render-to-string": "^6.7.0", "tslib": "^2.8.1" }, "bin": { @@ -614,6 +620,10 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/@ipp/core": { + "resolved": "shared", + "link": true + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -4101,6 +4111,10 @@ "node": ">= 4" } }, + "node_modules/immich-public-proxy": { + "resolved": "app", + "link": true + }, "node_modules/import-fresh": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", @@ -7548,6 +7562,26 @@ "engines": { "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" + } } } } diff --git a/package.json b/package.json new file mode 100644 index 0000000..dd68924 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/shared/package.json b/shared/package.json new file mode 100644 index 0000000..44d55a9 --- /dev/null +++ b/shared/package.json @@ -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" + } +} diff --git a/shared/src/config/access.ts b/shared/src/config/access.ts new file mode 100644 index 0000000..57d0fb6 --- /dev/null +++ b/shared/src/config/access.ts @@ -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 +} diff --git a/app/src/config/loader.ts b/shared/src/config/loader.ts similarity index 52% rename from app/src/config/loader.ts rename to shared/src/config/loader.ts index 7179f58..1b8a58a 100644 --- a/app/src/config/loader.ts +++ b/shared/src/config/loader.ts @@ -1,9 +1,16 @@ import { readFileSync } from 'fs' import { resolve } from 'path' -import { applyMigrations } from './migrations' export type Config = Record +/** Where each app keeps its config file, and how it upgrades legacy config shapes. */ +export interface LoadConfigOptions { + /** Absolute path of the bundled config file, used when `IPP_CONFIG` is unset. */ + defaultPath?: string + /** Rewrites legacy keys in place before the config is cached. */ + migrate?: (config: Config) => void +} + // Module-level cache populated by `loadConfig()`. Access through // `getCurrentConfig()` rather than importing directly; that gives // `config/access.ts` a stable read path even before `loadConfig()` has @@ -13,32 +20,35 @@ let currentConfig: Config = {} /** * Read the runtime configuration from `process.env.CONFIG` (an inline JSON * string, typically set in docker-compose) or from the config file. Applies - * 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 - * a fresh env to reset state. + * The default path comes from the app, not from this module's location: + * core is compiled into its own package, so a path relative to `__dirname` + * would point inside `@ipp/core` instead of at the app's bundled file. + * + * Called once from each app's `index.ts` at startup. Safe to call again in + * tests with a fresh env to reset state. */ -export function loadConfig (): Config { +export function loadConfig ({ defaultPath, migrate }: LoadConfigOptions = {}): Config { let config: Config = {} try { if (process.env.CONFIG) { // Attempt to parse docker-compose config string into JSON (if specified) config = JSON.parse(process.env.CONFIG) } else { - // Default config.json sits one level above the compiled dist/ output. // IPP_CONFIG (if set) is taken as-is for absolute paths, or resolved // against the current working directory for relative paths. - const configPath = process.env.IPP_CONFIG - ? resolve(process.env.IPP_CONFIG) - : resolve(__dirname, '../../config.json') - const configJson = JSON.parse(readFileSync(configPath, 'utf8')) - if (typeof configJson === 'object') config = configJson + const configPath = process.env.IPP_CONFIG ? resolve(process.env.IPP_CONFIG) : defaultPath + if (configPath) { + const configJson = JSON.parse(readFileSync(configPath, 'utf8')) + if (typeof configJson === 'object') config = configJson + } } } catch (e) { console.log(e) } - applyMigrations(config) + migrate?.(config) currentConfig = config return config } diff --git a/app/src/encrypt.ts b/shared/src/encrypt.ts similarity index 100% rename from app/src/encrypt.ts rename to shared/src/encrypt.ts diff --git a/app/src/http.ts b/shared/src/http.ts similarity index 96% rename from app/src/http.ts rename to shared/src/http.ts index fc69319..7cfa5b1 100644 --- a/app/src/http.ts +++ b/shared/src/http.ts @@ -1,6 +1,6 @@ import { NextFunction, Request, Response } from 'express-serve-static-core' import { getConfigOption } from './config/access' -import { respondToInvalidRequest } from './invalidRequestHandler' +import { respondToInvalidRequest } from './invalidRequest' import { log } from './utils/log' /** diff --git a/shared/src/immich/client.ts b/shared/src/immich/client.ts new file mode 100644 index 0000000..9c82c39 --- /dev/null +++ b/shared/src/immich/client.ts @@ -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 { + 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 { + 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) + } +} diff --git a/shared/src/immich/share.ts b/shared/src/immich/share.ts new file mode 100644 index 0000000..ef87800 --- /dev/null +++ b/shared/src/immich/share.ts @@ -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>({ 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 { + 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> { + 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 { + 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 { + 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 + } +} diff --git a/shared/src/index.ts b/shared/src/index.ts new file mode 100644 index 0000000..8a5dc20 --- /dev/null +++ b/shared/src/index.ts @@ -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' diff --git a/shared/src/invalidRequest.ts b/shared/src/invalidRequest.ts new file mode 100644 index 0000000..32a2a5c --- /dev/null +++ b/shared/src/invalidRequest.ts @@ -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) +} diff --git a/shared/src/session.ts b/shared/src/session.ts new file mode 100644 index 0000000..ae11036 --- /dev/null +++ b/shared/src/session.ts @@ -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 /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] +} diff --git a/shared/src/types.ts b/shared/src/types.ts new file mode 100644 index 0000000..51977be --- /dev/null +++ b/shared/src/types.ts @@ -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; +} diff --git a/shared/src/utils/log.ts b/shared/src/utils/log.ts new file mode 100644 index 0000000..bdb13d5 --- /dev/null +++ b/shared/src/utils/log.ts @@ -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 diff --git a/app/src/utils/sanitize.ts b/shared/src/utils/sanitize.ts similarity index 100% rename from app/src/utils/sanitize.ts rename to shared/src/utils/sanitize.ts diff --git a/app/src/utils/text.ts b/shared/src/utils/text.ts similarity index 100% rename from app/src/utils/text.ts rename to shared/src/utils/text.ts diff --git a/app/src/utils/ttlLruCache.ts b/shared/src/utils/ttlLruCache.ts similarity index 66% rename from app/src/utils/ttlLruCache.ts rename to shared/src/utils/ttlLruCache.ts index b375278..1f6f80f 100644 --- a/app/src/utils/ttlLruCache.ts +++ b/shared/src/utils/ttlLruCache.ts @@ -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: - TTL gives us freshness without rebuilding share state on every asset @@ -66,3 +66,32 @@ export class TtlLruCache { 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 ( + cache: TtlLruCache>, + key: string, + factory: () => Promise, + isValid: (value: T) => boolean = (value) => !!value +): Promise { + 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 +} diff --git a/app/src/utils/webStream.ts b/shared/src/utils/webStream.ts similarity index 100% rename from app/src/utils/webStream.ts rename to shared/src/utils/webStream.ts diff --git a/app/src/view/password.tsx b/shared/src/view/password.tsx similarity index 75% rename from app/src/view/password.tsx rename to shared/src/view/password.tsx index 75f76e9..7487821 100644 --- a/app/src/view/password.tsx +++ b/shared/src/view/password.tsx @@ -1,13 +1,17 @@ +import { jsonForInlineScript } from '../utils/text' + interface PasswordProps { shareKey: string notifyInvalidPassword: boolean + /** Path prefix the app is mounted under, without a trailing slash. Empty at the root. */ + basePath?: string } -const submitScript = ` +const submitScript = (unlockUrl: string) => ` async function submitForm (formElement) { const formData = new FormData(formElement) try { - const res = await fetch('/share/unlock', { + const res = await fetch(${jsonForInlineScript(unlockUrl)}, { method: 'POST', headers: { 'Content-Type': 'application/json' }, 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 ( Password required - - + +
@@ -65,7 +69,7 @@ export function Password ({ shareKey, notifyInvalidPassword }: PasswordProps) {
-