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): recover mobile credential projections

xd-bobo41663cb7eba6
diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
index fd80184026..bf136d01bf 100644
--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
@@ -135,8 +135,12 @@ describe('auth weak-network bootstrap', () => {
refreshStart,
authSource.indexOf('\n useEffect(() => {', refreshStart),
);
+ const reconcileAt = refreshBody.indexOf(
+ 'reconcileMobileActiveAuthSession({',
+ );
const readSessionAt = refreshBody.indexOf(
- 'const session = await serializeRefreshTokenMutation(',
+ 'const session = reconciledAuth.session;',
+ reconcileAt,
);
const emptySessionAt = refreshBody.indexOf('if (!session) {');
const loadRealmAt = refreshBody.indexOf(
@@ -151,7 +155,8 @@ describe('auth weak-network bootstrap', () => {
),
].map((match) => match.index);
- expect(readSessionAt).toBeGreaterThanOrEqual(0);
+ expect(reconcileAt).toBeGreaterThanOrEqual(0);
+ expect(readSessionAt).toBeGreaterThan(reconcileAt);
expect(
guards.some((index) => index > readSessionAt && index < emptySessionAt),
).toBe(true);
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index 0f93e24898..5ae5f88916 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -308,6 +308,18 @@ describe('mobile auth-server login', () => {
const refreshStart = authSource.indexOf('const refresh = useCallback');
const refreshEnd = authSource.indexOf('\n useEffect(() => {', refreshStart);
const refreshBody = authSource.slice(refreshStart, refreshEnd);
+ const crashReconcile = refreshBody.indexOf(
+ 'reconcileMobileActiveAuthSession({',
+ );
+ const networkRefresh = refreshBody.indexOf('.refresh(', crashReconcile);
+ expect(crashReconcile).toBeGreaterThan(-1);
+ expect(networkRefresh).toBeGreaterThan(crashReconcile);
+ expect(refreshBody).toContain(
+ 'readPersistedSession: readPersistedAuthSessionStrict',
+ );
+ expect(refreshBody).toContain(
+ 'clearPersistedSession: () => deleteSecureItem(AUTH_SESSION_KEY)',
+ );
const resourceVaultWrite = refreshBody.indexOf(
'await commitMobileRuntimeResourceSession({',
);
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 09909978eb..0547629884 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -94,6 +94,7 @@ import {
mutateMobileAccountVault,
patchMobileAccountMetadata,
readMobileAccountVault,
+ reconcileMobileActiveAuthSession,
rememberMobilePassportSession,
rememberMobileResourceSession,
removeMobileResourceSessionIfCurrent,
@@ -1051,9 +1052,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const did =
knownDeviceId ?? deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
- const persistedVault = await readMobileAccountVault().catch(
- () => null,
- );
+ const reconciledAuth = await serializeRefreshTokenMutation(() =>
+ reconcileMobileActiveAuthSession({
+ readPersistedSession: readPersistedAuthSessionStrict,
+ writePersistedSession: writePersistedAuthSession,
+ clearPersistedSession: () => deleteSecureItem(AUTH_SESSION_KEY),
+ }),
+ ).catch(() => null);
+ if (!reconciledAuth) return null;
+ const persistedVault = reconciledAuth.vault;
const activeResourceAtStart = persistedVault?.activeAccountKey
? {
accountKey: persistedVault.activeAccountKey,
@@ -1062,14 +1069,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
: null;
if (typeof persistedVault?.signedOutAt === 'number') {
- await serializeRefreshTokenMutation(() =>
- deleteSecureItem(AUTH_SESSION_KEY).catch(() => undefined),
- );
+ await clearCanaryChannel().catch(() => undefined);
return null;
}
- const session = await serializeRefreshTokenMutation(
- readPersistedAuthSession,
- );
+ const session = reconciledAuth.session;
if (authGenerationRef.current !== generation) return null;
if (!session) {
await clearCanaryChannel().catch(() => undefined);
diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
index 368a15322f..0c569378ca 100644
--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
@@ -28,6 +28,7 @@ import {
listMobileSavedAccounts,
mutateMobileAccountVault,
parseMobileAccountVault,
+ reconcileMobileActiveAuthSession,
removeMobilePassportSessionIfCurrent,
removeMobileResourceSessionIfCurrent,
replaceMobilePassportSessionIfCurrent,
@@ -119,6 +120,72 @@ describe('mobile account vault', () => {
]);
});
+ it('repairs an interrupted compatibility-session write from the active vault before refresh', async () => {
+ const accountKey = JSON.stringify(['global', metadata.membershipId]);
+ secureStorage.value = JSON.stringify({
+ version: 1,
+ activeAccountKey: accountKey,
+ resources: {
+ [accountKey]: {
+ realm: 'global',
+ refreshToken: 'resource-new',
+ metadata,
+ lastUsedAt: 10,
+ },
+ },
+ passports: {},
+ });
+ let session: {
+ version: 1;
+ realm: 'cn' | 'global';
+ refreshToken: string;
+ } = {
+ version: 1,
+ realm: 'global',
+ refreshToken: 'resource-old',
+ };
+ const writePersistedSession = vi.fn(
+ async (refreshToken: string, realm: 'cn' | 'global') => {
+ session = { version: 1, realm, refreshToken };
+ },
+ );
+ const clearPersistedSession = vi.fn(async () => undefined);
+
+ const reconciled = await reconcileMobileActiveAuthSession({
+ readPersistedSession: async () => session,
+ writePersistedSession,
+ clearPersistedSession,
+ });
+
+ expect(reconciled.session).toEqual({
+ version: 1,
+ realm: 'global',
+ refreshToken: 'resource-new',
+ });
+ expect(writePersistedSession).toHaveBeenCalledWith(
+ 'resource-new',
+ 'global',
+ );
+ expect(clearPersistedSession).not.toHaveBeenCalled();
+ expect(secureStorage.set).not.toHaveBeenCalled();
+
+ secureStorage.value = JSON.stringify({
+ version: 1,
+ activeAccountKey: null,
+ resources: {},
+ passports: {},
+ signedOutAt: 123,
+ });
+ await expect(
+ reconcileMobileActiveAuthSession({
+ readPersistedSession: async () => session,
+ writePersistedSession,
+ clearPersistedSession,
+ }),
+ ).resolves.toEqual(expect.objectContaining({ session: null }));
+ expect(clearPersistedSession).toHaveBeenCalledTimes(1);
+ });
+
it('does not trust an active key whose resource credential is missing', () => {
const raw = JSON.stringify({
version: 1,
diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.ts
index a57d1a692e..269e9ce4a5 100644
--- a/apps/mobile/src/auth/mobileAccountVault.ts
+++ b/apps/mobile/src/auth/mobileAccountVault.ts
@@ -7,6 +7,7 @@ import {
type AccountMembership,
type AuthMembership,
type AuthRegion,
+ type AuthSessionRecord,
type AuthTokenPair,
type StoredAccountMetadata,
} from '@cindy/auth-client';
@@ -46,6 +47,12 @@ export interface MobileSavedAccount extends StoredAccountMetadata {
let mutation = Promise.resolve();
+function enqueueMobileVaultOperation<T>(operation: () => Promise<T>): Promise<T> {
+ const run = mutation.then(operation);
+ mutation = run.then(() => undefined, () => undefined);
+ return run;
+}
+
export function emptyMobileAccountVault(): MobileAccountVault {
return { version: 1, activeAccountKey: null, resources: {}, passports: {} };
}
@@ -153,14 +160,13 @@ export function transactMobileAccountVault<T>(
operation: (vault: MobileAccountVault) => T | Promise<T>,
afterPersist: (result: T) => void | Promise<void> = () => undefined,
): Promise<T> {
- let result!: T;
- const run = mutation.then(async () => {
+ return enqueueMobileVaultOperation(async () => {
// A SecureStore read failure is not an empty vault. Propagate it so a
// transient keychain error can never turn the next mutation into a write
// that erases every saved credential.
const raw = await getSecureItem(MOBILE_ACCOUNT_VAULT_KEY);
const vault = parseMobileAccountVaultRecord(raw);
- result = await operation(vault);
+ const result = await operation(vault);
await writeMobileAccountVault(vault);
try {
// Keep the vault queue owned until every related durable write and
@@ -172,9 +178,60 @@ export function transactMobileAccountVault<T>(
else await setSecureItem(MOBILE_ACCOUNT_VAULT_KEY, raw);
throw error;
}
+ return result;
+ });
+}
+
+export interface ReconciledMobileAuthState {
+ vault: MobileAccountVault;
+ session: AuthSessionRecord | null;
+}
+
+/**
+ * Repair the compatibility auth session from the crash-consistent active
+ * Resource record before any refresh request can consume a stale generation.
+ * The vault queue remains owned through the repair so an account transition
+ * cannot interleave between the snapshot and the projection write.
+ */
+export function reconcileMobileActiveAuthSession(input: {
+ readPersistedSession: () => Promise<AuthSessionRecord | null>;
+ writePersistedSession: (
+ refreshToken: string,
+ realm: AuthRegion,
+ ) => Promise<void>;
+ clearPersistedSession: () => Promise<void>;
+}): Promise<ReconciledMobileAuthState> {
+ return enqueueMobileVaultOperation(async () => {
+ const raw = await getSecureItem(MOBILE_ACCOUNT_VAULT_KEY);
+ const vault = parseMobileAccountVaultRecord(raw);
+ let session = await input.readPersistedSession();
+
+ if (typeof vault.signedOutAt === 'number') {
+ if (session) await input.clearPersistedSession();
+ return { vault, session: null };
+ }
+
+ const activeResource = vault.activeAccountKey
+ ? vault.resources[vault.activeAccountKey]
+ : undefined;
+ if (!activeResource) return { vault, session };
+
+ if (
+ session?.realm !== activeResource.realm ||
+ session.refreshToken !== activeResource.refreshToken
+ ) {
+ await input.writePersistedSession(
+ activeResource.refreshToken,
+ activeResource.realm,
+ );
+ session = {
+ version: 1,
+ realm: activeResource.realm,
+ refreshToken: activeResource.refreshToken,
+ };
+ }
+ return { vault, session };
});
- mutation = run.then(() => undefined, () => undefined);
- return run.then(() => result);
}
export function mutateMobileAccountVault<T>(