Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(auth): 保留暂停恢复期间的凭证轮换与等待期限

Cindy82b74f4df833
diff --git a/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts
index 4393b01c8d..1824d1f733 100644
--- a/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts
+++ b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts
@@ -25,6 +25,8 @@ const source = ts.createSourceFile(
);
const names = new Set([
'apiFetch',
+ 'commitDesktopRefreshCredentials',
+ 'writeResourceSessionToVault',
'initialize',
'refresh',
'runColdStartRefreshFlow',
@@ -38,13 +40,14 @@ const compiled = ts.transpileModule(
let authStateEpoch = 0, loginFlowEpoch = 0, accessToken = null, currentUser = null;
let activeAuthRealm = 'global', pendingAuthRealm = null, loginFlowState = null;
let coldStartAuthInFlight = null, coldStartRetryWait = null, refreshTimer = null;
-let coldStartRecoveryStopped = false;
+let coldStartRecoveryStopped = false, coldStartRetryState = null;
let lastAcceptedRefreshToken = null, persistedRefreshTokenNeedsIdentityCheck = false;
let foreignDeviceLocalSignOut = false;
const passiveLocalSignOut = false, settledLoginCommitCount = 0;
const API_FETCH_TIMEOUT_MS = 15000;
const AUTH_REGION = 'global', RUNTIME_REFRESH_RETRY_MS = 60000;
const COLD_START_AUTH_GATE_TIMEOUT_MS = 20000;
+const LEGACY_RESOURCE_REFRESH_TOKEN_KEY = 'legacy-resource';
const LEGACY_REFRESH_TOKEN_KEY = 'legacy', LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'legacy-account';
const REFRESH_TOKEN_REPLACEMENT_RETRY_LIMIT = 2;
const COLD_START_REFRESH_TOKEN_REPLACEMENT_RECHECK_DELAYS_MS = [100, 250];
@@ -59,6 +62,7 @@ const hasPotentiallyPersistedAuthCredentials = () => !!saved.session;
const assertLoginFlowCurrent = (epoch) => { if (epoch !== loginFlowEpoch) throw new Error('superseded'); };
const finishColdStartSignedOut = async () => snapshotAuthState();
const recoverAccountFreeOwnerAtStartup = async () => {
+ onStartupFallback();
coldStartTimeoutFallbacks.record(authStateEpoch, authStateEpoch + 1);
authStateEpoch++; loginFlowEpoch++;
};
@@ -72,14 +76,28 @@ return {
manualLogin: () => runLoginAction({ type: 'discover', identifier: '[email protected]' }),
state: snapshotAuthState,
fallback: () => { coldStartTimeoutFallbacks.record(authStateEpoch, authStateEpoch + 1); authStateEpoch++; loginFlowEpoch++; },
- changeOwner: () => { authStateEpoch++; accessToken = 'test-new-login'; currentUser = { id: 'other' }; },
+ changeOwner: () => {
+ authStateEpoch++; accessToken = 'test-new-login'; currentUser = { id: 'other' };
+ saved.session = { version: 1, realm: 'global', refreshToken: 'other-refresh' };
+ vault.activeAccountKey = 'global:other';
+ vault.resources['global:other'] = { realm: 'global', refreshToken: 'other-refresh' };
+ },
+ stop: stopColdStartRecovery,
+ logoutForTest: () => { stopColdStartRecovery(); authStateEpoch++; saved.session = null;
+ vault.resources = {}; vault.activeAccountKey = null; vault.signedOutAt = Date.now(); },
};`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
).outputText;
function setup(random = 0) {
- const saved = { session: { version: 1, realm: 'global', refreshToken: 'test-refresh' } };
- const membership = { id: 'original', kind: 'personal' };
+ const saved: { session: any } = {
+ session: { version: 1, realm: 'global', refreshToken: 'test-refresh' },
+ };
+ const membership = { id: 'original', kind: 'personal', passportId: 'passport-original' };
+ const vault: any = {
+ activeAccountKey: 'global:original',
+ resources: { 'global:original': { realm: 'global', refreshToken: 'test-refresh' } },
+ };
const ok = {
ok: true,
status: 200,
@@ -89,15 +107,26 @@ function setup(random = 0) {
.fn<(...args: unknown[]) => Promise<any>>()
.mockResolvedValue({ ok: false, status: 0, data: null });
const loadProviders = vi.fn(async () => ({ step: 'identifier' }));
- const commit = vi.fn(async (data) => {
- saved.session.refreshToken = data.refreshToken;
- return 'active';
+ const transaction = vi.fn(async (mutate: any, afterPersist: any) => {
+ const result = mutate(vault);
+ await afterPersist(result);
+ return result;
});
const clear = vi.fn(async () => {
saved.session.refreshToken = '';
});
const deps = {
saved,
+ vault,
+ onStartupFallback: vi.fn(),
+ transactAuthAccountVault: transaction,
+ accountVaultKey: (realm: string, id: string) => `${realm}:${id}`,
+ loggedOutAccountKeySet: () => new Set(),
+ readSafe: () => null,
+ writePersistedAuthSessionOrThrow: (refreshToken: string, realm: string) => {
+ saved.session = { version: 1, realm, refreshToken };
+ },
+ metadataFromMembership: (membership: unknown) => membership,
AuthRefreshBackoff: class extends AuthRefreshBackoff {
constructor() {
super(
@@ -131,7 +160,6 @@ function setup(random = 0) {
clearConfirmedDeadRefreshTokens: clear,
resetActiveAuthRealmToBuild: vi.fn(),
isPassiveSharedUserDataInstance: () => false,
- commitDesktopRefreshCredentials: commit,
canRestoreAuthSessionForMembership: () => true,
getActiveAppSession: () => ({ mode: 'signed-out', dataOwnerId: null }),
withCloudOwnerCommit: async (options: any) => {
@@ -153,7 +181,7 @@ function setup(random = 0) {
notifyAuthListeners: vi.fn(),
};
const main = new Function(...Object.keys(deps), compiled)(...Object.values(deps));
- return { ...main, saved, request, ok, commit, clear, loadProviders, deps };
+ return { ...main, saved, vault, request, ok, transaction, clear, loadProviders, deps };
}
describe('saved login recovery after startup network failure', () => {
@@ -215,7 +243,7 @@ describe('saved login recovery after startup network failure', () => {
expect(h.request).toHaveBeenCalledTimes(2);
});
- it('does not publish or persist an old successful response after an owner change', async () => {
+ it('preserves only the old saved account rotation after an owner change', async () => {
const h = setup();
let resolve!: (value: unknown) => void;
h.request.mockImplementation(
@@ -229,9 +257,133 @@ describe('saved login recovery after startup network failure', () => {
h.changeOwner();
resolve(h.ok);
await expect(pending).resolves.toMatchObject({ user: { id: 'other' } });
- expect(h.commit).not.toHaveBeenCalled();
+ expect(h.saved.session.refreshToken).toBe('other-refresh');
+ expect(h.vault.resources['global:original'].refreshToken).toBe('test-rotated');
+ expect(h.vault.activeAccountKey).toBe('global:other');
+ expect(h.deps.notifyAuthListeners).not.toHaveBeenCalled();
});
+ // PR #7737: stopping publication must not lose a rotating request's result or
+ // its server deadline. Existing tests only stopped a timer or changed owner.
+ // Minimal sequences below execute initialize/reset with an in-flight reply (unit).
+ it.each(['network', 'vault'])(
+ 'keeps the rotation when manual login stops publication during %s',
+ async (phase) => {
+ const h = setup();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ if (phase === 'network')
+ h.request.mockImplementationOnce(async () => {
+ await gate;
+ return h.ok;
+ });
+ else {
+ h.request.mockResolvedValue(h.ok);
+ h.transaction.mockImplementationOnce(async (mutate: any, afterPersist: any) => {
+ await gate;
+ const result = mutate(h.vault);
+ await afterPersist(result);
+ return result;
+ });
+ }
+ const pending = h.start();
+ await vi.advanceTimersByTimeAsync(0);
+ await h.manualLogin();
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(h.deps.onStartupFallback).not.toHaveBeenCalled();
+ release();
+ await vi.advanceTimersByTimeAsync(0);
+ await pending;
+ expect(h.saved.session.refreshToken).toBe('test-rotated');
+ expect(h.state()).toMatchObject({ isAuthenticated: false });
+ expect(h.deps.notifyAuthListeners).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['logout', 'newer-token'])(
+ 'does not resurrect or overwrite credentials after %s',
+ async (change) => {
+ const h = setup();
+ let resolve!: (value: unknown) => void;
+ h.request.mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const pending = h.start();
+ await vi.advanceTimersByTimeAsync(0);
+ if (change === 'logout') h.logoutForTest();
+ else {
+ h.stop();
+ h.saved.session.refreshToken = 'newer-refresh';
+ h.vault.resources['global:original'].refreshToken = 'newer-refresh';
+ }
+ resolve(h.ok);
+ await pending;
+ expect(h.saved.session?.refreshToken).toBe(change === 'logout' ? undefined : 'newer-refresh');
+ expect(h.vault.resources['global:original']?.refreshToken).toBe(
+ change === 'logout' ? undefined : 'newer-refresh',
+ );
+ },
+ );
+
+ it('continues a retry requested before the stopped request fails without offering new login', async () => {
+ const h = setup();
+ let resolve!: (value: unknown) => void;
+ h.request.mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ void h.start();
+ await vi.advanceTimersByTimeAsync(0);
+ await h.manualLogin();
+ const reset = h.reset();
+ resolve({ ok: false, status: 0, data: null });
+ h.request.mockResolvedValue(h.ok);
+ await vi.advanceTimersByTimeAsync(20_000);
+ await reset;
+ expect(h.loadProviders).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(40_000);
+ expect(h.state()).toMatchObject({ isAuthenticated: true });
+ });
+
+ it.each([false, true])(
+ 'retains the server deadline across stopping and restarting (late=%s)',
+ async (late) => {
+ const h = setup(0.5);
+ const failure = { ok: false, status: 503, data: {}, retryAt: Date.now() + 120_000 };
+ let resolve!: (value: unknown) => void;
+ h.request.mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ void h.start();
+ await vi.advanceTimersByTimeAsync(0);
+ if (!late) {
+ resolve(failure);
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ h.stop();
+ if (late) resolve(failure);
+ await vi.advanceTimersByTimeAsync(0);
+ const reset = h.reset();
+ h.request.mockResolvedValue(h.ok);
+ await vi.advanceTimersByTimeAsync(20_000);
+ await reset;
+ await vi.advanceTimersByTimeAsync(129_999);
+ expect(h.request).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(h.state()).toMatchObject({ isAuthenticated: true });
+ },
+ );
+
it('coalesces multiple retry clicks and runtime refresh behind the pending request', async () => {
const h = setup();
let resolve!: (value: unknown) => void;
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
index 5924c052dc..d27e269225 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
@@ -837,7 +837,11 @@ describe('auth login-flow reset', () => {
expect(coldRealmActivation).toBeGreaterThan(coldPolicyGuard);
expect(coldBody).toContain('requestedToken,');
expect(coldBody).toContain('allowUnclaimedVault: true');
- expect(coldBody).toContain("epochChanged('before-cold-start-credential-commit')");
+ // Token rotation is durable before publication checks; stopping the UI must
+ // not lose the consumed credential. Ownership remains checked in the vault.
+ expect(coldBody.indexOf("epochChanged('after-cold-start-credential-commit')")).toBeGreaterThan(
+ coldCredentialCommit,
+ );
expect(coldBody).toContain("credentialCommit !== 'active'");
const inactiveCommit = coldBody.indexOf("credentialCommit !== 'active'");
const activeCandidateRead = coldBody.indexOf(
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index dac260f5e0..7e0322b4c1 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -1654,7 +1654,10 @@ async function commitDesktopRefreshCredentials(
const stillOwnsActiveSession =
requestedTokenStillStored && (vault.activeAccountKey === key || canClaimUninitializedVault);
const passportId = pair.membership.passportId;
- if (passportId && (stillOwnsActiveSession || vault.resources[key])) {
+ if (
+ passportId &&
+ (stillOwnsActiveSession || vault.resources[key]?.refreshToken === requestedRefreshToken)
+ ) {
// A passive stale refresh may still rotate account A's resource token
// after the primary has committed account B. Preserve A for a future
// explicit switch, but never let that late result reclaim activeAccountKey.
@@ -3371,17 +3374,20 @@ function scheduleNonXdOrgBetaDefault(input: {
let coldStartAuthInFlight: Promise<AuthState> | null = null;
// A newly mounted window must not restart recovery after the user took over.
let coldStartRecoveryStopped = false;
+// The saved credential owns the deadline, not the login page/recovery invocation.
+// Returning to the page must keep both Retry-After and its random spread.
+type ColdStartRetryState = {
+ refreshToken: string;
+ realm: AuthRegion;
+ backoff: AuthRefreshBackoff;
+ failure?: AuthRefreshResult;
+};
+let coldStartRetryState: ColdStartRetryState | null = null;
// Wakes only the delay between attempts, never aborts a rotating refresh request.
let coldStartRetryWait: ((cancel?: boolean) => void) | null = null;
-function waitForColdStartRetry(
- result: AuthRefreshResult,
- backoff: AuthRefreshBackoff,
-): Promise<void> {
- // The backoff belongs to this recovery flow, so startup UI fallback epochs
- // cannot reset its failure count and synchronize clients again.
- const retryAt = Date.now() + backoff.defer(0, result.retryAt);
+function waitForColdStartRetry(retry: ColdStartRetryState): Promise<void> {
return new Promise((resolve) => {
let timer: ReturnType<typeof setTimeout>;
const finish = () => {
@@ -3390,12 +3396,10 @@ function waitForColdStartRetry(
resolve();
};
const wake = (cancel = false) => {
- // Only an explicit retry of a transport failure can accelerate recovery.
- // Server failures and their randomized cooldown must remain protected.
- if (cancel || (result.status === 0 && !Number.isFinite(result.retryAt))) finish();
+ if (cancel || retry.backoff.remaining(0) === 0) finish();
};
const tick = () => {
- const remaining = retryAt - Date.now();
+ const remaining = retry.backoff.remaining(0);
if (remaining <= 0) finish();
else {
timer = setTimeout(tick, Math.min(remaining, 2_147_483_647));
@@ -3409,9 +3413,8 @@ function waitForColdStartRetry(
function stopColdStartRecovery(): void {
coldStartRecoveryStopped = true;
- if (coldStartAuthInFlight === null) return;
- authStateEpoch += 1;
- coldStartTimeoutFallbacks.clear();
+ // Pause publication/retries without poisoning an in-flight rotation. A reset
+ // can resume that same request; actual login/logout still advance auth epochs.
coldStartRetryWait?.(true);
}
@@ -4784,6 +4787,9 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
return awaitWithStartupTimeout(coldStartCompletion, {
timeoutMs: COLD_START_AUTH_GATE_TIMEOUT_MS,
onTimeout: async () => {
+ // A stopped recovery must not clear a newly opened manual login form,
+ // even if sibling windows previously recorded startup fallback epochs.
+ if (coldStartRecoveryStopped) return snapshotAuthState();
options.onColdStartPending?.(coldStartCompletion);
log.warn(
`cold-start auth still pending after ${COLD_START_AUTH_GATE_TIMEOUT_MS}ms — recovering the account-free projection before startup continues`,
@@ -4859,6 +4865,7 @@ async function runColdStartRefreshFlow(
*/
let flowAuthEpoch = epochAtStart;
const epochChanged = (point: string): boolean => {
+ if (coldStartRecoveryStopped) return true;
const resolution = commitColdStartRefreshIfCurrent({
registry: coldStartTimeoutFallbacks,
flowEpoch: flowAuthEpoch,
@@ -4878,7 +4885,6 @@ async function runColdStartRefreshFlow(
return true;
};
- const backoff = new AuthRefreshBackoff();
try {
// Keep the shared recovery alive beyond the splash deadline. A network outage
// must not turn a saved session into a fresh-login requirement. Each failed
@@ -4893,14 +4899,34 @@ async function runColdStartRefreshFlow(
}
storedToken = latest.refreshToken;
}
+ if (
+ coldStartRetryState?.refreshToken !== storedToken ||
+ coldStartRetryState.realm !== storedRealm
+ ) {
+ coldStartRetryState = {
+ refreshToken: storedToken,
+ realm: storedRealm,
+ backoff: new AuthRefreshBackoff(),
+ };
+ }
+ const retry = coldStartRetryState;
+ await waitForColdStartRetry(retry);
+ if (epochChanged('after-recovery-wait')) return snapshotAuthState();
+ // Another shared-data instance may have rotated/switched while we waited.
+ // Re-enter admission with its current credential instead of sending the old one.
+ if (!ownershipRecovery.expectedActiveVaultAccountKey) {
+ const latest = readPersistedAuthSession();
+ if (latest?.realm !== storedRealm || latest.refreshToken !== storedToken) continue;
+ }
try {
// Realm discovery can fail while offline too. Never fall back to sending
// a saved credential to a different realm's refresh endpoint.
await loadClientEndpointsForRealm(storedRealm);
} catch (error) {
+ retry.failure = { ok: false, status: 0, data: {} };
+ retry.backoff.defer(0);
if (epochChanged('after-realm-discovery')) return snapshotAuthState();
log.warn('persisted auth realm manifest unavailable; keeping session for retry', error);
- await waitForColdStartRetry({ ok: false, status: 0, data: {} }, backoff);
continue;
}
if (epochChanged('before-refresh')) return snapshotAuthState();
@@ -4909,24 +4935,42 @@ async function runColdStartRefreshFlow(
realm: storedRealm,
withTransientRetry: false,
});
+ // A successful rotation must become durable even when publication was
+ // stopped while the request was in flight. Credential ownership is checked
+ // inside the existing vault transaction below, separately from UI epochs.
+ if (run.result.ok) break;
+ const transient =
+ run.failureAction?.kind === 'transient-failure' ||
+ run.failureAction?.kind === 'replacement-retry';
+ if (transient) {
+ retry.failure = run.result;
+ retry.backoff.defer(0, run.result.retryAt);
+ }
if (epochChanged('after-recovery-attempt')) return snapshotAuthState();
- if (
- run.result.ok ||
- (run.failureAction?.kind !== 'transient-failure' &&
- run.failureAction?.kind !== 'replacement-retry')
- )
- break;
+ if (!transient) break;
log.warn(
`cold-start refresh failed status=${run.result.status} — keeping saved login and retrying in the background`,
);
- await waitForColdStartRetry(run.result, backoff);
}
const { result: refreshResult, attempts, failureAction, rejectedTokens, requestedToken } = run;
- // 迟到守卫①:refresh 期间用户手动登录 / 登出过 → 丢弃结果。成功也丢
- // (旧 token family 已被新登录取代);失败更不能把新登录的 token 删掉。
- if (epochChanged('after-refresh')) {
- return snapshotAuthState();
+ const credentialCommit = refreshResult.ok
+ ? await commitDesktopRefreshCredentials(
+ refreshResult.data as RefreshResponse,
+ storedRealm,
+ requestedToken,
+ {
+ allowUnclaimedVault: true,
+ },
+ )
+ : undefined;
+ if (
+ refreshResult.ok &&
+ coldStartRetryState?.refreshToken === storedToken &&
+ coldStartRetryState.realm === storedRealm
+ ) {
+ coldStartRetryState = null;
}
+ if (epochChanged('after-cold-start-credential-commit')) return snapshotAuthState();
const latestSession = readPersistedAuthSession();
if (
latestSession &&
@@ -5014,23 +5058,6 @@ async function runColdStartRefreshFlow(
const refreshData = refreshResult.data as RefreshResponse;
attemptedOwnershipTokens.add(requestedToken);
- const credentialCommit = await commitDesktopRefreshCredentials(
- refreshData,
- storedRealm,
- requestedToken,
- {
- allowUnclaimedVault: true,
- validateBeforeWrite: () => {
- if (epochChanged('before-cold-start-credential-commit')) {
- throw new AuthApiError(
- 'AUTH_FLOW_SUPERSEDED',
- 409,
- 'Cold-start credential commit was superseded',
- );
- }
- },
- },
- );
if (credentialCommit !== 'active') {
log.warn(
`cold-start refresh lost active credential ownership (${credentialCommit}); preserved only the still-saved account token`,
@@ -5496,6 +5523,14 @@ async function runLoginAction(
(coldStartAuthInFlight || credentialStoreHealth.unavailable || readPersistedAuthSession())
) {
coldStartRecoveryStopped = false;
+ // Only a deliberate retry of a transport failure can release a deadline;
+ // returning to the page must never erase server cooldown or failure count.
+ if (
+ coldStartRetryState?.failure?.status === 0 &&
+ !Number.isFinite(coldStartRetryState.failure.retryAt)
+ ) {
+ coldStartRetryState.backoff.release(0);
+ }
coldStartRetryWait?.();
await initialize();
// Startup may itself clear an obsolete owner generation. Its current
diff --git a/apps/desktop/src/main/authRefreshBackoff.ts b/apps/desktop/src/main/authRefreshBackoff.ts
index e577f635fc..c6d4ceb4cf 100644
--- a/apps/desktop/src/main/authRefreshBackoff.ts
+++ b/apps/desktop/src/main/authRefreshBackoff.ts
@@ -27,6 +27,11 @@ export class AuthRefreshBackoff {
return this.remaining(epoch);
}
+ /** Explicit transport retry releases the wait without resetting the failure count. */
+ release(epoch: number): void {
+ if (this.epoch === epoch) this.retryAt = 0;
+ }
+
clear(): void {
this.epoch = -1;
this.retryAt = 0;
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 75edb8b342..73e4beae41 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -183,7 +183,10 @@ Desktop 冷启动恢复已保存的登录时,DNS/断网、服务端临时错
不会清除凭证,也不在有限次数失败后放弃。启动画面仍只等待原有的 20 秒,恢复流程在
后台持续按下述随机退避策略重试;直到恢复成功、凭证明确
失效,或用户开始新的登录/退出/切换账号/进入未登录模式。人工操作使旧流程失效,
-迟到响应不能覆盖新状态;不通过中断正在轮换凭证的网络请求来实现取消。
+迟到响应不能覆盖新界面身份;不通过中断正在轮换凭证的网络请求来实现取消。
+已发出的刷新若成功,先在既有凭证事务中核对仍保存着请求所消费的凭证,再保存轮换结果;
+即使用户正在手动登录,也不能丢掉这一结果。旧账号仍保存时仅更新它的凭证,不重新激活,
+不覆盖较新的凭证,也不复活已退出的账号。
登录页「重试」优先恢复已保存的登录,复用正在进行的请求,并可提前结束普通网络失败
的等待,但不能绕过服务端冷却时间。运行时续期也不与冷启动流程并发轮换同一凭证。
实现与回归见 `authManager.ts`、`authColdStartRecovery.test.ts`。
@@ -193,7 +196,9 @@ Desktop 冷启动恢复与运行时 refresh 共用随机指数退避策略:连
429/503 的有效 `Retry-After` 更长时先遵守服务器期限,再追加当前退避档位的随机间隔,
防止所有客户端在同一个服务器恢复时间一起重试。等待期间的主动调用不发请求、不延长
原期限,也不清除凭证。成功续期/登录清除等待,登录代次改变后旧等待不约束新账号;
-冷启动画面超时转后台不能重置失败次数。
+冷启动画面超时转后台不能重置失败次数。冷启动的等待期限和失败次数归属于当前保存的
+凭证,返回/取消再恢复沿用原期限,取消后的迟到限流响应也必须保留期限;手动重试释放
+纯网络错误的等待时不清零失败次数。恢复停止期间的启动超时不能清除手动登录进度。
网络变化、resume 或 relay 恢复信号均不能跳过等待或清零失败次数;在途请求仍复用同一个
promise,恢复信号不能在旧请求结束后追加立即续期。只有用户主动点击登录页重试,且
此前失败没有服务端响应、没有服务端等待期限时,才能提前结束冷启动等待。