feat(mobile): ios oauth & magic-link login (#8581)

Co-authored-by: EYHN <cneyhn@gmail.com>
This commit is contained in:
Cats Juice
2024-10-28 14:12:33 +08:00
committed by GitHub
parent d6ec4cc597
commit 06dda70319
59 changed files with 929 additions and 219 deletions
@@ -1,6 +1,6 @@
import { Tooltip } from '@affine/component';
import { useCatchEventCallback } from '@affine/core/components/hooks/use-catch-event-hook';
import { popupWindow } from '@affine/core/utils';
import { UrlService } from '@affine/core/modules/url';
import { Unreachable } from '@affine/env/constant';
import { useI18n } from '@affine/i18n';
import {
@@ -9,6 +9,7 @@ import {
NewIcon,
ResetIcon,
} from '@blocksuite/icons/rc';
import { useService } from '@toeverything/infra';
import clsx from 'clsx';
import { useCallback, useMemo } from 'react';
@@ -186,6 +187,7 @@ export function AppUpdaterButton({
className,
style,
}: AddPageButtonProps) {
const urlService = useService(UrlService);
const handleClick = useCallback(() => {
if (updateReady) {
onQuitAndInstall();
@@ -197,7 +199,7 @@ export function AppUpdaterButton({
onDownloadUpdate();
}
} else {
popupWindow(
urlService.openPopupWindow(
`https://github.com/toeverything/AFFiNE/releases/tag/v${updateAvailable.version}`
);
}
@@ -213,6 +215,7 @@ export function AppUpdaterButton({
onQuitAndInstall,
autoDownload,
onDownloadUpdate,
urlService,
onOpenChangelog,
]);
@@ -6,6 +6,7 @@ export {
isNetworkError,
NetworkError,
} from './error';
export { WebSocketAuthProvider } from './provider/websocket-auth';
export { AccountChanged, AuthService } from './services/auth';
export { FetchService } from './services/fetch';
export { GraphQLService } from './services/graphql';
@@ -26,6 +27,7 @@ import {
WorkspaceScope,
} from '@toeverything/infra';
import { UrlService } from '../url';
import { CloudDocMeta } from './entities/cloud-doc-meta';
import { Invoices } from './entities/invoices';
import { ServerConfig } from './entities/server-config';
@@ -35,6 +37,8 @@ import { SubscriptionPrices } from './entities/subscription-prices';
import { UserCopilotQuota } from './entities/user-copilot-quota';
import { UserFeature } from './entities/user-feature';
import { UserQuota } from './entities/user-quota';
import { DefaultFetchProvider, FetchProvider } from './provider/fetch';
import { WebSocketAuthProvider } from './provider/websocket-auth';
import { AuthService } from './services/auth';
import { CloudDocMetaService } from './services/cloud-doc-meta';
import { FetchService } from './services/fetch';
@@ -57,17 +61,25 @@ import { UserQuotaStore } from './stores/user-quota';
export function configureCloudModule(framework: Framework) {
framework
.service(FetchService)
.service(FetchService, [FetchProvider])
.impl(FetchProvider, DefaultFetchProvider)
.service(GraphQLService, [FetchService])
.service(WebSocketService, [AuthService])
.service(
WebSocketService,
f =>
new WebSocketService(
f.get(AuthService),
f.getOptional(WebSocketAuthProvider)
)
)
.service(ServerConfigService)
.entity(ServerConfig, [ServerConfigStore])
.store(ServerConfigStore, [GraphQLService])
.service(AuthService, [FetchService, AuthStore])
.service(AuthService, [FetchService, AuthStore, UrlService])
.store(AuthStore, [FetchService, GraphQLService, GlobalState])
.entity(AuthSession, [AuthStore])
.service(SubscriptionService, [SubscriptionStore])
.store(SubscriptionStore, [GraphQLService, GlobalCache])
.store(SubscriptionStore, [GraphQLService, GlobalCache, UrlService])
.entity(Subscription, [AuthService, ServerConfigService, SubscriptionStore])
.entity(SubscriptionPrices, [ServerConfigService, SubscriptionStore])
.service(UserQuotaService)
@@ -0,0 +1,16 @@
import { createIdentifier } from '@toeverything/infra';
import type { FetchInit } from '../services/fetch';
export interface FetchProvider {
/**
* standard fetch, in ios&android, we can use native fetch to implement this
*/
fetch: (input: string | URL, init?: FetchInit) => Promise<Response>;
}
export const FetchProvider = createIdentifier<FetchProvider>('FetchProvider');
export const DefaultFetchProvider = {
fetch: globalThis.fetch.bind(globalThis),
};
@@ -0,0 +1,22 @@
import { createIdentifier } from '@toeverything/infra';
export interface WebSocketAuthProvider {
/**
* Returns the token and userId for WebSocket authentication
*
* Useful when cookies are not available for WebSocket connections
*
* @param url - The URL of the WebSocket endpoint
*/
getAuthToken: (url: string) => Promise<
| {
token?: string;
userId?: string;
}
| undefined
>;
}
export const WebSocketAuthProvider = createIdentifier<WebSocketAuthProvider>(
'WebSocketAuthProvider'
);
@@ -1,6 +1,6 @@
import { notify } from '@affine/component';
import { AIProvider } from '@affine/core/blocksuite/presets/ai';
import { apis, appInfo, events } from '@affine/electron-api';
import { apis, events } from '@affine/electron-api';
import type { OAuthProviderType } from '@affine/graphql';
import { I18n } from '@affine/i18n';
import { track } from '@affine/track';
@@ -13,6 +13,7 @@ import {
} from '@toeverything/infra';
import { distinctUntilChanged, map, skip } from 'rxjs';
import type { UrlService } from '../../url';
import { type AuthAccountInfo, AuthSession } from '../entities/session';
import type { AuthStore } from '../stores/auth';
import type { FetchService } from './fetch';
@@ -44,7 +45,8 @@ export class AuthService extends Service {
constructor(
private readonly fetchService: FetchService,
private readonly store: AuthStore
private readonly store: AuthStore,
private readonly urlService: UrlService
) {
super();
@@ -117,14 +119,14 @@ export class AuthService extends Service {
) {
track.$.$.auth.signIn({ method: 'magic-link' });
try {
const scheme = this.urlService.getClientSchema();
const magicLinkUrlParams = new URLSearchParams();
if (redirectUrl) {
magicLinkUrlParams.set('redirect_uri', redirectUrl);
}
magicLinkUrlParams.set(
'client',
BUILD_CONFIG.isElectron && appInfo ? appInfo.schema : 'web'
);
if (scheme) {
magicLinkUrlParams.set('client', scheme);
}
await this.fetchService.fetch('/api/auth/sign-in', {
method: 'POST',
body: JSON.stringify({
@@ -3,6 +3,7 @@ import { UserFriendlyError } from '@affine/graphql';
import { fromPromise, Service } from '@toeverything/infra';
import { BackendError, NetworkError } from '../error';
import type { FetchProvider } from '../provider/fetch';
export function getAffineCloudBaseUrl(): string {
if (BUILD_CONFIG.isElectron || BUILD_CONFIG.isIOS || BUILD_CONFIG.isAndroid) {
@@ -17,6 +18,9 @@ const logger = new DebugLogger('affine:fetch');
export type FetchInit = RequestInit & { timeout?: number };
export class FetchService extends Service {
constructor(private readonly fetchProvider: FetchProvider) {
super();
}
rxFetch = (
input: string,
init?: RequestInit & {
@@ -50,13 +54,15 @@ export class FetchService extends Service {
abortController.abort('timeout');
}, timeout);
const res = await fetch(new URL(input, getAffineCloudBaseUrl()), {
...init,
signal: abortController.signal,
}).catch(err => {
logger.debug('network error', err);
throw new NetworkError(err);
});
const res = await this.fetchProvider
.fetch(new URL(input, getAffineCloudBaseUrl()), {
...init,
signal: abortController.signal,
})
.catch(err => {
logger.debug('network error', err);
throw new NetworkError(err);
});
clearTimeout(timeoutId);
if (res.status === 504) {
const error = new Error('Gateway Timeout');
@@ -1,6 +1,7 @@
import { ApplicationStarted, OnEvent, Service } from '@toeverything/infra';
import { Manager } from 'socket.io-client';
import type { WebSocketAuthProvider } from '../provider/websocket-auth';
import { getAffineCloudBaseUrl } from '../services/fetch';
import type { AuthService } from './auth';
import { AccountChanged } from './auth';
@@ -13,10 +14,26 @@ export class WebSocketService extends Service {
transports: ['websocket'],
secure: location.protocol === 'https:',
});
socket = this.ioManager.socket('/');
socket = this.ioManager.socket('/', {
auth: this.webSocketAuthProvider
? cb => {
this.webSocketAuthProvider
?.getAuthToken(`${getAffineCloudBaseUrl()}/`)
.then(v => {
cb(v ?? {});
})
.catch(e => {
console.error('Failed to get auth token for websocket', e);
});
}
: undefined,
});
refCount = 0;
constructor(private readonly authService: AuthService) {
constructor(
private readonly authService: AuthService,
private readonly webSocketAuthProvider?: WebSocketAuthProvider
) {
super();
}
@@ -1,4 +1,3 @@
import { appInfo } from '@affine/electron-api';
import type {
CreateCheckoutSessionInput,
SubscriptionRecurring,
@@ -15,6 +14,7 @@ import {
import type { GlobalCache } from '@toeverything/infra';
import { Store } from '@toeverything/infra';
import type { UrlService } from '../../url';
import type { SubscriptionType } from '../entities/subscription';
import { getAffineCloudBaseUrl } from '../services/fetch';
import type { GraphQLService } from '../services/graphql';
@@ -22,14 +22,15 @@ import type { GraphQLService } from '../services/graphql';
const SUBSCRIPTION_CACHE_KEY = 'subscription:';
const getDefaultSubscriptionSuccessCallbackLink = (
plan: SubscriptionPlan | null
plan: SubscriptionPlan | null,
schema?: string
) => {
const path =
plan === SubscriptionPlan.AI ? '/ai-upgrade-success' : '/upgrade-success';
const urlString = getAffineCloudBaseUrl() + path;
const url = new URL(urlString);
if (BUILD_CONFIG.isElectron && appInfo) {
url.searchParams.set('schema', appInfo.schema);
if (schema) {
url.searchParams.set('schema', schema);
}
return url.toString();
};
@@ -37,7 +38,8 @@ const getDefaultSubscriptionSuccessCallbackLink = (
export class SubscriptionStore extends Store {
constructor(
private readonly gqlService: GraphQLService,
private readonly globalCache: GlobalCache
private readonly globalCache: GlobalCache,
private readonly urlService: UrlService
) {
super();
}
@@ -129,7 +131,10 @@ export class SubscriptionStore extends Store {
...input,
successCallbackLink:
input.successCallbackLink ||
getDefaultSubscriptionSuccessCallbackLink(input.plan),
getDefaultSubscriptionSuccessCallbackLink(
input.plan,
this.urlService.getClientSchema()
),
},
},
});
@@ -28,6 +28,7 @@ import { configureSystemFontFamilyModule } from './system-font-family';
import { configureTagModule } from './tag';
import { configureTelemetryModule } from './telemetry';
import { configureThemeEditorModule } from './theme-editor';
import { configureUrlModule } from './url';
import { configureUserspaceModule } from './userspace';
export function configureCommonModules(framework: Framework) {
@@ -61,4 +62,5 @@ export function configureCommonModules(framework: Framework) {
configureDocInfoModule(framework);
configureAppSidebarModule(framework);
configureJournalModule(framework);
configureUrlModule(framework);
}
@@ -0,0 +1,20 @@
import type { Framework } from '@toeverything/infra';
import { ClientSchemaProvider } from './providers/client-schema';
import { PopupWindowProvider } from './providers/popup-window';
import { UrlService } from './services/url';
export { ClientSchemaProvider } from './providers/client-schema';
export { PopupWindowProvider } from './providers/popup-window';
export { UrlService } from './services/url';
export const configureUrlModule = (container: Framework) => {
container.service(
UrlService,
f =>
new UrlService(
f.getOptional(PopupWindowProvider),
f.getOptional(ClientSchemaProvider)
)
);
};
@@ -0,0 +1,12 @@
import { createIdentifier } from '@toeverything/infra';
export interface ClientSchemaProvider {
/**
* Get the client schema in the current environment, used for the user to complete the authentication process in the browser and redirect back to the app.
*/
getClientSchema(): string | undefined;
}
export const ClientSchemaProvider = createIdentifier<ClientSchemaProvider>(
'ClientSchemaProvider'
);
@@ -0,0 +1,13 @@
import { createIdentifier } from '@toeverything/infra';
export interface PopupWindowProvider {
/**
* open a popup window, provide different implementations in different environments.
* e.g. in electron, use system default browser to open a popup window.
*/
open(url: string): void;
}
export const PopupWindowProvider = createIdentifier<PopupWindowProvider>(
'PopupWindowProvider'
);
@@ -0,0 +1,31 @@
import { Service } from '@toeverything/infra';
import type { ClientSchemaProvider } from '../providers/client-schema';
import type { PopupWindowProvider } from '../providers/popup-window';
export class UrlService extends Service {
constructor(
// those providers are optional, because they are not always available in some environments
private readonly popupWindowProvider?: PopupWindowProvider,
private readonly clientSchemaProvider?: ClientSchemaProvider
) {
super();
}
getClientSchema() {
return this.clientSchemaProvider?.getClientSchema();
}
/**
* open a popup window, provide different implementations in different environments.
* e.g. in electron, use system default browser to open a popup window.
*
* @param url only full url with http/https protocol is supported
*/
openPopupWindow(url: string) {
if (!url.startsWith('http')) {
throw new Error('only full url with http/https protocol is supported');
}
this.popupWindowProvider?.open(url);
}
}
@@ -1,4 +1,3 @@
import { popupWindow } from '@affine/core/utils';
import { apis } from '@affine/electron-api';
import { createIdentifier } from '@toeverything/infra';
import { parsePath, type To } from 'history';
@@ -20,7 +19,7 @@ export const BrowserWorkbenchNewTabHandler: WorkbenchNewTabHandler = ({
const link =
basename +
(typeof to === 'string' ? to : `${to.pathname}${to.search}${to.hash}`);
popupWindow(link);
window.open(link, '_blank');
};
export const DesktopWorkbenchNewTabHandler: WorkbenchNewTabHandler = ({
@@ -32,6 +32,7 @@ import { applyUpdate, encodeStateAsUpdate } from 'yjs';
import type {
AuthService,
FetchService,
GraphQLService,
WebSocketService,
} from '../../cloud';
@@ -59,7 +60,8 @@ export class CloudWorkspaceFlavourProviderService
private readonly authService: AuthService,
private readonly storageProvider: WorkspaceEngineStorageProvider,
private readonly graphqlService: GraphQLService,
private readonly webSocketService: WebSocketService
private readonly webSocketService: WebSocketService,
private readonly fetchService: FetchService
) {
super();
}
@@ -200,7 +202,7 @@ export class CloudWorkspaceFlavourProviderService
// get information from both cloud and local storage
// we use affine 'static' storage here, which use http protocol, no need to websocket.
const cloudStorage = new CloudStaticDocStorage(id);
const cloudStorage = new CloudStaticDocStorage(id, this.fetchService);
const docStorage = this.storageProvider.getDocStorage(id);
// download root doc
const localData = await docStorage.doc.get(id);
@@ -235,7 +237,7 @@ export class CloudWorkspaceFlavourProviderService
return localBlob;
}
const cloudBlob = new CloudBlobStorage(id);
const cloudBlob = new CloudBlobStorage(id, this.fetchService);
return await cloudBlob.get(blob);
}
getEngineProvider(workspaceId: string): WorkspaceEngineProvider {
@@ -255,8 +257,11 @@ export class CloudWorkspaceFlavourProviderService
getLocalBlobStorage: () => {
return this.storageProvider.getBlobStorage(workspaceId);
},
getRemoteBlobStorages() {
return [new CloudBlobStorage(workspaceId), new StaticBlobStorage()];
getRemoteBlobStorages: () => {
return [
new CloudBlobStorage(workspaceId, this.fetchService),
new StaticBlobStorage(),
];
},
};
}
@@ -1,7 +1,7 @@
import type { FetchService } from '@affine/core/modules/cloud';
import {
deleteBlobMutation,
fetcher,
getBaseUrl,
listBlobsQuery,
setBlobMutation,
UserFriendlyError,
@@ -12,7 +12,10 @@ import { BlobStorageOverCapacity } from '@toeverything/infra';
import { bufferToBlob } from '../../utils/buffer-to-blob';
export class CloudBlobStorage implements BlobStorage {
constructor(private readonly workspaceId: string) {}
constructor(
private readonly workspaceId: string,
private readonly fetchService: FetchService
) {}
name = 'cloud';
readonly = false;
@@ -22,15 +25,23 @@ export class CloudBlobStorage implements BlobStorage {
? key
: `/api/workspaces/${this.workspaceId}/blobs/${key}`;
return fetch(getBaseUrl() + suffix, { cache: 'default' }).then(
async res => {
return this.fetchService
.fetch(suffix, {
cache: 'default',
headers: {
Accept: 'application/octet-stream', // this is necessary for ios native fetch to return arraybuffer
},
})
.then(async res => {
if (!res.ok) {
// status not in the range 200-299
return null;
}
return bufferToBlob(await res.arrayBuffer());
}
);
})
.catch(() => {
return null;
});
}
async set(key: string, value: Blob) {
@@ -1,15 +1,23 @@
import type { FetchService } from '@affine/core/modules/cloud';
export class CloudStaticDocStorage {
name = 'cloud-static';
constructor(private readonly workspaceId: string) {}
constructor(
private readonly workspaceId: string,
private readonly fetchService: FetchService
) {}
async pull(
docId: string
): Promise<{ data: Uint8Array; state?: Uint8Array | undefined } | null> {
const response = await fetch(
const response = await this.fetchService.fetch(
`/api/workspaces/${this.workspaceId}/docs/${docId}`,
{
priority: 'high',
} as any
headers: {
Accept: 'application/octet-stream', // this is necessary for ios native fetch to return arraybuffer
},
}
);
if (response.ok) {
const arrayBuffer = await response.arrayBuffer();
@@ -1,5 +1,6 @@
import {
AuthService,
FetchService,
GraphQLService,
WebSocketService,
} from '@affine/core/modules/cloud';
@@ -33,6 +34,7 @@ export function configureBrowserWorkspaceFlavours(framework: Framework) {
WorkspaceEngineStorageProvider,
GraphQLService,
WebSocketService,
FetchService,
])
.impl(WorkspaceFlavourProvider('CLOUD'), p =>
p.get(CloudWorkspaceFlavourProviderService)