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): bind cached profiles to account vaults

xd-bobo4670024e707b
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index d25636603a..bd58382ad0 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -192,6 +192,18 @@ describe('auth login-flow reset', () => {
}
});
+ it('filters invalid vault children only for read-only projection', () => {
+ const readStart = source.indexOf('function readAuthAccountVault(');
+ const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);
+ const readBody = source.slice(readStart, readEnd);
+
+ expect(readBody).toContain('if (options.allowUnreadable) continue;');
+ expect(readBody).toContain("throw new Error('invalid saved resource credential')");
+ expect(readBody).toContain("throw new Error('invalid saved Passport credential')");
+ expect(readBody).toContain("throw new Error('invalid saved Passport membership')");
+ expect(readBody).toContain('memberships.length !== item.memberships.length');
+ });
+
it('atomically replaces the aggregate saved-account vault', () => {
const writeStart = source.indexOf('function writeAtomicSafe(');
const writeEnd = source.indexOf('\n}\n\nfunction removeAtomicSafeOrThrow', writeStart);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 492d53d442..cb55a4efc9 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -670,33 +670,47 @@ function readAuthAccountVault(options: { allowUnreadable?: boolean } = {}): Auth
}
const resources: Record<string, StoredResourceSession> = {};
for (const [key, candidate] of Object.entries(parsed.resources)) {
- if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
+ if (options.allowUnreadable) continue;
+ throw new Error('invalid saved resource credential');
+ }
const item = candidate as Partial<StoredResourceSession>;
if (
(item.realm !== 'cn' && item.realm !== 'global') ||
typeof item.refreshToken !== 'string' ||
!isStoredAccountMetadata(item.metadata) ||
typeof item.lastUsedAt !== 'number'
- )
- continue;
+ ) {
+ if (options.allowUnreadable) continue;
+ throw new Error('invalid saved resource credential');
+ }
resources[key] = item as StoredResourceSession;
}
const passports: Record<string, StoredPassportSession> = {};
for (const [key, candidate] of Object.entries(parsed.passports)) {
- if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
+ if (options.allowUnreadable) continue;
+ throw new Error('invalid saved Passport credential');
+ }
const item = candidate as Partial<StoredPassportSession>;
if (
(item.realm !== 'cn' && item.realm !== 'global') ||
typeof item.passportId !== 'string' ||
typeof item.accountRefreshToken !== 'string' ||
!Array.isArray(item.memberships)
- )
- continue;
+ ) {
+ if (options.allowUnreadable) continue;
+ throw new Error('invalid saved Passport credential');
+ }
+ const memberships = item.memberships.filter(isStoredAccountMetadata);
+ if (!options.allowUnreadable && memberships.length !== item.memberships.length) {
+ throw new Error('invalid saved Passport membership');
+ }
passports[key] = {
realm: item.realm,
passportId: item.passportId,
accountRefreshToken: item.accountRefreshToken,
- memberships: item.memberships.filter(isStoredAccountMetadata),
+ memberships,
};
}
return {
diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
index 967468abf3..fd80184026 100644
--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
@@ -15,12 +15,14 @@ describe('auth weak-network bootstrap', () => {
);
it('bootstrap 只在会话 realm 端点激活后用本地痕迹恢复登录视图', () => {
- // 快照恢复必须双条件:refresh token 还在 + 有缓存资料;二者缺一不得凭空造登录态。
- expect(authSource).toContain('if (storedSession && cachedUser) {');
+ // 快照恢复必须三条件:refresh token、缓存资料、vault 当前 owner 一致。
+ expect(authSource).toContain(
+ 'if (storedSession && cachedUser && cachedProfileMatchesActiveAccount) {',
+ );
expect(authSource).toContain('userRef.current = cachedUser;');
expect(authSource).toContain('setUser(cachedUser);');
const restoreStart = authSource.indexOf(
- 'if (storedSession && cachedUser) {',
+ 'if (storedSession && cachedUser && cachedProfileMatchesActiveAccount) {',
);
const restoreEnd = authSource.indexOf(
'\n if (!storedSession)',
@@ -40,6 +42,13 @@ describe('auth weak-network bootstrap', () => {
expect(publishOwnerAt).toBeGreaterThan(activateRealmAt);
expect(publishUserAt).toBeGreaterThan(publishOwnerAt);
expect(restoreBody).toContain('setDeferredSessionRecovery(true);');
+ expect(authSource).toContain(
+ 'persistedAccountVault?.activeAccountKey === cachedAccountKey',
+ );
+ expect(authSource).toContain('cachedProfile?.accountKey === cachedAccountKey');
+ expect(authSource).toContain(
+ 'writeCachedUserProfile(cachedUser, cachedAccountKey)',
+ );
// bootstrap 里的 refresh 失败必须是"保留降级会话",不许再出现坍缩式 .catch(() => null)。
expect(authSource).not.toContain('await refresh(did).catch(() => null)');
expect(authSource).toMatch(
@@ -56,6 +65,12 @@ describe('auth weak-network bootstrap', () => {
const applyUserBody = authSource.slice(applyUserStart, applyUserEnd);
expect(applyUserBody.indexOf('setMobileAuthOwner(next?.id);'))
.toBeLessThan(applyUserBody.indexOf('setUser(next);'));
+ expect(applyUserBody).toContain(
+ 'accountVaultKey(activeAuthRealmRef.current, next.id)',
+ );
+ expect(applyUserBody).toContain(
+ 'writeCachedUserProfile(next, profileAccountKey)',
+ );
const initializeFailure = authSource.indexOf(
"console.warn('[auth] initialize failed; normalized to signed-out'",
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index c366fbe883..c368d08ab2 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -217,6 +217,17 @@ export interface MobileUser {
passportId: string;
}
+interface CachedUserProfile {
+ accountKey: string | null;
+ user: MobileUser;
+}
+
+interface CachedUserProfileRecord {
+ version: 1;
+ accountKey: string;
+ user: MobileUser;
+}
+
export type MobileLoginAction =
| { type: 'reset' }
| { type: 'discover'; email: string }
@@ -744,11 +755,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 缓存资料恢复“已登录”视图,token 由后台刷新补齐。
const applyUser = useCallback(
(next: MobileUser | null) => {
+ const profileAccountKey = next
+ ? accountVaultKey(activeAuthRealmRef.current, next.id)
+ : null;
setDeferredSessionRecovery(false);
setMobileAuthOwner(next?.id);
userRef.current = next;
setUser(next);
- void serializeUserProfileMutation(() => writeCachedUserProfile(next));
+ void serializeUserProfileMutation(() =>
+ writeCachedUserProfile(next, profileAccountKey),
+ );
},
[serializeUserProfileMutation],
);
@@ -1178,10 +1194,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
};
}
}
- const [cachedUser, storedDeletionReceiptRaw] = await Promise.all([
+ const [cachedProfile, storedDeletionReceiptRaw] = await Promise.all([
readCachedUserProfile(),
getSecureItem(ACCOUNT_DELETION_RECEIPT_KEY).catch(() => null),
]);
+ const cachedUser = cachedProfile?.user ?? null;
const storedDeletionReceipt =
parseAccountDeletionReceiptRecord(storedDeletionReceiptRaw) ??
(storedDeletionReceiptRaw &&
@@ -1210,7 +1227,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 弱网冷启动只有在会话所属 realm 的业务端点已整体激活后,才发布缓存用户。
// 构建 realm 命中启动缓存,不增加网络依赖;跨区清单不可用时保持未认证,
// 防止业务调用先捕获构建区 URL、随后 refresh 又把对端 token 发给该 URL。
- if (storedSession && cachedUser) {
+ const cachedAccountKey =
+ storedSession && cachedUser
+ ? accountVaultKey(storedSession.realm, cachedUser.id)
+ : null;
+ const cachedProfileMatchesActiveAccount =
+ cachedAccountKey !== null &&
+ persistedAccountVault?.activeAccountKey === cachedAccountKey &&
+ (cachedProfile?.accountKey === cachedAccountKey ||
+ cachedProfile?.accountKey === null);
+ if (storedSession && cachedUser && cachedProfileMatchesActiveAccount) {
try {
await loadMobileEndpointsForRealm(storedSession.realm);
if (cancelled) return;
@@ -1219,6 +1245,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
userRef.current = cachedUser;
setMobileAuthOwner(cachedUser.id);
setUser(cachedUser);
+ if (cachedProfile.accountKey === null) {
+ void serializeUserProfileMutation(() =>
+ writeCachedUserProfile(cachedUser, cachedAccountKey),
+ );
+ }
} catch {
if (!cancelled) setDeferredSessionRecovery(true);
}
@@ -2854,31 +2885,52 @@ async function restorePersistedAuthSession(
}
}
-async function readCachedUserProfile(): Promise<MobileUser | null> {
+function parseCachedMobileUser(value: unknown): MobileUser | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const parsed = value as Partial<MobileUser>;
+ if (
+ typeof parsed.id !== 'string' ||
+ typeof parsed.name !== 'string' ||
+ (parsed.membershipKind !== 'personal' && parsed.membershipKind !== 'org')
+ )
+ return null;
+ return {
+ ...(parsed as MobileUser),
+ orgLogoUrl:
+ typeof parsed.orgLogoUrl === 'string' ? parsed.orgLogoUrl : null,
+ };
+}
+
+async function readCachedUserProfile(): Promise<CachedUserProfile | null> {
try {
const raw = await getSecureItem(USER_PROFILE_KEY);
if (!raw) return null;
- const parsed = JSON.parse(raw) as Partial<MobileUser>;
- if (
- typeof parsed.id !== 'string' ||
- typeof parsed.name !== 'string' ||
- (parsed.membershipKind !== 'personal' && parsed.membershipKind !== 'org')
- )
- return null;
- return {
- ...(parsed as MobileUser),
- orgLogoUrl:
- typeof parsed.orgLogoUrl === 'string' ? parsed.orgLogoUrl : null,
- };
+ const parsed = JSON.parse(raw) as unknown;
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ const record = parsed as Partial<CachedUserProfileRecord>;
+ if (record.version === 1 && typeof record.accountKey === 'string') {
+ const user = parseCachedMobileUser(record.user);
+ return user ? { accountKey: record.accountKey, user } : null;
+ }
+ }
+ const legacyUser = parseCachedMobileUser(parsed);
+ return legacyUser ? { accountKey: null, user: legacyUser } : null;
} catch {
return null;
}
}
-async function writeCachedUserProfile(user: MobileUser | null): Promise<void> {
+async function writeCachedUserProfile(
+ user: MobileUser | null,
+ accountKey: string | null,
+): Promise<void> {
try {
- if (user) await setSecureItem(USER_PROFILE_KEY, JSON.stringify(user));
- else await deleteSecureItem(USER_PROFILE_KEY);
+ if (user && accountKey) {
+ const record: CachedUserProfileRecord = { version: 1, accountKey, user };
+ await setSecureItem(USER_PROFILE_KEY, JSON.stringify(record));
+ } else {
+ await deleteSecureItem(USER_PROFILE_KEY);
+ }
} catch {
// Snapshot persistence is best effort and never blocks the auth flow.
}
diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
index 2c5d582951..0d8fdd23eb 100644
--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
@@ -61,6 +61,28 @@ describe('mobile account vault', () => {
});
});
+ it('filters damaged children only from the read-only projection', () => {
+ const accountKey = JSON.stringify(['global', metadata.membershipId]);
+ const raw = JSON.stringify({
+ version: 1,
+ activeAccountKey: accountKey,
+ resources: {
+ [accountKey]: {
+ realm: 'global',
+ refreshToken: 'resource-refresh',
+ metadata,
+ lastUsedAt: 10,
+ },
+ damaged: { realm: 'global', refreshToken: 'must-not-be-rewritten' },
+ },
+ passports: {},
+ });
+
+ expect(parseMobileAccountVault(raw).resources).toEqual({
+ [accountKey]: expect.objectContaining({ refreshToken: 'resource-refresh' }),
+ });
+ });
+
it('deduplicates resource and Passport projections and marks the active account', () => {
const accountKey = JSON.stringify(['global', 'membership-1']);
const raw = JSON.stringify({
@@ -214,6 +236,53 @@ describe('mobile account vault', () => {
expect(secureStorage.set).not.toHaveBeenCalled();
});
+ it('does not rewrite a vault containing a damaged resource child', async () => {
+ const original = JSON.stringify({
+ version: 1,
+ activeAccountKey: null,
+ resources: {
+ damaged: { realm: 'global', refreshToken: 'must-not-be-deleted' },
+ },
+ passports: {},
+ });
+ secureStorage.value = original;
+
+ await expect(
+ mutateMobileAccountVault((vault) => {
+ vault.activeAccountKey = null;
+ }),
+ ).rejects.toThrow('Saved resource credential could not be read safely');
+
+ expect(secureStorage.value).toBe(original);
+ expect(secureStorage.set).not.toHaveBeenCalled();
+ });
+
+ it('does not rewrite a Passport containing damaged membership metadata', async () => {
+ const original = JSON.stringify({
+ version: 1,
+ activeAccountKey: null,
+ resources: {},
+ passports: {
+ passport: {
+ realm: 'global',
+ passportId: 'passport-1',
+ accountRefreshToken: 'must-not-be-deleted',
+ memberships: [metadata, { membershipId: 'damaged' }],
+ },
+ },
+ });
+ secureStorage.value = original;
+
+ await expect(
+ mutateMobileAccountVault((vault) => {
+ vault.activeAccountKey = null;
+ }),
+ ).rejects.toThrow('Saved Passport membership could not be read safely');
+
+ expect(secureStorage.value).toBe(original);
+ expect(secureStorage.set).not.toHaveBeenCalled();
+ });
+
it('rolls the exact vault snapshot back before releasing a failed transaction', async () => {
const original = JSON.stringify({
version: 1,
diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.ts
index 5b58eb159f..707cd3ca5f 100644
--- a/apps/mobile/src/auth/mobileAccountVault.ts
+++ b/apps/mobile/src/auth/mobileAccountVault.ts
@@ -50,7 +50,10 @@ export function emptyMobileAccountVault(): MobileAccountVault {
return { version: 1, activeAccountKey: null, resources: {}, passports: {} };
}
-function parseMobileAccountVaultRecord(raw: string | null): MobileAccountVault {
+function parseMobileAccountVaultRecord(
+ raw: string | null,
+ options: { allowInvalidChildren?: boolean } = {},
+): MobileAccountVault {
if (raw === null) return emptyMobileAccountVault();
const value = JSON.parse(raw) as Partial<MobileAccountVault>;
if (
@@ -66,7 +69,10 @@ function parseMobileAccountVaultRecord(raw: string | null): MobileAccountVault {
}
const resources: Record<string, MobileStoredResourceSession> = {};
for (const [key, candidate] of Object.entries(value.resources)) {
- if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
+ if (options.allowInvalidChildren) continue;
+ throw new Error('Saved resource credential could not be read safely');
+ }
const item = candidate as Partial<MobileStoredResourceSession>;
if (
(item.realm !== 'cn' && item.realm !== 'global') ||
@@ -74,12 +80,18 @@ function parseMobileAccountVaultRecord(raw: string | null): MobileAccountVault {
!item.refreshToken ||
!isStoredAccountMetadata(item.metadata) ||
typeof item.lastUsedAt !== 'number'
- ) continue;
+ ) {
+ if (options.allowInvalidChildren) continue;
+ throw new Error('Saved resource credential could not be read safely');
+ }
resources[key] = item as MobileStoredResourceSession;
}
const passports: Record<string, MobileStoredPassportSession> = {};
for (const [key, candidate] of Object.entries(value.passports)) {
- if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
+ if (options.allowInvalidChildren) continue;
+ throw new Error('Saved Passport credential could not be read safely');
+ }
const item = candidate as Partial<MobileStoredPassportSession>;
if (
(item.realm !== 'cn' && item.realm !== 'global') ||
@@ -87,12 +99,22 @@ function parseMobileAccountVaultRecord(raw: string | null): MobileAccountVault {
typeof item.accountRefreshToken !== 'string' ||
!item.accountRefreshToken ||
!Array.isArray(item.memberships)
- ) continue;
+ ) {
+ if (options.allowInvalidChildren) continue;
+ throw new Error('Saved Passport credential could not be read safely');
+ }
+ const memberships = item.memberships.filter(isStoredAccountMetadata);
+ if (
+ !options.allowInvalidChildren &&
+ memberships.length !== item.memberships.length
+ ) {
+ throw new Error('Saved Passport membership could not be read safely');
+ }
passports[key] = {
realm: item.realm,
passportId: item.passportId,
accountRefreshToken: item.accountRefreshToken,
- memberships: item.memberships.filter(isStoredAccountMetadata),
+ memberships,
};
}
const active = typeof value.activeAccountKey === 'string' ? value.activeAccountKey : null;
@@ -109,7 +131,7 @@ function parseMobileAccountVaultRecord(raw: string | null): MobileAccountVault {
export function parseMobileAccountVault(raw: string | null): MobileAccountVault {
try {
- return parseMobileAccountVaultRecord(raw);
+ return parseMobileAccountVaultRecord(raw, { allowInvalidChildren: true });
} catch {
// Read-only projections may fall back, but mutations use the strict parser
// below so malformed encrypted content can never be overwritten.