Fix #214 - replace deprecated query password with POST

This commit is contained in:
Alan Grainger
2026-05-30 11:32:45 +08:00
parent 533363aca6
commit d500418500
2 changed files with 97 additions and 17 deletions
+91 -11
View File
@@ -45,14 +45,29 @@ const shareCache = new Map<string, ShareCacheEntry>()
const shareCacheTtlMs = 120_000 const shareCacheTtlMs = 120_000
const shareCacheMax = 100 const shareCacheMax = 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.
*/
type TokenCacheEntry = { promise: Promise<string | null>; expiresAt: number }
const tokenCache = new Map<string, TokenCacheEntry>()
const tokenCacheTtlMs = 120_000
const tokenCacheMax = 100
class Immich { class Immich {
/** /**
* Make a request to Immich API. We're not using the SDK to limit * Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app. * the possible attack surface of this app.
*/ */
async request (endpoint: string) { async request (endpoint: string, init?: RequestInit) {
try { try {
const res = await fetch(this.apiUrl() + endpoint) const res = await fetch(this.apiUrl() + endpoint, init)
if (res.status === 200) { if (res.status === 200) {
const contentType = res.headers.get('Content-Type') || '' const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) { if (contentType.includes('application/json')) {
@@ -212,10 +227,10 @@ class Immich {
private async fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> { private async fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
let link let link
const url = this.buildUrl(this.apiUrl() + '/shared-links/me', { const url = this.buildUrl(this.apiUrl() + '/shared-links/me', {
[keyType]: key, [keyType]: key
password
}) })
const res = await fetch(url) const headers = await this.authHeaders(keyType, key, password)
const res = await fetch(url, { headers })
if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) { if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) {
const jsonBody = await res.json() const jsonBody = await res.json()
if (jsonBody) { if (jsonBody) {
@@ -228,9 +243,8 @@ class Immich {
// the array of assets // the array of assets
if (link.type === AlbumType.album) { if (link.type === AlbumType.album) {
const albumRes = await fetch(this.buildUrl(this.apiUrl() + '/albums/' + link?.album?.id, { const albumRes = await fetch(this.buildUrl(this.apiUrl() + '/albums/' + link?.album?.id, {
[keyType]: key, [keyType]: key
password }), { headers })
}))
const album = await albumRes.json() as Album const album = await albumRes.json() as Album
if (!album?.id) { if (!album?.id) {
log('Invalid album ID - ' + link?.album?.id) log('Invalid album ID - ' + link?.album?.id)
@@ -306,13 +320,79 @@ class Immich {
* Get the content-type of a video, for the lightbox <video> element * Get the content-type of a video, for the lightbox <video> element
*/ */
async getVideoContentType (asset: Asset) { async getVideoContentType (asset: Asset) {
const headers = await this.authHeaders(asset.keyType, asset.key, asset.password)
const data = await this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', { const data = await this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
[asset.keyType]: asset.key, [asset.keyType]: asset.key
password: asset.password }), { headers })
}))
return data.headers.get('Content-Type') return data.headers.get('Content-Type')
} }
/**
* 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".
*/
async authHeaders (keyType: KeyType, key: string, password?: string): Promise<Record<string, string>> {
if (!password) return {}
const token = await this.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.
*/
private async getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
const cacheKey = `${keyType}:${key}:${password}`
const now = Date.now()
const cached = tokenCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
tokenCache.delete(cacheKey)
tokenCache.set(cacheKey, cached)
return cached.promise
}
const promise = this.sharedLinkLogin(key, password, keyType)
tokenCache.set(cacheKey, {
promise,
expiresAt: now + tokenCacheTtlMs
})
if (tokenCache.size > tokenCacheMax) {
const oldest = tokenCache.keys().next().value
if (oldest !== undefined && oldest !== cacheKey) tokenCache.delete(oldest)
}
promise.then(
(token) => { if (!token) tokenCache.delete(cacheKey) },
() => { tokenCache.delete(cacheKey) }
)
return promise
}
/**
* `POST /shared-links/login`. Replaces the deprecated `?password=...` query
* param.
* Returns the cookie value on success, null on any failure.
*/
private async sharedLinkLogin (key: string, password: string, keyType: KeyType): Promise<string | null> {
const url = this.buildUrl(this.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 * Build safely-encoded URL string
*/ */
+6 -6
View File
@@ -1,6 +1,6 @@
import immich from './immich' import immich from './immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, IncomingShareRequest, SharedLink } from './types' import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType, SharedLink } from './types'
import { canDownload, escapeHtml, getConfigOption, log, toString } from './functions' import { canDownload, escapeHtml, getConfigOption, log, toString } from './functions'
import archiver from 'archiver' import archiver from 'archiver'
import { respondToInvalidRequest } from './invalidRequestHandler' import { respondToInvalidRequest } from './invalidRequestHandler'
@@ -98,10 +98,10 @@ class Render {
const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, { const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
[asset.keyType || 'key']: asset.key, [asset.keyType || 'key']: asset.key,
size: sizeQueryParam, size: sizeQueryParam
password: asset.password
}) })
const data = await fetch(url, { headers: fetchHeaders }) const authHeaders = await immich.authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
const data = await fetch(url, { headers: { ...fetchHeaders, ...authHeaders } })
if (data.status < 200 || data.status >= 300) { if (data.status < 200 || data.status >= 300) {
let immichMessage = '' let immichMessage = ''
@@ -385,9 +385,9 @@ class Render {
const endpoint = this.resolveImageEndpoint(ImageSize.original, asset) const endpoint = this.resolveImageEndpoint(ImageSize.original, asset)
const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, { const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, {
[asset.keyType || 'key']: asset.key, [asset.keyType || 'key']: asset.key,
password: asset.password,
size: endpoint.sizeQueryParam size: endpoint.sizeQueryParam
}) })
const authHeaders = await immich.authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
// Phase 1: get response headers, retrying on transient failure. // Phase 1: get response headers, retrying on transient failure.
// We use AbortController + a clearable timer rather than // We use AbortController + a clearable timer rather than
@@ -404,7 +404,7 @@ class Render {
const controller = new AbortController() const controller = new AbortController()
const headerTimer = setTimeout(() => controller.abort(new Error(`No response headers within ${headerTimeoutMs}ms`)), headerTimeoutMs) const headerTimer = setTimeout(() => controller.abort(new Error(`No response headers within ${headerTimeoutMs}ms`)), headerTimeoutMs)
try { try {
const data = await fetch(url, { signal: controller.signal }) const data = await fetch(url, { signal: controller.signal, headers: authHeaders })
clearTimeout(headerTimer) clearTimeout(headerTimer)
if (data.ok) { if (data.ok) {
response = data response = data