mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 19:25:00 +03:00
fix(web): keep auth intents across reloads
Renew callback leases while handlers run. Keep recovery intents until the lease ends or the intent expires. Bind vault writes and deletes to the loaded revision.
This commit is contained in:
1 parent
db948a8c31
commit
e1c67abf93
9 files changed
+683
-113
No files matched your search
@@ -15,7 +15,7 @@ With `lazyTier1`, `openDesktopStore` reads no media at startup. It reads only th
|
||||
- Post `changes` messages on `idb:${dbName}` with document and blob IDs only, never frames or blob bytes.
|
||||
|
||||
- Only the holder of the Web Lock `affine:replicator:${dbName}` may start outbound cloud replication writes. Without Web Locks, replication is read-only. Local edits and IndexedDB change notifications continue.
|
||||
- Keep only the cookie credential marker and session metadata in the credential vault. Commit generation comparisons and updates in one IndexedDB transaction. Use the account Web Lock when available. Keep the session revision and at most 32 retired epochs after logout. Remove the session record and credential marker.
|
||||
- Keep only the cookie credential marker and session metadata in the credential vault. Commit generation comparisons and updates in one IndexedDB transaction. Use the account Web Lock when available. Bind writes and deletes to the revision of the loaded snapshot. A call without a snapshot requires one known revision since the last successful change. Keep the session revision and at most 32 retired epochs after logout. Remove the session record and credential marker.
|
||||
|
||||
## Hard boundaries
|
||||
|
||||
@@ -26,7 +26,7 @@ With `lazyTier1`, `openDesktopStore` reads no media at startup. It reads only th
|
||||
|
||||
- Keep at most one `aria-hidden="true"` zero-size safe-area probe in `index.html`.
|
||||
- Keep `#embed-layer` empty at rest. Strip `allow-same-origin` from every user HTML iframe.
|
||||
- Open the shell sign-in flow from the one-use intent for `/sign-in`. Run `auth-callback.html` or the shell's early callback dispatch on callback routes. Remove the query and fragment before sending a callback. A shell must check that it owns a pending flow before accepting live callbacks. Register the waiting flow with `registerFlow` before launch. Seal broadcast callbacks to its registered key with Web Crypto. Cancel the registration when the flow ends. Use the local intent when delivery has no receipt. Share callback receipt IDs across tabs and expire them in 60 seconds.
|
||||
- Open the shell sign-in flow from the one-use intent for `/sign-in`. Preserve `redirectUri`, `email`, `client`, and `error` in the intent. Run `auth-callback.html` or the shell's early callback dispatch on callback routes. Remove the query and fragment before sending a callback. A shell must check that it owns a pending flow before accepting live callbacks. Register the waiting flow with `registerFlow` before launch. Seal broadcast callbacks to its registered key with Web Crypto. Cancel the registration when the flow ends. Use a Web Lock for each cross-tab callback ID. Write an in-flight lease before the receiver calls the handler. Mark the lease as done on success. Remove the lease if the handler throws. Renew the lease while the handler holds the lock. Keep local recovery intents in session storage across reloads. Keep an intent while the receiver holds a lease. Remove the intent after a claim, a completed receipt, or expiration. Store only callback IDs, owners, states, and expiry times in shared storage. Expire the leases and receipts in 60 seconds. If a handler still owns the lock at the end of the wait, open the shell with a pending recovery intent. If Web Locks or shared storage are unavailable, use a local intent.
|
||||
- Load Cloudflare Turnstile only in the isolated-origin `auth-captcha-frame.html` iframe when the server requests a challenge. Check the sending origin, window, and one-use nonce. Remove the iframe when the challenge completes or is canceled.
|
||||
- Flush pending CRDT writes before any login or legacy fallback navigation. Abort navigation if the flush fails.
|
||||
|
||||
|
||||
@@ -46,9 +46,19 @@ export async function verifyColdAuthRoutes(
|
||||
) {
|
||||
for (const [path, kind, fields] of [
|
||||
[
|
||||
'/sign-in?redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1&email=alice%40example.com&token=discard#discard',
|
||||
'/sign-in?redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1&email=alice%40example.com&client=affine&error=oauth_denied&token=discard#discard',
|
||||
'sign-in',
|
||||
{ redirectUri: '/workspace/demo/doc-1', email: 'alice@example.com' },
|
||||
{
|
||||
redirectUri: '/workspace/demo/doc-1',
|
||||
email: 'alice@example.com',
|
||||
client: 'affine',
|
||||
error: 'oauth_denied',
|
||||
},
|
||||
],
|
||||
[
|
||||
'/sign-in?token=discard#discard',
|
||||
'sign-in',
|
||||
{ redirectUri: null, email: null, client: null, error: null },
|
||||
],
|
||||
[
|
||||
'/oauth/login?provider=google&flow=redirect&client=web&redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1',
|
||||
@@ -60,6 +70,11 @@ export async function verifyColdAuthRoutes(
|
||||
redirectUri: '/workspace/demo/doc-1',
|
||||
},
|
||||
],
|
||||
[
|
||||
'/redirect-proxy?redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1#discard',
|
||||
'redirect-proxy',
|
||||
{ redirectUri: '/workspace/demo/doc-1' },
|
||||
],
|
||||
[
|
||||
'/magic-link?email=alice%40example.com&token=one-use',
|
||||
'magic-link',
|
||||
@@ -73,6 +88,13 @@ export async function verifyColdAuthRoutes(
|
||||
tab.evalJs,
|
||||
'Boolean(window.__AFFINE_WEB_AUTH__ && !location.search && !location.hash)'
|
||||
);
|
||||
if (kind === 'sign-in' || kind === 'redirect-proxy') {
|
||||
await tab.send('Page.reload', {});
|
||||
await waitFor(
|
||||
tab.evalJs,
|
||||
'Boolean(window.__AFFINE_WEB_AUTH__ && performance.getEntriesByType("navigation")[0]?.type === "reload" && !location.search && !location.hash)'
|
||||
);
|
||||
}
|
||||
const result = await tab.evalJs(`({
|
||||
path: location.pathname,
|
||||
intent: window.__AFFINE_WEB_AUTH__.takeIntent(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
authRoute,
|
||||
createAuthIntentBridge,
|
||||
intentTtlMs,
|
||||
readAuthNavigation,
|
||||
storeAuthIntent,
|
||||
} from './auth-intent.js';
|
||||
import { runAuthTrampoline } from './auth-trampoline.js';
|
||||
|
||||
@@ -15,8 +15,11 @@ export function prepareWebAuth(win, shellPath) {
|
||||
void runAuthTrampoline(win, shellPath);
|
||||
return false;
|
||||
}
|
||||
if (payload) win.history.replaceState(null, '', shellPath);
|
||||
const intent = payload && { expiresAt: Date.now() + intentTtlMs, payload };
|
||||
let intent = null;
|
||||
if (payload) {
|
||||
win.history.replaceState(null, '', shellPath);
|
||||
intent = storeAuthIntent(win, payload);
|
||||
}
|
||||
let cancelCaptcha;
|
||||
win.__AFFINE_WEB_AUTH__ = {
|
||||
...createAuthIntentBridge(win, intent),
|
||||
|
||||
@@ -59,7 +59,13 @@ export function readAuthNavigation(route, search, origin) {
|
||||
const params = new URLSearchParams(search);
|
||||
const redirectUri = safeRedirect(params.get('redirect_uri'), origin);
|
||||
if (route === 'sign-in') {
|
||||
return { kind: route, redirectUri, email: params.get('email') };
|
||||
return {
|
||||
kind: route,
|
||||
redirectUri,
|
||||
email: params.get('email'),
|
||||
client: params.get('client'),
|
||||
error: params.get('error'),
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: route,
|
||||
@@ -90,13 +96,12 @@ export function readAuthCallback(route, pathname, search, origin) {
|
||||
}
|
||||
|
||||
export function storeAuthIntent(win, payload) {
|
||||
const intent = { expiresAt: Date.now() + intentTtlMs, payload };
|
||||
try {
|
||||
win.sessionStorage.setItem(
|
||||
intentKey,
|
||||
JSON.stringify({ expiresAt: Date.now() + intentTtlMs, payload })
|
||||
);
|
||||
win.sessionStorage.setItem(intentKey, JSON.stringify(intent));
|
||||
return null;
|
||||
} catch {
|
||||
// A restricted tab can still open the shell.
|
||||
return intent;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,36 +154,45 @@ function matchesPublicKey(expected, offered) {
|
||||
}
|
||||
|
||||
const receiptPrefix = 'affine:auth-receipt:';
|
||||
const offerTtlMs = 750;
|
||||
const receiptPollMs = 50;
|
||||
|
||||
function isCallbackClaimed(win, id) {
|
||||
try {
|
||||
return Number(win.localStorage.getItem(receiptPrefix + id)) > Date.now();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
function loadReceipt(storage, key) {
|
||||
const record = JSON.parse(storage.getItem(key));
|
||||
return typeof record === 'number'
|
||||
? { state: 'done', expiresAt: record }
|
||||
: record;
|
||||
}
|
||||
|
||||
// Store IDs and expiry times only. Session storage belongs to one tab.
|
||||
function claimCallback(win, id) {
|
||||
if (!id) return true;
|
||||
try {
|
||||
const storage = win.localStorage;
|
||||
const now = Date.now();
|
||||
const key = receiptPrefix + id;
|
||||
if (Number(storage.getItem(key)) > now) return false;
|
||||
for (let index = storage.length - 1; index >= 0; index--) {
|
||||
const expired = storage.key(index);
|
||||
if (
|
||||
expired?.startsWith(receiptPrefix) &&
|
||||
Number(storage.getItem(expired)) <= now
|
||||
) {
|
||||
storage.removeItem(expired);
|
||||
}
|
||||
}
|
||||
storage.setItem(key, String(now + intentTtlMs));
|
||||
return true;
|
||||
} catch {
|
||||
return null;
|
||||
function readReceipt(storage, key) {
|
||||
const record = loadReceipt(storage, key);
|
||||
return record?.expiresAt > Date.now() ? record : null;
|
||||
}
|
||||
|
||||
function writeReceipt(storage, key, state, owner) {
|
||||
storage.setItem(
|
||||
key,
|
||||
JSON.stringify({ state, owner, expiresAt: Date.now() + intentTtlMs })
|
||||
);
|
||||
}
|
||||
|
||||
function pruneReceipt(storage, key, locks) {
|
||||
if (!locks) {
|
||||
storage.removeItem(key);
|
||||
return;
|
||||
}
|
||||
void locks
|
||||
.request(key, { ifAvailable: true }, lock => {
|
||||
if (lock && !readReceipt(storage, key)) storage.removeItem(key);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
function pruneReceipts(storage, locks) {
|
||||
for (let index = storage.length - 1; index >= 0; index--) {
|
||||
const key = storage.key(index);
|
||||
if (key?.startsWith(receiptPrefix) && !readReceipt(storage, key))
|
||||
pruneReceipt(storage, key, locks);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +206,8 @@ export function deliverCallback(win, hint, payload) {
|
||||
} catch {
|
||||
// A cross-origin opener cannot receive a callback.
|
||||
}
|
||||
if (!win.crypto?.randomUUID) {
|
||||
const locks = win.navigator?.locks;
|
||||
if (!win.crypto?.randomUUID || !locks) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
@@ -206,8 +221,12 @@ export function deliverCallback(win, hint, payload) {
|
||||
return;
|
||||
}
|
||||
const id = payload.callbackId ?? win.crypto.randomUUID();
|
||||
const key = receiptPrefix + id;
|
||||
const acceptUntil = Date.now() + offerTtlMs;
|
||||
const waitUntil = acceptUntil + intentTtlMs;
|
||||
let selected = null;
|
||||
let finished = false;
|
||||
let deadline;
|
||||
const finish = delivered => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
@@ -229,7 +248,11 @@ export function deliverCallback(win, hint, payload) {
|
||||
const receipt = win.crypto.randomUUID();
|
||||
selected = { receiver: message.receiver, fromOpener, receipt };
|
||||
const frame = { type: 'callback', id, receiver: message.receiver };
|
||||
const contents = { payload: { ...payload, callbackId: id }, receipt };
|
||||
const contents = {
|
||||
payload: { ...payload, callbackId: id },
|
||||
receipt,
|
||||
acceptUntil,
|
||||
};
|
||||
if (fromOpener) {
|
||||
reply({ ...frame, ...contents });
|
||||
} else {
|
||||
@@ -258,8 +281,7 @@ export function deliverCallback(win, hint, payload) {
|
||||
selected.fromOpener === fromOpener &&
|
||||
message.receipt === selected.receipt
|
||||
) {
|
||||
finish(fromOpener ? 'opener' : 'channel');
|
||||
if (fromOpener) win.close();
|
||||
completeDelivery();
|
||||
}
|
||||
};
|
||||
const onMessage = event => {
|
||||
@@ -275,7 +297,30 @@ export function deliverCallback(win, hint, payload) {
|
||||
);
|
||||
}
|
||||
};
|
||||
const deadline = win.setTimeout(() => finish(false), 750);
|
||||
const completeDelivery = () => {
|
||||
finish(sameOriginOpener ? 'opener' : 'channel');
|
||||
if (sameOriginOpener) win.close();
|
||||
};
|
||||
const checkReceipt = () => {
|
||||
void locks
|
||||
.request(key, { ifAvailable: true }, lock => {
|
||||
if (finished) return;
|
||||
const receipt = readReceipt(win.localStorage, key);
|
||||
if (receipt?.state === 'done') {
|
||||
completeDelivery();
|
||||
} else if (
|
||||
(!lock || receipt?.state === 'inflight') &&
|
||||
Date.now() < waitUntil
|
||||
) {
|
||||
deadline = win.setTimeout(checkReceipt, receiptPollMs);
|
||||
} else {
|
||||
// Keep a local intent while the receiver holds the lock.
|
||||
finish(lock ? false : 'pending');
|
||||
}
|
||||
})
|
||||
.catch(() => finish(false));
|
||||
};
|
||||
deadline = win.setTimeout(checkReceipt, offerTtlMs);
|
||||
const offer = {
|
||||
type: 'offer',
|
||||
id,
|
||||
@@ -294,16 +339,14 @@ export function deliverCallback(win, hint, payload) {
|
||||
|
||||
export function createAuthIntentBridge(win, initialIntent = null) {
|
||||
let pending = initialIntent;
|
||||
if (!pending) {
|
||||
const discardIntent = () => {
|
||||
pending = null;
|
||||
try {
|
||||
const stored = win.sessionStorage.getItem(intentKey);
|
||||
win.sessionStorage.removeItem(intentKey);
|
||||
const entry = JSON.parse(stored);
|
||||
if (entry?.expiresAt > Date.now()) pending = entry;
|
||||
} catch {
|
||||
// A browser can disable session storage.
|
||||
}
|
||||
}
|
||||
};
|
||||
const flows = new Map();
|
||||
const removeFlow = key => {
|
||||
flows.delete(key);
|
||||
@@ -315,20 +358,51 @@ export function createAuthIntentBridge(win, initialIntent = null) {
|
||||
};
|
||||
return {
|
||||
takeIntent() {
|
||||
const intent = pending;
|
||||
pending = null;
|
||||
if (
|
||||
intent?.expiresAt > Date.now() &&
|
||||
claimCallback(win, intent.payload.callbackId) !== false
|
||||
) {
|
||||
return intent.payload;
|
||||
let intent = pending;
|
||||
if (!intent) {
|
||||
try {
|
||||
intent = JSON.parse(win.sessionStorage.getItem(intentKey));
|
||||
} catch {
|
||||
// A browser can disable session storage.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
if (!intent?.payload || !(intent.expiresAt > Date.now())) {
|
||||
discardIntent();
|
||||
return null;
|
||||
}
|
||||
const { callbackId } = intent.payload;
|
||||
if (callbackId) {
|
||||
try {
|
||||
const storage = win.localStorage;
|
||||
const locks = win.navigator?.locks;
|
||||
const key = receiptPrefix + callbackId;
|
||||
const receipt = loadReceipt(storage, key);
|
||||
if (receipt?.state === 'inflight') {
|
||||
if (receipt.expiresAt > Date.now()) return null;
|
||||
if (locks) {
|
||||
// A suspended receiver can still own an expired lease.
|
||||
pruneReceipt(storage, key, locks);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (receipt?.state === 'done' && receipt.expiresAt > Date.now()) {
|
||||
discardIntent();
|
||||
return null;
|
||||
}
|
||||
pruneReceipts(storage, locks);
|
||||
writeReceipt(storage, key, 'done', 'local');
|
||||
} catch {
|
||||
// A restricted tab can still consume its local intent.
|
||||
}
|
||||
}
|
||||
discardIntent();
|
||||
return intent.payload;
|
||||
},
|
||||
/** Register before launching the flow. Call the returned function to cancel it. */
|
||||
async registerFlow(hint) {
|
||||
const crypto = win.crypto;
|
||||
if (!crypto?.subtle || !crypto.randomUUID) return null;
|
||||
if (!crypto?.subtle || !crypto.randomUUID || !win.navigator?.locks)
|
||||
return null;
|
||||
try {
|
||||
const storage = win.localStorage;
|
||||
const now = Date.now();
|
||||
@@ -360,7 +434,8 @@ export function createAuthIntentBridge(win, initialIntent = null) {
|
||||
}
|
||||
},
|
||||
listen(accepts, onCallback) {
|
||||
if (!win.crypto?.randomUUID) return () => {};
|
||||
const locks = win.navigator?.locks;
|
||||
if (!win.crypto?.randomUUID || !locks) return () => {};
|
||||
const receiver = win.crypto.randomUUID();
|
||||
const offers = new Map();
|
||||
const { subtle } = win.crypto;
|
||||
@@ -418,13 +493,14 @@ export function createAuthIntentBridge(win, initialIntent = null) {
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const { payload, receipt } = contents ?? {};
|
||||
const { payload, receipt, acceptUntil } = contents ?? {};
|
||||
if (
|
||||
!active ||
|
||||
offers.get(message.id) !== offer ||
|
||||
offer.expiresAt <= Date.now() ||
|
||||
(offer.flow && flows.get(offer.flowKey) !== offer.flow) ||
|
||||
typeof receipt !== 'string' ||
|
||||
!Number.isFinite(acceptUntil) ||
|
||||
payload?.callbackId !== message.id ||
|
||||
payload?.kind !== offer.hint.kind ||
|
||||
payload.state !== offer.hint.state ||
|
||||
@@ -432,15 +508,42 @@ export function createAuthIntentBridge(win, initialIntent = null) {
|
||||
)
|
||||
return;
|
||||
offers.delete(message.id);
|
||||
const claimed = isCallbackClaimed(win, payload.callbackId);
|
||||
if (claimed === null && source === channel) return;
|
||||
if (!claimed) {
|
||||
try {
|
||||
await onCallback(payload);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
claimCallback(win, payload.callbackId);
|
||||
const key = receiptPrefix + message.id;
|
||||
try {
|
||||
const consumed = await locks.request(key, async () => {
|
||||
// The sender can recover after this time, even if decryption runs late.
|
||||
if (
|
||||
!active ||
|
||||
Date.now() >= acceptUntil ||
|
||||
(offer.flow && flows.get(offer.flowKey) !== offer.flow)
|
||||
)
|
||||
return false;
|
||||
const storage = win.localStorage;
|
||||
if (readReceipt(storage, key)) return false;
|
||||
pruneReceipts(storage, locks);
|
||||
writeReceipt(storage, key, 'inflight', receiver);
|
||||
const heartbeat = win.setInterval(() => {
|
||||
try {
|
||||
writeReceipt(storage, key, 'inflight', receiver);
|
||||
} catch {
|
||||
// The Web Lock still protects the callback.
|
||||
}
|
||||
}, intentTtlMs / 2);
|
||||
try {
|
||||
await onCallback(payload);
|
||||
} catch (error) {
|
||||
if (loadReceipt(storage, key)?.owner === receiver)
|
||||
storage.removeItem(key);
|
||||
throw error;
|
||||
} finally {
|
||||
win.clearInterval(heartbeat);
|
||||
}
|
||||
writeReceipt(storage, key, 'done', receiver);
|
||||
return true;
|
||||
});
|
||||
if (!consumed) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (offer.flow) removeFlow(offer.flowKey);
|
||||
if (active)
|
||||
|
||||
@@ -123,6 +123,12 @@ export class GenerationConflict extends Error {
|
||||
|
||||
const records = 'records';
|
||||
const retiredEpochLimit = 32;
|
||||
const vaultRevision = Symbol('affine.vault.revision');
|
||||
const ambiguousRevision = Symbol('ambiguous revision');
|
||||
|
||||
export function getVaultRevision(record) {
|
||||
return record?.[vaultRevision];
|
||||
}
|
||||
|
||||
/** Store only session metadata. The browser owns the HTTP-only cookies. */
|
||||
export function createWebCredentialVault({
|
||||
@@ -166,9 +172,14 @@ export function createWebCredentialVault({
|
||||
});
|
||||
}
|
||||
|
||||
async function mutate(scope, expectedGeneration, next) {
|
||||
async function mutate(scope, expectedGeneration, next, snapshot) {
|
||||
const key = keyFor(scope);
|
||||
const expectedRevision = observedRevision.get(key);
|
||||
const expectedRevision =
|
||||
snapshot === undefined
|
||||
? observedRevision.get(key)
|
||||
: typeof snapshot === 'number'
|
||||
? snapshot
|
||||
: getVaultRevision(snapshot);
|
||||
const transaction = async () => {
|
||||
const db = await open();
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -182,8 +193,7 @@ export function createWebCredentialVault({
|
||||
reject(conflict);
|
||||
return;
|
||||
}
|
||||
if (next) observedRevision.set(key, revision);
|
||||
else observedRevision.delete(key);
|
||||
observedRevision.set(key, revision);
|
||||
resolve();
|
||||
};
|
||||
tx.onabort = () => reject(tx.error);
|
||||
@@ -196,9 +206,7 @@ export function createWebCredentialVault({
|
||||
const oldEpoch = currentRecord?.sessionEpoch;
|
||||
const newEpoch = next?.sessionEpoch;
|
||||
const staleRevision =
|
||||
expectedGeneration !== null &&
|
||||
expectedRevision !== undefined &&
|
||||
expectedRevision !== currentRevision;
|
||||
expectedGeneration !== null && expectedRevision !== currentRevision;
|
||||
const staleEpoch =
|
||||
next &&
|
||||
currentRecord &&
|
||||
@@ -250,11 +258,24 @@ export function createWebCredentialVault({
|
||||
async load(scope) {
|
||||
const key = keyFor(scope);
|
||||
const entry = await read(key);
|
||||
if (entry?.record) observedRevision.set(key, entry.revision ?? 0);
|
||||
else observedRevision.delete(key);
|
||||
return entry?.record ?? null;
|
||||
const revision = entry?.revision ?? 0;
|
||||
const observed = observedRevision.get(key);
|
||||
observedRevision.set(
|
||||
key,
|
||||
observed === undefined || observed === revision
|
||||
? revision
|
||||
: ambiguousRevision
|
||||
);
|
||||
if (!entry?.record) return null;
|
||||
return Object.defineProperty({ ...entry.record }, vaultRevision, {
|
||||
value: revision,
|
||||
});
|
||||
},
|
||||
async compareAndSwap(expectedGeneration, record) {
|
||||
async compareAndSwap(
|
||||
expectedGeneration,
|
||||
record,
|
||||
expectedRevision = getVaultRevision(record)
|
||||
) {
|
||||
if (
|
||||
!Number.isSafeInteger(record.generation) ||
|
||||
record.generation < 0 ||
|
||||
@@ -275,11 +296,12 @@ export function createWebCredentialVault({
|
||||
credential: { kind: 'cookie' },
|
||||
pendingRefresh,
|
||||
sessionExpired: Boolean(record.sessionExpired),
|
||||
})
|
||||
}),
|
||||
expectedRevision
|
||||
);
|
||||
},
|
||||
remove(scope, expectedGeneration) {
|
||||
return mutate(scope, expectedGeneration, null);
|
||||
remove(scope, expectedGeneration, expectedRevision) {
|
||||
return mutate(scope, expectedGeneration, null, expectedRevision);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -100,10 +100,10 @@ await test('Web auth and replication across Chromium tabs', async t => {
|
||||
return tab;
|
||||
};
|
||||
// External tabs can reject script-initiated close requests.
|
||||
const openExternalCallback = async path => {
|
||||
const openExternalCallback = async (path, setup = '') => {
|
||||
const tab = await openTab();
|
||||
await tab.send('Page.addScriptToEvaluateOnNewDocument', {
|
||||
source: 'window.close = () => {};',
|
||||
source: 'window.close = () => {}; ' + setup,
|
||||
});
|
||||
await tab.send('Page.navigate', { url: base + path });
|
||||
return tab;
|
||||
@@ -112,7 +112,7 @@ await test('Web auth and replication across Chromium tabs', async t => {
|
||||
const b = await openTab();
|
||||
|
||||
await t.test(
|
||||
'sign-in, OAuth login, and auth callbacks preserve one-use intents and clean URLs',
|
||||
'cold auth routes clean the URL and preserve one-use intents across reload',
|
||||
async () => {
|
||||
await verifyAuthAssets(base);
|
||||
await verifyColdAuthRoutes(a, base, waitForCondition);
|
||||
@@ -219,6 +219,172 @@ await test('Web auth and replication across Chromium tabs', async t => {
|
||||
}
|
||||
);
|
||||
|
||||
await t.test(
|
||||
'redirect-proxy handlers consume one workspace intent before or after the wait limit',
|
||||
async () => {
|
||||
const counts = [];
|
||||
const redirectUri = '/workspace/demo/doc-1';
|
||||
for (const outcome of [
|
||||
'throw',
|
||||
'slow',
|
||||
'immediate',
|
||||
'over-limit-success',
|
||||
'over-limit-throw',
|
||||
]) {
|
||||
const overLimit = outcome.startsWith('over-limit');
|
||||
const throws = outcome.endsWith('throw');
|
||||
await a.evalJs(`(async () => {
|
||||
const { createAuthIntentBridge } = await import('/src/auth-intent.js');
|
||||
const bridge = createAuthIntentBridge(window);
|
||||
const hint = { kind: 'redirect-proxy' };
|
||||
const cancel = await bridge.registerFlow(hint);
|
||||
const gate = Promise.withResolvers();
|
||||
const realNow = Date.now;
|
||||
const realSetInterval = window.setInterval;
|
||||
if (${overLimit}) {
|
||||
let offset = 0;
|
||||
let renewLease;
|
||||
Date.now = () => realNow() + offset;
|
||||
window.setInterval = (fn, ms, ...args) => {
|
||||
if (ms === 30000) renewLease = fn;
|
||||
return realSetInterval(fn, ms, ...args);
|
||||
};
|
||||
window.advanceCallbackClock = milliseconds => {
|
||||
offset += milliseconds;
|
||||
renewLease?.();
|
||||
};
|
||||
}
|
||||
window.releaseCallback = gate.resolve;
|
||||
window.callbackEntered = false;
|
||||
window.workspaceIntents = [];
|
||||
const stop = bridge.listen(
|
||||
offer => offer.kind === hint.kind,
|
||||
async payload => {
|
||||
window.callbackEntered = payload.callbackId;
|
||||
const outcome = ${JSON.stringify(outcome)};
|
||||
if (outcome === 'slow') {
|
||||
await Promise.all([
|
||||
gate.promise,
|
||||
new Promise(resolve => setTimeout(resolve, 1100)),
|
||||
]);
|
||||
}
|
||||
if (${overLimit} || ${throws}) await gate.promise;
|
||||
if (${throws}) throw new Error('The callback failed');
|
||||
window.workspaceIntents.push(payload.redirectUri);
|
||||
}
|
||||
);
|
||||
window.stopListening = () => {
|
||||
stop();
|
||||
cancel();
|
||||
Date.now = realNow;
|
||||
window.setInterval = realSetInterval;
|
||||
};
|
||||
})()`);
|
||||
try {
|
||||
const sender = await openExternalCallback(
|
||||
'/redirect-proxy?redirect_uri=' +
|
||||
encodeURIComponent(redirectUri) +
|
||||
'#remove',
|
||||
`const timeout = window.setTimeout.bind(window);
|
||||
const realNow = Date.now;
|
||||
Date.now = () => realNow() + (window.callbackClockOffset ?? 0);
|
||||
window.setTimeout = (fn, ms, ...args) => timeout(() => {
|
||||
fn(...args);
|
||||
if (ms === 750) window.offerTimedOut = true;
|
||||
}, ms);`
|
||||
);
|
||||
const id = await waitForCondition(
|
||||
a.evalJs,
|
||||
'window.callbackEntered'
|
||||
);
|
||||
const receiptKey = JSON.stringify('affine:auth-receipt:' + id);
|
||||
if (outcome !== 'immediate') {
|
||||
await waitForCondition(
|
||||
sender.evalJs,
|
||||
'window.offerTimedOut === true'
|
||||
);
|
||||
assert.deepEqual(
|
||||
await sender.evalJs(
|
||||
'[location.pathname, sessionStorage.getItem("affine:auth-intent")]'
|
||||
),
|
||||
['/redirect-proxy', null]
|
||||
);
|
||||
if (overLimit) {
|
||||
await a.evalJs(
|
||||
'window.advanceCallbackClock(30000); window.advanceCallbackClock(30000)'
|
||||
);
|
||||
await sender.evalJs('window.callbackClockOffset = 60750');
|
||||
} else {
|
||||
await a.evalJs('window.releaseCallback()');
|
||||
}
|
||||
}
|
||||
await waitForCondition(
|
||||
sender.evalJs,
|
||||
'location.pathname === "/" && !location.search && !location.hash && Boolean(window.__AFFINE_WEB_AUTH__)'
|
||||
);
|
||||
if (overLimit) {
|
||||
const stored = await sender.evalJs(
|
||||
'sessionStorage.getItem("affine:auth-intent")'
|
||||
);
|
||||
assert.equal(JSON.parse(stored).payload.callbackId, id);
|
||||
assert.equal(
|
||||
await sender.evalJs('window.__AFFINE_WEB_AUTH__.takeIntent()'),
|
||||
null
|
||||
);
|
||||
await sender.send('Page.reload', {});
|
||||
await waitForCondition(
|
||||
sender.evalJs,
|
||||
'Boolean(window.__AFFINE_WEB_AUTH__ && performance.getEntriesByType("navigation")[0]?.type === "reload")'
|
||||
);
|
||||
assert.equal(
|
||||
await sender.evalJs('window.__AFFINE_WEB_AUTH__.takeIntent()'),
|
||||
null
|
||||
);
|
||||
assert.equal(
|
||||
await sender.evalJs(
|
||||
'sessionStorage.getItem("affine:auth-intent")'
|
||||
),
|
||||
stored
|
||||
);
|
||||
await a.evalJs(
|
||||
'window.advanceCallbackClock(1000); window.releaseCallback()'
|
||||
);
|
||||
await waitForCondition(
|
||||
sender.evalJs,
|
||||
throws
|
||||
? `localStorage.getItem(${receiptKey}) === null`
|
||||
: `JSON.parse(localStorage.getItem(${receiptKey}))?.state === "done"`
|
||||
);
|
||||
}
|
||||
const intents = await a.evalJs('window.workspaceIntents');
|
||||
const local = await sender.evalJs(
|
||||
'window.__AFFINE_WEB_AUTH__.takeIntent()'
|
||||
);
|
||||
assert.equal(Boolean(local), throws, outcome);
|
||||
if (local) {
|
||||
assert.equal(local.kind, 'redirect-proxy');
|
||||
intents.push(local.redirectUri);
|
||||
}
|
||||
assert.equal(
|
||||
await sender.evalJs('window.__AFFINE_WEB_AUTH__.takeIntent()'),
|
||||
null
|
||||
);
|
||||
assert.equal(
|
||||
await sender.evalJs(
|
||||
'sessionStorage.getItem("affine:auth-intent")'
|
||||
),
|
||||
null
|
||||
);
|
||||
assert.deepEqual(intents, [redirectUri], outcome);
|
||||
counts.push(intents.length);
|
||||
} finally {
|
||||
await a.evalJs('window.releaseCallback(); window.stopListening()');
|
||||
}
|
||||
}
|
||||
assert.deepEqual(counts, [1, 1, 1, 1, 1]);
|
||||
}
|
||||
);
|
||||
|
||||
await t.test(
|
||||
'magic links reach only the waiting tab for the normalized email',
|
||||
async () => {
|
||||
@@ -420,16 +586,17 @@ await test('Web auth and replication across Chromium tabs', async t => {
|
||||
delete navigator.locks;
|
||||
window.vault = createWebCredentialVault();
|
||||
window.scope = { origin: location.origin, userId: 'alice@example.com' };
|
||||
window.remove = expected => window.vault.remove(window.scope, expected)
|
||||
window.remove = (expected, revision) => window.vault.remove(window.scope, expected, revision)
|
||||
.then(() => 'ok', error => [error.name, error.current]);
|
||||
window.save = (expected, generation, epoch = 'epoch', fields = {}) => window.vault.compareAndSwap(expected, {
|
||||
window.save = (expected, generation, epoch = 'epoch', fields = {}, revision) => window.vault.compareAndSwap(expected, {
|
||||
scope: window.scope, generation, sessionEpoch: epoch, session: {},
|
||||
credential: { kind: 'cookie' }, pendingRefresh: { attemptId: 'retry' }, sessionExpired: generation === 2,
|
||||
...fields,
|
||||
}).then(() => 'ok', error => [error.name, error.current]);
|
||||
}, revision).then(() => 'ok', error => [error.name, error.current]);
|
||||
})()`;
|
||||
await Promise.all([a.evalJs(setup), b.evalJs(setup)]);
|
||||
assert.equal(await a.evalJs('window.save(null, 1)'), 'ok');
|
||||
await b.evalJs('window.vault.load(window.scope)');
|
||||
const writes = await Promise.all([
|
||||
a.evalJs('window.save(1, 2)'),
|
||||
b.evalJs('window.save(1, 2)'),
|
||||
@@ -530,6 +697,59 @@ await test('Web auth and replication across Chromium tabs', async t => {
|
||||
assert.equal(await a.evalJs('window.save(3, 4, 2)'), 'ok');
|
||||
}
|
||||
);
|
||||
await t.test(
|
||||
'a vault revision belongs to the loaded snapshot after the same tab reads a new login',
|
||||
async () => {
|
||||
const conflict = ['GenerationConflict', 1];
|
||||
for (const op of ['save', 'remove']) {
|
||||
const userId = op + '@example.com';
|
||||
for (const tab of [a, b]) {
|
||||
await tab.evalJs(
|
||||
`window.scope = { origin: location.origin, userId: ${JSON.stringify(userId)} }; true`
|
||||
);
|
||||
}
|
||||
assert.equal(await a.evalJs('window.save(null, 1)'), 'ok');
|
||||
assert.equal(
|
||||
await b.evalJs(`(async () => {
|
||||
const { getVaultRevision } = await import('/src/cloud-transport.js');
|
||||
window.firstSnapshot = await window.vault.load(window.scope);
|
||||
return getVaultRevision(window.firstSnapshot);
|
||||
})()`),
|
||||
1
|
||||
);
|
||||
assert.equal(await a.evalJs('window.remove(1)'), 'ok');
|
||||
assert.equal(await a.evalJs('window.save(null, 1)'), 'ok');
|
||||
assert.equal(
|
||||
await b.evalJs(`(async () => {
|
||||
const { getVaultRevision } = await import('/src/cloud-transport.js');
|
||||
window.secondSnapshot = await window.vault.load(window.scope);
|
||||
return getVaultRevision(window.secondSnapshot);
|
||||
})()`),
|
||||
3
|
||||
);
|
||||
for (const argument of ['', ', window.firstSnapshot']) {
|
||||
assert.deepEqual(
|
||||
await b.evalJs(`window.save(1, 2, 'epoch', {}${argument})`),
|
||||
conflict
|
||||
);
|
||||
assert.deepEqual(
|
||||
await b.evalJs(`window.remove(1${argument})`),
|
||||
conflict
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
await b.evalJs(
|
||||
op === 'save'
|
||||
? "window.save(1, 2, 'epoch', {}, window.secondSnapshot)"
|
||||
: 'window.remove(1, window.secondSnapshot)'
|
||||
),
|
||||
'ok'
|
||||
);
|
||||
const current = await a.evalJs('window.vault.load(window.scope)');
|
||||
assert.equal(current?.generation ?? null, op === 'save' ? 2 : null);
|
||||
}
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
for (const tab of tabs) tab.close();
|
||||
await closeBrowserResources(harness, null, server);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
|
||||
import {
|
||||
createCallbackKeyPair,
|
||||
@@ -10,16 +11,41 @@ import {
|
||||
createAuthIntentBridge,
|
||||
deliverCallback,
|
||||
intentKey,
|
||||
intentTtlMs,
|
||||
} from '../src/auth-intent.js';
|
||||
import { runAuthTrampoline } from '../src/auth-trampoline.js';
|
||||
import { createMemoryStorage } from './memory-idb.mjs';
|
||||
|
||||
const origin = 'https://example.com';
|
||||
|
||||
const heldLocks = new Map();
|
||||
const locks = {
|
||||
async request(key, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
while (heldLocks.has(key)) {
|
||||
if (options.ifAvailable) return callback(null);
|
||||
await heldLocks.get(key).promise;
|
||||
}
|
||||
const release = Promise.withResolvers();
|
||||
heldLocks.set(key, release);
|
||||
try {
|
||||
return await callback({ name: key });
|
||||
} finally {
|
||||
heldLocks.delete(key);
|
||||
release.resolve();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
function windowForCallback(path, options = {}) {
|
||||
const win = new EventTarget();
|
||||
const url = new URL(path, origin);
|
||||
win.crypto = globalThis.crypto;
|
||||
win.navigator = { locks };
|
||||
win.close = () => {};
|
||||
win.location = {
|
||||
origin,
|
||||
pathname: url.pathname,
|
||||
@@ -34,13 +60,15 @@ function windowForCallback(path, options = {}) {
|
||||
},
|
||||
};
|
||||
win.setTimeout = (callback, ms) => {
|
||||
assert.equal(ms, 750);
|
||||
win.deadlineDelay = ms;
|
||||
win.deadline = callback;
|
||||
return 1;
|
||||
};
|
||||
win.clearTimeout = () => {
|
||||
win.deadline = null;
|
||||
};
|
||||
win.setInterval = (...args) => setInterval(...args);
|
||||
win.clearInterval = timer => clearInterval(timer);
|
||||
win.sessionStorage = createMemoryStorage();
|
||||
win.localStorage = createMemoryStorage();
|
||||
return Object.assign(win, options);
|
||||
@@ -188,7 +216,7 @@ void test('an external callback leaves the trampoline after a receipt or unavail
|
||||
assert.equal(unknown.navigation, '/');
|
||||
});
|
||||
|
||||
void test('the fallback shell drops a callback consumed by another tab when its receipt arrives too late', async () => {
|
||||
void test('a completed lease suppresses local recovery when the receipt is lost', async () => {
|
||||
const { Channel, seen, received } = createCallbackBus({ dropReceipt: true });
|
||||
const localStorage = createMemoryStorage();
|
||||
const sender = windowForCallback('/magic-link?token=one-use', {
|
||||
@@ -215,10 +243,7 @@ void test('the fallback shell drops a callback consumed by another tab when its
|
||||
sender.deadline();
|
||||
await completion;
|
||||
assert.equal(sender.navigation, '/');
|
||||
assert.equal(
|
||||
JSON.parse(sender.sessionStorage.getItem(intentKey)).payload.callbackId,
|
||||
callback.callbackId
|
||||
);
|
||||
assert.equal(sender.sessionStorage.getItem(intentKey), null);
|
||||
assert.equal(createAuthIntentBridge(sender).takeIntent(), null);
|
||||
} finally {
|
||||
stop();
|
||||
@@ -341,6 +366,7 @@ void test('a failed receiving callback leaves no receipt and remains available i
|
||||
try {
|
||||
const completion = runAuthTrampoline(sender, '/');
|
||||
const id = await attempted.promise;
|
||||
await setImmediate();
|
||||
sender.deadline();
|
||||
await completion;
|
||||
assert.equal(
|
||||
@@ -355,6 +381,111 @@ void test('a failed receiving callback leaves no receipt and remains available i
|
||||
}
|
||||
});
|
||||
|
||||
void test('callback handlers consume one intent when they throw, succeed, or outlast the wait', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setInterval'], now: 1_000 });
|
||||
const counts = [];
|
||||
for (const outcome of [
|
||||
'throw',
|
||||
'slow',
|
||||
'immediate',
|
||||
'over-limit-success',
|
||||
'over-limit-throw',
|
||||
]) {
|
||||
const overLimit = outcome.startsWith('over-limit');
|
||||
const throws = outcome.endsWith('throw');
|
||||
const { Channel, received } = createCallbackBus();
|
||||
const localStorage = createMemoryStorage();
|
||||
const options = { localStorage, BroadcastChannel: Channel };
|
||||
const sender = windowForCallback(
|
||||
'/redirect-proxy?redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1#remove',
|
||||
options
|
||||
);
|
||||
const bridge = createAuthIntentBridge(windowForCallback('/', options));
|
||||
const cancel = await bridge.registerFlow({ kind: 'redirect-proxy' });
|
||||
const entered = Promise.withResolvers();
|
||||
const release = Promise.withResolvers();
|
||||
const consumed = [];
|
||||
const stop = bridge.listen(
|
||||
hint => hint.kind === 'redirect-proxy',
|
||||
async payload => {
|
||||
entered.resolve(payload);
|
||||
if (outcome !== 'immediate') await release.promise;
|
||||
if (throws) throw new Error('The callback failed');
|
||||
consumed.push(payload.redirectUri);
|
||||
}
|
||||
);
|
||||
try {
|
||||
const completion = runAuthTrampoline(sender, '/');
|
||||
const payload = await entered.promise;
|
||||
const key = 'affine:auth-receipt:' + payload.callbackId;
|
||||
const lease = JSON.parse(localStorage.getItem(key));
|
||||
assert.deepEqual(Object.keys(lease).sort(), [
|
||||
'expiresAt',
|
||||
'owner',
|
||||
'state',
|
||||
]);
|
||||
assert.equal(lease.state, 'inflight');
|
||||
const duplicate = createAuthIntentBridge(sender, {
|
||||
payload,
|
||||
expiresAt: Date.now() + intentTtlMs,
|
||||
});
|
||||
assert.equal(duplicate.takeIntent(), null);
|
||||
let recovery;
|
||||
if (outcome !== 'immediate') {
|
||||
assert.equal(sender.deadlineDelay, 750);
|
||||
t.mock.timers.tick(750);
|
||||
sender.deadline();
|
||||
await setImmediate();
|
||||
assert.equal(sender.navigation, undefined);
|
||||
assert.equal(sender.sessionStorage.getItem(intentKey), null);
|
||||
if (overLimit) {
|
||||
t.mock.timers.tick(intentTtlMs);
|
||||
sender.deadline();
|
||||
await completion;
|
||||
assert.equal(sender.navigation, '/');
|
||||
const stored = sender.sessionStorage.getItem(intentKey);
|
||||
assert.equal(
|
||||
JSON.parse(stored).payload.callbackId,
|
||||
payload.callbackId
|
||||
);
|
||||
assert.ok(
|
||||
JSON.parse(localStorage.getItem(key)).expiresAt > Date.now()
|
||||
);
|
||||
recovery = createAuthIntentBridge(sender);
|
||||
assert.equal(recovery.takeIntent(), null);
|
||||
assert.equal(sender.sessionStorage.getItem(intentKey), stored);
|
||||
t.mock.timers.tick(250);
|
||||
} else {
|
||||
t.mock.timers.tick(350);
|
||||
}
|
||||
release.resolve();
|
||||
}
|
||||
if (throws) {
|
||||
await setImmediate();
|
||||
assert.equal(localStorage.getItem(key), null);
|
||||
if (!overLimit) sender.deadline();
|
||||
} else {
|
||||
await received;
|
||||
}
|
||||
await completion;
|
||||
recovery ??= createAuthIntentBridge(sender);
|
||||
const local = recovery.takeIntent();
|
||||
if (local) consumed.push(local.redirectUri);
|
||||
assert.equal(Boolean(local), throws);
|
||||
assert.equal(recovery.takeIntent(), null);
|
||||
assert.equal(sender.sessionStorage.getItem(intentKey), null);
|
||||
assert.equal(JSON.parse(localStorage.getItem(key)).state, 'done');
|
||||
assert.deepEqual(consumed, ['/workspace/demo/doc-1'], outcome);
|
||||
counts.push(consumed.length);
|
||||
} finally {
|
||||
release.resolve();
|
||||
stop();
|
||||
cancel();
|
||||
}
|
||||
}
|
||||
assert.deepEqual(counts, [1, 1, 1, 1, 1]);
|
||||
});
|
||||
|
||||
void test('absent, expired, ambiguous, and unavailable flow registrations use local recovery', async () => {
|
||||
for (const condition of ['absent', 'expired', 'ambiguous', 'unavailable']) {
|
||||
const localStorage = createMemoryStorage();
|
||||
|
||||
@@ -155,7 +155,7 @@ void test('a11y tree enforces inert + tabindex exclusivity and mountSandboxedEmb
|
||||
host.dispose();
|
||||
});
|
||||
|
||||
void test('callback routes remove URL secrets before persisting a one-use shell intent', async () => {
|
||||
void test('callback routes remove URL secrets and preserve a one-use intent across reload', async () => {
|
||||
for (const [path, kind, field, value] of [
|
||||
['/oauth/callback?code=one&state=two#private', 'oauth', 'code', 'one'],
|
||||
[
|
||||
@@ -207,29 +207,50 @@ void test('callback routes remove URL secrets before persisting a one-use shell
|
||||
]);
|
||||
assert.equal(win.location.pathname, '/desktop/');
|
||||
assert.equal(prepareWebAuth(win, '/desktop/'), true);
|
||||
assert.equal(sessionStorage.getItem(intentKey), null);
|
||||
assert.ok(sessionStorage.getItem(intentKey));
|
||||
const beforeReload = win.__AFFINE_WEB_AUTH__;
|
||||
win.location.search = '';
|
||||
assert.equal(prepareWebAuth(win, '/desktop/'), true);
|
||||
assert.equal(win.__AFFINE_WEB_AUTH__.takeIntent()[field], value);
|
||||
assert.equal(sessionStorage.getItem(intentKey), null);
|
||||
assert.equal(win.__AFFINE_WEB_AUTH__.takeIntent(), null);
|
||||
assert.equal(beforeReload.takeIntent(), null);
|
||||
}
|
||||
});
|
||||
|
||||
void test('direct sign-in replaces the current history entry and signals once in either shell', () => {
|
||||
void test('direct sign-in cleans the URL and preserves its one-use fields across reload', () => {
|
||||
for (const shell of ['/', '/desktop/']) {
|
||||
const win = {
|
||||
location: { pathname: '/sign-in' },
|
||||
history: {
|
||||
replaceState(_state, _title, target) {
|
||||
assert.equal(target, shell);
|
||||
for (const search of [
|
||||
'',
|
||||
'?client=affine&redirect_uri=%2Fworkspace%2Fdemo%2Fdoc-1&error=oauth_denied&email=alice%40example.com',
|
||||
]) {
|
||||
const win = {
|
||||
location: {
|
||||
pathname: '/sign-in',
|
||||
search,
|
||||
origin: 'https://example.com',
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.equal(prepareWebAuth(win, shell), true);
|
||||
assert.deepEqual(win.__AFFINE_WEB_AUTH__.takeIntent(), {
|
||||
kind: 'sign-in',
|
||||
redirectUri: null,
|
||||
email: null,
|
||||
});
|
||||
assert.equal(win.__AFFINE_WEB_AUTH__.takeIntent(), null);
|
||||
sessionStorage: createMemoryStorage(),
|
||||
history: {
|
||||
replaceState(_state, _title, target) {
|
||||
assert.equal(target, shell);
|
||||
win.location.pathname = target;
|
||||
win.location.search = '';
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.equal(prepareWebAuth(win, shell), true);
|
||||
assert.ok(win.sessionStorage.getItem(intentKey));
|
||||
assert.equal(prepareWebAuth(win, shell), true);
|
||||
assert.deepEqual(win.__AFFINE_WEB_AUTH__.takeIntent(), {
|
||||
kind: 'sign-in',
|
||||
redirectUri: search ? '/workspace/demo/doc-1' : null,
|
||||
email: search ? 'alice@example.com' : null,
|
||||
client: search ? 'affine' : null,
|
||||
error: search ? 'oauth_denied' : null,
|
||||
});
|
||||
assert.equal(win.__AFFINE_WEB_AUTH__.takeIntent(), null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
createWebHttpTransport,
|
||||
createWebSocketDriver,
|
||||
GenerationConflict,
|
||||
getVaultRevision,
|
||||
} from '../src/cloud-transport.js';
|
||||
import { createMemoryIdbFactory } from './memory-idb.mjs';
|
||||
|
||||
@@ -221,6 +222,53 @@ void test('a reused generation and epoch cannot authorize a stale snapshot after
|
||||
assert.equal(await first.load(scope), null);
|
||||
});
|
||||
|
||||
void test('vault changes require the loaded revision after the same instance sees a new login', async () => {
|
||||
const options = { indexedDB: createMemoryIdbFactory(), origin };
|
||||
const writer = createWebCredentialVault(options);
|
||||
const reader = createWebCredentialVault(options);
|
||||
for (const operation of ['save', 'remove']) {
|
||||
const scope = { origin, userId: operation + '@example.com' };
|
||||
const record = {
|
||||
scope,
|
||||
generation: 1,
|
||||
sessionEpoch: 1,
|
||||
session: {},
|
||||
credential: { kind: 'cookie' },
|
||||
pendingRefresh: null,
|
||||
sessionExpired: false,
|
||||
};
|
||||
await writer.compareAndSwap(null, record);
|
||||
const s1 = await reader.load(scope);
|
||||
assert.equal(getVaultRevision(s1), 1);
|
||||
assert.deepEqual(s1, record);
|
||||
await writer.remove(scope, 1);
|
||||
assert.equal(await reader.load(scope), null);
|
||||
await writer.compareAndSwap(null, record);
|
||||
const s2 = await reader.load(scope);
|
||||
assert.equal(getVaultRevision(s2), 3);
|
||||
|
||||
const updated = { ...s2, generation: 2 };
|
||||
const conflict = error =>
|
||||
error instanceof GenerationConflict && error.current === 1;
|
||||
for (const revision of [undefined, s1, getVaultRevision(s1)]) {
|
||||
await assert.rejects(
|
||||
reader.compareAndSwap(1, updated, revision),
|
||||
conflict
|
||||
);
|
||||
await assert.rejects(reader.remove(scope, 1, revision), conflict);
|
||||
}
|
||||
assert.deepEqual(await writer.load(scope), record);
|
||||
if (operation === 'save') {
|
||||
s2.generation = 2;
|
||||
await reader.compareAndSwap(1, s2);
|
||||
assert.deepEqual(await writer.load(scope), updated);
|
||||
} else {
|
||||
await reader.remove(scope, 1, getVaultRevision(s2));
|
||||
assert.equal(await writer.load(scope), null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
void test('an expired session can be replaced and a retired epoch cannot refresh it', async () => {
|
||||
const indexedDB = createMemoryIdbFactory();
|
||||
const first = createWebCredentialVault({ indexedDB, origin });
|
||||
|
||||
Reference in new issue
Block a user