mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-01 22:32:32 -08:00
fix: keep service worker session persistence alive (#1624)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- 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 - [ ] 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:
2 files changed
+117
-15
No files matched your search
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
/* oxlint-disable vitest/require-mock-type-parameters */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { readPersistedSession } from './sw-session-persistence';
|
||||
|
||||
vi.mock('workbox-precaching', () => ({
|
||||
cleanupOutdatedCaches: vi.fn(),
|
||||
precacheAndRoute: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('readPersistedSession', () => {
|
||||
it('keeps older persisted sessions instead of expiring them after one minute', () => {
|
||||
const persistedAt = Date.now() - 1000 * 60 * 60 * 6;
|
||||
@@ -20,3 +26,95 @@ describe('readPersistedSession', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('service worker session persistence', () => {
|
||||
let addEventListener: ReturnType<typeof vi.fn>;
|
||||
let cachePut: ReturnType<typeof vi.fn>;
|
||||
let resolveCachePut: (() => void) | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
addEventListener = vi.fn();
|
||||
cachePut = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveCachePut = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
vi.stubGlobal('self', {
|
||||
__WB_MANIFEST: [],
|
||||
addEventListener,
|
||||
caches: {
|
||||
open: vi.fn(async () => ({
|
||||
delete: vi.fn(async () => true),
|
||||
match: vi.fn(async () => undefined),
|
||||
put: cachePut,
|
||||
})),
|
||||
},
|
||||
clients: {
|
||||
claim: vi.fn(),
|
||||
get: vi.fn(),
|
||||
matchAll: vi.fn(async () => []),
|
||||
},
|
||||
registration: {},
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn<typeof globalThis.fetch>());
|
||||
await import('./sw');
|
||||
});
|
||||
|
||||
it('keeps setSession persistence alive through waitUntil', async () => {
|
||||
const messageHandler = addEventListener.mock.calls.find(([type]) => type === 'message')?.[1] as
|
||||
| ((event: ExtendableMessageEvent) => void)
|
||||
| undefined;
|
||||
const waitUntil = vi.fn<(promise: Promise<unknown>) => void>();
|
||||
|
||||
messageHandler?.({
|
||||
source: { id: 'client-a' },
|
||||
data: {
|
||||
type: 'setSession',
|
||||
accessToken: 'token',
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
},
|
||||
waitUntil,
|
||||
} as unknown as ExtendableMessageEvent);
|
||||
|
||||
expect(messageHandler).toBeTypeOf('function');
|
||||
expect(waitUntil).toHaveBeenCalledOnce();
|
||||
|
||||
let settled = false;
|
||||
const lifetime = waitUntil.mock.calls[0]?.[0];
|
||||
void lifetime?.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await vi.waitFor(() => expect(resolveCachePut).toBeTypeOf('function'));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(settled).toBe(false);
|
||||
|
||||
resolveCachePut?.();
|
||||
await expect(lifetime).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('settles the worker lifetime when session persistence fails', async () => {
|
||||
cachePut.mockRejectedValueOnce(new Error('cache unavailable'));
|
||||
const messageHandler = addEventListener.mock.calls.find(([type]) => type === 'message')?.[1] as
|
||||
| ((event: ExtendableMessageEvent) => void)
|
||||
| undefined;
|
||||
const waitUntil = vi.fn<(promise: Promise<unknown>) => void>();
|
||||
|
||||
messageHandler?.({
|
||||
source: { id: 'client-a' },
|
||||
data: {
|
||||
type: 'setSession',
|
||||
accessToken: 'token',
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
},
|
||||
waitUntil,
|
||||
} as unknown as ExtendableMessageEvent);
|
||||
|
||||
expect(waitUntil).toHaveBeenCalledOnce();
|
||||
await expect(waitUntil.mock.calls[0]?.[0]).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import { EventType } from 'matrix-js-sdk/lib/@types/event';
|
||||
|
||||
import { createPushNotifications } from './sw/pushNotification';
|
||||
import { withMediaFetchSlot } from './app/utils/mediaConcurrency';
|
||||
import { readPersistedSession } from './sw-session-persistence';
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope;
|
||||
|
||||
@@ -105,15 +106,7 @@ async function loadPersistedSession(): Promise<SessionInfo | undefined> {
|
||||
const cache = await self.caches.open(SW_SESSION_CACHE);
|
||||
const response = await cache.match(SW_SESSION_URL);
|
||||
if (!response) return undefined;
|
||||
const s = await response.json();
|
||||
if (typeof s.accessToken === 'string' && typeof s.baseUrl === 'string') {
|
||||
return {
|
||||
accessToken: s.accessToken,
|
||||
baseUrl: s.baseUrl,
|
||||
userId: typeof s.userId === 'string' ? s.userId : undefined,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
return readPersistedSession(await response.json());
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -157,7 +150,13 @@ async function cleanupDeadClients() {
|
||||
});
|
||||
}
|
||||
|
||||
function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, userId?: unknown) {
|
||||
function setSession(
|
||||
clientId: string,
|
||||
accessToken: unknown,
|
||||
baseUrl: unknown,
|
||||
userId?: unknown
|
||||
): Promise<void> {
|
||||
let persistence: Promise<void>;
|
||||
if (typeof accessToken === 'string' && typeof baseUrl === 'string') {
|
||||
const info: SessionInfo = {
|
||||
accessToken,
|
||||
@@ -169,13 +168,13 @@ function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, us
|
||||
preloadedSession = undefined;
|
||||
console.debug('[SW] setSession: stored', clientId, baseUrl);
|
||||
// Persist so push-event fetches work after iOS restarts the SW.
|
||||
persistSession(info).catch(() => undefined);
|
||||
persistence = persistSession(info);
|
||||
} else {
|
||||
// Logout or invalid session
|
||||
sessions.delete(clientId);
|
||||
preloadedSession = undefined;
|
||||
console.debug('[SW] setSession: removed', clientId);
|
||||
clearPersistedSession().catch(() => undefined);
|
||||
persistence = clearPersistedSession();
|
||||
}
|
||||
|
||||
const pending = pendingSessionRequests.get(clientId);
|
||||
@@ -183,6 +182,8 @@ function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, us
|
||||
pending.resolve(sessions.get(clientId));
|
||||
pendingSessionRequests.delete(clientId);
|
||||
}
|
||||
|
||||
return persistence;
|
||||
}
|
||||
|
||||
function requestSession(client: Client): Promise<SessionInfo | undefined> {
|
||||
@@ -580,8 +581,11 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => {
|
||||
const { type, accessToken, baseUrl, userId } = data as Record<string, unknown>;
|
||||
|
||||
if (type === 'setSession') {
|
||||
setSession(client.id, accessToken, baseUrl, userId);
|
||||
event.waitUntil(cleanupDeadClients());
|
||||
event.waitUntil(
|
||||
Promise.all([setSession(client.id, accessToken, baseUrl, userId), cleanupDeadClients()]).then(
|
||||
() => undefined
|
||||
)
|
||||
);
|
||||
}
|
||||
if (type === 'swMediaAuthProbe') {
|
||||
// Capability handshake: prove this SW intercepts authenticated media so the
|
||||
|
||||
Reference in new issue
Block a user