Skip to content

High performance self-hosted photo and video management solution.

5.4 KB
Raw Blame
import {
  calculateJwkThumbprint,
  exportJWK,
  importPKCS8,
  importSPKI,
  SignJWT,
} from 'jose';
import Provider from 'oidc-provider';
import { PRIVATE_KEY_PEM, PUBLIC_KEY_PEM } from './test-keys';

export enum OAuthClient {
  DEFAULT = 'client-default',
  RS256_TOKENS = 'client-RS256-tokens',
  RS256_PROFILE = 'client-RS256-profile',
}

export enum OAuthUser {
  NO_EMAIL = 'no-email',
  NO_NAME = 'no-name',
  ID_TOKEN_CLAIMS = 'id-token-claims',
  WITH_QUOTA = 'with-quota',
  WITH_USERNAME = 'with-username',
  WITH_ROLE = 'with-role',
  WITH_EMBEDDED_PROFILE_PICTURE = 'with-embedded-profile-picture',
}

const claims = [
  { sub: OAuthUser.NO_EMAIL },
  {
    sub: OAuthUser.NO_NAME,
    email: '[email protected]',
    email_verified: true,
  },
  {
    sub: OAuthUser.WITH_USERNAME,
    email: '[email protected]',
    email_verified: true,
    immich_username: 'user-username',
  },
  {
    sub: OAuthUser.WITH_QUOTA,
    email: '[email protected]',
    email_verified: true,
    preferred_username: 'user-quota',
    immich_quota: 25,
  },
  {
    sub: OAuthUser.WITH_ROLE,
    email: '[email protected]',
    email_verified: true,
    immich_role: 'admin',
  },
  {
    sub: OAuthUser.WITH_EMBEDDED_PROFILE_PICTURE,
    email: '[email protected]',
    email_verified: true,
    picture:
      'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NHB4IiBoZWlnaHQ9IjY0cHgiIHZpZXdCb3g9IjAgMCA2NCA2NCIgdmVyc2lvbj0iMS4xIj48cmVjdCBmaWxsPSIjMzc3YjM3IiBjeD0iMzIiIGN5PSIzMiIgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByPSIzMiIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBzdHlsZT0iY29sb3I6ICNmZmY7IGxpbmUtaGVpZ2h0OiAxOyBmb250LWZhbWlseTogJ1JlZEhhdFRleHQnLCdPdmVycGFzcycsb3ZlcnBhc3MsaGVsdmV0aWNhLGFyaWFsLHNhbnMtc2VyaWY7ICIgZmlsbD0iI2ZmZiIgYWxpZ25tZW50LWJhc2VsaW5lPSJtaWRkbGUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZvbnQtc2l6ZT0iMjgiIGZvbnQtd2VpZ2h0PSI0MDAiIGR5PSIuMWVtIj5BQTwvdGV4dD48L3N2Zz4=',
  },
];

const privateKey = await importPKCS8(PRIVATE_KEY_PEM, 'RS256', {
  extractable: true,
});
const publicKey = await importSPKI(PUBLIC_KEY_PEM, 'RS256', {
  extractable: true,
});
const kid = await calculateJwkThumbprint(await exportJWK(publicKey));

export async function generateLogoutToken(iss: string, sub: string) {
  return await new SignJWT({
    iss: iss,
    aud: OAuthClient.DEFAULT,
    iat: Math.floor(Date.now() / 1000),
    jti: crypto.randomUUID(),
    sub: sub,
    events: {
      'http://schemas.openid.net/event/backchannel-logout': {},
    },
  })
    .setProtectedHeader({ alg: 'RS256', typ: 'logout+jwt', kid: kid })
    .sign(privateKey);
}

const withDefaultClaims = (sub: string) => ({
  sub,
  email: `${sub}@immich.app`,
  name: 'OAuth User',
  given_name: `OAuth`,
  family_name: 'User',
  email_verified: true,
});

const getClaims = (sub: string, use?: string) => {
  if (sub === OAuthUser.ID_TOKEN_CLAIMS) {
    return {
      sub,
      email: `oauth-${sub}@immich.app`,
      email_verified: true,
      name: use === 'id_token' ? 'ID Token User' : 'Userinfo User',
    };
  }
  return claims.find((user) => user.sub === sub) || withDefaultClaims(sub);
};

const setup = async () => {
  const redirectUris = [
    'http://127.0.0.1:2285/auth/login',
    'https://photos.immich.app/oauth/mobile-redirect',
  ];
  const port = 2286;
  const host = '0.0.0.0';
  const oidc = new Provider(`http://${host}:${port}`, {
    renderError: async (ctx, out, error) => {
      console.error(out);
      console.error(error);
      ctx.body = 'Internal Server Error';
    },
    findAccount: (ctx, sub) => ({
      accountId: sub,
      claims: (use) => getClaims(sub, use),
    }),
    scopes: ['openid', 'email', 'profile'],
    claims: {
      openid: ['sub'],
      email: ['email', 'email_verified'],
      profile: [
        'name',
        'given_name',
        'family_name',
        'preferred_username',
        'immich_quota',
        'immich_username',
        'immich_role',
        'picture',
      ],
    },
    features: {
      jwtUserinfo: {
        enabled: true,
      },
    },
    cookies: {
      names: {
        session: 'oidc.session',
        interaction: 'oidc.interaction',
        resume: 'oidc.resume',
      },
    },
    conformIdTokenClaims: false,
    pkce: {
      required: () => false,
    },
    jwks: { keys: [await exportJWK(privateKey)] },
    clients: [
      {
        client_id: OAuthClient.DEFAULT,
        client_secret: OAuthClient.DEFAULT,
        redirect_uris: redirectUris,
        grant_types: ['authorization_code'],
        response_types: ['code'],
      },
      {
        client_id: OAuthClient.RS256_TOKENS,
        client_secret: OAuthClient.RS256_TOKENS,
        redirect_uris: redirectUris,
        grant_types: ['authorization_code'],
        id_token_signed_response_alg: 'RS256',
        jwks: { keys: [await exportJWK(publicKey)] },
      },
      {
        client_id: OAuthClient.RS256_PROFILE,
        client_secret: OAuthClient.RS256_PROFILE,
        redirect_uris: redirectUris,
        grant_types: ['authorization_code'],
        userinfo_signed_response_alg: 'RS256',
        jwks: { keys: [await exportJWK(publicKey)] },
      },
    ],
  });

  const onStart = () =>
    console.log(
      `[e2e-auth-server] http://${host}:${port}/.well-known/openid-configuration`,
    );
  const app = oidc.listen(port, host, onStart);
  return () => app.close();
};

export default setup;