GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — opencode-mobile/shared/storage/connection-profiles.ts at main · drpr/opencode-mobile

Expand file tree

/

connection-profiles.ts

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
184 lines (164 loc) · 9.28 KB
/

connection-profiles.ts

Copy path

File metadata and controls

184 lines (164 loc) · 9.28 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import AsyncStorage from '@react-native-async-storage/async-storage';
import { randomUUID } from 'expo-crypto';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
import { parseWorkspaces, WORKSPACES_STORAGE_KEY } from '@/shared/storage/workspace-storage';
import { getConnectionPassword } from '@/shared/storage/connection-password';
import { getProfileHeaders, getConnectionHeaders } from '@/shared/storage/connection-headers';
import { getConnectionCertificate, getProfileCertificate } from '@/shared/storage/connection-certificates';
import type { ConnectionCertificate } from '@/shared/contracts/connection-certificate';
import type { ConnectionHeaders } from '@/shared/contracts/connection-headers';
import { parseConnectionOidc, type ConnectionOidc } from '@/shared/contracts/connection-oidc';
import { getConnectCredentialError, parseConnectMetadata, type ConnectMetadata } from '@/shared/contracts/cloud-link';
import { getConnectTestSecret, setConnectTestSecret } from '@/shared/storage/cloud-link';
import { getConnectionScope, type ConnectionIdentity } from '@/shared/contracts/connection-scope';
import { CONNECTION_PROFILES_STORAGE_KEY, SETTINGS_STORAGE_KEY } from '@/shared/storage/keys';
import { isValidServerUrl } from '@/shared/contracts/server-url';
import { ConnectionProfile, toConnectionProfile, findProfileByConnectionScope } from '@/shared/contracts/connection-profiles';
// SecureStore keys may only contain alphanumerics, ".", "-" and "_".
function passwordKey(profileId: string) {
return `opencode-mobile.connection-profile-password.${profileId}`;
}
export function createProfileId() {
return randomUUID();
}
async function writeConnectionProfiles(profiles: ConnectionProfile[]) {
await AsyncStorage.setItem(CONNECTION_PROFILES_STORAGE_KEY, JSON.stringify(profiles));
}
let profileMutations: Promise<unknown> = Promise.resolve();
function serializeProfiles<T>(operation: () => Promise<T>) {
const result = profileMutations.then(operation);
profileMutations = result.catch(() => undefined);
return result;
}
export function loadConnectionProfiles(strict = false) {
return serializeProfiles(() => readConnectionProfiles(strict));
}
// Credential changes and metadata rollback must finish before another writer reads.
export function mutateConnectionProfiles<T>(operation: (profiles: ConnectionProfile[], save: typeof writeConnectionProfiles) => Promise<T>) {
return serializeProfiles(async () => operation(await readConnectionProfiles(true), writeSanitizedProfiles));
}
async function readConnectionProfiles(strict = false): Promise<ConnectionProfile[]> {
let raw: string | null;
try {
raw = await AsyncStorage.getItem(CONNECTION_PROFILES_STORAGE_KEY);
} catch (error) {
if (strict) throw error;
// A transient read failure leaves the stored value untouched.
return [];
}
if (!raw) return [];
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
await AsyncStorage.removeItem(CONNECTION_PROFILES_STORAGE_KEY).catch(() => undefined);
return [];
}
if (!Array.isArray(parsed)) {
await AsyncStorage.removeItem(CONNECTION_PROFILES_STORAGE_KEY).catch(() => undefined);
return [];
}
const profiles = parsed.map(toConnectionProfile).filter((profile): profile is ConnectionProfile => profile !== undefined);
// Rewrite when the stored value carried unexpected fields or dropped
// entries, so plain AsyncStorage never keeps anything the model excludes.
if (JSON.stringify(profiles) !== raw) {
await writeConnectionProfiles(profiles).catch(() => undefined);
}
return profiles;
}
async function writeSanitizedProfiles(profiles: ConnectionProfile[]) {
const sanitized = profiles
.map(toConnectionProfile)
.filter((profile): profile is ConnectionProfile => profile !== undefined);
await writeConnectionProfiles(sanitized);
}
/**
* Resolves credentials for a connection that may no longer be the active one.
* Connect metadata travels with the password so background clients also guard
* expiry on every fetch and reject credential-bearing redirects.
*
* Resolution order:
* 1. the saved profile whose scope matches (password in SecureStore),
* 2. the active connection when the record belongs to it, which also covers a
* connection that has not been saved as a profile yet.
*
* Returns `undefined` when no credential is available. Callers must keep the
* pending record instead of dropping it or borrowing another connection's
* password. Gateway headers travel with the same resolution.
*/
export async function resolveConnectionCredentials(identity: ConnectionIdentity): Promise<{ password: string; headers: ConnectionHeaders; certificate?: ConnectionCertificate; oidc?: ConnectionOidc; connect?: ConnectMetadata } | undefined> {
if (!identity.serverUrl.trim() || !isValidServerUrl(identity.serverUrl)) return undefined;
const connectionScope = getConnectionScope(identity);
// Background notifications and widget actions honor explicit disconnects too.
try {
const raw = await AsyncStorage.getItem(WORKSPACES_STORAGE_KEY);
if (raw && !parseWorkspaces(raw).connections.some((entry) => entry.enabled && getConnectionScope(entry.settings) === connectionScope)) return undefined;
} catch { return undefined; }
try {
const profiles = await loadConnectionProfiles();
const profile = findProfileByConnectionScope(profiles, connectionScope);
if (profile) {
if (getConnectCredentialError(profile.connect, 'present')) return undefined;
const [password, headers, certificate] = await Promise.all([getProfilePassword(profile.id), getProfileHeaders(profile.id), getProfileCertificate(profile.id)]);
return getConnectCredentialError(profile.connect, password) ? undefined : { password, headers, ...(certificate ? { certificate } : {}), ...(profile.oidc ? { oidc: profile.oidc } : {}), ...(profile.connect ? { connect: profile.connect } : {}) };
}
} catch {
// Fall through to the active connection.
}
try {
const raw = await AsyncStorage.getItem(SETTINGS_STORAGE_KEY);
if (!raw) return undefined;
const settings = JSON.parse(raw) as Record<string, unknown>;
if (typeof settings.serverUrl !== 'string') return undefined;
const activeScope = getConnectionScope({
serverUrl: settings.serverUrl,
username: typeof settings.username === 'string' ? settings.username : '',
});
if (activeScope !== connectionScope) return undefined;
const [password, headers, certificate] = await Promise.all([getConnectionPassword(), getConnectionHeaders(), getConnectionCertificate()]);
const connect = parseConnectMetadata(settings.connect);
if (settings.connect !== undefined && (!connect || getConnectCredentialError(connect, password))) return undefined;
const oidc = parseConnectionOidc(settings.oidc);
return { password: password || '', headers, ...(certificate ? { certificate } : {}), ...(oidc ? { oidc } : {}), ...(connect ? { connect } : {}) };
} catch {
return undefined;
}
}
export async function getProfilePassword(profileId: string) {
if (Platform.OS === 'web') return getConnectTestSecret(passwordKey(profileId));
return (await SecureStore.getItemAsync(passwordKey(profileId))) ?? '';
}
export async function saveProfilePassword(profileId: string, password: string, background = false) {
if (Platform.OS === 'web') { setConnectTestSecret(passwordKey(profileId), password); return; }
if (password) {
await SecureStore.setItemAsync(passwordKey(profileId), password, background ? { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY } : undefined);
return;
}
await SecureStore.deleteItemAsync(passwordKey(profileId));
}
export async function deleteProfilePassword(profileId: string) {
if (Platform.OS === 'web') { setConnectTestSecret(passwordKey(profileId), ''); return; }
await SecureStore.deleteItemAsync(passwordKey(profileId));
}
export async function saveConnectProfile(controlPlaneUrl: string, claim: import('@/shared/contracts/cloud-link').ConnectClaim) {
return mutateConnectionProfiles(async (profiles, save) => {
const previous = profiles.filter((profile) => profile.connect?.controlPlaneUrl === controlPlaneUrl && profile.connect.machineId === claim.machine_id);
if (previous[0] && new URL(previous[0].serverUrl).hostname !== new URL(claim.server_url).hostname) throw new Error('machine_hostname_mismatch: Access returned a different hostname.');
const profile: ConnectionProfile = {
id: previous[0]?.id ?? createProfileId(), name: previous[0]?.name ?? claim.machine_name, serverUrl: claim.server_url, username: claim.device_id,
...(previous[0]?.modelPreferences ? { modelPreferences: previous[0].modelPreferences } : {}),
connect: { controlPlaneUrl, machineId: claim.machine_id, machineName: claim.machine_name, deviceId: claim.device_id, expiresAt: claim.expires_at },
};
const oldPassword = previous[0] ? await getProfilePassword(profile.id) : '';
await saveProfilePassword(profile.id, claim.device_secret, true);
try {
await save([...profiles.filter((item) => !previous.includes(item)), profile]);
} catch (error) {
await saveProfilePassword(profile.id, oldPassword, true).catch(() => undefined);
throw error;
}
await Promise.all(previous.filter((item) => item.id !== profile.id).map((item) => deleteProfilePassword(item.id)));
return profile;
});
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.