Compare commits

..

5 Commits

Author SHA1 Message Date
Ben Beckford
d1517786d1 Merge branch 'main' into chore/test-assetdatefilter 2026-07-21 12:57:25 -07:00
Daniel Dietzler
5d7283e44d fix: album update event emitting (#30120) 2026-07-21 19:43:27 +00:00
Lorenzo Rota
73329a8ce8 fix(server): send id_token_hint on OIDC logout (#29720)
Co-authored-by: Daniel Dietzler <mail@ddietzler.dev>
2026-07-21 19:19:13 +02:00
Ben Beckford
975a1572e4 Merge branch 'main' into chore/test-assetdatefilter 2026-07-21 09:39:14 -07:00
Ben Beckford
832294818d chore(server): test assetDateFilter workflow method 2026-07-21 09:30:55 -07:00
14 changed files with 187 additions and 60 deletions

View File

@@ -4,7 +4,8 @@
select
"id",
"expiresAt",
"pinExpiresAt"
"pinExpiresAt",
"oauthBearerToken"
from
"session"
where

View File

@@ -83,7 +83,7 @@ export class OAuthRepository {
url: string,
expectedState: string,
codeVerifier: string,
): Promise<{ profile: OAuthProfile; sid?: string }> {
): Promise<{ profile: OAuthProfile; sid?: string; idToken?: string }> {
const client = await this.getClient(config);
const pkceCodeVerifier = client.serverMetadata().supportsPKCE() ? codeVerifier : undefined;
@@ -111,7 +111,7 @@ export class OAuthRepository {
}
}
return { profile, sid };
return { profile, sid, idToken: tokens.id_token };
} catch (error: Error | any) {
if (error.message.includes('unexpected JWT alg received')) {
this.logger.warn(

View File

@@ -32,7 +32,7 @@ export class SessionRepository {
get(id: string) {
return this.db
.selectFrom('session')
.select(['id', 'expiresAt', 'pinExpiresAt'])
.select(['id', 'expiresAt', 'pinExpiresAt', 'oauthBearerToken'])
.where('id', '=', id)
.executeTakeFirst();
}

View File

@@ -0,0 +1,9 @@
import { Kysely, sql } from 'kysely';
export async function up(db: Kysely<any>): Promise<void> {
await sql`ALTER TABLE "session" ADD "oauthBearerToken" character varying;`.execute(db);
}
export async function down(db: Kysely<any>): Promise<void> {
await sql`ALTER TABLE "session" DROP COLUMN "oauthBearerToken";`.execute(db);
}

View File

@@ -55,4 +55,7 @@ export class SessionTable {
@Column({ nullable: true, index: true })
oauthSid!: string | null;
@Column({ nullable: true })
oauthBearerToken!: string | null;
}

View File

@@ -351,9 +351,12 @@ export class AssetMediaService extends BaseService {
}
await this.albumRepository.addAssetIds(album.id, [assetId]);
for (const { user } of album.albumUsers) {
await this.eventRepository.emit('AlbumUpdate', { id: album.id, recipientId: user.id });
}
const userIds = album.albumUsers.map(({ user }) => user.id);
await this.eventRepository.emit('AlbumUpdate', {
id: album.id,
userIds,
recipientIds: userIds,
});
}
private requireQuota(auth: AuthDto, size: number) {

View File

@@ -160,7 +160,25 @@ describe(AuthService.name, () => {
await expect(sut.logout(auth, AuthType.OAuth)).resolves.toEqual({
successful: true,
redirectUri: 'http://end-session-endpoint',
redirectUri: 'http://end-session-endpoint/',
});
});
it('should include the id token hint for OAuth sessions', async () => {
const auth = AuthFactory.from().session().build();
mocks.systemMetadata.get.mockResolvedValue(systemConfigStub.enabled);
mocks.session.get.mockResolvedValue({
id: auth.session!.id,
expiresAt: null,
oauthBearerToken: 'id-token',
pinExpiresAt: null,
});
mocks.session.delete.mockResolvedValue();
await expect(sut.logout(auth, AuthType.OAuth)).resolves.toEqual({
successful: true,
redirectUri: 'http://end-session-endpoint/?id_token_hint=id-token',
});
});
@@ -173,7 +191,7 @@ describe(AuthService.name, () => {
await expect(sut.logout(auth, AuthType.OAuth)).resolves.toEqual({
successful: true,
redirectUri: 'http://custom-logout-url',
redirectUri: 'http://custom-logout-url/',
});
});
@@ -186,7 +204,7 @@ describe(AuthService.name, () => {
await expect(sut.logout(auth, AuthType.OAuth)).resolves.toEqual({
successful: true,
redirectUri: 'http://end-session-endpoint',
redirectUri: 'http://end-session-endpoint/',
});
});
@@ -201,6 +219,12 @@ describe(AuthService.name, () => {
it('should delete the access token', async () => {
const auth = { user: { id: '123' }, session: { id: 'token123' } } as AuthDto;
mocks.session.get.mockResolvedValue({
id: auth.session!.id,
expiresAt: null,
oauthBearerToken: null,
pinExpiresAt: null,
});
mocks.session.delete.mockResolvedValue();
await expect(sut.logout(auth, AuthType.Password)).resolves.toEqual({
@@ -722,6 +746,27 @@ describe(AuthService.name, () => {
expect(mocks.user.update).toHaveBeenCalledWith(user.id, { oauthId: profile.sub });
});
it('should store the OAuth bearer token on the new session', async () => {
const user = UserFactory.create();
const profile = OAuthProfileFactory.create();
mocks.systemMetadata.get.mockResolvedValue(systemConfigStub.oauthEnabled);
mocks.oauth.getProfileAndOAuthSid.mockResolvedValue({ profile, sid: 'oauth-sid', idToken: 'oauth-bearer-token' });
mocks.user.getByEmail.mockResolvedValue(user);
mocks.user.update.mockResolvedValue(user);
mocks.session.create.mockResolvedValue(SessionFactory.create());
await sut.callback(
{ url: 'http://immich/auth/login?code=abc123', state: 'xyz789', codeVerifier: 'foobar' },
{},
loginDetails,
);
expect(mocks.session.create).toHaveBeenCalledWith(
expect.objectContaining({ oauthSid: 'oauth-sid', oauthBearerToken: 'oauth-bearer-token' }),
);
});
it('should normalize the email from the OAuth profile before linking', async () => {
const user = UserFactory.create();
const profile = OAuthProfileFactory.create({ email: ' TEST@IMMICH.CLOUD ' });
@@ -1125,6 +1170,7 @@ describe(AuthService.name, () => {
mocks.oauth.getProfileAndOAuthSid.mockResolvedValue({
profile: { sub: 'sub' },
sid: session.oauthSid ?? undefined,
idToken: session.oauthBearerToken ?? undefined,
});
mocks.user.update.mockResolvedValue(user);
mocks.session.update.mockResolvedValue(session);
@@ -1135,7 +1181,10 @@ describe(AuthService.name, () => {
{},
);
expect(mocks.session.update).toHaveBeenCalledWith(session.id, { oauthSid: session.oauthSid });
expect(mocks.session.update).toHaveBeenCalledWith(session.id, {
oauthSid: session.oauthSid,
oauthBearerToken: session.oauthBearerToken,
});
expect(mocks.user.update).toHaveBeenCalledWith(auth.user.id, { oauthId: 'sub' });
});
@@ -1169,7 +1218,7 @@ describe(AuthService.name, () => {
expect(mocks.user.update).toHaveBeenCalledWith(auth.user.id, { oauthId: '' });
});
it('should unlink an account and remove the oauthSid from the session', async () => {
it('should unlink an account and remove the OAuth data from the session', async () => {
const user = UserFactory.create();
const session = SessionFactory.create();
const auth = AuthFactory.from(user).session(session).build();
@@ -1180,7 +1229,7 @@ describe(AuthService.name, () => {
await sut.unlink(auth);
expect(mocks.session.update).toHaveBeenCalledWith(session.id, { oauthSid: null });
expect(mocks.session.update).toHaveBeenCalledWith(session.id, { oauthSid: null, oauthBearerToken: null });
expect(mocks.user.update).toHaveBeenCalledWith(auth.user.id, { oauthId: '' });
});
});

View File

@@ -76,14 +76,17 @@ export class AuthService extends BaseService {
}
async logout(auth: AuthDto, authType: AuthType): Promise<LogoutResponseDto> {
let oauthBearerToken: string | undefined;
if (auth.session) {
const session = await this.sessionRepository.get(auth.session.id);
oauthBearerToken = session?.oauthBearerToken ?? undefined;
await this.sessionRepository.delete(auth.session.id);
await this.eventRepository.emit('SessionDelete', { sessionId: auth.session.id });
}
return {
successful: true,
redirectUri: await this.getLogoutEndpoint(authType),
redirectUri: await this.getLogoutEndpoint(authType, oauthBearerToken),
};
}
@@ -306,12 +309,11 @@ export class AuthService extends BaseService {
}
const url = this.resolveRedirectUri(oauth, dto.url);
const { profile, sid: oauthSid } = await this.oauthRepository.getProfileAndOAuthSid(
oauth,
url,
expectedState,
codeVerifier,
);
const {
profile,
sid: oauthSid,
idToken: oauthBearerToken,
} = await this.oauthRepository.getProfileAndOAuthSid(oauth, url, expectedState, codeVerifier);
const normalizedEmail = profile.email ? profile.email.trim().toLowerCase() : undefined;
const { autoRegister, defaultStorageQuota, storageLabelClaim, storageQuotaClaim, roleClaim } = oauth;
this.logger.debug(`Logging in with OAuth: ${JSON.stringify(profile)}`);
@@ -378,7 +380,7 @@ export class AuthService extends BaseService {
await this.syncProfilePicture(user, profile.picture);
}
return this.createLoginResponse(user, loginDetails, oauthSid);
return this.createLoginResponse(user, loginDetails, oauthSid, oauthBearerToken);
}
private async syncProfilePicture(user: UserAdmin, url: string) {
@@ -419,6 +421,7 @@ export class AuthService extends BaseService {
const {
profile: { sub: oauthId },
sid,
idToken,
} = await this.oauthRepository.getProfileAndOAuthSid(oauth, dto.url, expectedState, codeVerifier);
const duplicate = await this.userRepository.getByOAuthId(oauthId);
if (duplicate && duplicate.id !== auth.user.id) {
@@ -426,8 +429,11 @@ export class AuthService extends BaseService {
throw new BadRequestException('This OAuth account has already been linked to another user.');
}
if (auth.session && sid) {
await this.sessionRepository.update(auth.session.id, { oauthSid: sid });
if (auth.session && (sid || idToken)) {
await this.sessionRepository.update(auth.session.id, {
oauthSid: sid,
oauthBearerToken: idToken,
});
}
const user = await this.userRepository.update(auth.user.id, { oauthId });
@@ -436,14 +442,14 @@ export class AuthService extends BaseService {
async unlink(auth: AuthDto): Promise<UserAdminResponseDto> {
if (auth.session) {
await this.sessionRepository.update(auth.session.id, { oauthSid: null });
await this.sessionRepository.update(auth.session.id, { oauthSid: null, oauthBearerToken: null });
}
const user = await this.userRepository.update(auth.user.id, { oauthId: '' });
return mapUserAdmin(user);
}
private async getLogoutEndpoint(authType: AuthType): Promise<string> {
private async getLogoutEndpoint(authType: AuthType, oauthBearerToken?: string | null): Promise<string> {
if (authType !== AuthType.OAuth) {
return LOGIN_URL;
}
@@ -453,11 +459,20 @@ export class AuthService extends BaseService {
return LOGIN_URL;
}
if (config.oauth.endSessionEndpoint) {
return config.oauth.endSessionEndpoint;
const endSessionEndpoint =
config.oauth.endSessionEndpoint || (await this.oauthRepository.getLogoutEndpoint(config.oauth));
if (!endSessionEndpoint) {
return LOGIN_URL;
}
return (await this.oauthRepository.getLogoutEndpoint(config.oauth)) || LOGIN_URL;
const url = new URL(endSessionEndpoint);
if (oauthBearerToken) {
url.searchParams.set('id_token_hint', oauthBearerToken);
}
return url.href;
}
private getBearerToken(headers: IncomingHttpHeaders): string | null {
@@ -599,7 +614,12 @@ export class AuthService extends BaseService {
await this.sessionRepository.update(auth.session.id, { pinExpiresAt: null });
}
private async createLoginResponse(user: UserAdmin, loginDetails: LoginDetails, oauthSid?: string) {
private async createLoginResponse(
user: UserAdmin,
loginDetails: LoginDetails,
oauthSid?: string,
oauthBearerToken?: string,
) {
const token = this.cryptoRepository.randomBytesAsText(32);
const hashed = this.cryptoRepository.hashSha256(token);
@@ -610,6 +630,7 @@ export class AuthService extends BaseService {
appVersion: loginDetails.appVersion,
userId: user.id,
oauthSid: oauthSid ?? null,
oauthBearerToken: oauthBearerToken ?? null,
});
return mapLoginResponse(user, token);

View File

@@ -26,6 +26,7 @@ export class SessionFactory {
updatedAt: newDate(),
userId: newUuid(),
oauthSid: newUuid(),
oauthBearerToken: 'oauth-bearer-token',
...dto,
});
}

View File

@@ -216,7 +216,8 @@ describe(AssetService.name, () => {
expect(ctx.getMock(EventRepository).emit).toHaveBeenCalledWith('AlbumUpdate', {
id: album.id,
recipientId: user.id,
userIds: [user.id],
recipientIds: [user.id],
});
});

View File

@@ -433,9 +433,10 @@ describe('core plugin', () => {
describe('assetDateFilter', () => {
it('should favorite assets created during the first 7 days of a specific year and month', async () => {
const { user } = await ctx.newUser();
const [{ asset: asset1 }, { asset: asset2 }] = await Promise.all([
const [{ asset: asset1 }, { asset: asset2 }, { asset: asset3 }] = await Promise.all([
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2000-04-01') }),
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2000-04-07T23:59:59Z') }),
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2000-04-08T00:00:00Z') }),
]);
const workflow = await createWorkflow({
@@ -461,6 +462,46 @@ describe('core plugin', () => {
await ctx.sut.handleAssetTrigger({ workflowId: workflow.id, assetId: asset2.id });
await expect(ctx.get(AssetRepository).getById(asset2.id)).resolves.toMatchObject({ isFavorite: true });
await ctx.sut.handleAssetTrigger({ workflowId: workflow.id, assetId: asset3.id });
await expect(ctx.get(AssetRepository).getById(asset3.id)).resolves.toMatchObject({ isFavorite: false });
});
it('should match recurring dates regardless of the year', async () => {
const { user } = await ctx.newUser();
const [{ asset: asset1 }, { asset: asset2 }, { asset: asset3 }] = await Promise.all([
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2026-03-01') }),
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('1998-12-21') }),
ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2000-04-08T00:00:00Z') }),
]);
await ctx.newAsset({ ownerId: user.id, localDateTime: new Date('2010-06-15') });
const workflow = await createWorkflow({
ownerId: user.id,
trigger: WorkflowTrigger.AssetCreate,
steps: [
{
method: 'immich-plugin-core#assetDateFilter',
config: {
startDate: { day: 12, month: 12, year: 2000 },
endDate: { day: 30, month: 3, year: 2001 },
recurring: true,
},
},
{
method: 'immich-plugin-core#assetFavorite',
},
],
});
await ctx.sut.handleAssetTrigger({ workflowId: workflow.id, assetId: asset1.id });
await expect(ctx.get(AssetRepository).getById(asset1.id)).resolves.toMatchObject({ isFavorite: true });
await ctx.sut.handleAssetTrigger({ workflowId: workflow.id, assetId: asset2.id });
await expect(ctx.get(AssetRepository).getById(asset2.id)).resolves.toMatchObject({ isFavorite: true });
await ctx.sut.handleAssetTrigger({ workflowId: workflow.id, assetId: asset3.id });
await expect(ctx.get(AssetRepository).getById(asset3.id)).resolves.toMatchObject({ isFavorite: false });
});
});

View File

@@ -22,7 +22,7 @@ const authFactory = ({
user,
}: {
apiKey?: Partial<AuthApiKey>;
session?: { id?: string; hasElevatedPermission?: boolean };
session?: { id?: string; hasElevatedPermission?: boolean; oauthBearerToken?: string | null };
user?: Omit<
Partial<UserAdmin>,
'createdAt' | 'updatedAt' | 'deletedAt' | 'fileCreatedAt' | 'fileModifiedAt' | 'localDateTime' | 'profileChangedAt'

View File

@@ -55,36 +55,34 @@
{/each}
</div> -->
<div class="overflow-x-auto pb-1">
<div class="grid grid-flow-col grid-rows-7 gap-0.5">
<div class="row-span-7 grid grid-rows-subgrid">
{#if Info.getStartOfWeek({ locale: $locale }) === 7}
<div></div>
{/if}
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[0]}</Text></div>
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[1]}</Text></div>
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[2]}</Text></div>
{#if Info.getStartOfWeek({ locale: $locale }) === 1}
<div class="-my-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[3]}</Text></div>
{/if}
</div>
{#each data.series as day, idx (day.date)}
{@const date = DateTime.fromISO(day.date, { zone: 'utc' }).toLocaleString(
{ month: 'short', day: 'numeric' },
{ locale: $locale },
)}
<div
class="aspect-square size-full rounded-sm {itemColors(day.count)} row-start-(--heatmap-row-start)"
style:--heatmap-row-start={idx === 0 ? padding + 1 : undefined}
title={itemLabel({ date, count: day.count })}
aria-label={itemLabel({ date, count: day.count })}
></div>
{/each}
<div class="grid grid-flow-col grid-rows-7 gap-0.5">
<div class="row-span-7 grid grid-rows-subgrid">
{#if Info.getStartOfWeek({ locale: $locale }) === 7}
<div></div>
{/if}
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[0]}</Text></div>
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[1]}</Text></div>
<div class="row-span-2 -mt-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[2]}</Text></div>
{#if Info.getStartOfWeek({ locale: $locale }) === 1}
<div class="-my-1"><Text size="tiny" class="mr-0.5 font-mono">{weekdays[3]}</Text></div>
{/if}
</div>
{#each data.series as day, idx (day.date)}
{@const date = DateTime.fromISO(day.date, { zone: 'utc' }).toLocaleString(
{ month: 'short', day: 'numeric' },
{ locale: $locale },
)}
<div
class="aspect-square size-full rounded-sm {itemColors(day.count)} row-start-(--heatmap-row-start)"
style:--heatmap-row-start={idx === 0 ? padding + 1 : undefined}
title={itemLabel({ date, count: day.count })}
aria-label={itemLabel({ date, count: day.count })}
></div>
{/each}
</div>
<div class="mt-2 flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<div class="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<span>{$t('less')}</span>
<span class="size-3 rounded-sm bg-gray-200 dark:bg-gray-700"></span>
<span class="size-3 rounded-sm bg-immich-primary/30"></span>

View File

@@ -213,7 +213,7 @@
</Stack>
</AdminCard>
<div class="col-span-full px-4 py-2">
<div class="col-span-2 px-4 py-2">
<div class="flex gap-2 text-primary">
<Icon icon={mdiCloudUploadOutline} size="1.5rem" />
<CardTitle>{$t('uploads')}</CardTitle>