refactor(db): the Immich, Synology and AirTrail columns of users get repositories of their own

UserImmichRepository, UserSynologyRepository and UserAirtrailRepository hold the eighteen connection statements UsersRepository carried, on the same users table and with their statements unchanged, provided through a small module as factories over the EntityManager. ImmichService, SynologyService, AirtrailService and JourneyService inject them instead of the account repository. UserRow drops the dead immich_access_token column (the table keeps it), and a shape test pins the account repository's size.
This commit is contained in:
Maurice
2026-10-10 13:26:38 +02:00
parent 3b58694eb9
commit 8350d04a63
23 changed files with 673 additions and 416 deletions
@@ -0,0 +1,89 @@
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { Users } from '../entities/Users.entity';
import { TrekRepository } from './_shared/trek-repository';
/**
* The AirTrail connection a user keeps on their own `users` row
* (`airtrail_url`, `airtrail_api_key`, `airtrail_allow_insecure_tls`,
* `airtrail_write_enabled`): the statements `AirtrailService` issues, apart
* from the rest of the account in `UsersRepository`. Same table, no move of
* the columns.
*
* The encrypt-in-service discipline of `DawarichConnectionsRepository`: every
* value below is exactly what the SERVICE hands this repository — encrypted,
* plaintext or null, at the same point in the pipeline the raw SQL saw it.
* This repository never calls maybe_encrypt_api_key/decrypt_api_key itself.
*/
export class UserAirtrailRepository extends TrekRepository<Users> {
/** Built over the context-resolving EntityManager, like the repositories MikroORM hands out per entity. */
constructor(em: EntityManager) {
super(em as SqlEntityManager, Users);
}
/** ATC1 (`airtrail.service.ts#readRow`) — `SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailConnRow(id: number): Promise<{
airtrail_url: string | null;
airtrail_api_key: string | null;
airtrail_allow_insecure_tls: number | null;
airtrail_write_enabled: number | null;
} | null> {
const row = await this.findOne(
{ id },
{ fields: ['airtrail_url', 'airtrail_api_key', 'airtrail_allow_insecure_tls', 'airtrail_write_enabled'] },
);
return row
? {
airtrail_url: row.airtrail_url ?? null,
airtrail_api_key: row.airtrail_api_key ?? null,
airtrail_allow_insecure_tls: row.airtrail_allow_insecure_tls ?? null,
airtrail_write_enabled: row.airtrail_write_enabled ?? null,
}
: null;
}
/** ATC2 (`airtrail.service.ts#isAirtrailWriteEnabled`) — `SELECT airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailWriteEnabled(id: number): Promise<number | null> {
const row = await this.findOne({ id }, { fields: ['airtrail_write_enabled'] });
return row?.airtrail_write_enabled ?? null;
}
/**
* ATC3 (`airtrail.service.ts#saveSettings`, newKey branch) — `UPDATE users
* SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls
* = ?, airtrail_write_enabled = ? WHERE id = ?`. **No transaction** — the
* plan's Risks section flags this as a pre-existing asymmetry with
* `DawarichConnectionsRepository`'s equivalent `saveSettings` (which DOES
* wrap its writes in `uow.transactional`): preserved exactly, not
* "fixed" to match Dawarich's shape.
*/
async setAirtrailSettingsWithKey(id: number, url: string | null, apiKey: string, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate(
{ id },
{ airtrail_url: url, airtrail_api_key: apiKey, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled },
);
}
/**
* ATC4 (`airtrail.service.ts#saveSettings`, no-newKey branch) — `UPDATE
* users SET airtrail_url = ?, airtrail_allow_insecure_tls = ?,
* airtrail_write_enabled = ? WHERE id = ?`. Same no-transaction asymmetry
* as {@link setAirtrailSettingsWithKey} — preserved, not fixed.
*/
async setAirtrailSettings(id: number, url: string | null, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_url: url, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled });
}
/**
* ATC5 (`airtrail.service.ts#saveSettings`, URL-cleared branch) — `UPDATE
* users SET airtrail_api_key = NULL WHERE id = ?`. **SECURITY**:
* credential scrub — a cleared URL with no key left makes the connection
* meaningless, so the key is dropped too. Same no-transaction asymmetry
* as the two methods above — this is a THIRD, separate statement in the
* legacy `saveSettings` (its own `if (!trimmedUrl)` branch), not folded
* into {@link setAirtrailSettings}.
*/
async clearAirtrailApiKey(id: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_api_key: null });
}
}
@@ -0,0 +1,104 @@
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { Users } from '../entities/Users.entity';
import { TrekRepository } from './_shared/trek-repository';
import { coalesceOverrideWhileSame } from '../dialect/sql-functions';
/**
* The Immich connection a user keeps on their own `users` row (`immich_url`,
* `immich_api_key`, `immich_allow_insecure_tls`, `immich_auto_upload`): the
* statements `ImmichService` and `JourneyService` issue, apart from the rest
* of the account in `UsersRepository`. Same table, no move of the columns.
*
* Every value stays exactly what the SERVICE hands this repository —
* encrypted, plaintext or null, at the same point in the pipeline the raw SQL
* saw it. This repository never calls `encrypt_api_key`/`decrypt_api_key`/
* `maybe_encrypt_api_key` itself.
*/
export class UserImmichRepository extends TrekRepository<Users> {
/** Built over the context-resolving EntityManager, like the repositories MikroORM hands out per entity. */
constructor(em: EntityManager) {
super(em as SqlEntityManager, Users);
}
/**
* IM1 (`ImmichService.getImmichCredentials`) — `SELECT immich_url,
* immich_api_key, immich_allow_insecure_tls FROM users WHERE id = ?`
* (the TLS switch joined the read with #2475).
*/
async getImmichCredentials(
id: number,
): Promise<{ immich_url: string | null; immich_api_key: string | null; immich_allow_insecure_tls: number | null } | null> {
const row = await this.findOne({ id }, { fields: ['immich_url', 'immich_api_key', 'immich_allow_insecure_tls'] });
return row
? {
immich_url: row.immich_url ?? null,
immich_api_key: row.immich_api_key ?? null,
immich_allow_insecure_tls: row.immich_allow_insecure_tls ?? null,
}
: null;
}
/** JV1 (`JourneyService.immichAutoUploadEnabled`) — `SELECT immich_auto_upload FROM users WHERE id = ?`. */
async getImmichAutoUpload(id: number): Promise<number | null> {
const row = await this.findOne({ id }, { fields: ['immich_auto_upload'] });
return row?.immich_auto_upload ?? null;
}
/**
* IM2 (`ImmichService.getConnectionSettings`'s prefs read) — `SELECT
* immich_auto_upload, immich_allow_insecure_tls FROM users WHERE id = ?`
* (the TLS switch joined the read with #2475).
*/
async getImmichConnectionPrefs(
id: number,
): Promise<{ immich_auto_upload: number | null; immich_allow_insecure_tls: number | null } | null> {
const row = await this.findOne({ id }, { fields: ['immich_auto_upload', 'immich_allow_insecure_tls'] });
return row
? { immich_auto_upload: row.immich_auto_upload ?? null, immich_allow_insecure_tls: row.immich_allow_insecure_tls ?? null }
: null;
}
/** IM3 (`ImmichService.setImmichAutoUpload`) — `UPDATE users SET immich_auto_upload = ? WHERE id = ?`. */
async setImmichAutoUpload(id: number, enabled: number): Promise<void> {
await this.nativeUpdate({ id }, { immich_auto_upload: enabled });
}
/**
* IM4 (`ImmichService.saveImmichSettings`'s URL branch) — `UPDATE users SET
* immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = CASE WHEN
* immich_url IS ? THEN COALESCE(?, immich_allow_insecure_tls) ELSE
* COALESCE(?, 0) END WHERE id = ?` (#2475).
*
* One statement, as the legacy write was: SET expressions read the row as
* it was, so the CASE compares the STORED url with the new one and decides
* the switch inside the UPDATE itself (`coalesceOverrideWhileSame`).
* `allow_insecure_tls` null keeps the stored choice while the URL stays the
* same, and a new URL without an explicit value starts off.
*/
async setImmichSettings(
id: number,
immich_url: string,
immich_api_key: string | null,
allow_insecure_tls: number | null,
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
{ id },
{
immich_url,
immich_api_key,
immich_allow_insecure_tls: coalesceOverrideWhileSame(platform, allow_insecure_tls, 'immich_allow_insecure_tls', 'immich_url', immich_url),
},
);
}
/**
* IM5 (`ImmichService.saveImmichSettings`'s disconnect branch) — `UPDATE
* users SET immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = 0
* WHERE id = ?` with a `null` URL: disconnecting always turns the switch off.
*/
async clearImmichSettings(id: number, immich_api_key: string | null): Promise<void> {
await this.nativeUpdate({ id }, { immich_url: null, immich_api_key, immich_allow_insecure_tls: 0 });
}
}
@@ -0,0 +1,111 @@
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { Users } from '../entities/Users.entity';
import { TrekRepository } from './_shared/trek-repository';
/**
* The six Synology credential/session columns `_readSynologyUser` reads
* selectively — a closed union, not a dynamic column string, matching
* `InstanceApiKeyName`'s reasoning in `Users.repository.ts`.
*/
export type SynologyUserColumn = 'synology_url' | 'synology_username' | 'synology_password' | 'synology_sid' | 'synology_did' | 'synology_skip_ssl';
/**
* {@link UserSynologyRepository.getSynologyFields}'s return shape — structurally
* identical to `synology.service.ts`'s own `SynologyUserRecord` (every field
* optional, so an unrequested column is simply absent), deliberately
* defined here rather than imported from the service: a repository does not
* depend on a domain service's types, and the two stay structurally
* assignable without either side casting.
*/
export interface SynologyFieldsRow {
synology_url?: string | null;
synology_username?: string | null;
synology_password?: string | null;
synology_sid?: string | null;
synology_did?: string | null;
synology_skip_ssl?: number | null;
}
/**
* The Synology Photos connection a user keeps on their own `users` row
* (`synology_url`, `synology_username`, `synology_password`, `synology_sid`,
* `synology_did`, `synology_skip_ssl`): the statements `SynologyService`
* issues, apart from the rest of the account in `UsersRepository`. Same
* table, no move of the columns. Values stay as the service hands them in
* (the password encrypted by the service, never here).
*/
export class UserSynologyRepository extends TrekRepository<Users> {
/** Built over the context-resolving EntityManager, like the repositories MikroORM hands out per entity. */
constructor(em: EntityManager) {
super(em as SqlEntityManager, Users);
}
/**
* SY1 (`SynologyService._readSynologyUser`) — `SELECT synology_url,
* synology_username, synology_password, synology_sid, synology_did,
* synology_skip_ssl FROM users WHERE id = ?`, column-filtered in JS by the
* legacy code. This method selects only the requested columns (MikroORM's
* typed `fields`) rather than all six and filtering after — the RESULT is
* identical (only the requested keys populated, matching the legacy
* `filtered` object exactly; an unrequested key is `undefined`, same as
* the legacy object never having had it set). `null` means no such user
* row (SY1's "User not found" branch).
*
* Explicit per-column `if` guards, not a generic `Pick<UserRow, K>` +
* indexed-assignment loop: MikroORM's `fields` option types against
* `AutoPath<Users, K, ...>`, which does not resolve for a free type
* parameter `K` the way it does for the concrete literal union used here
* (the same reason `getApiKeyColumn` above stays non-generic); an
* indexed-assignment loop over a union key has the identical problem on
* the write side. Six `if`s reads worse but needs neither a generic nor a
* cast.
*/
async getSynologyFields(id: number, columns: SynologyUserColumn[]): Promise<SynologyFieldsRow | null> {
const row = await this.findOne({ id }, { fields: columns });
if (!row) return null;
const result: SynologyFieldsRow = {};
if (columns.includes('synology_url')) result.synology_url = row.synology_url ?? null;
if (columns.includes('synology_username')) result.synology_username = row.synology_username ?? null;
if (columns.includes('synology_password')) result.synology_password = row.synology_password ?? null;
if (columns.includes('synology_sid')) result.synology_sid = row.synology_sid ?? null;
if (columns.includes('synology_did')) result.synology_did = row.synology_did ?? null;
if (columns.includes('synology_skip_ssl')) result.synology_skip_ssl = row.synology_skip_ssl;
return result;
}
/** SY2 (`SynologyService._clearSynologySID`) — `UPDATE users SET synology_sid = NULL WHERE id = ?`. */
async clearSynologySID(id: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid: null });
}
/** SY3 (`SynologyService._clearSynologySession`) — `UPDATE users SET synology_sid = NULL, synology_did = NULL WHERE id = ?`. */
async clearSynologySession(id: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid: null, synology_did: null });
}
/**
* SY4/SY7 (`SynologyService._getSynologySession`'s session-refresh write,
* `testSynologyConnection`'s sid persist) — byte-identical `UPDATE users
* SET synology_sid = ? WHERE id = ?` at both legacy sites, one method (D4).
*/
async setSynologySid(id: number, synology_sid: string): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid });
}
/** SY5 (`SynologyService.updateSynologySettings`) — `UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ?, synology_skip_ssl = ? WHERE id = ?`. */
async setSynologySettings(id: number, synology_url: string, synology_username: string, synology_password: string | null, synology_skip_ssl: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_url, synology_username, synology_password, synology_skip_ssl });
}
/** SY6 (`SynologyService.getSynologyStatus`) — `SELECT synology_username FROM users WHERE id = ?`. */
async getSynologyUsername(id: number): Promise<string | null> {
const row = await this.findOne({ id }, { fields: ['synology_username'] });
return row?.synology_username ?? null;
}
/** SY8 (`SynologyService.testSynologyConnection`'s did persist) — `UPDATE users SET synology_did = ? WHERE id = ?`. */
async setSynologyDid(id: number, synology_did: string): Promise<void> {
await this.nativeUpdate({ id }, { synology_did });
}
}
+10 -260
View File
@@ -1,6 +1,6 @@
import { Users } from '../entities/Users.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { coalesce, coalesceOverrideWhileSame, columnIncrementedBy, currentTimestamp, lower, lowerParam } from '../dialect/sql-functions';
import { coalesce, columnIncrementedBy, currentTimestamp, lower, lowerParam } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import { UniqueConstraintViolationException } from '@mikro-orm/core';
@@ -41,7 +41,6 @@ export interface UserRow {
mfa_secret: string | null;
mfa_backup_codes: string | null;
immich_url: string | null;
immich_access_token: string | null;
synology_url: string | null;
synology_username: string | null;
synology_password: string | null;
@@ -66,7 +65,15 @@ export interface UserRow {
immich_allow_insecure_tls: number;
}
const _userRowKeys: AssertRowKeys<UserRow, Users> = true;
/**
* Columns the table still holds but no code reads or writes, left out of
* {@link UserRow}: `immich_access_token` predates `immich_api_key` and has been
* dead since. The column stays (old databases have it, and migrations are
* append-only), so a row read whole still carries it; only the type drops it.
*/
type DeadUserColumns = 'immich_access_token';
const _userRowKeys: AssertRowKeys<UserRow, Omit<Users, DeadUserColumns>> = true;
/** `AuthService.registerUser` (AU10) / `OidcService.findOrCreateUser` (O14) — the two column sets `insertUser` covers as one method (Task 1 brief's Required set: "one method, nullable oidc/avatar fields"). */
export interface NewUserRow {
@@ -1235,164 +1242,6 @@ export class UsersRepository extends TrekRepository<Users> {
return row ? { id: row.id, username: row.username } : undefined;
}
// ---------------------------------------------------------------------
// Plan 3e Task 7 (memories' provider half) — additive: the Immich/Synology
// encrypted-credential statements (IM1-5/SY1-8, inventory §7d, R6). Every
// value stays exactly what the SERVICE (`ImmichService`/`SynologyService`)
// hands this repository — encrypted, plaintext or null, at the same point
// in the pipeline the raw SQL saw it. This repository never calls
// `encrypt_api_key`/`decrypt_api_key`/`maybe_encrypt_api_key` itself.
// ---------------------------------------------------------------------
/**
* IM1 (`ImmichService.getImmichCredentials`) — `SELECT immich_url,
* immich_api_key, immich_allow_insecure_tls FROM users WHERE id = ?`
* (the TLS switch joined the read with #2475).
*/
async getImmichCredentials(
id: number,
): Promise<{ immich_url: string | null; immich_api_key: string | null; immich_allow_insecure_tls: number | null } | null> {
const row = await this.findOne({ id }, { fields: ['immich_url', 'immich_api_key', 'immich_allow_insecure_tls'] });
return row
? {
immich_url: row.immich_url ?? null,
immich_api_key: row.immich_api_key ?? null,
immich_allow_insecure_tls: row.immich_allow_insecure_tls ?? null,
}
: null;
}
/** JV1 (`JourneyService.immichAutoUploadEnabled`) — `SELECT immich_auto_upload FROM users WHERE id = ?`. */
async getImmichAutoUpload(id: number): Promise<number | null> {
const row = await this.findOne({ id }, { fields: ['immich_auto_upload'] });
return row?.immich_auto_upload ?? null;
}
/**
* IM2 (`ImmichService.getConnectionSettings`'s prefs read) — `SELECT
* immich_auto_upload, immich_allow_insecure_tls FROM users WHERE id = ?`
* (the TLS switch joined the read with #2475).
*/
async getImmichConnectionPrefs(
id: number,
): Promise<{ immich_auto_upload: number | null; immich_allow_insecure_tls: number | null } | null> {
const row = await this.findOne({ id }, { fields: ['immich_auto_upload', 'immich_allow_insecure_tls'] });
return row
? { immich_auto_upload: row.immich_auto_upload ?? null, immich_allow_insecure_tls: row.immich_allow_insecure_tls ?? null }
: null;
}
/** IM3 (`ImmichService.setImmichAutoUpload`) — `UPDATE users SET immich_auto_upload = ? WHERE id = ?`. */
async setImmichAutoUpload(id: number, enabled: number): Promise<void> {
await this.nativeUpdate({ id }, { immich_auto_upload: enabled });
}
/**
* IM4 (`ImmichService.saveImmichSettings`'s URL branch) — `UPDATE users SET
* immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = CASE WHEN
* immich_url IS ? THEN COALESCE(?, immich_allow_insecure_tls) ELSE
* COALESCE(?, 0) END WHERE id = ?` (#2475).
*
* One statement, as the legacy write was: SET expressions read the row as
* it was, so the CASE compares the STORED url with the new one and decides
* the switch inside the UPDATE itself (`coalesceOverrideWhileSame`).
* `allow_insecure_tls` null keeps the stored choice while the URL stays the
* same, and a new URL without an explicit value starts off.
*/
async setImmichSettings(
id: number,
immich_url: string,
immich_api_key: string | null,
allow_insecure_tls: number | null,
): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate(
{ id },
{
immich_url,
immich_api_key,
immich_allow_insecure_tls: coalesceOverrideWhileSame(platform, allow_insecure_tls, 'immich_allow_insecure_tls', 'immich_url', immich_url),
},
);
}
/**
* IM5 (`ImmichService.saveImmichSettings`'s disconnect branch) — `UPDATE
* users SET immich_url = ?, immich_api_key = ?, immich_allow_insecure_tls = 0
* WHERE id = ?` with a `null` URL: disconnecting always turns the switch off.
*/
async clearImmichSettings(id: number, immich_api_key: string | null): Promise<void> {
await this.nativeUpdate({ id }, { immich_url: null, immich_api_key, immich_allow_insecure_tls: 0 });
}
/**
* SY1 (`SynologyService._readSynologyUser`) — `SELECT synology_url,
* synology_username, synology_password, synology_sid, synology_did,
* synology_skip_ssl FROM users WHERE id = ?`, column-filtered in JS by the
* legacy code. This method selects only the requested columns (MikroORM's
* typed `fields`) rather than all six and filtering after — the RESULT is
* identical (only the requested keys populated, matching the legacy
* `filtered` object exactly; an unrequested key is `undefined`, same as
* the legacy object never having had it set). `null` means no such user
* row (SY1's "User not found" branch).
*
* Explicit per-column `if` guards, not a generic `Pick<UserRow, K>` +
* indexed-assignment loop: MikroORM's `fields` option types against
* `AutoPath<Users, K, ...>`, which does not resolve for a free type
* parameter `K` the way it does for the concrete literal union used here
* (the same reason `getApiKeyColumn` above stays non-generic); an
* indexed-assignment loop over a union key has the identical problem on
* the write side. Six `if`s reads worse but needs neither a generic nor a
* cast.
*/
async getSynologyFields(id: number, columns: SynologyUserColumn[]): Promise<SynologyFieldsRow | null> {
const row = await this.findOne({ id }, { fields: columns });
if (!row) return null;
const result: SynologyFieldsRow = {};
if (columns.includes('synology_url')) result.synology_url = row.synology_url ?? null;
if (columns.includes('synology_username')) result.synology_username = row.synology_username ?? null;
if (columns.includes('synology_password')) result.synology_password = row.synology_password ?? null;
if (columns.includes('synology_sid')) result.synology_sid = row.synology_sid ?? null;
if (columns.includes('synology_did')) result.synology_did = row.synology_did ?? null;
if (columns.includes('synology_skip_ssl')) result.synology_skip_ssl = row.synology_skip_ssl;
return result;
}
/** SY2 (`SynologyService._clearSynologySID`) — `UPDATE users SET synology_sid = NULL WHERE id = ?`. */
async clearSynologySID(id: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid: null });
}
/** SY3 (`SynologyService._clearSynologySession`) — `UPDATE users SET synology_sid = NULL, synology_did = NULL WHERE id = ?`. */
async clearSynologySession(id: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid: null, synology_did: null });
}
/**
* SY4/SY7 (`SynologyService._getSynologySession`'s session-refresh write,
* `testSynologyConnection`'s sid persist) — byte-identical `UPDATE users
* SET synology_sid = ? WHERE id = ?` at both legacy sites, one method (D4).
*/
async setSynologySid(id: number, synology_sid: string): Promise<void> {
await this.nativeUpdate({ id }, { synology_sid });
}
/** SY5 (`SynologyService.updateSynologySettings`) — `UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ?, synology_skip_ssl = ? WHERE id = ?`. */
async setSynologySettings(id: number, synology_url: string, synology_username: string, synology_password: string | null, synology_skip_ssl: number): Promise<void> {
await this.nativeUpdate({ id }, { synology_url, synology_username, synology_password, synology_skip_ssl });
}
/** SY6 (`SynologyService.getSynologyStatus`) — `SELECT synology_username FROM users WHERE id = ?`. */
async getSynologyUsername(id: number): Promise<string | null> {
const row = await this.findOne({ id }, { fields: ['synology_username'] });
return row?.synology_username ?? null;
}
/** SY8 (`SynologyService.testSynologyConnection`'s did persist) — `UPDATE users SET synology_did = ? WHERE id = ?`. */
async setSynologyDid(id: number, synology_did: string): Promise<void> {
await this.nativeUpdate({ id }, { synology_did });
}
// ---------------------------------------------------------------------
// UM11 — UnifiedMemoriesService._notifySharedTripPhotos
// ---------------------------------------------------------------------
@@ -1429,81 +1278,6 @@ export class UsersRepository extends TrekRepository<Users> {
return row ? { id: row.id, username: row.username } : null;
}
// ---------------------------------------------------------------------
// Plan 3h Task 4 (`AirtrailService` — R7, the encrypt-in-service
// discipline identical to Task 3's `DawarichConnectionsRepository`:
// every value below is exactly what the SERVICE hands this repository —
// encrypted, plaintext or null, at the same point in the pipeline the
// raw SQL saw it. This repository never calls
// maybe_encrypt_api_key/decrypt_api_key itself.
// ---------------------------------------------------------------------
/** ATC1 (`airtrail.service.ts#readRow`) — `SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailConnRow(id: number): Promise<{
airtrail_url: string | null;
airtrail_api_key: string | null;
airtrail_allow_insecure_tls: number | null;
airtrail_write_enabled: number | null;
} | null> {
const row = await this.findOne(
{ id },
{ fields: ['airtrail_url', 'airtrail_api_key', 'airtrail_allow_insecure_tls', 'airtrail_write_enabled'] },
);
return row
? {
airtrail_url: row.airtrail_url ?? null,
airtrail_api_key: row.airtrail_api_key ?? null,
airtrail_allow_insecure_tls: row.airtrail_allow_insecure_tls ?? null,
airtrail_write_enabled: row.airtrail_write_enabled ?? null,
}
: null;
}
/** ATC2 (`airtrail.service.ts#isAirtrailWriteEnabled`) — `SELECT airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailWriteEnabled(id: number): Promise<number | null> {
const row = await this.findOne({ id }, { fields: ['airtrail_write_enabled'] });
return row?.airtrail_write_enabled ?? null;
}
/**
* ATC3 (`airtrail.service.ts#saveSettings`, newKey branch) — `UPDATE users
* SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls
* = ?, airtrail_write_enabled = ? WHERE id = ?`. **No transaction** — the
* plan's Risks section flags this as a pre-existing asymmetry with
* `DawarichConnectionsRepository`'s equivalent `saveSettings` (which DOES
* wrap its writes in `uow.transactional`): preserved exactly, not
* "fixed" to match Dawarich's shape.
*/
async setAirtrailSettingsWithKey(id: number, url: string | null, apiKey: string, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate(
{ id },
{ airtrail_url: url, airtrail_api_key: apiKey, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled },
);
}
/**
* ATC4 (`airtrail.service.ts#saveSettings`, no-newKey branch) — `UPDATE
* users SET airtrail_url = ?, airtrail_allow_insecure_tls = ?,
* airtrail_write_enabled = ? WHERE id = ?`. Same no-transaction asymmetry
* as {@link setAirtrailSettingsWithKey} — preserved, not fixed.
*/
async setAirtrailSettings(id: number, url: string | null, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_url: url, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled });
}
/**
* ATC5 (`airtrail.service.ts#saveSettings`, URL-cleared branch) — `UPDATE
* users SET airtrail_api_key = NULL WHERE id = ?`. **SECURITY**:
* credential scrub — a cleared URL with no key left makes the connection
* meaningless, so the key is dropped too. Same no-transaction asymmetry
* as the two methods above — this is a THIRD, separate statement in the
* legacy `saveSettings` (its own `if (!trimmedUrl)` branch), not folded
* into {@link setAirtrailSettings}.
*/
async clearAirtrailApiKey(id: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_api_key: null });
}
// ---------------------------------------------------------------------
// Plan 3i Task 1 (`AdminService` — AD1-AD17, admin's user-CRUD surface).
// Every statement not already covered by an existing method above
@@ -1644,27 +1418,3 @@ export class UsersRepository extends TrekRepository<Users> {
return row ? { id: row.id, username: row.username, display_name: row.display_name ?? null, avatar: row.avatar ?? null } : null;
}
}
/**
* The six Synology credential/session columns `_readSynologyUser` reads
* selectively — a closed union, not a dynamic column string, matching
* `InstanceApiKeyName`'s reasoning above.
*/
export type SynologyUserColumn = 'synology_url' | 'synology_username' | 'synology_password' | 'synology_sid' | 'synology_did' | 'synology_skip_ssl';
/**
* {@link UsersRepository.getSynologyFields}'s return shape — structurally
* identical to `synology.service.ts`'s own `SynologyUserRecord` (every field
* optional, so an unrequested column is simply absent), deliberately
* defined here rather than imported from the service: a repository does not
* depend on a domain service's types, and the two stay structurally
* assignable without either side casting.
*/
export interface SynologyFieldsRow {
synology_url?: string | null;
synology_username?: string | null;
synology_password?: string | null;
synology_sid?: string | null;
synology_did?: string | null;
synology_skip_ssl?: number | null;
}
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import { UserAirtrailRepository } from '../../db/repositories/UserAirtrail.repository';
import { UserImmichRepository } from '../../db/repositories/UserImmich.repository';
import { UserSynologyRepository } from '../../db/repositories/UserSynology.repository';
/**
* Provides the repositories for the third-party connections a user keeps on
* their own `users` row (Immich, Synology Photos, AirTrail). They share the
* `users` table with `UsersRepository`, so MikroORM's one-repository-per-entity
* `@InjectRepository(Users)` cannot hand them out; each is a factory over the
* context-resolving global `EntityManager`, as `MaintenanceModule` does, so it
* resolves the request or transaction fork active when a method runs.
*/
@Module({
providers: [
{ provide: UserImmichRepository, useFactory: (em: EntityManager) => new UserImmichRepository(em), inject: [EntityManager] },
{ provide: UserSynologyRepository, useFactory: (em: EntityManager) => new UserSynologyRepository(em), inject: [EntityManager] },
{ provide: UserAirtrailRepository, useFactory: (em: EntityManager) => new UserAirtrailRepository(em), inject: [EntityManager] },
],
exports: [UserImmichRepository, UserSynologyRepository, UserAirtrailRepository],
})
export class UserConnectionRepositoriesModule {}
@@ -11,6 +11,7 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';
import { AirtrailClient } from './airtrail.client';
import { AirtrailLinkService } from './airtrail-link.service';
import { AirtrailService } from './airtrail.service';
import { UserConnectionRepositoriesModule } from '../database/user-connection-repositories.module';
/**
* The AirTrail pieces ReservationsModule may inject: the HTTP client, the
@@ -35,6 +36,7 @@ import { AirtrailService } from './airtrail.service';
AddonsModule,
RealtimeModule,
ReservationsReadModule,
UserConnectionRepositoriesModule,
MikroOrmModule.forFeature([Users, Reservations, ReservationEndpoints, AppSettings]),
],
providers: [AirtrailClient, AirtrailService, AirtrailLinkService],
@@ -1,8 +1,6 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { AirtrailFlight } from '@trek/shared';
import { Users } from '../../db/entities/Users.entity';
import { UsersRepository } from '../../db/repositories/Users.repository';
import { UserAirtrailRepository } from '../../db/repositories/UserAirtrail.repository';
import { AuditService } from '../audit/audit.service';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf } from '../../utils/ssrfGuard';
@@ -33,7 +31,7 @@ interface UserConnRow {
* and bought nothing while AirTrail is the only integration of this shape.
*
* Plan 3h Task 4 (ATC1-5): the raw `users` reads/writes now go through
* `UsersRepository`'s additive `getAirtrailConnRow`/`getAirtrailWriteEnabled`/
* `UserAirtrailRepository`'s (same `users` table) `getAirtrailConnRow`/`getAirtrailWriteEnabled`/
* `setAirtrailSettingsWithKey`/`setAirtrailSettings`/`clearAirtrailApiKey`
* methods (R7 — the repository sees only opaque, already-encrypted TEXT;
* `maybe_encrypt_api_key`/`decrypt_api_key` stay here). `saveSettings` keeps
@@ -44,19 +42,19 @@ interface UserConnRow {
@Injectable()
export class AirtrailService {
constructor(
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
private readonly airtrailRepo: UserAirtrailRepository,
private readonly audit: AuditService,
private readonly client: AirtrailClient,
) {}
private async readRow(userId: number): Promise<UserConnRow | undefined> {
const row = await this.usersRepo.getAirtrailConnRow(userId);
const row = await this.airtrailRepo.getAirtrailConnRow(userId);
return row ?? undefined;
}
/** Has this user opted in to TREK writing their flight edits back to AirTrail? (#1240) */
async isAirtrailWriteEnabled(userId: number): Promise<boolean> {
const value = await this.usersRepo.getAirtrailWriteEnabled(userId);
const value = await this.airtrailRepo.getAirtrailWriteEnabled(userId);
return !!value;
}
@@ -122,12 +120,12 @@ export class AirtrailService {
const newKey = provided && provided !== KEY_MASK ? maybe_encrypt_api_key(provided) : undefined;
if (newKey !== undefined) {
await this.usersRepo.setAirtrailSettingsWithKey(userId, trimmedUrl || null, newKey, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0);
await this.airtrailRepo.setAirtrailSettingsWithKey(userId, trimmedUrl || null, newKey, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0);
} else {
await this.usersRepo.setAirtrailSettings(userId, trimmedUrl || null, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0);
await this.airtrailRepo.setAirtrailSettings(userId, trimmedUrl || null, allowInsecureTls ? 1 : 0, writeEnabled ? 1 : 0);
// Clearing the URL with no key left makes the connection meaningless — drop the key too.
if (!trimmedUrl) {
await this.usersRepo.clearAirtrailApiKey(userId);
await this.airtrailRepo.clearAirtrailApiKey(userId);
}
}
+4 -1
View File
@@ -19,6 +19,7 @@ import { buildStorageUploadOptions } from '../storage/storage-upload.factory';
import { journeyImageFileFilter, journeyUploadFilename } from './journey.controller';
import { Users } from '../../db/entities/Users.entity';
import { JourneyBooks } from '../../db/entities/JourneyBooks.entity';
import { UserConnectionRepositoriesModule } from '../database/user-connection-repositories.module';
@Module({
// MemoriesModule: the journey gallery streams provider assets and uploads to Immich.
@@ -38,7 +39,9 @@ import { JourneyBooks } from '../../db/entities/JourneyBooks.entity';
}),
StorageModule,
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule, JourneyPhotoCaptureModule,
// Plan 3g Task 3: `JourneyService` (JV1, `UsersRepository.getImmichAutoUpload`)
// JourneyService's JV1 read (`UserImmichRepository.getImmichAutoUpload`).
UserConnectionRepositoriesModule,
// Plan 3g Task 3: `JourneyService` (JV1, now through the module above)
// and `JourneyBookService` (JB1-JB7, `JourneyBooksRepository`) both
// constructed HERE — `@InjectRepository` resolves from this module's own
// `forFeature` graph, not from `AuthModule`'s (which registers `Users`
+4 -6
View File
@@ -1,5 +1,4 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyShareService } from './journey-share.service';
import { ImmichService } from '../memories/immich.service';
@@ -7,8 +6,7 @@ import { PhotoProviderRegistry } from '../memories/photo-provider.registry';
import { PhotoResolverService } from '../memories/photo-resolver.service';
import { AddonsService } from '../addons/addons.service';
import { ADDON_IDS } from '../../addons';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { UserImmichRepository } from '../../db/repositories/UserImmich.repository';
import type { Response } from 'express';
/**
@@ -26,7 +24,7 @@ export class JourneyService {
private readonly photoResolver: PhotoResolverService,
private readonly journey: JourneyDomainService,
private readonly share: JourneyShareService,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
private readonly immichRepo: UserImmichRepository,
) {}
async journeyAddonEnabled(): Promise<boolean> {
@@ -86,9 +84,9 @@ export class JourneyService {
deleteJourneyShareLink(id: number, userId: number) { return this.share.deleteJourneyShareLink(id, userId); }
// Immich mirror (only when the user opted in via integration settings)
// JV1 — `UsersRepository.getImmichAutoUpload`.
// JV1 — `UserImmichRepository.getImmichAutoUpload`.
async immichAutoUploadEnabled(userId: number): Promise<boolean> {
return !!(await this.usersRepo.getImmichAutoUpload(userId));
return !!(await this.immichRepo.getImmichAutoUpload(userId));
}
uploadToImmich(userId: number, relativePath: string, originalName: string) { return this.immich.uploadToImmich(userId, relativePath, originalName); }
+7 -9
View File
@@ -1,7 +1,6 @@
import { Injectable } from '@nestjs/common';
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
import type { Response } from 'express';
import { InjectRepository } from '@mikro-orm/nestjs';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf, safeFetch, type SafeFetchOptions } from '../../utils/ssrfGuard';
import { AuditService } from '../audit/audit.service';
@@ -10,9 +9,8 @@ import fsPromises from 'node:fs/promises';
import path from 'node:path';
import { MemoriesAccessService } from './memories-access.service';
import { describeFetchFailure, fail, handleServiceResult, isWithinLocalDayRange, pipeAsset, shiftCalendarDay, sortAssetsByTakenAtDesc, type Selection } from './memories.helpers';
import { Users } from '../../db/entities/Users.entity';
import { UnitOfWork } from '../database/unit-of-work';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { UserImmichRepository } from '../../db/repositories/UserImmich.repository';
const ALBUM_PAGE_SIZE = 1000;
const ALBUM_MAX_PAGES = 20;
@@ -81,12 +79,12 @@ export class ImmichService {
private readonly audit: AuditService,
private readonly access: MemoriesAccessService,
private readonly storage: StorageService,
@InjectRepository(Users) private readonly users: UsersRepository,
private readonly immichRepo: UserImmichRepository,
private readonly uow: UnitOfWork,
) {}
async getImmichCredentials(userId: number): Promise<ImmichCreds | null> {
const user = await this.users.getImmichCredentials(userId);
const user = await this.immichRepo.getImmichCredentials(userId);
if (!user?.immich_url || !user?.immich_api_key) return null;
const apiKey = decrypt_api_key(user.immich_api_key);
if (!apiKey) return null;
@@ -123,7 +121,7 @@ export class ImmichService {
async getConnectionSettings(userId: number) {
const creds = await this.getImmichCredentials(userId);
const prefs = await this.users.getImmichConnectionPrefs(userId);
const prefs = await this.immichRepo.getImmichConnectionPrefs(userId);
return {
immich_url: creds?.immich_url || '',
connected: !!(creds?.immich_url && creds?.immich_api_key),
@@ -133,7 +131,7 @@ export class ImmichService {
}
async setImmichAutoUpload(userId: number, enabled: boolean): Promise<void> {
await this.users.setImmichAutoUpload(userId, enabled ? 1 : 0);
await this.immichRepo.setImmichAutoUpload(userId, enabled ? 1 : 0);
}
/**
@@ -165,9 +163,9 @@ export class ImmichService {
if (immichUrl) {
const insecure = allowInsecureTls === undefined ? null : Number(allowInsecureTls);
// The stored URL decides whether an undefined switch keeps its value (IM4).
await this.users.setImmichSettings(userId, url, maybe_encrypt_api_key(immichApiKey), insecure);
await this.immichRepo.setImmichSettings(userId, url, maybe_encrypt_api_key(immichApiKey), insecure);
} else {
await this.users.clearImmichSettings(userId, maybe_encrypt_api_key(immichApiKey));
await this.immichRepo.clearImmichSettings(userId, maybe_encrypt_api_key(immichApiKey));
}
if (typeof autoUpload === 'boolean') await this.setImmichAutoUpload(userId, autoUpload);
});
@@ -3,6 +3,7 @@ import { MikroOrmModule } from '@mikro-orm/nestjs';
import { MemoriesService } from './memories.service';
import { MemoriesAccessService } from './memories-access.service';
import { ImmichService } from './immich.service';
import { UserConnectionRepositoriesModule } from '../database/user-connection-repositories.module';
import { SynologyService } from './synology.service';
import { UnifiedMemoriesService } from './unified-memories.service';
import { PhotoResolverService } from './photo-resolver.service';
@@ -75,6 +76,7 @@ import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
@Module({
imports: [
NotificationsModule, AddonsModule, AuditModule, TrekPhotosModule, RealtimeModule, SchedulingModule, StorageModule,
UserConnectionRepositoriesModule,
MikroOrmModule.forFeature([TripPhotos, TrekPhotos, TripAlbumLinks, Trips, TrekPhotoCacheMeta, PhotoProviders, Users, Journeys, JourneyContributors, JourneyPhotos]),
],
controllers: [UnifiedMemoriesController, ImmichMemoriesController, SynologyMemoriesController],
+10 -12
View File
@@ -1,11 +1,9 @@
import { Injectable } from '@nestjs/common';
import { Response } from 'express';
import { InjectRepository } from '@mikro-orm/nestjs';
import { decrypt_api_key, encrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { safeFetch, SsrfBlockedError, checkSsrf } from '../../utils/ssrfGuard';
import { MemoriesAccessService } from './memories-access.service';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository, SynologyUserColumn } from '../../db/repositories/Users.repository';
import { UserSynologyRepository, type SynologyUserColumn } from '../../db/repositories/UserSynology.repository';
import {
dayStartEpochSeconds,
fail,
@@ -139,12 +137,12 @@ export class SynologyService {
constructor(
private readonly access: MemoriesAccessService,
private readonly notifications: NotificationsService,
@InjectRepository(Users) private readonly users: UsersRepository,
private readonly synologyRepo: UserSynologyRepository,
) {}
private async _readSynologyUser(userId: number, columns: SynologyUserColumn[]): Promise<ServiceResult<SynologyUserRecord>> {
try {
const filtered = await this.users.getSynologyFields(userId, columns);
const filtered = await this.synologyRepo.getSynologyFields(userId, columns);
if (!filtered) {
return fail('User not found', 404);
@@ -309,11 +307,11 @@ export class SynologyService {
private async _clearSynologySID(userId: number): Promise<void> {
await this.users.clearSynologySID(userId);
await this.synologyRepo.clearSynologySID(userId);
}
private async _clearSynologySession(userId: number): Promise<void> {
await this.users.clearSynologySession(userId);
await this.synologyRepo.clearSynologySession(userId);
}
private _splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } | null {
@@ -352,7 +350,7 @@ export class SynologyService {
return resp as ServiceResult<string>;
}
await this.users.setSynologySid(userId, encrypt_api_key(resp.data.sid));
await this.synologyRepo.setSynologySid(userId, encrypt_api_key(resp.data.sid));
return success(resp.data.sid);
}
@@ -406,7 +404,7 @@ export class SynologyService {
}
try {
await this.users.setSynologySettings(
await this.synologyRepo.setSynologySettings(
userId,
synologyUrl,
synologyUsername,
@@ -425,7 +423,7 @@ export class SynologyService {
if ('error' in sid) return success({ connected: false, error: sid.error.message });
if (!sid.data) return success({ connected: false, error: 'Not connected to Synology' });
try {
const synologyUsername = await this.users.getSynologyUsername(userId);
const synologyUsername = await this.synologyRepo.getSynologyUsername(userId);
return success({ connected: true, user: { name: synologyUsername || 'unknown user' } });
} catch (err: unknown) {
return success({ connected: true, user: { name: 'unknown user' } });
@@ -446,9 +444,9 @@ export class SynologyService {
// Persist the session so the OTP code is not required again on save.
// The did (device token) allows future re-logins without OTP.
await this.users.setSynologySid(userId, encrypt_api_key(resp.data.sid));
await this.synologyRepo.setSynologySid(userId, encrypt_api_key(resp.data.sid));
if (resp.data.did) {
await this.users.setSynologyDid(userId, encrypt_api_key(resp.data.did));
await this.synologyRepo.setSynologyDid(userId, encrypt_api_key(resp.data.did));
}
return success({ connected: true, user: { name: synologyUsername } });