chore(deps): matrix-js-sdk 41.7 -> 44.0 (#201)
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (pull_request) Successful in 3m24s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 10s
CI / Playwright smoke (e2e) (pull_request) Successful in 16m50s

Picks up three releases of MatrixRTC / delayed-event fixes and
matrix-sdk-crypto-wasm 18.3.1 -> 18.9.0.

SDK 43 moved OAuth (MSC3861) into the SDK and dropped oidc-client-ts, so
the native-OAuth sign-in is ported:
- login discovers the auth server via /auth_metadata, registers with
  OAuth2.registerClient, and keeps the PKCE verifier + device in its own
  sessionStorage entry keyed by `state` (single use; CSRF check);
- refresh is done by the SDK (oauthClientId + onTokenRefresh); the #16
  cross-tab protection is kept by a narrow guard on refresh-token grants
  (the SDK calls the global fetch for OAuth, not fetchFn), which
  serialises them with a Web Lock and adopts a sibling tab's tokens;
- logout and forced logout revoke via mx.logout() (the SDK revokes at
  the auth server for OAuth sessions);
- the callback page parsed its params on every render, re-running the
  single-use code exchange in a loop; parsed once now.

Also: notification_type is deprecated in MSC4075 (ring in DMs, notify
elsewhere when omitted), _onRTCSessionMemberUpdate ->
ensureRecalculateSessionMembers, precache limit 6 -> 10 MB for the
7.8 MB crypto wasm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
This commit is contained in:
Lotus CI
2026-10-24 00:32:13 -04:00
committed by jared
co-authored by Claude Opus 5.5
parent bfed37bf50
commit 70206d6033
19 changed files with 682 additions and 268 deletions
+6 -2
View File
@@ -571,7 +571,11 @@ function IncomingCallListener({ callEmbed, joined }: IncomingCallListenerProps)
? content.sender_ts
: event.getTs();
const lifetime = Math.min(content.lifetime, 120000);
const notificationType = content.notification_type;
// `notification_type` is deprecated in MSC4075 (matrix-js-sdk 43+): newer
// senders may omit it and leave the presentation to us. Then ring in a
// direct chat and notify quietly elsewhere, like Element Web.
const notificationType =
content.notification_type ?? (directs.has(room.roomId) ? 'ring' : 'notification');
const relation =
event.getRelation()?.rel_type === RelationType.Reference ? event.getRelation() : undefined;
const refEventId = relation?.event_id;
@@ -653,7 +657,7 @@ function IncomingCallListener({ callEmbed, joined }: IncomingCallListenerProps)
mx.getRooms().forEach((r) => {
mx.matrixRTC
.getActiveRoomSession(r)
?._onRTCSessionMemberUpdate()
?.ensureRecalculateSessionMembers()
.catch(() => undefined);
});
};
+4 -13
View File
@@ -1,5 +1,5 @@
import { ReactNode, useCallback, useMemo } from 'react';
import { Capabilities, validateAuthMetadata, ValidatedAuthMetadata } from 'matrix-js-sdk';
import { Capabilities, ValidatedAuthMetadata } from 'matrix-js-sdk';
import { AsyncStatus, useAsyncCallbackValue } from '../hooks/useAsyncCallback';
import { useMatrixClient } from '../hooks/useMatrixClient';
import { MediaConfig } from '../hooks/useMediaConfig';
@@ -28,23 +28,14 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
const capabilities = promiseFulfilledResult(result[0]);
const mediaConfig = promiseFulfilledResult(result[1]);
// getAuthMetadata validates (and rejects when the server has no native
// OAuth, which is normal for servers using traditional SSO).
const authMetadata = promiseFulfilledResult(result[2]);
let validatedAuthMetadata: ValidatedAuthMetadata | undefined;
// Only validate if the server returned metadata — a rejected promise means no native
// Matrix OIDC (MSC3861/MAS), which is normal for servers using traditional SSO.
if (authMetadata !== undefined) {
try {
validatedAuthMetadata = validateAuthMetadata(authMetadata);
} catch (e) {
console.error(e);
}
}
return {
capabilities,
mediaConfig,
authMetadata: validatedAuthMetadata,
authMetadata,
};
}, [mx]),
);
+1 -5
View File
@@ -68,11 +68,7 @@ export function Login() {
<Text as="h1" size="H2" priority="400">
Login
</Text>
<OidcLogin
issuer={oidc.issuer}
homeserverBaseUrl={discovery['m.homeserver'].base_url}
serverName={server}
/>
<OidcLogin homeserverBaseUrl={discovery['m.homeserver'].base_url} serverName={server} />
<span data-spacing-node />
<Text align="Center">
Do not have an account? <Link to={getRegisterPath(server)}>Register</Link>
+2 -3
View File
@@ -4,7 +4,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { startOidcLogin } from '../oidc/oidcLoginUtil';
type OidcLoginProps = {
issuer: string;
homeserverBaseUrl: string;
serverName: string;
};
@@ -13,7 +12,7 @@ type OidcLoginProps = {
* with the homeserver's OIDC provider and redirects to it. Mirrors `SSOLogin`'s
* single-button styling.
*/
export function OidcLogin({ issuer, homeserverBaseUrl, serverName }: OidcLoginProps) {
export function OidcLogin({ homeserverBaseUrl, serverName }: OidcLoginProps) {
const [state, startLogin] = useAsyncCallback<void, unknown, Parameters<typeof startOidcLogin>>(
useCallback(startOidcLogin, []),
);
@@ -35,7 +34,7 @@ export function OidcLogin({ issuer, homeserverBaseUrl, serverName }: OidcLoginPr
variant="Secondary"
fill="Soft"
outlined
onClick={() => startLogin(issuer, homeserverBaseUrl)}
onClick={() => startLogin(homeserverBaseUrl)}
disabled={ongoing}
before={ongoing ? <Spinner size="200" variant="Secondary" /> : undefined}
>
+24 -17
View File
@@ -1,43 +1,45 @@
import { Box, Button, Icon, Icons, Spinner, Text, color, config } from 'folds';
import React, { useCallback, useEffect } from 'react';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { createClient } from 'matrix-js-sdk';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { setFallbackSession } from '../../../state/sessions';
import { completeAuthorizationCodeGrant } from './oidcLoginUtil';
import { getOidcCallbackUrl } from './oidcConfig';
import { completeOidcCodeGrant } from './oidcLoginUtil';
import {
invalidateCachedClient,
isStaleClientError,
parseOidcCallbackParams,
readStoredOidcIssuer,
takePendingOidcLogin,
} from './oidcState';
/**
* Exchange the authorization code for a Matrix session and persist it. The SDK
* (oidc-client-ts) reads the transient PKCE/state it stored in sessionStorage
* before the redirect and validates `state` (CSRF). `redirectUri` is the
* deterministic callback URL, recomputed here.
* Exchange the authorization code for a Matrix session and persist it. The
* pending sign-in saved before the redirect must exist for this `state`
* (CSRF check) and is consumed here.
*/
const completeOidcLogin = async (code: string, state: string): Promise<void> => {
const { tokenResponse, homeserverUrl, oidcClientSettings, idTokenClaims } =
await completeAuthorizationCodeGrant(code, state);
const pending = takePendingOidcLogin(state);
if (!pending) throw new Error('No pending sign-in for this state.');
const tokenResponse = await completeOidcCodeGrant(code, pending);
// Derive Matrix user_id + device_id from the freshly-issued access token (the
// device is owned by the authentication service under MSC3861).
const tmp = createClient({ baseUrl: homeserverUrl, accessToken: tokenResponse.access_token });
const tmp = createClient({
baseUrl: pending.homeserverUrl,
accessToken: tokenResponse.access_token,
});
const { user_id: userId, device_id: deviceId } = await tmp.whoami();
if (!userId || !deviceId) {
throw new Error('Homeserver did not return a user/device for the OIDC session.');
}
setFallbackSession(tokenResponse.access_token, deviceId, userId, homeserverUrl, {
setFallbackSession(tokenResponse.access_token, deviceId, userId, pending.homeserverUrl, {
refreshToken: tokenResponse.refresh_token,
expiresInMs: tokenResponse.expires_in ? tokenResponse.expires_in * 1000 : undefined,
oidc: {
issuer: oidcClientSettings.issuer,
clientId: oidcClientSettings.clientId,
redirectUri: getOidcCallbackUrl(),
idTokenClaims: idTokenClaims as unknown as Record<string, unknown>,
issuer: pending.issuer,
clientId: pending.clientId,
redirectUri: pending.redirectUri,
},
});
};
@@ -71,14 +73,19 @@ function CallbackError({ message }: { message: string }) {
* router, since the redirect_uri must be a real non-hash path).
*/
export function OidcCallback() {
const params = parseOidcCallbackParams(window.location.search);
// Parsed once: a fresh object per render would re-run the effects below on
// every state change, and the code (and its pending sign-in) is single-use.
const params = useMemo(() => parseOidcCallbackParams(window.location.search), []);
const redeemed = useRef(false);
const [state, complete] = useAsyncCallback<void, unknown, [string, string]>(
useCallback(completeOidcLogin, []),
);
useEffect(() => {
if (params.kind === 'success') complete(params.code, params.state);
if (params.kind !== 'success' || redeemed.current) return;
redeemed.current = true;
complete(params.code, params.state);
}, [params, complete]);
useEffect(() => {
+12 -13
View File
@@ -1,4 +1,4 @@
import type { OidcRegistrationClientMetadata } from 'matrix-js-sdk';
import type { OAuthRegistrationRequest } from 'matrix-js-sdk';
import { OIDC_CALLBACK_PATH } from '../../paths';
import { getOriginBaseUrl, withOriginBaseUrl } from '../../pathUtils';
@@ -17,22 +17,21 @@ export const getOidcCallbackUrl = (): string =>
withOriginBaseUrl(getOriginBaseUrl(), OIDC_CALLBACK_PATH);
/**
* Client metadata sent during MSC2966 dynamic client registration.
* Client metadata sent during dynamic client registration.
*
* `registerOidcClient` drops any URI that doesn't share `clientUri` as a common
* base, so every URI here lives under our origin base.
* The SDK drops any URI that doesn't share `client_uri` as a common base, so
* every URI here lives under our origin base.
*/
export const getOidcClientMetadata = (): OidcRegistrationClientMetadata => {
export const getOidcClientMetadata = (): OAuthRegistrationRequest => {
// `${origin}${BASE_URL}` (with trailing slash) — the common base for all URIs.
const clientUri = getOriginBaseUrl();
return {
clientName: 'Lotus Chat',
clientUri,
logoUri: new URL(LotusLogo, window.location.origin).href,
applicationType: 'web',
contacts: ['support@lotusguild.org'],
tosUri: clientUri,
policyUri: clientUri,
redirectUris: [getOidcCallbackUrl()],
client_name: 'Lotus Chat',
client_uri: clientUri,
logo_uri: new URL(LotusLogo, window.location.origin).href,
application_type: 'web',
tos_uri: clientUri,
policy_uri: clientUri,
redirect_uris: [getOidcCallbackUrl()],
};
};
+50 -27
View File
@@ -1,57 +1,80 @@
import {
completeAuthorizationCodeGrant,
discoverAndValidateOIDCIssuerWellKnown,
generateOidcAuthorizationUrl,
OidcClientConfig,
registerOidcClient,
} from 'matrix-js-sdk';
import { createClient, OAuth2, ValidatedAuthMetadata } from 'matrix-js-sdk';
import { getOidcCallbackUrl, getOidcClientMetadata } from './oidcConfig';
import {
cacheClientId,
getCachedClientId,
invalidateCachedClient,
isStaleClientError,
PendingOidcLogin,
savePendingOidcLogin,
} from './oidcState';
export { completeAuthorizationCodeGrant };
/**
* The homeserver's OAuth 2.0 metadata (`GET /_matrix/client/v1/auth_metadata`).
* This is also how the SDK finds the auth server for token refresh and logout,
* so login uses the same source.
*/
export const discoverAuthMetadata = (homeserverBaseUrl: string): Promise<ValidatedAuthMetadata> =>
createClient({ baseUrl: homeserverBaseUrl }).getAuthMetadata();
export const getOrRegisterClientId = async (
config: OidcClientConfig,
issuer: string,
metadata: ValidatedAuthMetadata,
redirectUri: string,
): Promise<string> => {
const cached = getCachedClientId(issuer, redirectUri);
const cached = getCachedClientId(metadata.issuer, redirectUri);
if (cached) return cached;
const clientId = await registerOidcClient(config, getOidcClientMetadata());
cacheClientId(issuer, clientId, redirectUri);
const clientId = await OAuth2.registerClient(metadata, getOidcClientMetadata());
cacheClientId(metadata.issuer, clientId, redirectUri);
return clientId;
};
/**
* Begin the OIDC authorization-code flow: discover + validate the issuer,
* (re)register a client, build the PKCE authorization URL (oidc-client-ts
* persists the transient code_verifier/state/nonce/homeserverUrl into
* sessionStorage for the callback), then redirect.
* Begin the OAuth authorization-code flow: discover the auth server through
* the homeserver, (re)register a client, remember the PKCE verifier + device
* under a fresh `state` (oidcState), then redirect. The callback reads the
* result from the query string (`response_mode=query`).
*/
export const startOidcLogin = async (issuer: string, homeserverBaseUrl: string): Promise<void> => {
export const startOidcLogin = async (homeserverBaseUrl: string): Promise<void> => {
const redirectUri = getOidcCallbackUrl();
let issuer: string | undefined;
try {
const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);
const clientId = await getOrRegisterClientId(config, issuer, redirectUri);
const url = await generateOidcAuthorizationUrl({
metadata: config,
redirectUri,
const metadata = await discoverAuthMetadata(homeserverBaseUrl);
issuer = metadata.issuer;
const clientId = await getOrRegisterClientId(metadata, redirectUri);
const oauth = new OAuth2(metadata, { clientId });
const state = crypto.randomUUID();
const pending: PendingOidcLogin = {
issuer,
clientId,
deviceId: oauth.context.deviceId,
codeVerifier: oauth.context.codeVerifier,
homeserverUrl: homeserverBaseUrl,
nonce: crypto.randomUUID(),
});
window.location.assign(url);
redirectUri,
};
savePendingOidcLogin(state, pending);
window.location.assign(
await oauth.generateAuthorizationCodeGrantUrl(state, redirectUri, 'query'),
);
} catch (e) {
// #67 — drop the cached client so the next attempt re-registers, but ONLY
// when the failure says the client id itself was rejected. Network and
// discovery failures keep the cache, otherwise each retry would register
// yet another throwaway dynamic client at the provider.
if (isStaleClientError(e)) invalidateCachedClient(issuer);
if (issuer && isStaleClientError(e)) invalidateCachedClient(issuer);
throw e;
}
};
/**
* Exchange the authorization code using the pending sign-in saved before the
* redirect. The metadata is fetched again (it isn't stored).
*/
export const completeOidcCodeGrant = async (code: string, pending: PendingOidcLogin) => {
const metadata = await discoverAuthMetadata(pending.homeserverUrl);
const oauth = new OAuth2(metadata, {
clientId: pending.clientId,
deviceId: pending.deviceId,
codeVerifier: pending.codeVerifier,
});
return oauth.completeAuthorizationCodeGrant(code, pending.redirectUri);
};
+21 -11
View File
@@ -7,6 +7,8 @@ import {
parseOidcCallbackParams,
isStaleClientError,
readStoredOidcIssuer,
savePendingOidcLogin,
takePendingOidcLogin,
} from './oidcState';
const installStorage = (): Map<string, string> => {
@@ -131,21 +133,29 @@ test('isStaleClientError: also recognises the OidcCallback error-redirect shape
);
});
test('readStoredOidcIssuer reads the issuer persisted by generateOidcAuthorizationUrl', () => {
const store = installSessionStorage();
const pending = {
issuer: 'https://issuer.example/',
clientId: 'client1',
deviceId: 'DEVICEABCD',
codeVerifier: 'v'.repeat(96),
homeserverUrl: 'https://hs.example',
redirectUri: 'https://app.example/oidc/callback',
};
test('pending sign-in: saved by state, read for the issuer, consumed once', () => {
installSessionStorage();
assert.equal(readStoredOidcIssuer('xyz'), undefined); // nothing stored yet
store.set(
'mx_oidc_xyz',
JSON.stringify({ authority: 'https://issuer.example', client_id: 'abc' }),
);
assert.equal(readStoredOidcIssuer('xyz'), 'https://issuer.example');
savePendingOidcLogin('xyz', pending);
assert.equal(readStoredOidcIssuer('xyz'), 'https://issuer.example/');
assert.equal(readStoredOidcIssuer('other-state'), undefined); // different state = miss
assert.deepEqual(takePendingOidcLogin('xyz'), pending);
assert.equal(takePendingOidcLogin('xyz'), undefined, 'single use');
});
test('readStoredOidcIssuer tolerates corrupt or missing storage', () => {
test('pending sign-in tolerates corrupt or incomplete storage', () => {
const store = installSessionStorage();
store.set('mx_oidc_bad', '{ not json');
store.set('lotus_oidc_pending_bad', '{ not json');
assert.equal(readStoredOidcIssuer('bad'), undefined);
store.set('mx_oidc_noauth', JSON.stringify({ client_id: 'abc' }));
assert.equal(readStoredOidcIssuer('noauth'), undefined);
store.set('lotus_oidc_pending_partial', JSON.stringify({ ...pending, codeVerifier: '' }));
assert.equal(takePendingOidcLogin('partial'), undefined);
});
+50 -13
View File
@@ -97,23 +97,60 @@ export const parseOidcCallbackParams = (search: string): OidcCallbackParams => {
};
/**
* #102 — the issuer for a pending sign-in isn't available on the callback's
* error branch (we bail out before `completeAuthorizationCodeGrant`, which is
* what would otherwise surface it). oidc-client-ts's `generateOidcAuthorizationUrl`
* persists the pending sign-in's `SigninState` (including `authority` and
* `client_id`) into sessionStorage before redirecting, keyed by
* `mx_oidc_<state>` (WebStorageStateStore prefix `mx_oidc_`, keyed by the same
* `state` value the provider echoes back on redirect). Read it directly so a
* genuinely stale cached client id (`invalid_client`) can be evicted even when
* the callback errors before a token exchange is attempted.
* [Gitea #201, SDK 44] The app keeps a pending OAuth sign-in itself (the SDK's
* OAuth2 class no longer persists anything). Saved in sessionStorage right
* before the redirect, keyed by the `state` we send, which the provider echoes
* back: a callback whose state has no entry is rejected (CSRF), and an entry is
* used once. Holds the PKCE code verifier, so it never goes to localStorage.
*/
export const readStoredOidcIssuer = (state: string): string | undefined => {
export type PendingOidcLogin = {
issuer: string;
clientId: string;
deviceId: string;
codeVerifier: string;
homeserverUrl: string;
redirectUri: string;
};
const PENDING_PREFIX = 'lotus_oidc_pending_';
const isPending = (v: unknown): v is PendingOidcLogin => {
if (!v || typeof v !== 'object') return false;
const p = v as Record<string, unknown>;
return ['issuer', 'clientId', 'deviceId', 'codeVerifier', 'homeserverUrl', 'redirectUri'].every(
(k) => typeof p[k] === 'string' && (p[k] as string).length > 0,
);
};
export const savePendingOidcLogin = (state: string, pending: PendingOidcLogin): void => {
sessionStorage.setItem(`${PENDING_PREFIX}${state}`, JSON.stringify(pending));
};
/** Read the pending sign-in for `state` without consuming it. */
export const readPendingOidcLogin = (state: string): PendingOidcLogin | undefined => {
try {
const raw = sessionStorage.getItem(`mx_oidc_${state}`);
const raw = sessionStorage.getItem(`${PENDING_PREFIX}${state}`);
if (!raw) return undefined;
const { authority } = JSON.parse(raw) as { authority?: unknown };
return typeof authority === 'string' ? authority : undefined;
const parsed: unknown = JSON.parse(raw);
return isPending(parsed) ? parsed : undefined;
} catch {
return undefined;
}
};
/** Read and remove: an authorization code can only be redeemed once anyway. */
export const takePendingOidcLogin = (state: string): PendingOidcLogin | undefined => {
const pending = readPendingOidcLogin(state);
try {
sessionStorage.removeItem(`${PENDING_PREFIX}${state}`);
} catch {
// storage unavailable — nothing to clean up
}
return pending;
};
/**
* #102 — on the callback's error branch, the pending sign-in's issuer tells
* us whose cached client id to evict when the provider rejected it.
*/
export const readStoredOidcIssuer = (state: string): string | undefined =>
readPendingOidcLogin(state)?.issuer;
+5 -6
View File
@@ -55,7 +55,6 @@ import { SecurityBanner } from '../../features/security-nudge/SecurityBanner';
import { AuthMetadataProvider } from '../../hooks/useAuthMetadata';
import { getFallbackSession, removeFallbackSession } from '../../state/sessions';
import { pushSessionToSW } from '../../../sw-session';
import { revokeOidcTokens } from '../../../client/oidcLogout';
import { useSessionSync } from '../../hooks/useSessionSync';
import { installCryptoDiagLog } from '../../utils/cryptoDiagLog';
import { AutoDiscovery } from './AutoDiscovery';
@@ -159,11 +158,11 @@ const useLogoutListener = (mx?: MatrixClient) => {
pushSessionToSW();
mx?.stopClient();
// Best-effort issuer revocation for OIDC sessions (the token is already
// server-revoked here, but revoke the refresh token too). Before we drop
// the stored session below.
const loggedOutSession = getFallbackSession();
if (loggedOutSession?.oidc) {
await revokeOidcTokens(loggedOutSession).catch(() => undefined);
// server-revoked here, but revoke the refresh token too). For an OAuth
// session the SDK's logout() only revokes at the auth server (no /logout
// call). Before we drop the stored session below.
if (getFallbackSession()?.oidc) {
await mx?.logout().catch(() => undefined);
}
await mx?.clearStores();
// The opt-in local search index holds DECRYPTED message plaintext. Wipe it
+3 -3
View File
@@ -5,9 +5,9 @@
// setLocalStorageItem,
// } from './utils/atomWithLocalStorage';
// OIDC/next-gen-auth (MSC3861) metadata needed to refresh + revoke tokens. Kept
// as a generic claims object so this core module stays decoupled from
// oidc-client-ts (the refresher casts idTokenClaims to IdTokenClaims).
// OIDC/next-gen-auth (MSC3861) metadata needed to refresh + revoke tokens. Since
// matrix-js-sdk 43 only `clientId` is used (the SDK finds the auth server via
// /auth_metadata); `idTokenClaims` is kept for sessions saved by older builds.
export type OidcSessionMeta = {
issuer: string;
clientId: string;