fix(immich): a server with a self-signed certificate can be connected, as the other providers can

Synology Photos, AirTrail and Dawarich each have a switch to trust a
self-signed certificate; Immich had none, so every request to such a
server failed with a bare "fetch failed" (#2475).

Immich gets the same switch, per user and off by default:

- users.immich_allow_insecure_tls (migration 243, column guarded) and a
  settings row labelled with the existing skipSSLVerification string, so
  no new translations. The settings card on desktop and phone draws it
  from that row.
- Every request to the user's Immich (status, browse, search, asset info
  and proxy, albums, upload) passes rejectUnauthorized from the switch.
  Only 1 counts as on. A shared photo follows its owner's switch, since
  it goes to the owner's server with the owner's key.
- Settings PUT and the connection test take allow_insecure_tls as a
  boolean. Absent on a save keeps the stored choice, so an older client
  cannot clear it; disconnecting turns it off again.
- A failed request names its cause, e.g. "fetch failed (self-signed
  certificate)", instead of only the undici message.
- The upload mirror gets a timeout: the journey upload waits on it.

Fresh installs also never showed "Mirror journey photos to Immich on
upload": migration 112 added that row only where the Immich provider
already existed, and on a new database the seeds create it after the
migrations. The row is now in the seeds, and migration 243 adds it where
the provider exists without it.

