fix: guard getAppPathFromHref against Tauri synthetic origin mismatch (#1233)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

fixes the page not found after login

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
haz authored and GitHub committed 2026-07-23 08:50:33 +00:00
commit 95d64f389d
5 files changed
+126 -14

No files matched your search

+86 -3
View File
@@ -1,6 +1,11 @@
import { describe, it, expect } from 'vitest';
import type { BearerTokenResponse } from '$types/matrix-sdk';
import { deviceIdFromScope, expiresInMsFromToken } from './oidcLoginUtil';
import { beforeEach, describe, it, expect, vi } from 'vitest';
import type { BearerTokenResponse, ValidatedAuthMetadata } from '$types/matrix-sdk';
import {
deviceIdFromScope,
expiresInMsFromToken,
completeOidcLogin,
persistOauthContext,
} from './oidcLoginUtil';
describe('deviceIdFromScope', () => {
it('extracts the device id from the stable device scope', () => {
@@ -35,3 +40,81 @@ describe('expiresInMsFromToken', () => {
).toBeUndefined();
});
});
const mocks = vi.hoisted(() => ({
oauth2Context: vi.fn<(context: unknown) => void>(),
completeAuthorizationCodeGrant: vi.fn<(code: string) => Promise<BearerTokenResponse>>(),
getAuthMetadata: vi.fn<() => Promise<ValidatedAuthMetadata>>(),
whoami: vi.fn<() => Promise<{ user_id: string; device_id?: string }>>(),
setAccessToken: vi.fn<(token: string) => void>(),
}));
vi.mock('$types/matrix-sdk', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return {
...actual,
OAuth2: class {
public constructor(_metadata: unknown, context: unknown) {
mocks.oauth2Context(context);
}
public completeAuthorizationCodeGrant = mocks.completeAuthorizationCodeGrant;
public context = { deviceId: 'dev', codeVerifier: 'verifier' };
},
createClient: vi
.fn<(opts: { baseUrl: string; fetchFn: typeof fetch }) => Record<string, unknown>>()
.mockImplementation(() => ({
getAuthMetadata: mocks.getAuthMetadata,
setAccessToken: mocks.setAccessToken,
whoami: mocks.whoami,
})),
};
});
const metadata = {
issuer: 'https://issuer.example',
authorization_endpoint: 'https://issuer.example/authorize',
token_endpoint: 'https://issuer.example/token',
revocation_endpoint: 'https://issuer.example/revoke',
registration_endpoint: 'https://issuer.example/register',
response_modes_supported: ['query', 'fragment'],
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'],
code_challenge_methods_supported: ['S256'],
} as ValidatedAuthMetadata;
const tokenResponse = {
access_token: 'access-tok',
token_type: 'Bearer',
refresh_token: 'refresh-tok',
expires_in: 300,
} as BearerTokenResponse;
describe('completeOidcLogin', () => {
beforeEach(() => {
sessionStorage.clear();
mocks.oauth2Context.mockReset();
mocks.completeAuthorizationCodeGrant.mockReset().mockResolvedValue(tokenResponse);
mocks.getAuthMetadata.mockReset().mockResolvedValue(metadata);
mocks.whoami
.mockReset()
.mockResolvedValue({ user_id: '@alice:hs.example', device_id: 'DEV123' });
mocks.setAccessToken.mockReset();
});
it('uses the registered redirect URI from the OAuth context, not a re-parsed callback URL', async () => {
persistOauthContext('s1', {
issuer: 'https://issuer.example',
clientId: 'client',
redirectUri: 'moe.sable.app:/login',
deviceId: 'dev',
codeVerifier: 'verifier',
homeserverUrl: 'https://hs.example',
});
await completeOidcLogin('code-1', 's1');
expect(mocks.oauth2Context).toHaveBeenCalledWith(
expect.objectContaining({ redirectUri: 'moe.sable.app:/login' })
);
});
});
@@ -86,10 +86,6 @@ const startBackgroundClient = async (session: Session): Promise<MatrixClient> =>
const tempClient = createClient({
baseUrl: session.baseUrl,
fetchFn: fetch,
accessToken: session.accessToken,
refreshToken: session.refreshToken,
userId: session.userId,
deviceId: session.deviceId,
});
const tokenRefresher = createSessionTokenRefresher(session, tempClient);
+31 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { getSettingsPath } from './pathUtils';
import { getAppPathFromHref, getSettingsPath } from './pathUtils';
describe('getSettingsPath', () => {
it('returns the settings root path', () => {
@@ -13,3 +13,33 @@ describe('getSettingsPath', () => {
);
});
});
describe('getAppPathFromHref', () => {
it('extracts the app path for a matching browser-router origin', () => {
expect(getAppPathFromHref('https://app.sable.moe/', 'https://app.sable.moe/')).toBe('/');
expect(getAppPathFromHref('https://app.sable.moe/', 'https://app.sable.moe/login')).toBe(
'/login'
);
expect(
getAppPathFromHref('https://app.sable.moe/', 'https://app.sable.moe/home/room/%21abc')
).toBe('/home/room/%21abc');
});
it('extracts the app path for a matching hash-router origin', () => {
expect(getAppPathFromHref('https://app.sable.moe/#/', 'https://app.sable.moe/#/')).toBe('/');
expect(
getAppPathFromHref('https://app.sable.moe/#/', 'https://app.sable.moe/#/login?code=c&state=s')
).toBe('/login?code=c&state=s');
});
it('extracts the path from the href when the origin does not match the base (Tauri)', () => {
expect(getAppPathFromHref('https://app.sable.moe/', 'https://tauri.localhost/')).toBe('/');
expect(
getAppPathFromHref('https://app.sable.moe/', 'https://tauri.localhost/login?code=c&state=s')
).toBe('/login?code=c&state=s');
});
it('returns empty when a hash-router base is paired with a hashless href', () => {
expect(getAppPathFromHref('https://app.sable.moe/#/', 'https://tauri.localhost/')).toBe('');
});
});
+9 -2
View File
@@ -64,16 +64,23 @@ export const getAppPathFromHref = (baseUrl: string, href: string): string => {
const baseHashIndex = baseUrl.indexOf('#');
if (baseHashIndex > -1) {
const hrefHashIndex = href.indexOf('#');
if (hrefHashIndex === -1) return '';
// href may/not have "/" around "#"
// we need to take care of this when extracting app path
const trimmedBaseUrl = trimLeadingSlash(baseUrl.slice(baseHashIndex + 1));
const trimmedHref = trimLeadingSlash(href.slice(hrefHashIndex + 1));
const appPath = trimmedHref.slice(trimmedBaseUrl.length);
const appPath = trimmedHref.startsWith(trimmedBaseUrl)
? trimmedHref.slice(trimmedBaseUrl.length)
: '';
return `/${trimLeadingSlash(appPath)}`;
}
return href.slice(trimTrailingSlash(baseUrl).length);
const trimmedBaseUrl = trimTrailingSlash(baseUrl);
if (href.startsWith(trimmedBaseUrl)) return href.slice(trimmedBaseUrl.length);
const { pathname, search } = new URL(href);
return pathname + search;
};
export const getRootPath = (): string => ROOT_PATH;
-4
View File
@@ -260,10 +260,6 @@ const buildClient = async (session: Session): Promise<BuiltClient> => {
const tempClient = createClient({
baseUrl: session.baseUrl,
fetchFn: fetch,
accessToken: session.accessToken,
refreshToken: session.refreshToken,
userId: session.userId,
deviceId: session.deviceId,
});
const tokenRefresher = createSessionTokenRefresher(session, tempClient);