@unisim/sdk 0.231.2 → 0.233.0
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.
- package/README.md +188 -2
- package/dist/PreferencesDialog.d.ts.map +1 -1
- package/dist/PreferencesDialog.js +12 -2
- package/dist/PreferencesDialog.js.map +1 -1
- package/dist/SyncedSettingsSync.d.ts +2 -0
- package/dist/SyncedSettingsSync.d.ts.map +1 -0
- package/dist/SyncedSettingsSync.js +34 -0
- package/dist/SyncedSettingsSync.js.map +1 -0
- package/dist/TuneAccountSection.d.ts +8 -1
- package/dist/TuneAccountSection.d.ts.map +1 -1
- package/dist/TuneAccountSection.js +2 -2
- package/dist/TuneAccountSection.js.map +1 -1
- package/dist/TuneSync.d.ts.map +1 -1
- package/dist/TuneSync.js +49 -158
- package/dist/TuneSync.js.map +1 -1
- package/dist/defaultView.d.ts +4 -2
- package/dist/defaultView.d.ts.map +1 -1
- package/dist/defaultView.js +8 -2
- package/dist/defaultView.js.map +1 -1
- package/dist/desktop.d.ts +33 -0
- package/dist/desktop.d.ts.map +1 -1
- package/dist/desktop.js.map +1 -1
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +24 -0
- package/dist/i18n.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +15 -1
- package/dist/provider.js.map +1 -1
- package/dist/rowSync.d.ts +37 -0
- package/dist/rowSync.d.ts.map +1 -0
- package/dist/rowSync.js +172 -0
- package/dist/rowSync.js.map +1 -0
- package/dist/suiteDesktopSession.d.ts +37 -0
- package/dist/suiteDesktopSession.d.ts.map +1 -0
- package/dist/suiteDesktopSession.js +143 -0
- package/dist/suiteDesktopSession.js.map +1 -0
- package/dist/syncedSettings.d.ts +100 -0
- package/dist/syncedSettings.d.ts.map +1 -0
- package/dist/syncedSettings.js +272 -0
- package/dist/syncedSettings.js.map +1 -0
- package/electron/handoff.cjs +11 -1
- package/electron/signin.cjs +51 -17
- package/electron/suite-session.cjs +561 -0
- package/package.json +3 -1
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
// Suite session — one sign-in for every UNI·SIM desktop app on a computer.
|
|
2
|
+
//
|
|
3
|
+
// James, 2026-11-20: signing in to one suite desktop app should greet you in
|
|
4
|
+
// the others, with no click. Each app has its own session (its own refresh
|
|
5
|
+
// token, in its own storage), and that must stay so: a refresh token is
|
|
6
|
+
// single-use under rotation, so two apps holding one would each spend it, and
|
|
7
|
+
// GoTrue would treat the second spend as theft and sign BOTH out. So what the
|
|
8
|
+
// apps share is not a session. It is a GRANT:
|
|
9
|
+
//
|
|
10
|
+
// • The browser sign-in (signin.cjs) also asks `desktop-sign-in` for a grant:
|
|
11
|
+
// an id and a random 32-byte secret, made only after the hub has checked
|
|
12
|
+
// the person's company rules (migration 0332, the server half).
|
|
13
|
+
// • The grant is kept in the operating system's protected store for this OS
|
|
14
|
+
// user (below), where every suite app can reach it.
|
|
15
|
+
// • A suite app that starts with nobody signed in, or is open when another
|
|
16
|
+
// signs in, presents it (`grant_redeem`) and gets a single-use magic-link
|
|
17
|
+
// token for a NEW session of its own, redeemed in its renderer exactly as a
|
|
18
|
+
// browser sign-in is. No window, no click; if anything fails it simply
|
|
19
|
+
// stays signed out, and "Sign in with your browser" is still there.
|
|
20
|
+
// • Every use ROTATES the secret. A retired secret presented again tells the
|
|
21
|
+
// server two copies exist, and it ends the grant for everybody.
|
|
22
|
+
// • "Sign out" signs out of THIS app only, and this app then leaves that
|
|
23
|
+
// grant alone (`declined`). "Sign out of every UNI·SIM app on this
|
|
24
|
+
// computer" ends the grant on the server, deletes it here, and tells the
|
|
25
|
+
// other apps (the events file), which each sign their own session out.
|
|
26
|
+
//
|
|
27
|
+
// ── Where the grant lives, per OS (Electron's safeStorage CANNOT be shared) ──
|
|
28
|
+
// safeStorage keeps its key per APP: on macOS a Keychain item "<App> Safe
|
|
29
|
+
// Storage" whose access list names that app alone; on Windows an AES key in
|
|
30
|
+
// the app's own `Local State`, wrapped with DPAPI; on Linux a libsecret item
|
|
31
|
+
// per app. Text one suite app encrypts with it, another cannot read. So:
|
|
32
|
+
//
|
|
33
|
+
// macOS the login Keychain, through /usr/bin/security: a generic password
|
|
34
|
+
// (service `uk.co.unisim.suite.desktop-sign-in`). Encrypted at rest,
|
|
35
|
+
// locked with the login keychain, never in a plain file. The item
|
|
36
|
+
// trusts the `security` tool, so any process running as this OS
|
|
37
|
+
// user can read it without a prompt — which is also true today of
|
|
38
|
+
// each app's own session in its Local Storage. A Keychain ACCESS
|
|
39
|
+
// GROUP (team ZH9C5TS86A) would limit it to the suite's signed apps,
|
|
40
|
+
// but needs a native module plus a Developer ID provisioning profile
|
|
41
|
+
// per app; see the README's "Hardening later".
|
|
42
|
+
// Windows DPAPI (CurrentUser) through Windows PowerShell, so the file in
|
|
43
|
+
// %APPDATA%\UNISIM is ciphertext only this Windows user can open.
|
|
44
|
+
// DPAPI is per-user, not per-app, so every suite app can.
|
|
45
|
+
// Linux libsecret through `secret-tool` (libsecret-tools). Without it, or
|
|
46
|
+
// without a running keyring, there is no shared sign-in on that
|
|
47
|
+
// computer and nothing is written.
|
|
48
|
+
//
|
|
49
|
+
// The secret goes to those tools on stdin, never on a command line, where
|
|
50
|
+
// other processes could read it.
|
|
51
|
+
//
|
|
52
|
+
// The shared folder (app.getPath('appData')/UNISIM) holds only plain, secret-
|
|
53
|
+
// free files: the lock, and `desktop-sign-in.events.json` (when a sign-in or
|
|
54
|
+
// a sign-out-everywhere last happened). Each app's own `declined` /
|
|
55
|
+
// `epochSeen` lives in its own userData.
|
|
56
|
+
//
|
|
57
|
+
// This module has no top-level Electron import, so tests can drive it with an
|
|
58
|
+
// in-memory store and a fake fetch (tests/suite-session.mjs).
|
|
59
|
+
|
|
60
|
+
const crypto = require('node:crypto')
|
|
61
|
+
const fs = require('node:fs')
|
|
62
|
+
const fsp = require('node:fs/promises')
|
|
63
|
+
const path = require('node:path')
|
|
64
|
+
const { execFile, spawn } = require('node:child_process')
|
|
65
|
+
|
|
66
|
+
const KEYCHAIN_SERVICE = 'uk.co.unisim.suite.desktop-sign-in'
|
|
67
|
+
const STORE_ACCOUNT = 'grant'
|
|
68
|
+
const STORE_LABEL = 'UNISIM desktop sign-in'
|
|
69
|
+
const NAMESPACE = /^[a-z0-9-]{1,32}$/
|
|
70
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
71
|
+
const SECRET = /^[A-Za-z0-9_-]{43}$/
|
|
72
|
+
/** Codes from `grant_redeem` that mean the grant is finished for everyone. */
|
|
73
|
+
const GRANT_DEAD = new Set(['invalid_grant', 'grant_reused', 'grant_expired', 'not_signed_in', 'two_step_needed', 'sso_needed'])
|
|
74
|
+
const LOCK_STALE_MS = 30_000
|
|
75
|
+
const LOCK_WAIT_MS = 15_000
|
|
76
|
+
const TOOL_TIMEOUT_MS = 10_000
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Only an https Supabase project (or a suite host) may be told a code, a
|
|
80
|
+
* verifier or a grant. The renderer supplies the URL from its own config, and
|
|
81
|
+
* a renderer that has been talked into pointing it elsewhere must not get to
|
|
82
|
+
* hand any of them to a stranger.
|
|
83
|
+
*/
|
|
84
|
+
function isPlatformUrl(url) {
|
|
85
|
+
try {
|
|
86
|
+
const u = new URL(url)
|
|
87
|
+
if (u.protocol !== 'https:') return false
|
|
88
|
+
return u.hostname.endsWith('.supabase.co') || u.hostname === 'unisim.co.uk' || u.hostname.endsWith('.unisim.co.uk')
|
|
89
|
+
} catch {
|
|
90
|
+
return false
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Tests set UNISIM_SUITE_SIGNIN_NAMESPACE so they never touch a real grant. */
|
|
95
|
+
function namespace() {
|
|
96
|
+
const ns = String(process.env.UNISIM_SUITE_SIGNIN_NAMESPACE || '')
|
|
97
|
+
return NAMESPACE.test(ns) ? ns : ''
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ── The protected stores ────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
function run(cmd, args, { input, timeout = TOOL_TIMEOUT_MS } = {}) {
|
|
103
|
+
return new Promise((resolve) => {
|
|
104
|
+
let child
|
|
105
|
+
try {
|
|
106
|
+
child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
|
|
107
|
+
} catch (err) {
|
|
108
|
+
resolve({ code: -1, stdout: '', stderr: String(err), missing: err && err.code === 'ENOENT' })
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
let stdout = ''
|
|
112
|
+
let stderr = ''
|
|
113
|
+
let done = false
|
|
114
|
+
const timer = setTimeout(() => { try { child.kill() } catch { /* gone */ } finish({ code: -1, timedOut: true }) }, timeout)
|
|
115
|
+
function finish(extra) {
|
|
116
|
+
if (done) return
|
|
117
|
+
done = true
|
|
118
|
+
clearTimeout(timer)
|
|
119
|
+
resolve({ stdout, stderr, ...extra })
|
|
120
|
+
}
|
|
121
|
+
child.stdout.on('data', (d) => { stdout += d })
|
|
122
|
+
child.stderr.on('data', (d) => { stderr += d })
|
|
123
|
+
child.on('error', (err) => finish({ code: -1, missing: err && err.code === 'ENOENT' }))
|
|
124
|
+
child.on('close', (code) => finish({ code }))
|
|
125
|
+
child.stdin.on('error', () => { /* the tool exited early; `close` reports it */ })
|
|
126
|
+
child.stdin.end(input == null ? '' : input)
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** macOS: the login Keychain through /usr/bin/security. */
|
|
131
|
+
function keychainStore(service) {
|
|
132
|
+
const base = ['-s', service, '-a', STORE_ACCOUNT]
|
|
133
|
+
async function read() {
|
|
134
|
+
const r = await run('/usr/bin/security', ['find-generic-password', ...base, '-w'])
|
|
135
|
+
if (r.code === 44) return null // errSecItemNotFound
|
|
136
|
+
if (r.code !== 0) throw new Error(`keychain read failed (${r.code})`)
|
|
137
|
+
const out = r.stdout.trim()
|
|
138
|
+
// `-w` prints bytes that are not plain text as hex.
|
|
139
|
+
if (/^[0-9a-f]+$/i.test(out) && out.length % 2 === 0 && !out.startsWith('{')) {
|
|
140
|
+
const text = Buffer.from(out, 'hex').toString('utf8')
|
|
141
|
+
if (text.startsWith('{')) return text
|
|
142
|
+
}
|
|
143
|
+
return out || null
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
kind: 'keychain',
|
|
147
|
+
read,
|
|
148
|
+
async write(value) {
|
|
149
|
+
// `security -i` reads its command from stdin, so the secret is on no
|
|
150
|
+
// command line; -X takes it as hex, so it needs no quoting.
|
|
151
|
+
const hex = Buffer.from(value, 'utf8').toString('hex')
|
|
152
|
+
const r = await run('/usr/bin/security', ['-i'], {
|
|
153
|
+
input: `add-generic-password -U -s ${service} -a ${STORE_ACCOUNT} -l "${STORE_LABEL}" -X ${hex}\n`,
|
|
154
|
+
})
|
|
155
|
+
if (r.code !== 0 || (await read()) !== value) throw new Error('keychain write failed')
|
|
156
|
+
},
|
|
157
|
+
async clear() {
|
|
158
|
+
const r = await run('/usr/bin/security', ['delete-generic-password', ...base])
|
|
159
|
+
if (r.code !== 0 && r.code !== 44) throw new Error(`keychain delete failed (${r.code})`)
|
|
160
|
+
},
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Windows: a file in the suite folder, encrypted with DPAPI for this user. */
|
|
165
|
+
function dpapiStore(file) {
|
|
166
|
+
const exe = process.env.SystemRoot
|
|
167
|
+
? path.join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
168
|
+
: 'powershell.exe'
|
|
169
|
+
const entropy = KEYCHAIN_SERVICE
|
|
170
|
+
function script(protect) {
|
|
171
|
+
return [
|
|
172
|
+
"$ErrorActionPreference='Stop'",
|
|
173
|
+
'Add-Type -AssemblyName System.Security',
|
|
174
|
+
`$e=[Text.Encoding]::UTF8.GetBytes('${entropy}')`,
|
|
175
|
+
'$i=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())',
|
|
176
|
+
`$o=[Security.Cryptography.ProtectedData]::${protect ? 'Protect' : 'Unprotect'}($i,$e,[Security.Cryptography.DataProtectionScope]::CurrentUser)`,
|
|
177
|
+
'[Console]::Out.Write([Convert]::ToBase64String($o))',
|
|
178
|
+
].join(';')
|
|
179
|
+
}
|
|
180
|
+
async function ps(protect, b64) {
|
|
181
|
+
const encoded = Buffer.from(script(protect), 'utf16le').toString('base64')
|
|
182
|
+
const r = await run(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], { input: b64 })
|
|
183
|
+
if (r.code !== 0) throw new Error(`dpapi ${protect ? 'protect' : 'unprotect'} failed (${r.code})`)
|
|
184
|
+
return r.stdout.trim()
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
kind: 'dpapi',
|
|
188
|
+
async read() {
|
|
189
|
+
let sealed
|
|
190
|
+
try { sealed = (await fsp.readFile(file, 'utf8')).trim() } catch (err) {
|
|
191
|
+
if (err && err.code === 'ENOENT') return null
|
|
192
|
+
throw err
|
|
193
|
+
}
|
|
194
|
+
if (!sealed) return null
|
|
195
|
+
return Buffer.from(await ps(false, sealed), 'base64').toString('utf8')
|
|
196
|
+
},
|
|
197
|
+
async write(value) {
|
|
198
|
+
const sealed = await ps(true, Buffer.from(value, 'utf8').toString('base64'))
|
|
199
|
+
await writeAtomic(file, sealed)
|
|
200
|
+
},
|
|
201
|
+
async clear() {
|
|
202
|
+
await fsp.rm(file, { force: true })
|
|
203
|
+
},
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Linux: libsecret through secret-tool. */
|
|
208
|
+
function secretToolStore(service) {
|
|
209
|
+
const attrs = ['service', service, 'account', STORE_ACCOUNT]
|
|
210
|
+
return {
|
|
211
|
+
kind: 'libsecret',
|
|
212
|
+
async read() {
|
|
213
|
+
const r = await run('secret-tool', ['lookup', ...attrs])
|
|
214
|
+
if (r.missing) throw new Error('secret-tool is not installed')
|
|
215
|
+
if (r.code === 1 && !r.stdout) return null
|
|
216
|
+
if (r.code !== 0) throw new Error(`secret-tool lookup failed (${r.code})`)
|
|
217
|
+
return r.stdout.trim() || null
|
|
218
|
+
},
|
|
219
|
+
async write(value) {
|
|
220
|
+
const r = await run('secret-tool', ['store', `--label=${STORE_LABEL}`, ...attrs], { input: value })
|
|
221
|
+
if (r.missing) throw new Error('secret-tool is not installed')
|
|
222
|
+
if (r.code !== 0) throw new Error(`secret-tool store failed (${r.code})`)
|
|
223
|
+
},
|
|
224
|
+
async clear() {
|
|
225
|
+
const r = await run('secret-tool', ['clear', ...attrs])
|
|
226
|
+
if (r.missing) throw new Error('secret-tool is not installed')
|
|
227
|
+
},
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The store for this OS, or null where there is none. */
|
|
232
|
+
function osStore(dir, platform = process.platform) {
|
|
233
|
+
const ns = namespace()
|
|
234
|
+
const service = ns ? `${KEYCHAIN_SERVICE}.${ns}` : KEYCHAIN_SERVICE
|
|
235
|
+
if (platform === 'darwin') return keychainStore(service)
|
|
236
|
+
if (platform === 'win32') return dpapiStore(path.join(dir, ns ? `desktop-sign-in.${ns}.dpapi` : 'desktop-sign-in.dpapi'))
|
|
237
|
+
if (platform === 'linux') return secretToolStore(service)
|
|
238
|
+
return null
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** For tests: the same three calls, kept in memory. */
|
|
242
|
+
function memoryStore(initial = null) {
|
|
243
|
+
let value = initial
|
|
244
|
+
return {
|
|
245
|
+
kind: 'memory',
|
|
246
|
+
async read() { return value },
|
|
247
|
+
async write(v) { value = v },
|
|
248
|
+
async clear() { value = null },
|
|
249
|
+
peek() { return value },
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ── Small file helpers ──────────────────────────────────────────────────────
|
|
254
|
+
|
|
255
|
+
async function writeAtomic(file, text) {
|
|
256
|
+
await fsp.mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
257
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`
|
|
258
|
+
await fsp.writeFile(tmp, text, { mode: 0o600 })
|
|
259
|
+
await fsp.rename(tmp, file)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function readJson(file) {
|
|
263
|
+
try {
|
|
264
|
+
const v = JSON.parse(await fsp.readFile(file, 'utf8'))
|
|
265
|
+
return v && typeof v === 'object' ? v : {}
|
|
266
|
+
} catch {
|
|
267
|
+
return {}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* A lock across processes: a directory, because creating one is atomic on
|
|
275
|
+
* every OS. One left behind by a crash is taken over after LOCK_STALE_MS.
|
|
276
|
+
*/
|
|
277
|
+
async function withLock(lockDir, fn, now = Date.now) {
|
|
278
|
+
const until = now() + LOCK_WAIT_MS
|
|
279
|
+
await fsp.mkdir(path.dirname(lockDir), { recursive: true, mode: 0o700 })
|
|
280
|
+
for (;;) {
|
|
281
|
+
try {
|
|
282
|
+
await fsp.mkdir(lockDir)
|
|
283
|
+
break
|
|
284
|
+
} catch (err) {
|
|
285
|
+
if (!err || err.code !== 'EEXIST') throw err
|
|
286
|
+
try {
|
|
287
|
+
const st = await fsp.stat(lockDir)
|
|
288
|
+
if (now() - st.mtimeMs > LOCK_STALE_MS) {
|
|
289
|
+
await fsp.rm(lockDir, { recursive: true, force: true })
|
|
290
|
+
continue
|
|
291
|
+
}
|
|
292
|
+
} catch { continue }
|
|
293
|
+
if (now() > until) throw new Error('lock_timeout')
|
|
294
|
+
await sleep(100)
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
return await fn()
|
|
299
|
+
} finally {
|
|
300
|
+
await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {})
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── The suite session ───────────────────────────────────────────────────────
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* @param {object} o
|
|
308
|
+
* @param {string} o.dir The shared suite folder (…/UNISIM).
|
|
309
|
+
* @param {string} o.stateFile This app's own state file (its userData).
|
|
310
|
+
* @param {string} o.appId This app's id (`pdf`), for the server's record.
|
|
311
|
+
* @param {object|null} [o.store] The protected store (default: this OS's).
|
|
312
|
+
* @param {typeof fetch} [o.fetch]
|
|
313
|
+
* @param {() => number} [o.now]
|
|
314
|
+
*/
|
|
315
|
+
function createSuiteSession(o) {
|
|
316
|
+
const dir = o.dir
|
|
317
|
+
const stateFile = o.stateFile
|
|
318
|
+
const appId = o.appId
|
|
319
|
+
const store = o.store === undefined ? osStore(dir) : o.store
|
|
320
|
+
const fetchImpl = o.fetch || ((...a) => fetch(...a))
|
|
321
|
+
const now = o.now || Date.now
|
|
322
|
+
const ns = namespace()
|
|
323
|
+
const eventsFile = path.join(dir, ns ? `desktop-sign-in.${ns}.events.json` : 'desktop-sign-in.events.json')
|
|
324
|
+
const lockDir = path.join(dir, ns ? `desktop-sign-in.${ns}.lock` : 'desktop-sign-in.lock')
|
|
325
|
+
|
|
326
|
+
// One operation at a time inside this process; the lock covers the others.
|
|
327
|
+
let queue = Promise.resolve()
|
|
328
|
+
const serial = (fn) => {
|
|
329
|
+
const next = queue.then(fn, fn)
|
|
330
|
+
queue = next.catch(() => {})
|
|
331
|
+
return next
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function readGrant() {
|
|
335
|
+
if (!store) return null
|
|
336
|
+
let raw
|
|
337
|
+
try { raw = await store.read() } catch { return null }
|
|
338
|
+
if (!raw) return null
|
|
339
|
+
try {
|
|
340
|
+
const g = JSON.parse(raw)
|
|
341
|
+
if (g && g.v === 1 && UUID.test(g.id) && SECRET.test(g.secret)) return g
|
|
342
|
+
} catch { /* not ours */ }
|
|
343
|
+
return null
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function writeGrant(g) {
|
|
347
|
+
await store.write(JSON.stringify({ v: 1, id: g.id, secret: g.secret, exp: g.exp || null }))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function clearGrantIf(id) {
|
|
351
|
+
const g = await readGrant()
|
|
352
|
+
if (g && (!id || g.id === id)) await store.clear().catch(() => {})
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const readState = () => readJson(stateFile)
|
|
356
|
+
const writeState = async (patch) => writeAtomic(stateFile, JSON.stringify({ ...(await readState()), ...patch }))
|
|
357
|
+
const readEvents = () => readJson(eventsFile)
|
|
358
|
+
const writeEvents = async (patch) => writeAtomic(eventsFile, JSON.stringify({ ...(await readEvents()), ...patch }))
|
|
359
|
+
|
|
360
|
+
async function post(net, body) {
|
|
361
|
+
let res
|
|
362
|
+
try {
|
|
363
|
+
res = await fetchImpl(`${net.supabaseUrl}/functions/v1/desktop-sign-in`, {
|
|
364
|
+
method: 'POST',
|
|
365
|
+
headers: { 'content-type': 'application/json', apikey: net.apikey },
|
|
366
|
+
body: JSON.stringify(body),
|
|
367
|
+
signal: AbortSignal.timeout(20000),
|
|
368
|
+
})
|
|
369
|
+
} catch {
|
|
370
|
+
return { ok: false, error: 'offline' }
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const data = await res.json()
|
|
374
|
+
return data && typeof data === 'object' ? data : { ok: false, error: `http_${res.status}` }
|
|
375
|
+
} catch {
|
|
376
|
+
return { ok: false, error: `http_${res.status}` }
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* What this app should do now. `signedIn`: whether it holds a (non-guest)
|
|
382
|
+
* session. Returns { action: 'none' | 'sign_in' | 'sign_out', token_hash?, error? }.
|
|
383
|
+
*/
|
|
384
|
+
function sync(net, signedIn) {
|
|
385
|
+
return serial(async () => {
|
|
386
|
+
const events = await readEvents()
|
|
387
|
+
const state = await readState()
|
|
388
|
+
const signedOutAt = Number(events.signedOutAt) || 0
|
|
389
|
+
if (signedIn) {
|
|
390
|
+
// Someone chose "Sign out of every UNI·SIM app on this computer" since
|
|
391
|
+
// this app last signed in.
|
|
392
|
+
if (signedOutAt > (Number(state.epochSeen) || 0)) return { action: 'sign_out' }
|
|
393
|
+
return { action: 'none' }
|
|
394
|
+
}
|
|
395
|
+
if (!store) return { action: 'none', error: 'no_store' }
|
|
396
|
+
const peek = await readGrant()
|
|
397
|
+
if (!peek) return { action: 'none' }
|
|
398
|
+
if (state.declined && state.declined === peek.id) return { action: 'none', error: 'declined' }
|
|
399
|
+
if (peek.exp && Date.parse(peek.exp) <= now()) {
|
|
400
|
+
await clearGrantIf(peek.id)
|
|
401
|
+
return { action: 'none', error: 'grant_expired' }
|
|
402
|
+
}
|
|
403
|
+
if (!net) return { action: 'none', error: 'bad_request' }
|
|
404
|
+
|
|
405
|
+
let result
|
|
406
|
+
try {
|
|
407
|
+
result = await withLock(lockDir, async () => {
|
|
408
|
+
// Read again under the lock: another app may have just rotated it.
|
|
409
|
+
const g = await readGrant()
|
|
410
|
+
if (!g) return { action: 'none' }
|
|
411
|
+
if (state.declined && state.declined === g.id) return { action: 'none', error: 'declined' }
|
|
412
|
+
const data = await post(net, { action: 'grant_redeem', grant_id: g.id, secret: g.secret, app: appId })
|
|
413
|
+
if (data.ok && typeof data.token_hash === 'string' && typeof data.secret === 'string' && SECRET.test(data.secret)) {
|
|
414
|
+
// Save the new secret before anything else: the old one is
|
|
415
|
+
// retired, and presenting it again would end the grant.
|
|
416
|
+
try {
|
|
417
|
+
await writeGrant({ ...g, secret: data.secret })
|
|
418
|
+
} catch {
|
|
419
|
+
await store.clear().catch(() => {})
|
|
420
|
+
}
|
|
421
|
+
return { action: 'sign_in', token_hash: data.token_hash, grant: g.id }
|
|
422
|
+
}
|
|
423
|
+
const error = String(data.error || 'failed')
|
|
424
|
+
if (GRANT_DEAD.has(error)) await store.clear().catch(() => {})
|
|
425
|
+
return { action: 'none', error }
|
|
426
|
+
}, now)
|
|
427
|
+
} catch (err) {
|
|
428
|
+
return { action: 'none', error: String((err && err.message) || err) }
|
|
429
|
+
}
|
|
430
|
+
if (result.action === 'sign_in') await writeState({ declined: null, epochSeen: signedOutAt })
|
|
431
|
+
return result
|
|
432
|
+
})
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** This app has just signed in (any way): it takes part again. */
|
|
436
|
+
function signedIn() {
|
|
437
|
+
return serial(async () => {
|
|
438
|
+
const events = await readEvents()
|
|
439
|
+
await writeState({ declined: null, epochSeen: Number(events.signedOutAt) || 0 })
|
|
440
|
+
return { ok: true }
|
|
441
|
+
})
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* This app has signed out. `here`: the person chose to sign out of THIS app,
|
|
446
|
+
* so it must not sign itself straight back in with the grant on its next
|
|
447
|
+
* start; a NEW grant (a fresh browser sign-in in any suite app) brings it
|
|
448
|
+
* back. `suite`: it signed out because of a sign-out everywhere.
|
|
449
|
+
*/
|
|
450
|
+
function signedOut(reason) {
|
|
451
|
+
return serial(async () => {
|
|
452
|
+
const events = await readEvents()
|
|
453
|
+
if (reason === 'suite') {
|
|
454
|
+
await writeState({ epochSeen: Number(events.signedOutAt) || 0 })
|
|
455
|
+
} else {
|
|
456
|
+
const g = await readGrant()
|
|
457
|
+
await writeState({ declined: g ? g.id : null })
|
|
458
|
+
}
|
|
459
|
+
return { ok: true }
|
|
460
|
+
})
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** "Sign out of every UNI·SIM app on this computer". */
|
|
464
|
+
function signOutAll(net) {
|
|
465
|
+
return serial(async () => {
|
|
466
|
+
const at = now()
|
|
467
|
+
let g = null
|
|
468
|
+
try {
|
|
469
|
+
g = await withLock(lockDir, async () => {
|
|
470
|
+
const held = await readGrant()
|
|
471
|
+
if (store) await store.clear().catch(() => {})
|
|
472
|
+
return held
|
|
473
|
+
}, now)
|
|
474
|
+
} catch {
|
|
475
|
+
if (store) await store.clear().catch(() => {})
|
|
476
|
+
}
|
|
477
|
+
// This app is signing itself out; the others read the events file.
|
|
478
|
+
await writeState({ declined: null, epochSeen: at })
|
|
479
|
+
await writeEvents({ signedOutAt: at })
|
|
480
|
+
if (g && net) await post(net, { action: 'grant_revoke', grant_id: g.id, secret: g.secret })
|
|
481
|
+
return { ok: true }
|
|
482
|
+
})
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** A browser sign-in in this app brought back a grant: keep it for all. */
|
|
486
|
+
function saveGrant(grant, net) {
|
|
487
|
+
return serial(async () => {
|
|
488
|
+
if (!store) return { ok: false, error: 'no_store' }
|
|
489
|
+
if (!grant || !UUID.test(grant.id) || !SECRET.test(grant.secret)) return { ok: false, error: 'bad_grant' }
|
|
490
|
+
let old = null
|
|
491
|
+
try {
|
|
492
|
+
old = await withLock(lockDir, async () => {
|
|
493
|
+
const prev = await readGrant()
|
|
494
|
+
await writeGrant({ id: grant.id, secret: grant.secret, exp: grant.expires_at || null })
|
|
495
|
+
return prev
|
|
496
|
+
}, now)
|
|
497
|
+
} catch (err) {
|
|
498
|
+
return { ok: false, error: String((err && err.message) || err) }
|
|
499
|
+
}
|
|
500
|
+
const events = await readEvents()
|
|
501
|
+
await writeState({ declined: null, epochSeen: Number(events.signedOutAt) || 0 })
|
|
502
|
+
await writeEvents({ grantAt: now() })
|
|
503
|
+
// The grant it replaces is ended, so at most one is ever live here.
|
|
504
|
+
if (old && old.id !== grant.id && net) await post(net, { action: 'grant_revoke', grant_id: old.id, secret: old.secret })
|
|
505
|
+
return { ok: true }
|
|
506
|
+
})
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Whether this computer's protected store answers at all (Linux may not). */
|
|
510
|
+
async function canStore() {
|
|
511
|
+
if (!store) return false
|
|
512
|
+
try { await store.read(); return true } catch { return false }
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Calls `onChange` when another app signs in or signs out everywhere. */
|
|
516
|
+
function watch(onChange, interval = 1500) {
|
|
517
|
+
let last = null
|
|
518
|
+
const tick = async () => {
|
|
519
|
+
const e = await readEvents()
|
|
520
|
+
const key = `${e.signedOutAt || 0}|${e.grantAt || 0}`
|
|
521
|
+
if (last !== null && key !== last) onChange(e)
|
|
522
|
+
last = key
|
|
523
|
+
}
|
|
524
|
+
void tick()
|
|
525
|
+
const timer = setInterval(() => { void tick() }, interval)
|
|
526
|
+
if (timer.unref) timer.unref()
|
|
527
|
+
return () => clearInterval(timer)
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** The IPC entry point: one channel, an `op`. */
|
|
531
|
+
async function handle(payload) {
|
|
532
|
+
const op = payload && payload.op
|
|
533
|
+
const url = String((payload && payload.supabaseUrl) || '').replace(/\/+$/, '')
|
|
534
|
+
const apikey = String((payload && payload.apikey) || '')
|
|
535
|
+
const net = isPlatformUrl(url) && apikey ? { supabaseUrl: url, apikey } : null
|
|
536
|
+
try {
|
|
537
|
+
if (op === 'sync') return await sync(net, !!(payload && payload.signedIn))
|
|
538
|
+
if (op === 'signed-in') return await signedIn()
|
|
539
|
+
if (op === 'signed-out') return await signedOut(payload && payload.reason === 'suite' ? 'suite' : 'here')
|
|
540
|
+
if (op === 'sign-out-all') return await signOutAll(net)
|
|
541
|
+
if (op === 'status') {
|
|
542
|
+
const g = await readGrant()
|
|
543
|
+
return { ok: true, available: !!store, store: store ? store.kind : null, hasGrant: !!g }
|
|
544
|
+
}
|
|
545
|
+
} catch (err) {
|
|
546
|
+
return { ok: false, action: 'none', error: String((err && err.message) || err) }
|
|
547
|
+
}
|
|
548
|
+
return { ok: false, action: 'none', error: 'bad_request' }
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return { sync, signedIn, signedOut, signOutAll, saveGrant, canStore, watch, handle, readGrant, eventsFile, lockDir, store }
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
module.exports = {
|
|
555
|
+
createSuiteSession,
|
|
556
|
+
isPlatformUrl,
|
|
557
|
+
memoryStore,
|
|
558
|
+
osStore,
|
|
559
|
+
withLock,
|
|
560
|
+
KEYCHAIN_SERVICE,
|
|
561
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unisim/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.233.0",
|
|
4
4
|
"description": "Shared React SDK for the Universal Suite — auth, entitlements, usage telemetry, changelog, org admin.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Universal Simulation Ltd",
|
|
@@ -76,6 +76,7 @@
|
|
|
76
76
|
"test:account-links": "npm run build && node tests/account-links.mjs",
|
|
77
77
|
"test:account-switch-menu": "npm run build && node tests/account-switch-menu.browser.mjs",
|
|
78
78
|
"test:shared-signout": "node tests/shared-signout.mjs",
|
|
79
|
+
"test:suite-session": "node --test tests/suite-session.mjs",
|
|
79
80
|
"test:folder-drop": "npm run build && node tests/folder-drop.mjs",
|
|
80
81
|
"test:suite-apps": "npm run build && node tests/suite-apps.mjs",
|
|
81
82
|
"test:suite-store": "npm run build && node tests/suite-store.browser.mjs",
|
|
@@ -129,6 +130,7 @@
|
|
|
129
130
|
"test:tune-account": "npm run build && node tests/tune-account.browser.mjs",
|
|
130
131
|
"test:guest-tuning": "npm run build && node tests/guest-tuning.browser.mjs",
|
|
131
132
|
"test:tune-sync": "npm run build && node tests/tune-sync.mjs && node tests/tune-sync.browser.mjs",
|
|
133
|
+
"test:synced-settings": "npm run build && node tests/synced-settings.mjs && node tests/synced-settings.browser.mjs",
|
|
132
134
|
"test:empty-actions": "npm run build && node tests/empty-actions.browser.mjs",
|
|
133
135
|
"test:menu-row-close": "npm run build && node tests/menu-row-close.browser.mjs",
|
|
134
136
|
"prepublishOnly": "npm run typecheck && npm run build",
|