@unisim/sdk 0.219.0 → 0.221.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.
@@ -0,0 +1,193 @@
1
+ // Browser sign-in — the MAIN-PROCESS half of "Sign in with your browser".
2
+ //
3
+ // A desktop Universal App can't see the browser's .unisim.co.uk session, so on
4
+ // its own it can never greet a person who is already signed in to the suite.
5
+ // Typing an email and a code into the app works, but Microsoft / Google /
6
+ // Apple, passkeys and company two-step rules all need a real browser. So the
7
+ // app opens the hub's /desktop-sign-in page in the SYSTEM browser instead:
8
+ // someone already signed in there presses Continue once, and the app comes
9
+ // back signed in as them (RFC 8252, the pattern Slack, Figma and VS Code use).
10
+ //
11
+ // 1. We make a random verifier and put only its SHA-256 (the challenge), a
12
+ // random state and the app's id in the hub link, with the port of a
13
+ // loopback listener opened for this one sign-in (http://127.0.0.1:<port>).
14
+ // 2. The hub page asks the platform's `desktop-sign-in` function for a SEALED
15
+ // one-time code (the company's two-step and Microsoft/Google rules are
16
+ // checked there) and sends the browser to our listener with it.
17
+ // 3. We check the state and trade code + verifier for a single-use magic-link
18
+ // token, which goes back to the renderer. The renderer redeems it with
19
+ // supabase-js `verifyOtp`, so the session lands in the SDK's own storage
20
+ // exactly as an in-app sign-in would: a NEW session of this app's own,
21
+ // never a copy of the browser's (a shared refresh token signs both out).
22
+ //
23
+ // The verifier never leaves this process, so a code read off the browser's
24
+ // history, or caught by another program on the machine, is useless.
25
+ //
26
+ // The same flow already signs in Ergo Assess Desktop (its own copy, in
27
+ // Ergo_Assess/desktop/main.cjs, which also claims a seat). This is the shared
28
+ // one for every Universal App's Electron shell:
29
+ //
30
+ // // main.cjs
31
+ // const { installBrowserSignIn } = require('@unisim/sdk/electron')
32
+ // installBrowserSignIn({ app: 'pdf' })
33
+ //
34
+ // and two lines in the app's preload (see PRELOAD_SNIPPET in handoff.cjs).
35
+
36
+ const crypto = require('node:crypto')
37
+ const http = require('node:http')
38
+ const { BrowserWindow, app: electronApp, ipcMain, shell } = require('electron')
39
+
40
+ /** IPC channels. Preloads must use these exact strings — see PRELOAD_SNIPPET. */
41
+ const CHANNEL_SIGN_IN = 'unisim:browser-sign-in'
42
+ const CHANNEL_SIGN_IN_CANCEL = 'unisim:browser-sign-in-cancel'
43
+
44
+ const DEFAULT_HUB_URL = 'https://app.unisim.co.uk'
45
+ /** The sealed code itself lives 10 minutes; nobody should wait longer here. */
46
+ const SIGN_IN_TIMEOUT_MS = 10 * 60 * 1000
47
+ /** Lower-case letters, digits and dashes: it ends up in a URL and a lookup. */
48
+ const APP_ID = /^[a-z0-9-]{1,32}$/
49
+
50
+ const b64url = (buf) =>
51
+ Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
52
+
53
+ /**
54
+ * Only an https Supabase project (or a suite host) may be told the code and
55
+ * verifier. The renderer supplies the URL from its own config, and a renderer
56
+ * that has been talked into pointing it elsewhere must not get to hand the
57
+ * pair to a stranger.
58
+ */
59
+ function isPlatformUrl(url) {
60
+ try {
61
+ const u = new URL(url)
62
+ if (u.protocol !== 'https:') return false
63
+ return u.hostname.endsWith('.supabase.co') || u.hostname === 'unisim.co.uk' || u.hostname.endsWith('.unisim.co.uk')
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ function listenLoopback() {
70
+ return new Promise((resolve, reject) => {
71
+ const server = http.createServer()
72
+ server.once('error', reject)
73
+ server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port }))
74
+ })
75
+ }
76
+
77
+ /**
78
+ * Wire up the browser sign-in IPC. Call once, after `app.whenReady()`.
79
+ *
80
+ * @param {object} options
81
+ * @param {string} options.app This app's id on the hub page (`pdf`,
82
+ * `jukebox`…), so the page can name it.
83
+ * @param {string} [options.hubUrl] The hub. Defaults to app.unisim.co.uk, or
84
+ * UNISIM_HUB_URL when set (local testing).
85
+ * @param {(url: string) => Promise<void>} [options.openExternal]
86
+ * How to open the browser (tests).
87
+ * @returns {() => void} Removes the handlers again (tests, teardown).
88
+ */
89
+ function installBrowserSignIn(options = {}) {
90
+ const appId = String(options.app || '')
91
+ if (!APP_ID.test(appId)) throw new Error(`installBrowserSignIn: bad app id "${appId}"`)
92
+ const hubUrl = String(options.hubUrl || process.env.UNISIM_HUB_URL || DEFAULT_HUB_URL).replace(/\/+$/, '')
93
+ const openExternal = options.openExternal || ((url) => shell.openExternal(url))
94
+
95
+ /** The sign-in in flight, if any: `{ cancel }`. One at a time. */
96
+ let pending = null
97
+
98
+ async function signIn(payload, sender) {
99
+ const supabaseUrl = String(payload?.supabaseUrl || '').replace(/\/+$/, '')
100
+ const apikey = String(payload?.apikey || '')
101
+ if (!isPlatformUrl(supabaseUrl) || !apikey) return { ok: false, error: 'bad_request' }
102
+
103
+ if (pending) pending.cancel()
104
+ let server = null
105
+ try {
106
+ const verifier = b64url(crypto.randomBytes(32))
107
+ const challenge = b64url(crypto.createHash('sha256').update(verifier).digest())
108
+ const state = b64url(crypto.randomBytes(16))
109
+ const loop = await listenLoopback()
110
+ server = loop.server
111
+
112
+ const got = await new Promise((resolve) => {
113
+ const timer = setTimeout(() => finish({ error: 'timeout' }), SIGN_IN_TIMEOUT_MS)
114
+ const mine = { cancel: () => finish({ error: 'cancelled' }) }
115
+ function finish(v) {
116
+ clearTimeout(timer)
117
+ if (pending === mine) pending = null
118
+ resolve(v)
119
+ }
120
+ pending = mine
121
+ server.on('request', (req, res) => {
122
+ let url
123
+ try { url = new URL(req.url, 'http://127.0.0.1') } catch { url = null }
124
+ if (!url || url.pathname !== '/callback') {
125
+ res.writeHead(404).end()
126
+ return
127
+ }
128
+ const ok = url.searchParams.get('state') === state && !!url.searchParams.get('code')
129
+ // Back to the hub, which says in the person's own language that they
130
+ // can close the tab: this listener has no words of its own.
131
+ const back = new URLSearchParams({ app: appId, done: ok ? '1' : 'error' })
132
+ res.writeHead(302, { location: `${hubUrl}/desktop-sign-in?${back}` }).end()
133
+ // A wrong state is someone else's link: ignore it and keep waiting.
134
+ if (ok) finish({ code: url.searchParams.get('code') })
135
+ })
136
+ const link = `${hubUrl}/desktop-sign-in?${new URLSearchParams({ app: appId, port: String(loop.port), state, challenge })}`
137
+ Promise.resolve(openExternal(link)).catch(() => finish({ error: 'no_browser' }))
138
+ })
139
+ if (got.error) return { ok: false, error: got.error }
140
+
141
+ let res
142
+ try {
143
+ res = await fetch(`${supabaseUrl}/functions/v1/desktop-sign-in`, {
144
+ method: 'POST',
145
+ headers: { 'content-type': 'application/json', apikey },
146
+ body: JSON.stringify({ action: 'finish', code: got.code, verifier }),
147
+ signal: AbortSignal.timeout(20000),
148
+ })
149
+ } catch {
150
+ return { ok: false, error: 'offline' }
151
+ }
152
+ let data = null
153
+ try { data = await res.json() } catch { /* a gateway page */ }
154
+ if (!data?.ok || typeof data.token_hash !== 'string') {
155
+ return { ok: false, error: data?.error || `http_${res.status}` }
156
+ }
157
+
158
+ // The person is looking at their browser. Bring the window they started
159
+ // from back to the front, where the greeting is about to appear.
160
+ const win = sender ? BrowserWindow.fromWebContents(sender) : null
161
+ if (win && !win.isDestroyed()) {
162
+ if (win.isMinimized()) win.restore()
163
+ win.show()
164
+ win.focus()
165
+ }
166
+ if (process.platform === 'darwin') electronApp.focus({ steal: true })
167
+
168
+ return { ok: true, token_hash: data.token_hash }
169
+ } catch (err) {
170
+ return { ok: false, error: String((err && err.message) || err) }
171
+ } finally {
172
+ if (server) server.close()
173
+ }
174
+ }
175
+
176
+ ipcMain.handle(CHANNEL_SIGN_IN, (event, payload) => signIn(payload, event.sender))
177
+ ipcMain.handle(CHANNEL_SIGN_IN_CANCEL, () => {
178
+ if (pending) pending.cancel()
179
+ return { ok: true }
180
+ })
181
+
182
+ return function uninstall() {
183
+ if (pending) pending.cancel()
184
+ ipcMain.removeHandler(CHANNEL_SIGN_IN)
185
+ ipcMain.removeHandler(CHANNEL_SIGN_IN_CANCEL)
186
+ }
187
+ }
188
+
189
+ module.exports = {
190
+ installBrowserSignIn,
191
+ CHANNEL_SIGN_IN,
192
+ CHANNEL_SIGN_IN_CANCEL,
193
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unisim/sdk",
3
- "version": "0.219.0",
3
+ "version": "0.221.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",
@@ -82,6 +82,7 @@
82
82
  "test:suite-switcher": "npm run build && node tests/suite-switcher-close.browser.mjs",
83
83
  "test:hover-click": "npm run build && node tests/hover-click.browser.mjs",
84
84
  "test:multi-org": "npm run build && node tests/multi-org.mjs",
85
+ "test:org-load": "npm run build && node tests/org-load-shared.browser.mjs",
85
86
  "test:email-auth": "npm run build && node tests/email-auth.mjs",
86
87
  "test:about-credits": "npm run build && node tests/about-credits.browser.mjs",
87
88
  "test:knowledge-base": "npm run build && node tests/knowledge-base.browser.mjs",