@buwigs/auth-electron 0.0.0-stage → 0.2.0-alpha.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,11 @@
1
+ Buwigs Auth SDK
2
+ Copyright 2026 Buwigs.
3
+
4
+ This distribution contains SDK source code authored and maintained by Buwigs.
5
+ No third-party implementation source is bundled in this package. Runtime
6
+ libraries are declared as package dependencies, distributed separately, and
7
+ remain subject to their own license terms and notices.
8
+
9
+ The Buwigs Auth server implementation and its private repository are separate
10
+ works and are not licensed under this notice or the Apache License 2.0 copy
11
+ accompanying this SDK package.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # `@buwigs/auth-electron`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install after publication to npm:
4
+
5
+ ```sh
6
+ npm install @buwigs/auth-electron@0.2.0-alpha.1
7
+ ```
8
+
9
+ Electron public-client helpers for system-browser OIDC using Authorization Code
10
+ + PKCE. Requires Electron with Node.js 20 or newer and the shared
11
+ `@buwigs/auth-sdk` package. It does not embed a webview or accept a client
12
+ secret.
13
+
14
+ ```js
15
+ import { app, safeStorage, shell } from 'electron'
16
+ import { ElectronAuthClient } from '@buwigs/auth-electron'
17
+
18
+ const auth = new ElectronAuthClient({
19
+ issuer: 'https://auth.buwigs.com/realms/buwigs-local',
20
+ clientId: 'buwigs-desktop', // public OIDC client
21
+ apiAudience: 'buwigs-api:your-organization:desktop',
22
+ shell,
23
+ safeStorage,
24
+ userDataPath: app.getPath('userData'),
25
+ })
26
+
27
+ const session = await auth.signInWithSystemBrowser()
28
+ // Map only by (session.principal.issuer, session.principal.subject).
29
+ // Product authorization is still owned by your application.
30
+ ```
31
+
32
+ The SDK binds an ephemeral HTTP listener to `127.0.0.1`, starts the OS browser,
33
+ uses PKCE S256, random state and nonce, validates the callback host/path/state,
34
+ validates both returned tokens with the shared Node OIDC SDK, and stores the
35
+ token set only through Electron `safeStorage`. It fails closed if OS-protected
36
+ encryption is unavailable and rejects Electron's Linux `basic_text` backend.
37
+ On Linux, configure a supported Secret Service or KWallet backend. It stores an encrypted session under the supplied
38
+ Electron user data directory and exposes explicit load, refresh, sign-out, and
39
+ clear methods. Refresh is single-flight per client instance, validates the new
40
+ access token against the stored immutable subject, and persists rotated tokens
41
+ atomically through `safeStorage`. Sign-out attempts refresh-token revocation and
42
+ provider browser-session logout, then clears local storage even if a provider
43
+ call fails. A sign-out error means remote revocation was not confirmed; local
44
+ credentials have still been cleared.
45
+
46
+ ## Provider registration requirements
47
+
48
+ Register a **public** client and the exact loopback callback path
49
+ `/buwigs-auth/callback`. The OS assigns a port per run. Buwigs Auth must permit
50
+ dynamic ports only for a registered public-client loopback URI, with exact
51
+ scheme, loopback host, and path matching. It must not widen matching to other
52
+ hosts or paths. Use the server's exact loopback URI policy; do not register a
53
+ wildcard redirect URI.
54
+
55
+ ## Current server limitation
56
+
57
+ This SDK implements the desktop client side; it does not create a Buwigs login
58
+ session. The current Auth authorization endpoint requires a Buwigs session
59
+ cookie belonging to the browser on `auth.buwigs.com`. An Electron app's local
60
+ session is not that cookie, and a cookie from the app's own origin is not sent
61
+ to Auth. Consequently, first-time sign-in works only if the OS browser already
62
+ has an eligible Buwigs Auth session (for example, from a supported web login).
63
+ Without that existing browser session, authorization stops at the provider's
64
+ authentication-required response. A secure first-login handoff/device flow is
65
+ not implemented by this SDK and must be added server-side; this SDK does not
66
+ claim to complete standalone first-time desktop login until then.
67
+
68
+ The loopback callback requires a local HTTP listener. Applications with strict
69
+ firewall policy should choose a different standards-compliant native callback
70
+ registration. Tests use synthetic OIDC responses and a fake safeStorage adapter;
71
+ they do not represent a real Electron OS key store or a live Buwigs deployment.
72
+
73
+ ## License
74
+
75
+ This SDK source is licensed under Apache-2.0. See the bundled `LICENSE` and
76
+ `NOTICE`. The Buwigs Auth server is separate proprietary software.
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@buwigs/auth-electron",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-alpha.1",
4
+ "description": "System-browser OIDC helpers for Buwigs Auth Electron clients",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "main": "./src/index.js",
8
+ "module": "./src/index.js",
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "files": [
13
+ "src/**",
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./src/index.d.ts",
21
+ "import": "./src/index.js"
22
+ }
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "test": "node --test"
29
+ },
30
+ "dependencies": {
31
+ "@buwigs/auth-sdk": "0.2.0-alpha.1"
32
+ }
33
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Principal } from '@buwigs/auth-sdk'
4
+
5
+ export interface ElectronTokenSet {
6
+ access_token: string
7
+ id_token: string
8
+ refresh_token?: string
9
+ expires_in?: number
10
+ token_type?: string
11
+ [key: string]: unknown
12
+ }
13
+
14
+ export interface ElectronSession {
15
+ tokens: ElectronTokenSet
16
+ principal: Pick<Principal, 'issuer' | 'subject'>
17
+ storedAt: number
18
+ /** Internal protocol binding persisted only inside safeStorage ciphertext. */
19
+ redirectUri: string
20
+ nonce: string
21
+ }
22
+
23
+ export interface ElectronAuthConfig {
24
+ issuer: string
25
+ clientId: string
26
+ apiAudience: string
27
+ shell: { openExternal(url: string): Promise<void> | void }
28
+ safeStorage: {
29
+ isEncryptionAvailable(): boolean
30
+ encryptString(value: string): Buffer
31
+ decryptString(value: Buffer): string
32
+ }
33
+ userDataPath: string
34
+ timeoutMs?: number
35
+ /** Mainly for tests; production uses OidcClient.discover from the shared SDK. */
36
+ oidcFactory?: (config: Record<string, unknown>) => Promise<unknown>
37
+ }
38
+
39
+ export const CALLBACK_PATH: '/buwigs-auth/callback'
40
+
41
+ export class ElectronAuthClient {
42
+ constructor(config: ElectronAuthConfig)
43
+ signInWithSystemBrowser(): Promise<ElectronSession>
44
+ getStoredSession(): Promise<ElectronSession | null>
45
+ refreshStoredSession(): Promise<ElectronSession | null>
46
+ signOut(): Promise<void>
47
+ clearStoredSession(): Promise<void>
48
+ }
package/src/index.js ADDED
@@ -0,0 +1,261 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { createServer } from 'node:http'
4
+ import { randomBytes } from 'node:crypto'
5
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
6
+ import { join } from 'node:path'
7
+ import { OidcClient } from '@buwigs/auth-sdk'
8
+
9
+ const CALLBACK_PATH = '/buwigs-auth/callback'
10
+
11
+ function requireSafeStorage(safeStorage) {
12
+ if (!safeStorage || typeof safeStorage.isEncryptionAvailable !== 'function' ||
13
+ typeof safeStorage.encryptString !== 'function' || typeof safeStorage.decryptString !== 'function' ||
14
+ !safeStorage.isEncryptionAvailable()) {
15
+ throw new Error('OS-protected Electron safeStorage encryption is unavailable')
16
+ }
17
+ if (typeof safeStorage.getSelectedStorageBackend === 'function' &&
18
+ safeStorage.getSelectedStorageBackend() === 'basic_text') {
19
+ throw new Error('Electron selected the insecure basic_text storage backend; configure an OS keyring')
20
+ }
21
+ }
22
+
23
+ async function writeEncryptedAtomically(path, safeStorage, value) {
24
+ requireSafeStorage(safeStorage)
25
+ const directory = join(path, 'buwigs-auth')
26
+ await mkdir(directory, { recursive: true, mode: 0o700 })
27
+ const target = join(directory, 'session.bin')
28
+ const temporary = join(directory, `.session-${randomBytes(12).toString('hex')}.tmp`)
29
+ const encrypted = safeStorage.encryptString(JSON.stringify(value))
30
+ try {
31
+ await writeFile(temporary, encrypted, { flag: 'wx', mode: 0o600 })
32
+ await rename(temporary, target)
33
+ } catch (error) {
34
+ await unlink(temporary).catch(() => {})
35
+ throw error
36
+ }
37
+ }
38
+
39
+ async function readEncrypted(path, safeStorage) {
40
+ requireSafeStorage(safeStorage)
41
+ const target = join(path, 'buwigs-auth', 'session.bin')
42
+ let info
43
+ try { info = await lstat(target) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
44
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error('refusing unsafe token storage file')
45
+ const encrypted = await readFile(target)
46
+ const result = JSON.parse(safeStorage.decryptString(encrypted))
47
+ if (!result || typeof result !== 'object') throw new Error('invalid encrypted session record')
48
+ return result
49
+ }
50
+
51
+ async function clearEncrypted(path) {
52
+ await unlink(join(path, 'buwigs-auth', 'session.bin')).catch(error => { if (error.code !== 'ENOENT') throw error })
53
+ }
54
+
55
+ function callbackResult(server, timeoutMs) {
56
+ return new Promise((resolve, reject) => {
57
+ const timer = setTimeout(() => finish(new Error('system-browser authentication timed out')), timeoutMs)
58
+ timer.unref?.()
59
+ let completed = false
60
+ const finish = error => {
61
+ if (completed) return
62
+ completed = true
63
+ clearTimeout(timer)
64
+ server.close()
65
+ error ? reject(error) : resolve(result)
66
+ }
67
+ let result
68
+ server.on('request', (request, response) => {
69
+ if (request.method !== 'GET' || request.url?.split('?')[0] !== CALLBACK_PATH) {
70
+ response.writeHead(404, { connection: 'close' }).end('Not found')
71
+ return
72
+ }
73
+ const expectedHost = `127.0.0.1:${server.address().port}`
74
+ if (request.headers.host !== expectedHost) {
75
+ response.writeHead(400, { connection: 'close' }).end('Invalid callback')
76
+ finish(new Error('callback host mismatch'))
77
+ return
78
+ }
79
+ const params = new URL(request.url, `http://${expectedHost}`).searchParams
80
+ if ([...params.keys()].some(key => !['code', 'state', 'error', 'error_description'].includes(key)) ||
81
+ ['code', 'state', 'error', 'error_description'].some(key => params.getAll(key).length > 1)) {
82
+ response.writeHead(400, { connection: 'close' }).end('Invalid callback')
83
+ finish(new Error('invalid authorization callback'))
84
+ return
85
+ }
86
+ const state = params.get('state')
87
+ if (!state || state.length > 512) {
88
+ response.writeHead(400, { connection: 'close' }).end('Invalid callback')
89
+ finish(new Error('authorization callback state is missing'))
90
+ return
91
+ }
92
+ if (params.has('error')) {
93
+ if (params.has('code')) {
94
+ response.writeHead(400, { connection: 'close' }).end('Invalid callback')
95
+ finish(new Error('invalid authorization error response'))
96
+ return
97
+ }
98
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', connection: 'close' }).end('Sign-in was not completed. You may close this window.')
99
+ result = { state, error: params.get('error') }
100
+ finish()
101
+ return
102
+ }
103
+ const code = params.get('code')
104
+ if (!code || code.length > 4096) {
105
+ response.writeHead(400, { connection: 'close' }).end('Invalid callback')
106
+ finish(new Error('authorization code is missing'))
107
+ return
108
+ }
109
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', connection: 'close' }).end('Sign-in completed. You may close this window.')
110
+ result = { state, code }
111
+ finish()
112
+ })
113
+ server.on('error', error => finish(error))
114
+ })
115
+ }
116
+
117
+ /**
118
+ * Electron OIDC public-client flow using the OS browser and a loopback callback.
119
+ * No embedded webview and no client secret are used.
120
+ */
121
+ export class ElectronAuthClient {
122
+ #refreshPromise
123
+
124
+ constructor({ issuer, clientId, apiAudience, shell, safeStorage, userDataPath, timeoutMs = 180_000, oidcFactory = OidcClient.discover }) {
125
+ if (!issuer || !clientId || !apiAudience || typeof shell?.openExternal !== 'function' || !userDataPath) {
126
+ throw new TypeError('issuer, client ID, API audience, Electron shell, and userDataPath are required')
127
+ }
128
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 600_000) throw new TypeError('timeoutMs must be between 1 second and 10 minutes')
129
+ this.config = { issuer, clientId, apiAudience }
130
+ this.shell = shell
131
+ this.safeStorage = safeStorage
132
+ this.userDataPath = userDataPath
133
+ this.timeoutMs = timeoutMs
134
+ this.oidcFactory = oidcFactory
135
+ }
136
+
137
+ async signInWithSystemBrowser() {
138
+ const server = createServer()
139
+ server.listen(0, '127.0.0.1')
140
+ await new Promise((resolve, reject) => {
141
+ server.once('listening', resolve)
142
+ server.once('error', reject)
143
+ })
144
+ const address = server.address()
145
+ if (!address || typeof address === 'string' || address.address !== '127.0.0.1') {
146
+ server.close()
147
+ throw new Error('failed to bind a loopback-only callback listener')
148
+ }
149
+ const redirectUri = `http://127.0.0.1:${address.port}${CALLBACK_PATH}`
150
+ let oidc
151
+ let transaction
152
+ let callbackPromise
153
+ try {
154
+ oidc = await this.oidcFactory({ ...this.config, redirectUri, allowLocalHttp: true })
155
+ transaction = oidc.authorizationRequest(['openid', 'profile'])
156
+ callbackPromise = callbackResult(server, this.timeoutMs)
157
+ // Prevent an openExternal failure from leaving an unhandled timeout rejection.
158
+ callbackPromise.catch(() => {})
159
+ await this.shell.openExternal(transaction.url)
160
+ const callback = await callbackPromise
161
+ oidc.validateState(transaction.state, callback.state)
162
+ if (callback.error) throw new Error('identity provider did not complete sign-in')
163
+ const tokens = await oidc.exchangeCode(callback.code, transaction.verifier)
164
+ if (typeof tokens.id_token !== 'string' || typeof tokens.access_token !== 'string') throw new Error('provider returned an incomplete token response')
165
+ const principal = await oidc.verifyIdToken(tokens.id_token, { expectedNonce: transaction.nonce })
166
+ const apiPrincipal = await oidc.verifyAccessToken(tokens.access_token)
167
+ if (principal.issuer !== apiPrincipal.issuer || principal.subject !== apiPrincipal.subject) throw new Error('ID and access token identities do not match')
168
+ const session = {
169
+ tokens,
170
+ principal: { issuer: principal.issuer, subject: principal.subject },
171
+ storedAt: Date.now(),
172
+ redirectUri,
173
+ nonce: transaction.nonce,
174
+ }
175
+ await writeEncryptedAtomically(this.userDataPath, this.safeStorage, session)
176
+ return { ...session }
177
+ } catch (error) {
178
+ server.close()
179
+ throw error
180
+ }
181
+ }
182
+
183
+ async getStoredSession() {
184
+ const session = await readEncrypted(this.userDataPath, this.safeStorage)
185
+ if (!session) return null
186
+ if (!session.tokens || typeof session.tokens.access_token !== 'string' || typeof session.principal?.subject !== 'string') {
187
+ throw new Error('stored session record is incomplete')
188
+ }
189
+ return session
190
+ }
191
+
192
+ /** Refreshes once per client instance and persists the rotated token set atomically. */
193
+ async refreshStoredSession() {
194
+ this.#refreshPromise ??= this.#refreshStoredSession().finally(() => { this.#refreshPromise = undefined })
195
+ return this.#refreshPromise
196
+ }
197
+
198
+ async #refreshStoredSession() {
199
+ const session = await this.getStoredSession()
200
+ if (!session) return null
201
+ if (typeof session.tokens.refresh_token !== 'string' || !session.redirectUri || !session.nonce) {
202
+ throw new Error('stored session cannot be refreshed')
203
+ }
204
+ const oidc = await this.oidcFactory({
205
+ ...this.config,
206
+ redirectUri: session.redirectUri,
207
+ allowLocalHttp: true,
208
+ })
209
+ const rotated = await oidc.refreshToken(session.tokens.refresh_token)
210
+ if (typeof rotated.access_token !== 'string') throw new Error('provider returned an incomplete refresh response')
211
+ const accessPrincipal = await oidc.verifyAccessToken(rotated.access_token)
212
+ if (accessPrincipal.issuer !== session.principal.issuer || accessPrincipal.subject !== session.principal.subject) {
213
+ throw new Error('refreshed token identity does not match the stored session')
214
+ }
215
+ if (typeof rotated.id_token === 'string') {
216
+ const idPrincipal = await oidc.verifyIdToken(rotated.id_token, { expectedNonce: session.nonce })
217
+ if (idPrincipal.issuer !== session.principal.issuer || idPrincipal.subject !== session.principal.subject) {
218
+ throw new Error('refreshed ID token identity does not match the stored session')
219
+ }
220
+ }
221
+ const updated = {
222
+ ...session,
223
+ tokens: { ...session.tokens, ...rotated },
224
+ storedAt: Date.now(),
225
+ }
226
+ await writeEncryptedAtomically(this.userDataPath, this.safeStorage, updated)
227
+ return updated
228
+ }
229
+
230
+ /** Revokes the refresh token, asks the provider to end its browser session, and clears local storage. */
231
+ async signOut() {
232
+ let failure
233
+ try {
234
+ const session = await this.getStoredSession()
235
+ if (session) {
236
+ const oidc = await this.oidcFactory({
237
+ ...this.config,
238
+ redirectUri: session.redirectUri,
239
+ allowLocalHttp: true,
240
+ })
241
+ if (typeof session.tokens.refresh_token === 'string') {
242
+ try { await oidc.revokeToken(session.tokens.refresh_token, 'refresh_token') } catch (error) { failure = error }
243
+ }
244
+ if (typeof session.tokens.id_token === 'string') {
245
+ try { await this.shell.openExternal(oidc.endSessionUrl({ idTokenHint: session.tokens.id_token })) } catch (error) { failure ??= error }
246
+ }
247
+ }
248
+ } catch (error) {
249
+ failure ??= error
250
+ } finally {
251
+ await this.clearStoredSession()
252
+ }
253
+ if (failure) throw failure
254
+ }
255
+
256
+ async clearStoredSession() {
257
+ await clearEncrypted(this.userDataPath)
258
+ }
259
+ }
260
+
261
+ export { CALLBACK_PATH }