Add "ui login" support

This commit is contained in:
schroda
2025-07-27 00:03:51 +02:00
parent 403cab7d80
commit 4aad410957
33 changed files with 1270 additions and 203 deletions

View File

@@ -7,12 +7,60 @@
*/
import { AppStorage } from '@/lib/storage/AppStorage.ts';
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
import { AuthManager } from '@/features/authentication/AuthManager.ts';
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
export abstract class BaseClient<Client, ClientConfig, Fetcher> {
protected abstract client: Client;
public abstract readonly fetcher: Fetcher;
private static activeTokenRefreshPromise: Promise<UserRefreshMutation | null | undefined> | null = null;
protected static async refreshAccessToken(
refreshFn: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>,
): Promise<UserRefreshMutation | null | undefined> {
const refreshToken = AuthManager.getRefreshToken();
if (!AuthManager.isAuthRequired()) {
AuthManager.setAuthRequired(true);
}
if (!refreshToken) {
throw new Error('No refresh token found');
}
if (this.activeTokenRefreshPromise) {
return this.activeTokenRefreshPromise;
}
const refreshRequest = refreshFn(refreshToken).response;
this.activeTokenRefreshPromise = refreshRequest.then((result) => result.data);
try {
const result = await refreshRequest;
const { data } = result;
if (!data) {
throw new Error('No refreshed access token returned');
}
AuthManager.setAccessToken(data.refreshToken.accessToken);
return data;
} catch (e) {
AuthManager.removeTokens();
throw e;
} finally {
this.activeTokenRefreshPromise = null;
}
}
protected constructor(
protected handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>,
) {}
public getBaseUrl(): string {
const { hostname, port, protocol } = window.location;

View File

@@ -6,6 +6,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { onError } from '@apollo/client/link/error';
import { setContext } from '@apollo/client/link/context';
import {
ApolloClient,
ApolloClientOptions,
@@ -14,6 +16,7 @@ import {
NormalizedCacheObject,
split,
from,
fromPromise,
} from '@apollo/client';
import createUploadLink from 'apollo-upload-client/createUploadLink.mjs';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
@@ -23,6 +26,9 @@ import { TypePolicies } from '@apollo/client/cache';
import { removeTypenameFromVariables } from '@apollo/client/link/remove-typename';
import { BaseClient } from '@/lib/requests/client/BaseClient.ts';
import { StrictTypedTypePolicies } from '@/lib/graphql/generated/apollo-helpers.ts';
import { AuthManager } from '@/features/authentication/AuthManager.ts';
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
/* eslint-disable no-underscore-dangle */
const typePolicies: StrictTypedTypePolicies = {
@@ -187,8 +193,8 @@ export class GraphQLClient extends BaseClient<
private wsClient!: Client;
constructor() {
super();
constructor(handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>) {
super(handleRefreshToken);
this.createClient();
}
@@ -201,8 +207,44 @@ export class GraphQLClient extends BaseClient<
this.wsClient.terminate();
}
private createErrorLink() {
return onError(({ graphQLErrors, operation, forward }) => {
if (!graphQLErrors) {
return undefined;
}
const isAuthError = graphQLErrors.some((graphQLError) =>
graphQLError.message.includes('suwayomi.tachidesk.server.user.UnauthorizedException'),
);
if (!isAuthError) {
return undefined;
}
return fromPromise(BaseClient.refreshAccessToken(this.handleRefreshToken))
.filter(Boolean)
.flatMap(() => forward(operation));
});
}
private createAuthLink() {
return setContext((_, { headers }) => {
const isAuthRequired = AuthManager.isAuthRequired();
const accessToken = AuthManager.getAccessToken();
return {
headers: {
credentials: 'include',
...headers,
Authorization: isAuthRequired && accessToken ? `Bearer ${accessToken}` : '',
},
};
});
}
private createUploadLink() {
return createUploadLink({ uri: () => this.getBaseUrl(), credentials: 'include' });
return createUploadLink({
uri: () => this.getBaseUrl(),
});
}
private createWSLink() {
@@ -218,8 +260,13 @@ export class GraphQLClient extends BaseClient<
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
this.createWSLink(),
// apollo-upload-client dependency is outdated (see 134e47763faae9e62db4d4e3a8387a74e32e5568) and thus types are not matching, but they are still correct
from([removeTypenameLink, this.createUploadLink() as unknown as ApolloLink]),
from([
this.createErrorLink(),
this.createAuthLink(),
removeTypenameLink,
// apollo-upload-client dependency is outdated (see 134e47763faae9e62db4d4e3a8387a74e32e5568) and thus types are not matching, but they are still correct
this.createUploadLink() as unknown as ApolloLink,
]),
);
}
@@ -230,6 +277,14 @@ export class GraphQLClient extends BaseClient<
url: () => this.getBaseUrl().replace(/http(|s)/g, 'ws'),
keepAlive: heartbeatInterval,
retryAttempts: 10,
connectionParams: () => {
const isAuthRequired = AuthManager.isAuthRequired();
const accessToken = AuthManager.getAccessToken();
return {
Authorization: isAuthRequired && accessToken ? accessToken : undefined,
};
},
});
let lastHeartbeat: number = 0;

View File

@@ -7,6 +7,9 @@
*/
import { BaseClient } from '@/lib/requests/client/BaseClient.ts';
import { AuthManager } from '@/features/authentication/AuthManager.ts';
import { UserRefreshMutation } from '@/lib/graphql/generated/graphql.ts';
import { AbortableApolloMutationResponse } from '@/lib/requests/RequestManager.ts';
export enum HttpMethod {
GET = 'GET',
@@ -48,17 +51,28 @@ export class RestClient
} = {},
): Promise<Response> => {
const updatedUrl = url.startsWith('http') ? url : `${this.getBaseUrl()}${url}`;
const accessToken = AuthManager.getAccessToken();
let result: Response;
switch (httpMethod) {
case HttpMethod.GET:
result = await this.client(updatedUrl, { ...this.config, ...config, method: httpMethod });
result = await this.client(updatedUrl, {
...this.config,
...config,
method: httpMethod,
headers: {
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
...this.config.headers,
...config?.headers,
},
});
break;
case HttpMethod.POST:
case HttpMethod.PATCH:
case HttpMethod.DELETE:
result = await this.client(updatedUrl, {
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
...this.config,
...config,
method: httpMethod,
@@ -69,6 +83,11 @@ export class RestClient
throw new Error(`Unexpected HttpMethod "${httpMethod}"`);
}
if (result.status === 401) {
await BaseClient.refreshAccessToken(this.handleRefreshToken);
return this.fetcher(url, { data, httpMethod, config, checkResponseIsJson });
}
if (result.status !== 200) {
throw new Error(`status ${result.status}: ${result.statusText}`);
}
@@ -80,8 +99,8 @@ export class RestClient
return result;
};
constructor() {
super();
constructor(handleRefreshToken: (refreshToken: string) => AbortableApolloMutationResponse<UserRefreshMutation>) {
super(handleRefreshToken);
this.createClient();
}