Extract @ipp/core npm workspace package

This commit is contained in:
Alan Grainger
2026-10-05 15:55:18 +13:00
parent 54c0f91c4e
commit d03a77f691
65 changed files with 1056 additions and 746 deletions
+125
View File
@@ -0,0 +1,125 @@
import dayjs from 'dayjs'
import { ImmichVersion, KeyType } from '../types'
import { log } from '../utils/log'
/**
* Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app.
*/
export async function request (endpoint: string, init?: RequestInit) {
try {
const res = await fetch(apiUrl() + endpoint, init)
if (res.status === 200) {
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
return res.json()
} else {
return res
}
} else {
log('Immich API status ' + res.status)
console.log(await res.text())
}
} catch (e) {
log('Unable to reach Immich on ' + process.env.IMMICH_URL)
log(`From the container IPP is running in, run this and check you receive a JSON result: node -e "fetch('${apiUrl()}/server/ping').then(r => r.text()).then(console.log).catch(console.error)"`)
log('Avoid testing with curl - curl uses its own DNS resolver and can succeed even when the resolver Node/IPP uses (musl getaddrinfo) fails. See https://github.com/alangrainger/immich-public-proxy/issues/263')
}
}
export function apiUrl () {
return (process.env.IMMICH_URL || '').replace(/\/*$/, '') + '/api'
}
/**
* Build safely-encoded URL string.
*/
export function buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
// Remove empty properties
params = Object.fromEntries(Object.entries(params).filter(([_, value]) => !!value))
let query = ''
// Safely encode query parameters
if (Object.entries(params).length) {
query = '?' + (new URLSearchParams(params as {
[key: string]: string
})).toString()
}
return baseUrl + query
}
/**
* Check if a provided ID matches the Immich ID format
*/
export function isId (id: string) {
return !!id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
}
/**
* Check if a provided key matches the Immich shared-link key format.
* It appears that the key is always 67 chars long, but since I don't know that this
* will always be the case, I've left it open-ended.
*/
export function isKey (key: string) {
return !!key.match(/^[\w-]+$/)
}
/**
* Map the URL path prefix (`share` or `s`) to the corresponding `KeyType`.
*/
export function getKeyTypeFromShare (shareType: string) {
return shareType === 's' ? KeyType.slug : KeyType.key
}
/**
* Reachability ping for the `/share/healthcheck` route.
*/
export async function accessible () {
return !!(await request('/server/ping'))
}
// Minimum Immich server version IPP is compatible with
export const MIN_IMMICH_VERSION: ImmichVersion = { major: 2, minor: 0, patch: 0 }
const formatVersion = (v: ImmichVersion) => `${v.major}.${v.minor}.${v.patch}`
/**
* Fetch the Immich server version from the public `/server/version` endpoint
* (no auth required). Returns null if Immich is unreachable or the response
* isn't the expected `{ major, minor, patch }` shape.
*/
export async function getImmichVersion (): Promise<ImmichVersion | null> {
const res = await request('/server/version')
if (res && typeof res.major === 'number' && typeof res.minor === 'number' && typeof res.patch === 'number') {
return { major: res.major, minor: res.minor, patch: res.patch }
}
return null
}
/**
* True if `version` is at least MIN_IMMICH_VERSION. A prerelease of the
* minimum version (e.g. 3.0.0-beta) counts as supported.
*/
export function isImmichVersionSupported (version: ImmichVersion): boolean {
if (version.major !== MIN_IMMICH_VERSION.major) return version.major > MIN_IMMICH_VERSION.major
if (version.minor !== MIN_IMMICH_VERSION.minor) return version.minor > MIN_IMMICH_VERSION.minor
return version.patch >= MIN_IMMICH_VERSION.patch
}
/**
* Startup guard. If we can positively confirm the Immich server is older than
* IPP supports, log and exit rather than silently serving broken album shares.
* If the version can't be determined (Immich not yet reachable at boot, or an
* unexpected response), log a warning and continue - a transient blip must not
* crash-loop the container, and per-request handling still copes.
*/
export async function enforceMinimumImmichVersion (): Promise<void> {
const version = await getImmichVersion()
if (!version) {
log('Could not determine the Immich server version. Check that Immich is reachable and running ' + formatVersion(MIN_IMMICH_VERSION) + ' or newer.')
return
}
if (!isImmichVersionSupported(version)) {
console.error(dayjs().format() + ' FATAL: Immich server is version ' + formatVersion(version) + ', but IPP requires Immich ' + formatVersion(MIN_IMMICH_VERSION) + ' or newer.')
process.exit(1)
}
}
+138
View File
@@ -0,0 +1,138 @@
import dayjs from 'dayjs'
import { KeyType, SharedLink, SharedLinkResult } from '../types'
import { log } from '../utils/log'
import { cachedPromise, TtlLruCache } from '../utils/ttlLruCache'
import { apiUrl, buildUrl } from './client'
/*
Immich replaced the deprecated `?password=...` query-param auth for shared
links with `POST /shared-links/login`, which returns an
`immich_shared_link_token` cookie used on subsequent calls. This cache holds
one such token per (keyType, key, password) so the gallery's many asset
requests reuse a single login round-trip. Keying by password is load-bearing
for security: a request without the correct password produces a different
cache key (often empty) and falls through to a fresh login that Immich will
reject - IPP never serves cached tokens to unauthenticated visitors.
*/
const tokenCache = new TtlLruCache<Promise<string | null>>({ ttlMs: 120_000, max: 100 })
/**
* Display title for a shared link. Prefers the user-set link description,
* falls back to the album name (for album shares), or a generic placeholder.
*/
export function title (share: SharedLink): string {
return share.description || share?.album?.albumName || 'Gallery'
}
/**
* Fetch and interpret `GET /shared-links/me` for a key. Uncached: each app
* wraps this with its own cache.
*
* On success the link carries `keyType` and `password`, and whatever `assets`
* Immich sent - an empty array for album shares, which the caller enumerates
* if it needs them. An expired link, an invalid key or an unexpected response
* is `{ valid: false }`; a 401 for anything other than a bad key is
* `passwordRequired`.
*/
export async function fetchSharedLink (key: string, keyType: KeyType = KeyType.key, password?: string): Promise<SharedLinkResult> {
const url = buildUrl(apiUrl() + '/shared-links/me', {
[keyType]: key
})
const headers = await authHeaders(keyType, key, password)
const res = await fetch(url, { headers })
if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) {
const jsonBody = await res.json()
if (jsonBody) {
if (res.status === 200) {
const link = jsonBody as SharedLink
link.keyType = keyType
link.password = password
if (link.expiresAt && dayjs(link.expiresAt) < dayjs()) {
// This link has expired
log('Expired link ' + key)
} else {
return {
valid: true,
link
}
}
} else if (res.status === 401) {
// Immich returns 401 for both invalid keys and password-protected shares.
// Check the message to distinguish between the two cases.
if (jsonBody?.message === 'Invalid share key' || jsonBody?.message === 'Invalid share slug') {
// Known invalid key/slug - treat as invalid request
log('Invalid share key ' + key)
} else {
// Default: treat as password required (fail-safe)
return {
valid: true,
passwordRequired: true
}
}
} else {
console.log(JSON.stringify(jsonBody))
}
}
} else {
// Otherwise return failure
log('Immich response ' + res.status + ' for key ' + key)
try {
console.log(res.headers.get('Content-Type'))
console.log((await res.text()).slice(0, 500))
log('Unexpected response from Immich API at ' + apiUrl())
log('Please make sure the IPP container is able to reach this path.')
} catch (e) {
console.log(e)
}
}
return {
valid: false
}
}
/**
* Build the `Cookie` header that authenticates to Immich for a
* password-protected share. Returns `{}` (no Cookie header) when the share
* has no password or login failed; in those cases Immich will respond 401
* for protected resources, which the caller handles as "password required".
*/
export async function authHeaders (keyType: KeyType, key: string, password?: string): Promise<Record<string, string>> {
if (!password) return {}
const token = await getSharedLinkToken(key, password, keyType)
return token ? { Cookie: `immich_shared_link_token=${token}` } : {}
}
/**
* Cached login: fetch an `immich_shared_link_token` for the given password,
* or return null on failure. The cache is per (keyType, key, password) so
* that a request without the correct password can't reuse another visitor's
* authenticated session. See `tokenCache` doc-comment for the security
* argument.
*/
function getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
const cacheKey = `${keyType}:${key}:${password}`
// Default eviction (falsy is invalid) drops a null/empty token, so a failed
// login is never cached.
return cachedPromise(tokenCache, cacheKey, () => sharedLinkLogin(key, password, keyType))
}
/**
* `POST /shared-links/login`. Replaces the deprecated `?password=...` query
* param. Returns the cookie value on success, null on any failure.
*/
async function sharedLinkLogin (key: string, password: string, keyType: KeyType): Promise<string | null> {
const url = buildUrl(apiUrl() + '/shared-links/login', { [keyType]: key })
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password })
})
if (res.status !== 201) return null
const setCookie = res.headers.get('set-cookie') || ''
const match = setCookie.match(/immich_shared_link_token=([^;,]+)/)
return match ? match[1] : null
} catch (e) {
return null
}
}