Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/add-native-oidc-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: minor
---

Add Native OIDC (OAuth 2.0) login so you can sign in to and register on homeservers that use delegated authentication, such as continuwuity and Synapse with the Matrix Authentication Service. Sessions stay signed in through automatic token refresh, and signing out revokes the tokens on the server.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"linkify-react": "^4.3.3",
"linkifyjs": "^4.3.3",
"marked": "^18.0.5",
"matrix-js-sdk": "^41.9.0",
"matrix-js-sdk": "42.0.0-rc.0",
"matrix-widget-api": "^1.17.0",
"pdfjs-dist": "^6.1.200",
"react": "^18.3.1",
Expand Down
26 changes: 5 additions & 21 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 12 additions & 6 deletions src/app/components/AuthFlowsLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr

const [state, load] = useAsyncCallback(
useCallback(async () => {
const result = await Promise.allSettled([mx.loginFlows(), mx.registerRequest({})]);
const result = await Promise.allSettled([
mx.loginFlows(),
mx.registerRequest({}),
mx.getAuthMetadata(),
]);
const loginFlows = promiseFulfilledResult(result[0]);
const registerResp = promiseRejectedResult(result[1]) as MatrixError | undefined;
const authMetadata = promiseFulfilledResult(result[2]);
let registerFlows: RegisterFlowsResponse = {
status: RegisterFlowStatus.InvalidRequest,
};
Expand All @@ -32,16 +37,17 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr
registerFlows = parseRegisterErrResp(registerResp);
}

if (!loginFlows) {
const validLoginFlows = loginFlows && !('errcode' in loginFlows) ? loginFlows : undefined;

// OIDC-only servers reject GET /login; that is fine when the OAuth 2.0 API is available.
if (!validLoginFlows && !authMetadata) {
throw new Error('Missing auth flow!');
}
if ('errcode' in loginFlows) {
throw new Error('Failed to load auth flow!');
}

const authFlows: AuthFlows = {
loginFlows,
loginFlows: validLoginFlows ?? { flows: [] },
registerFlows,
authMetadata,
};

return authFlows;
Expand Down
18 changes: 16 additions & 2 deletions src/app/components/LogoutDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { forwardRef, useCallback } from 'react';
import { Dialog, Header, config, Box, Text, Button, Spinner, color } from 'folds';
import { useAtomValue, useSetAtom } from 'jotai';
import { logoutClient } from '$client/initMatrix';
import { activeSessionIdAtom, sessionsAtom } from '$state/sessions';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useCrossSigningActive } from '$hooks/useCrossSigning';
Expand All @@ -16,6 +18,11 @@ type LogoutDialogProps = {
export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
({ handleClose }, ref) => {
const mx = useMatrixClient();
const sessions = useAtomValue(sessionsAtom);
const activeSessionId = useAtomValue(activeSessionIdAtom);
const setSessions = useSetAtom(sessionsAtom);
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
const activeSession = sessions.find((s) => s.userId === activeSessionId) ?? sessions[0];
const hasEncryptedRoom = !!mx.getRooms().find((room) => room.hasEncryptionStateEvent());
const crossSigningActive = useCrossSigningActive();
const verificationStatus = useDeviceVerificationStatus(
Expand All @@ -26,8 +33,15 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(

const [logoutState, logout] = useAsyncCallback<void, Error, []>(
useCallback(async () => {
await logoutClient(mx);
}, [mx])
await logoutClient(mx, activeSession);
if (activeSession) {
setSessions({ type: 'DELETE', session: activeSession });
setActiveSessionId(
sessions.find((s) => s.userId !== activeSession.userId)?.userId ?? undefined
);
}
window.location.reload();
}, [mx, activeSession, sessions, setSessions, setActiveSessionId])
);

const ongoingLogout = logoutState.status === AsyncStatus.Loading;
Expand Down
13 changes: 1 addition & 12 deletions src/app/components/ServerConfigsLoader.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import type { ReactNode } from 'react';
import { useCallback, useMemo } from 'react';
import type { Capabilities, ValidatedAuthMetadata } from '$types/matrix-sdk';
import { validateAuthMetadata } from '$types/matrix-sdk';
import { AsyncStatus, useAsyncCallbackValue } from '$hooks/useAsyncCallback';
import { useMatrixClient } from '$hooks/useMatrixClient';
import type { MediaConfig } from '$hooks/useMediaConfig';
import { promiseFulfilledResult } from '$utils/common';
import { createLogger } from '$utils/debug';

export type ServerConfigs = {
capabilities?: Capabilities;
Expand All @@ -18,8 +16,6 @@ type ServerConfigsLoaderProps = {
children: (configs: ServerConfigs) => ReactNode;
};

const log = createLogger('ServerConfigsLoader');

export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
const mx = useMatrixClient();
const fallbackConfigs = useMemo(() => ({}), []);
Expand All @@ -35,18 +31,11 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
const capabilities = promiseFulfilledResult(result[0]);
const mediaConfig = promiseFulfilledResult(result[1]);
const authMetadata = promiseFulfilledResult(result[2]);
let validatedAuthMetadata: ValidatedAuthMetadata | undefined;

try {
validatedAuthMetadata = validateAuthMetadata(authMetadata);
} catch (e) {
log.error('Failed to validate auth metadata:', e);
}

return {
capabilities,
mediaConfig,
authMetadata: validatedAuthMetadata,
authMetadata,
};
}, [mx])
);
Expand Down
8 changes: 3 additions & 5 deletions src/app/features/settings/general/General.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1393,11 +1393,9 @@ export function Sync() {
const handleSetSlidingSync = (value: boolean) => {
if (!activeSession) return;
setSessions({
type: 'PUT',
session: {
...activeSession,
slidingSyncOptIn: value,
},
type: 'UPDATE',
userId: activeSession.userId,
patch: { slidingSyncOptIn: value },
});
window.location.reload();
};
Expand Down
8 changes: 7 additions & 1 deletion src/app/hooks/useAuthFlows.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { createContext, useContext } from 'react';
import type { IAuthData, MatrixError, ILoginFlowsResponse } from '$types/matrix-sdk';
import type {
IAuthData,
MatrixError,
ILoginFlowsResponse,
ValidatedAuthMetadata,
} from '$types/matrix-sdk';

export enum RegisterFlowStatus {
FlowRequired = 401,
Expand Down Expand Up @@ -43,6 +48,7 @@ export const parseRegisterErrResp = (matrixError: MatrixError): RegisterFlowsRes
export type AuthFlows = {
loginFlows: ILoginFlowsResponse;
registerFlows: RegisterFlowsResponse;
authMetadata?: ValidatedAuthMetadata;
};

const AuthFlowsContext = createContext<AuthFlows | null>(null);
Expand Down
26 changes: 26 additions & 0 deletions src/app/hooks/useParsedLoginFlows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest';
import type { ISSOFlow } from '$types/matrix-sdk';
import { isOauthAwarePreferred } from './useParsedLoginFlows';

describe('isOauthAwarePreferred', () => {
it('is false for an undefined flow', () => {
expect(isOauthAwarePreferred(undefined)).toBe(false);
});

it('is false for a plain SSO flow', () => {
expect(isOauthAwarePreferred({ type: 'm.login.sso' } as ISSOFlow)).toBe(false);
});

it('reads the stable oauth_aware_preferred field', () => {
const flow = { type: 'm.login.sso', oauth_aware_preferred: true } as ISSOFlow;
expect(isOauthAwarePreferred(flow)).toBe(true);
});

it('reads the deprecated msc3824 field', () => {
const flow = {
type: 'm.login.sso',
'org.matrix.msc3824.delegated_oidc_compatibility': true,
} as ISSOFlow;
expect(isOauthAwarePreferred(flow)).toBe(true);
});
});
7 changes: 7 additions & 0 deletions src/app/hooks/useParsedLoginFlows.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { useMemo } from 'react';
import type { ILoginFlow, IPasswordFlow, ISSOFlow, LoginFlow } from '$types/matrix-sdk';
import { OAUTH_AWARE_PREFERRED_FLOW_FIELD } from '$types/matrix-sdk';

export const getSSOFlow = (loginFlows: LoginFlow[]): ISSOFlow | undefined =>
loginFlows.find((flow) => flow.type === 'm.login.sso' || flow.type === 'm.login.cas') as
| ISSOFlow
| undefined;

export const isOauthAwarePreferred = (ssoFlow: ISSOFlow | undefined): boolean =>
Boolean(
ssoFlow?.[OAUTH_AWARE_PREFERRED_FLOW_FIELD.name] ??
ssoFlow?.[OAUTH_AWARE_PREFERRED_FLOW_FIELD.altName]
);

export const getPasswordFlow = (loginFlows: LoginFlow[]): IPasswordFlow | undefined =>
loginFlows.find((flow) => flow.type === 'm.login.password') as IPasswordFlow;
export const getTokenFlow = (loginFlows: LoginFlow[]): LoginFlow | undefined =>
Expand Down
13 changes: 10 additions & 3 deletions src/app/hooks/usePathWithOrigin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,32 @@ import { useMemo } from 'react';
import { trimLeadingSlash, trimSlash, trimTrailingSlash } from '$utils/common';
import { useClientConfig } from './useClientConfig';

export const usePathWithOrigin = (path: string): string => {
export const usePathWithOrigin = (
path: string,
options?: {
/** OAuth redirect URIs must not contain a fragment (RFC 6749). */
ignoreHashRouter?: boolean;
}
): string => {
const { hashRouter } = useClientConfig();
const { origin } = window.location;
const ignoreHashRouter = options?.ignoreHashRouter ?? false;

const pathWithOrigin = useMemo(() => {
let url: string = trimSlash(origin);

url += `/${trimSlash(import.meta.env.BASE_URL ?? '')}`;
url = trimTrailingSlash(url);

if (hashRouter?.enabled) {
if (hashRouter?.enabled && !ignoreHashRouter) {
url += `/#/${trimSlash(hashRouter.basename ?? '')}`;
url = trimTrailingSlash(url);
}

url += `/${trimLeadingSlash(path)}`;

return url;
}, [path, hashRouter, origin]);
}, [path, hashRouter, origin, ignoreHashRouter]);

return pathWithOrigin;
};
Loading
Loading