livedesk 0.1.606 → 0.1.608

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -80,11 +80,12 @@ const RETIRED_CLIENT_MODEL_SINGLE_OPTIONS = new Set(['--ai', '--no-ai', '--fake-
80
80
  const RETIRED_CLIENT_MODEL_VALUE_OPTION = '--ai-model';
81
81
  let activeAgentProcess = null;
82
82
  let roleRestartRequest = null;
83
- let agentRestartRequest = null;
84
- let linuxVideoAccelerationStatus = null;
85
- let discoveryWakeController = new AbortController();
86
- let networkChangeMonitor = null;
87
- const sessionRefreshesInFlight = new WeakMap();
83
+ let agentRestartRequest = null;
84
+ let linuxVideoAccelerationStatus = null;
85
+ let discoveryWakeController = new AbortController();
86
+ let networkChangeMonitor = null;
87
+ let desktopMainAuthSession = null;
88
+ const sessionRefreshesInFlight = new WeakMap();
88
89
  const disposeAgentTerminationHandlers = installAgentTerminationHandlers({
89
90
  getAgentProcess: () => activeAgentProcess
90
91
  });
@@ -1097,8 +1098,11 @@ export function clearCachedHubTarget() {
1097
1098
  }
1098
1099
  }
1099
1100
 
1100
- function readSavedSessionFromFile() {
1101
- for (const path of [preferredClientAuthPath(), CLIENT_AUTH_PATH, UNIFIED_CLIENT_AUTH_PATH]) {
1101
+ function readSavedSessionFromFile() {
1102
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) {
1103
+ return desktopMainAuthSession;
1104
+ }
1105
+ for (const path of [preferredClientAuthPath(), CLIENT_AUTH_PATH, UNIFIED_CLIENT_AUTH_PATH]) {
1102
1106
  try {
1103
1107
  const state = JSON.parse(readFileSync(path, 'utf8'));
1104
1108
  const raw = state?.[CLIENT_AUTH_STORAGE_KEY];
@@ -1113,20 +1117,43 @@ function readSavedSessionFromFile() {
1113
1117
  return null;
1114
1118
  }
1115
1119
 
1116
- function writeSavedSessionToFile(session) {
1117
- const normalized = normalizeRuntimeAuthSession(session, { requireRefreshToken: true });
1118
- if (!normalized.ok) {
1119
- return false;
1120
- }
1121
- const storage = createFileStorage(preferredClientAuthPath());
1120
+ function writeSavedSessionToFile(session) {
1121
+ const normalized = normalizeRuntimeAuthSession(session, { requireRefreshToken: true });
1122
+ if (!normalized.ok) {
1123
+ return false;
1124
+ }
1125
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) {
1126
+ return Boolean(desktopMainAuthSession?.access_token);
1127
+ }
1128
+ const storage = createFileStorage(preferredClientAuthPath());
1122
1129
  storage.setItem(CLIENT_AUTH_STORAGE_KEY, JSON.stringify({ ...session, ...normalized.session }));
1123
1130
  return true;
1124
1131
  }
1125
1132
 
1126
- function clearSavedSession() {
1127
- rmSync(CLIENT_AUTH_PATH, { force: true });
1128
- rmSync(UNIFIED_CLIENT_AUTH_PATH, { force: true });
1129
- }
1133
+ function clearSavedSession() {
1134
+ desktopMainAuthSession = null;
1135
+ rmSync(CLIENT_AUTH_PATH, { force: true });
1136
+ rmSync(UNIFIED_CLIENT_AUTH_PATH, { force: true });
1137
+ }
1138
+
1139
+ export function acceptDesktopMainAuthSession(session) {
1140
+ if (!isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) return null;
1141
+ const normalized = normalizeRuntimeAuthSession(session, { requireRefreshToken: true });
1142
+ if (!normalized.ok) return null;
1143
+ desktopMainAuthSession = {
1144
+ ...session,
1145
+ ...normalized.session,
1146
+ user: {
1147
+ ...(session?.user && typeof session.user === 'object' ? session.user : {}),
1148
+ ...normalized.session.user
1149
+ }
1150
+ };
1151
+ return desktopMainAuthSession;
1152
+ }
1153
+
1154
+ export function clearDesktopMainAuthSession() {
1155
+ desktopMainAuthSession = null;
1156
+ }
1130
1157
 
1131
1158
  export async function fetchSupabaseWithDeadline(
1132
1159
  input,
@@ -1167,22 +1194,28 @@ export async function fetchSupabaseWithDeadline(
1167
1194
  }
1168
1195
  }
1169
1196
 
1170
- async function createSupabaseClient() {
1171
- const { createClient } = await import('@supabase/supabase-js');
1172
- return createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY, {
1173
- global: {
1174
- fetch: fetchSupabaseWithDeadline
1175
- },
1176
- auth: {
1177
- autoRefreshToken: false,
1178
- persistSession: true,
1179
- detectSessionInUrl: false,
1180
- flowType: 'pkce',
1181
- storageKey: CLIENT_AUTH_STORAGE_KEY,
1182
- storage: createFileStorage(preferredClientAuthPath())
1183
- }
1184
- });
1185
- }
1197
+ export async function createSupabaseClient() {
1198
+ const { createClient } = await import('@supabase/supabase-js');
1199
+ const desktopMainOwnsAuth = isTruthy(process.env.LIVEDESK_DESKTOP_HOST);
1200
+ return createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY, {
1201
+ global: {
1202
+ fetch: fetchSupabaseWithDeadline
1203
+ },
1204
+ ...(desktopMainOwnsAuth ? {
1205
+ // Electron Main rotates and encrypts the refresh token. The local
1206
+ // runtime receives only the current in-memory session and asks this
1207
+ // client to attach its access token to database requests.
1208
+ accessToken: async () => desktopMainAuthSession?.access_token || null
1209
+ } : { auth: {
1210
+ autoRefreshToken: false,
1211
+ persistSession: true,
1212
+ detectSessionInUrl: false,
1213
+ flowType: 'pkce',
1214
+ storageKey: CLIENT_AUTH_STORAGE_KEY,
1215
+ storage: createFileStorage(preferredClientAuthPath())
1216
+ } })
1217
+ });
1218
+ }
1186
1219
 
1187
1220
  function getNestedErrorCode(error) {
1188
1221
  let cursor = error;
@@ -1313,8 +1346,12 @@ async function recoverRotatedSession(supabase, previousSession) {
1313
1346
  return null;
1314
1347
  }
1315
1348
 
1316
- async function refreshSessionIfNeededCore(supabase) {
1317
- let existingSession = null;
1349
+ async function refreshSessionIfNeededCore(supabase) {
1350
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) {
1351
+ const normalized = normalizeRuntimeAuthSession(desktopMainAuthSession, { requireRefreshToken: true });
1352
+ return normalized.ok ? desktopMainAuthSession : null;
1353
+ }
1354
+ let existingSession = null;
1318
1355
  try {
1319
1356
  const { data: existing } = await supabase.auth.getSession();
1320
1357
  existingSession = existing?.session || null;
@@ -1382,12 +1419,17 @@ function openBrowser(url) {
1382
1419
  spawn(command, [launchUrl.toString()], { detached: true, stdio: 'ignore' }).unref();
1383
1420
  }
1384
1421
 
1385
- async function activateSupabaseSession(supabase, session) {
1386
- const normalized = normalizeRuntimeAuthSession(session, { requireRefreshToken: true });
1387
- if (!normalized.ok) {
1388
- throw new Error(normalized.error);
1389
- }
1390
- const { data: current } = await supabase.auth.getSession();
1422
+ async function activateSupabaseSession(supabase, session) {
1423
+ const normalized = normalizeRuntimeAuthSession(session, { requireRefreshToken: true });
1424
+ if (!normalized.ok) {
1425
+ throw new Error(normalized.error);
1426
+ }
1427
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) {
1428
+ const activeSession = acceptDesktopMainAuthSession(session);
1429
+ if (!activeSession) throw new Error('desktop-main-session-required');
1430
+ return activeSession;
1431
+ }
1432
+ const { data: current } = await supabase.auth.getSession();
1391
1433
  if (current?.session?.access_token === normalized.session.access_token) {
1392
1434
  const activeSession = current.session;
1393
1435
  if (!writeSavedSessionToFile(activeSession)) {
@@ -3173,7 +3215,7 @@ async function startConnectionChoiceServer(supabase, options = {}) {
3173
3215
 
3174
3216
  if (requestUrl.pathname === '/logout') {
3175
3217
  try {
3176
- await supabase.auth.signOut();
3218
+ await supabase.auth.signOut({ scope: 'local' });
3177
3219
  } catch {
3178
3220
  }
3179
3221
  clearSavedSession();
@@ -3410,10 +3452,13 @@ async function chooseClientConnection(supabase, options = {}) {
3410
3452
  roleVersion: process.env.LIVEDESK_ROLE_VERSION,
3411
3453
  savedSession: options.savedSession,
3412
3454
  loadSavedSession: options.loadSavedSession,
3413
- initialChoice: options.initialChoice,
3414
- initialChoiceMessage: options.initialChoiceMessage,
3415
- beginGoogleSignIn: async redirectTo => {
3416
- const activeSupabase = await getSupabase();
3455
+ initialChoice: options.initialChoice,
3456
+ initialChoiceMessage: options.initialChoiceMessage,
3457
+ onAuthSessionAccepted: acceptDesktopMainAuthSession,
3458
+ onAuthSessionCleared: clearDesktopMainAuthSession,
3459
+ beginGoogleSignIn: async redirectTo => {
3460
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) throw new Error('desktop-main-auth-required');
3461
+ const activeSupabase = await getSupabase();
3417
3462
  if (!activeSupabase?.auth) throw new Error('supabase-session-required');
3418
3463
  const { data, error } = await activeSupabase.auth.signInWithOAuth({
3419
3464
  provider: 'google',
@@ -3426,9 +3471,10 @@ async function chooseClientConnection(supabase, options = {}) {
3426
3471
  if (error) throw error;
3427
3472
  if (!data?.url) throw new Error('google-authorization-url-missing');
3428
3473
  return { url: data.url };
3429
- },
3430
- exchangeGoogleCode: async code => {
3431
- const activeSupabase = await getSupabase();
3474
+ },
3475
+ exchangeGoogleCode: async code => {
3476
+ if (isTruthy(process.env.LIVEDESK_DESKTOP_HOST)) throw new Error('desktop-main-auth-required');
3477
+ const activeSupabase = await getSupabase();
3432
3478
  if (!activeSupabase?.auth) throw new Error('supabase-session-required');
3433
3479
  const { data, error } = await activeSupabase.auth.exchangeCodeForSession(code);
3434
3480
  if (error) throw error;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livedesk/client",
3
- "version": "0.1.261",
3
+ "version": "0.1.262",
4
4
  "description": "VuvoDesk local remote client",
5
5
  "type": "module",
6
6
  "bin": {
@@ -979,9 +979,13 @@ function writeSavedSession(session) {
979
979
  return true;
980
980
  }
981
981
 
982
- function clearSavedSession() {
983
- writePrivateJsonAtomic(CLIENT_AUTH_PATH, {});
984
- }
982
+ function clearSavedSession() {
983
+ if (process.env.LIVEDESK_DESKTOP_HOST === '1') {
984
+ rmSync(CLIENT_AUTH_PATH, { force: true });
985
+ return;
986
+ }
987
+ writePrivateJsonAtomic(CLIENT_AUTH_PATH, {});
988
+ }
985
989
 
986
990
  function readBody(req) {
987
991
  return new Promise((resolveBody, reject) => {
@@ -1316,8 +1320,11 @@ export function createClientRuntimeServer(options = {}) {
1316
1320
  runtime.emit('client.auth.session', { result: state.auth.lastResult, error: message });
1317
1321
  };
1318
1322
 
1319
- const complete = (choice, message = 'Client credentials accepted. Finding the Hub.') => {
1320
- lastChoice = choice || lastChoice;
1323
+ const complete = (choice, message = 'Client credentials accepted. Finding the Hub.') => {
1324
+ if (choice?.session?.access_token) {
1325
+ options.onAuthSessionAccepted?.(choice.session);
1326
+ }
1327
+ lastChoice = choice || lastChoice;
1321
1328
  if (completed) {
1322
1329
  if (choice?.session?.access_token) {
1323
1330
  const accountProfile = readClientAccountProfile(choice.session);
@@ -1634,9 +1641,10 @@ export function createClientRuntimeServer(options = {}) {
1634
1641
  respondJson(200, { ok: true, authenticated: true, persisted: true, role: 'client' });
1635
1642
  return;
1636
1643
  }
1637
- if (pathname === '/api/auth/session' && req.method === 'DELETE') {
1638
- clearSavedSession();
1639
- loggedOut = true;
1644
+ if (pathname === '/api/auth/session' && req.method === 'DELETE') {
1645
+ clearSavedSession();
1646
+ options.onAuthSessionCleared?.();
1647
+ loggedOut = true;
1640
1648
  completed = false;
1641
1649
  lastChoice = null;
1642
1650
  state.manager = '';
@@ -0,0 +1,183 @@
1
+ export const DEFAULT_INSTALLER_QUIT_CONFIRMATION_MS = 1_000;
2
+
3
+ export const InstallerQuitDecision = Object.freeze({
4
+ NORMAL: 'normal-quit',
5
+ HOLD: 'hold-update-quit',
6
+ BLOCK: 'block-stale-update-quit',
7
+ ALLOW: 'allow-update-quit'
8
+ });
9
+
10
+ function normalizeDelay(value) {
11
+ const milliseconds = Number(value);
12
+ return Number.isFinite(milliseconds) && milliseconds >= 0
13
+ ? Math.round(milliseconds)
14
+ : DEFAULT_INSTALLER_QUIT_CONFIRMATION_MS;
15
+ }
16
+
17
+ /**
18
+ * electron-updater reports that it intends to quit before the Windows NSIS
19
+ * spawn promise has necessarily rejected. This gate holds the first quit for
20
+ * a short error window without importing Electron, so its race is executable
21
+ * in a plain Node regression test.
22
+ */
23
+ export function createInstallerQuitGate({
24
+ requestQuit,
25
+ confirmationDelayMs = DEFAULT_INSTALLER_QUIT_CONFIRMATION_MS,
26
+ setTimer = setTimeout,
27
+ clearTimer = clearTimeout
28
+ } = {}) {
29
+ if (typeof requestQuit !== 'function') {
30
+ throw new TypeError('installer-quit-gate-request-quit-required');
31
+ }
32
+
33
+ const confirmationDelay = normalizeDelay(confirmationDelayMs);
34
+ let generation = 0;
35
+ let attempt = null;
36
+
37
+ const clearConfirmationTimer = ownedAttempt => {
38
+ if (!ownedAttempt || ownedAttempt.confirmationTimer === null) return;
39
+ clearTimer(ownedAttempt.confirmationTimer);
40
+ ownedAttempt.confirmationTimer = null;
41
+ };
42
+
43
+ const snapshot = () => {
44
+ if (!attempt) {
45
+ return {
46
+ generation,
47
+ state: 'idle',
48
+ intentObserved: false,
49
+ failed: false,
50
+ firstQuitHeld: false,
51
+ quitReissueRequested: false,
52
+ staleQuitBlocked: false,
53
+ error: ''
54
+ };
55
+ }
56
+ return {
57
+ generation: attempt.generation,
58
+ state: attempt.state,
59
+ intentObserved: attempt.intentObserved,
60
+ failed: attempt.failed,
61
+ firstQuitHeld: attempt.firstQuitHeld,
62
+ quitReissueRequested: attempt.quitReissueRequested,
63
+ staleQuitBlocked: attempt.staleQuitBlocked,
64
+ error: attempt.error
65
+ };
66
+ };
67
+
68
+ const beginInstall = () => {
69
+ clearConfirmationTimer(attempt);
70
+ attempt = {
71
+ generation: ++generation,
72
+ state: 'preparing',
73
+ intentObserved: false,
74
+ failed: false,
75
+ firstQuitHeld: false,
76
+ quitReissueRequested: false,
77
+ staleQuitBlocked: false,
78
+ error: '',
79
+ confirmationTimer: null
80
+ };
81
+ return attempt.generation;
82
+ };
83
+
84
+ const noteBeforeQuitForUpdate = () => {
85
+ if (!attempt) return false;
86
+ attempt.intentObserved = true;
87
+ if (attempt.failed) {
88
+ attempt.state = 'failed-update-quit-intent';
89
+ } else if (!attempt.firstQuitHeld) {
90
+ attempt.state = 'update-quit-intent';
91
+ }
92
+ return true;
93
+ };
94
+
95
+ const failInstall = error => {
96
+ if (!attempt) return false;
97
+ attempt.failed = true;
98
+ attempt.error = String(error?.message || error || 'desktop-update-installer-launch-failed');
99
+ clearConfirmationTimer(attempt);
100
+
101
+ if (attempt.firstQuitHeld && !attempt.quitReissueRequested) {
102
+ // The updater-owned quit was already intercepted. There is no later quit
103
+ // to consume, so a user's subsequent normal quit must remain available.
104
+ attempt.intentObserved = false;
105
+ attempt.state = 'failed-after-held-quit';
106
+ } else if (attempt.intentObserved) {
107
+ // The updater has announced a quit, or our delayed reissue is in flight.
108
+ // Consume that one stale quit before returning to normal quit handling.
109
+ attempt.state = 'failed-update-quit-pending';
110
+ } else {
111
+ // electron-updater can dispatch its spawn error before its queued
112
+ // before-quit-for-update event. Retain the failed attempt for that event.
113
+ attempt.state = 'failed-awaiting-update-quit-intent';
114
+ }
115
+ return true;
116
+ };
117
+
118
+ const scheduleConfirmedQuit = ownedAttempt => {
119
+ if (ownedAttempt.confirmationTimer !== null) return;
120
+ const fire = () => {
121
+ ownedAttempt.confirmationTimer = null;
122
+ if (
123
+ attempt !== ownedAttempt
124
+ || ownedAttempt.failed
125
+ || !ownedAttempt.intentObserved
126
+ || ownedAttempt.quitReissueRequested
127
+ ) {
128
+ return;
129
+ }
130
+ ownedAttempt.quitReissueRequested = true;
131
+ ownedAttempt.state = 'reissuing-update-quit';
132
+ try {
133
+ requestQuit();
134
+ } catch (error) {
135
+ ownedAttempt.failed = true;
136
+ ownedAttempt.intentObserved = false;
137
+ ownedAttempt.error = String(error?.message || error);
138
+ ownedAttempt.state = 'quit-reissue-failed';
139
+ }
140
+ };
141
+ ownedAttempt.confirmationTimer = setTimer(fire, confirmationDelay);
142
+ ownedAttempt.confirmationTimer?.unref?.();
143
+ };
144
+
145
+ const handleBeforeQuit = () => {
146
+ const ownedAttempt = attempt;
147
+ if (!ownedAttempt?.intentObserved) return InstallerQuitDecision.NORMAL;
148
+
149
+ if (ownedAttempt.failed) {
150
+ ownedAttempt.intentObserved = false;
151
+ ownedAttempt.staleQuitBlocked = true;
152
+ ownedAttempt.state = 'failed-update-quit-blocked';
153
+ return InstallerQuitDecision.BLOCK;
154
+ }
155
+
156
+ if (ownedAttempt.quitReissueRequested) {
157
+ ownedAttempt.intentObserved = false;
158
+ ownedAttempt.state = 'update-quit-allowed';
159
+ return InstallerQuitDecision.ALLOW;
160
+ }
161
+
162
+ if (!ownedAttempt.firstQuitHeld) {
163
+ ownedAttempt.firstQuitHeld = true;
164
+ ownedAttempt.state = 'holding-update-quit';
165
+ scheduleConfirmedQuit(ownedAttempt);
166
+ }
167
+ return InstallerQuitDecision.HOLD;
168
+ };
169
+
170
+ const dispose = () => {
171
+ clearConfirmationTimer(attempt);
172
+ attempt = null;
173
+ };
174
+
175
+ return {
176
+ beginInstall,
177
+ noteBeforeQuitForUpdate,
178
+ failInstall,
179
+ handleBeforeQuit,
180
+ getState: snapshot,
181
+ dispose
182
+ };
183
+ }