Wiki: Photo-Providers.md documents the switch.
This commit is contained in:
Maurice
2026-09-23 16:12:18 +02:00
parent 41b14ebc2a
commit ae80ad266d
17 changed files with 704 additions and 53 deletions
+31
View File
@@ -5226,6 +5226,37 @@ function runMigrations(db: Database.Database): void {
const seated = reseatBookedNights(db);
if (seated > 0) console.log(`[DB] Seated ${seated} booked night(s) at the head of their day`);
},
/*
* Immich learns the switch Synology, AirTrail and Dawarich already have: a
* server behind a self-signed certificate can be trusted per user (#2475).
* Off by default, and only 1 counts as on.
*
* The two settings rows are the toggle for it and the auto-upload toggle
* migration 112 meant to add. That one only ran where the Immich provider
* row already existed, which on a fresh install it never did (the seeds run
* after the migrations), so fresh installs never showed the upload toggle.
* Both rows are in seeds.ts as well for the same reason; here they reach the
* installs that already have the provider row. Re-runnable.
*/
() => {
const hasColumn = db
.prepare("SELECT 1 FROM pragma_table_info('users') WHERE name = 'immich_allow_insecure_tls'")
.get();
if (!hasColumn) {
db.exec('ALTER TABLE users ADD COLUMN immich_allow_insecure_tls INTEGER NOT NULL DEFAULT 0');
}
const hasImmich = db.prepare("SELECT 1 FROM photo_providers WHERE id = 'immich'").get();
if (hasImmich) {
db.exec(`
INSERT OR IGNORE INTO photo_provider_fields
(provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order)
VALUES
('immich', 'immich_allow_insecure_tls', 'skipSSLVerification', 'checkbox', NULL, NULL, 0, 0, 'allow_insecure_tls', 'allow_insecure_tls', 2),
('immich', 'immich_auto_upload', 'immichAutoUpload', 'checkbox', NULL, NULL, 0, 0, 'auto_upload', 'auto_upload', 5)
`);
}
},
];
if (currentVersion < migrations.length) {
+2
View File
@@ -155,6 +155,8 @@ function seedAddons(db: Database.Database): void {
const providerFields = [
{ provider_id: 'immich', field_key: 'immich_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://immich.example.com', hint: null, required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 },
{ provider_id: 'immich', field_key: 'immich_api_key', label: 'providerApiKey', input_type: 'password', placeholder: 'API Key', hint: null, required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 },
{ provider_id: 'immich', field_key: 'immich_allow_insecure_tls', label: 'skipSSLVerification', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, settings_key: 'allow_insecure_tls', payload_key: 'allow_insecure_tls', sort_order: 2 },
{ provider_id: 'immich', field_key: 'immich_auto_upload', label: 'immichAutoUpload', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, settings_key: 'auto_upload', payload_key: 'auto_upload', sort_order: 5 },
{ provider_id: 'synologyphotos', field_key: 'synology_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://synology.example.com/photo', hint: 'providerUrlHintSynology', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'synology_url', sort_order: 0 },
{ provider_id: 'synologyphotos', field_key: 'synology_username', label: 'providerUsername', input_type: 'text', placeholder: 'Username', hint: null, required: 1, secret: 0, settings_key: 'synology_username', payload_key: 'synology_username', sort_order: 1 },
{ provider_id: 'synologyphotos', field_key: 'synology_password', label: 'providerPassword', input_type: 'password', placeholder: 'Password', hint: null, required: 1, secret: 1, settings_key: null, payload_key: 'synology_password', sort_order: 2 },
@@ -35,8 +35,10 @@ export class ImmichMemoriesController {
@Req() req: Request,
@Res() res: Response,
): Promise<void> {
const { immich_url, immich_api_key, auto_upload } = body;
const result = await this.memories.immichSaveSettings(user.id, immich_url, immich_api_key, getClientIp(req));
const { immich_url, immich_api_key, auto_upload, allow_insecure_tls } = body;
// Absent stays undefined and leaves the stored choice alone, so an older
// client cannot clear it by saving.
const result = await this.memories.immichSaveSettings(user.id, immich_url, immich_api_key, getClientIp(req), allow_insecure_tls);
if (!result.success) {
res.status(400).json({ error: result.error });
return;
@@ -59,11 +61,11 @@ export class ImmichMemoriesController {
@Post('test')
@HttpCode(200)
async test(@Body() body: ImmichTestDto) {
const { immich_url, immich_api_key } = body;
const { immich_url, immich_api_key, allow_insecure_tls } = body;
if (!immich_url || !immich_api_key) {
return { connected: false, error: 'URL and API key required' };
}
return this.memories.immichTestConnection(immich_url, immich_api_key);
return this.memories.immichTestConnection(immich_url, immich_api_key, allow_insecure_tls === true);
}
@Get('browse')
+75 -31
View File
@@ -1,14 +1,14 @@
import { Injectable } from '@nestjs/common';
import type { Response } from 'express';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf, safeFetch } from '../../utils/ssrfGuard';
import { checkSsrf, safeFetch, type SafeFetchOptions } from '../../utils/ssrfGuard';
import { AuditService } from '../audit/audit.service';
import { StorageService } from '../storage/storage.service';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import { DatabaseService } from '../database/database.service';
import { MemoriesAccessService } from './memories-access.service';
import { fail, handleServiceResult, isWithinLocalDayRange, pipeAsset, shiftCalendarDay, sortAssetsByTakenAtDesc, type Selection } from './memories.helpers';
import { describeFetchFailure, fail, handleServiceResult, isWithinLocalDayRange, pipeAsset, shiftCalendarDay, sortAssetsByTakenAtDesc, type Selection } from './memories.helpers';
const ALBUM_PAGE_SIZE = 1000;
const ALBUM_MAX_PAGES = 20;
@@ -23,6 +23,25 @@ const ALBUM_MAX_PAGES = 20;
* partial page for every page the caller asks for.
*/
const SEARCH_MAX_RAW_PAGES = 20;
/** A mirrored journey upload is one photo; a server that sits on it this long is not coming back. */
const UPLOAD_TIMEOUT_MS = 60_000;
/** One user's Immich connection, as every request to that server needs it. */
export interface ImmichCreds {
immich_url: string;
immich_api_key: string;
/** The user trusts a self-signed certificate on this server (#2475). */
allow_insecure_tls: boolean;
}
/**
* The TLS half of every request to a user's Immich. The certificate check is
* the only thing the switch relaxes: the SSRF guard and the DNS pinning still
* run on every hop.
*/
function tlsOptions(allowInsecureTls: boolean): SafeFetchOptions {
return { rejectUnauthorized: !allowInsecureTls };
}
/**
* Immich photo provider: credentials, connection test, timeline/search browsing,
@@ -40,12 +59,19 @@ export class ImmichService {
private readonly storage: StorageService,
) {}
getImmichCredentials(userId: number) {
const user = this.db.prepare('SELECT immich_url, immich_api_key FROM users WHERE id = ?').get(userId) as any;
getImmichCredentials(userId: number): ImmichCreds | null {
const user = this.db
.prepare('SELECT immich_url, immich_api_key, immich_allow_insecure_tls FROM users WHERE id = ?')
.get(userId) as { immich_url: string | null; immich_api_key: string | null; immich_allow_insecure_tls: number | null } | undefined;
if (!user?.immich_url || !user?.immich_api_key) return null;
const apiKey = decrypt_api_key(user.immich_api_key);
if (!apiKey) return null;
return { immich_url: user.immich_url as string, immich_api_key: apiKey };
return {
immich_url: user.immich_url,
immich_api_key: apiKey,
// Fail closed: anything but an explicit 1 keeps the certificate check on.
allow_insecure_tls: user.immich_allow_insecure_tls === 1,
};
}
/** Validate that an asset ID is a safe UUID-like string (no path traversal). */
@@ -73,11 +99,14 @@ export class ImmichService {
getConnectionSettings(userId: number) {
const creds = this.getImmichCredentials(userId);
const prefs = this.db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined;
const prefs = this.db
.prepare('SELECT immich_auto_upload, immich_allow_insecure_tls FROM users WHERE id = ?')
.get(userId) as { immich_auto_upload?: number; immich_allow_insecure_tls?: number } | undefined;
return {
immich_url: creds?.immich_url || '',
connected: !!(creds?.immich_url && creds?.immich_api_key),
auto_upload: !!(prefs?.immich_auto_upload),
allow_insecure_tls: prefs?.immich_allow_insecure_tls === 1,
};
}
@@ -85,11 +114,17 @@ export class ImmichService {
this.db.prepare('UPDATE users SET immich_auto_upload = ? WHERE id = ?').run(enabled ? 1 : 0, userId);
}
/**
* `allowInsecureTls` left undefined keeps the stored choice, so a client that
* does not know the switch cannot clear it by saving. Disconnecting (no URL)
* always turns it off again.
*/
async saveImmichSettings(
userId: number,
immichUrl: string | undefined,
immichApiKey: string | undefined,
clientIp: string | null
clientIp: string | null,
allowInsecureTls?: boolean,
): Promise<{ success: boolean; warning?: string; error?: string }> {
if (immichUrl) {
if (immichUrl.endsWith('/')) {
@@ -99,11 +134,16 @@ export class ImmichService {
if (!ssrf.allowed) {
return { success: false, error: `Invalid Immich URL: ${ssrf.error}` };
}
this.db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run(
immichUrl.trim(),
maybe_encrypt_api_key(immichApiKey),
userId
);
this.db
.prepare(
'UPDATE users SET immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = COALESCE(?, immich_allow_insecure_tls) WHERE id = ?',
)
.run(
immichUrl.trim(),
maybe_encrypt_api_key(immichApiKey),
allowInsecureTls === undefined ? null : Number(allowInsecureTls),
userId,
);
if (ssrf.isPrivate) {
this.audit.writeAudit({
userId,
@@ -117,7 +157,7 @@ export class ImmichService {
};
}
} else {
this.db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run(
this.db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = 0 WHERE id = ?').run(
null,
maybe_encrypt_api_key(immichApiKey),
userId
@@ -130,7 +170,8 @@ export class ImmichService {
async testConnection(
immichUrl: string,
immichApiKey: string
immichApiKey: string,
allowInsecureTls = false,
): Promise<{ connected: boolean; error?: string; user?: { name?: string; email?: string }; canonicalUrl?: string }> {
if (immichUrl.endsWith('/')) {
immichUrl = immichUrl.slice(0, -1);
@@ -141,7 +182,7 @@ export class ImmichService {
const resp = await safeFetch(`${immichUrl}/api/users/me`, {
headers: { 'x-api-key': immichApiKey, 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000) as any,
});
}, tlsOptions(allowInsecureTls));
if (!resp.ok) return { connected: false, error: `HTTP ${resp.status}` };
const data = await resp.json() as { name?: string; email?: string };
@@ -162,7 +203,7 @@ export class ImmichService {
return { connected: true, user: { name: data.name, email: data.email }, canonicalUrl };
} catch (err: unknown) {
return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' };
return { connected: false, error: describeFetchFailure(err) };
}
}
@@ -175,12 +216,12 @@ export class ImmichService {
const resp = await safeFetch(`${creds.immich_url}/api/users/me`, {
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { connected: false, error: `HTTP ${resp.status}` };
const data = await resp.json() as { name?: string; email?: string };
return { connected: true, user: { name: data.name, email: data.email } };
} catch (err: unknown) {
return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' };
return { connected: false, error: describeFetchFailure(err) };
}
}
@@ -197,7 +238,7 @@ export class ImmichService {
method: 'GET',
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { error: 'Failed to fetch from Immich', status: resp.status };
const buckets = await resp.json();
return { buckets };
@@ -214,7 +255,7 @@ export class ImmichService {
* that has to stay identical on every page of the same search.
*/
private async fetchSearchPage(
creds: { immich_url: string; immich_api_key: string },
creds: ImmichCreds,
from: string | undefined,
to: string | undefined,
page: number,
@@ -258,7 +299,7 @@ export class ImmichService {
page,
}),
signal: AbortSignal.timeout(15000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { status: resp.status };
const data = await resp.json() as { assets?: { items?: any[] } };
return { items: data.assets?.items || [] };
@@ -354,7 +395,7 @@ export class ImmichService {
const resp = await safeFetch(`${creds.immich_url}/api/assets/${assetId}`, {
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { error: 'Failed', status: resp.status };
const asset = await resp.json() as any;
return {
@@ -398,7 +439,7 @@ export class ImmichService {
const resp = await safeFetch(url, {
headers: { 'x-api-key': creds.immich_api_key },
signal: AbortSignal.timeout(10000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { error: 'Upstream error', status: resp.status };
const contentType = resp.headers.get('content-type') || 'image/jpeg';
const bytes = Buffer.from(await resp.arrayBuffer());
@@ -459,7 +500,7 @@ export class ImmichService {
timeout = 30000;
}
await pipeAsset(url, response, headers, timeout ? AbortSignal.timeout(timeout) : undefined, cacheControl);
await pipeAsset(url, response, headers, timeout ? AbortSignal.timeout(timeout) : undefined, cacheControl, tlsOptions(creds.allow_insecure_tls));
}
// ── Albums ──────────────────────────────────────────────────────────────────
@@ -476,11 +517,11 @@ export class ImmichService {
safeFetch(`${creds.immich_url}/api/albums`, {
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000) as any,
}),
}, tlsOptions(creds.allow_insecure_tls)),
safeFetch(`${creds.immich_url}/api/albums?shared=true`, {
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000) as any,
}),
}, tlsOptions(creds.allow_insecure_tls)),
]);
if (!ownResp.ok) return { error: 'Failed to fetch albums', status: ownResp.status };
const ownAlbums = await ownResp.json() as any[];
@@ -534,13 +575,13 @@ export class ImmichService {
* the search path is correct. A version probe with a wrong boundary would not be.
*/
private async fetchAlbumAssets(
creds: { immich_url: string; immich_api_key: string },
creds: ImmichCreds,
albumId: string,
): Promise<{ assets?: any[]; status?: number }> {
const resp = await safeFetch(`${creds.immich_url}/api/albums/${albumId}`, {
headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { status: resp.status };
const albumData = await resp.json() as { assets?: any[] };
@@ -557,7 +598,7 @@ export class ImmichService {
* it Immich omits `exifInfo` entirely and every photo's city/country goes null.
*/
private async fetchAlbumAssetsViaSearch(
creds: { immich_url: string; immich_api_key: string },
creds: ImmichCreds,
albumId: string,
): Promise<{ assets?: any[]; status?: number }> {
const all: any[] = [];
@@ -575,7 +616,7 @@ export class ImmichService {
page,
}),
signal: AbortSignal.timeout(15000) as any,
});
}, tlsOptions(creds.allow_insecure_tls));
if (!resp.ok) return { status: resp.status };
const data = await resp.json() as { assets?: { items?: any[] } };
@@ -710,7 +751,10 @@ export class ImmichService {
'Content-Length': String(body.length),
},
body,
});
// The journey upload waits on this mirror, so a server that never
// answers must not hold the upload open with it.
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
}, tlsOptions(creds.allow_insecure_tls));
if (res.ok) {
const data = await res.json() as { id?: string };
@@ -213,6 +213,24 @@ export type AssetInfo = {
fileName?: string | null;
}
/**
* Why a request to a provider never got an answer, worded for the settings card.
*
* undici rejects with a bare "fetch failed" and keeps the reason on `cause`
* (an unknown host, a refused connection, a self-signed certificate), so the
* message alone gave the user nothing to act on (#2475). The first cause that
* says something is appended; an error without one reads exactly as before.
*/
export function describeFetchFailure(err: unknown): string {
if (!(err instanceof Error)) return 'Connection failed';
let cause: unknown = err.cause;
for (let depth = 0; depth < 3 && cause instanceof Error; depth++) {
if (cause.message && cause.message !== err.message) return `${err.message} (${cause.message})`;
cause = cause.cause;
}
return err.message;
}
/**
* Proxy an upstream asset straight to the client.
*
+4 -4
View File
@@ -67,8 +67,8 @@ export class MemoriesService {
return this.immich.getConnectionSettings(userId);
}
immichSaveSettings(userId: number, immichUrl: string | undefined, immichApiKey: string | undefined, clientIp: string | null) {
return this.immich.saveImmichSettings(userId, immichUrl, immichApiKey, clientIp);
immichSaveSettings(userId: number, immichUrl: string | undefined, immichApiKey: string | undefined, clientIp: string | null, allowInsecureTls?: boolean) {
return this.immich.saveImmichSettings(userId, immichUrl, immichApiKey, clientIp, allowInsecureTls);
}
immichSetAutoUpload(userId: number, enabled: boolean): void {
@@ -79,8 +79,8 @@ export class MemoriesService {
return this.immich.getConnectionStatus(userId);
}
immichTestConnection(immichUrl: string, immichApiKey: string) {
return this.immich.testConnection(immichUrl, immichApiKey);
immichTestConnection(immichUrl: string, immichApiKey: string, allowInsecureTls: boolean) {
return this.immich.testConnection(immichUrl, immichApiKey, allowInsecureTls);
}
immichBrowseTimeline(userId: number) {