eversince 0.2.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/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,9 @@
1
+ Eversince CLI
2
+ Copyright 2026 Eversince
3
+
4
+ This product includes software developed at Eversince (https://eversince.ai).
5
+
6
+ Licensed under the Apache License, Version 2.0. See the LICENSE file.
7
+
8
+ "Eversince" and the Eversince logo are trademarks of Eversince. The Apache
9
+ License grants no rights to use them; see section 6 of the LICENSE.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # eversince
2
+
3
+ Your Eversince workspace, from the command line — for agents and the people who run them.
4
+
5
+ ```bash
6
+ npm install -g eversince
7
+ eversince login
8
+ eversince init
9
+ ```
10
+
11
+ `init` connects the agents on this machine and installs a skill that teaches them
12
+ how to use this. Restart the agent and it can work in your library.
13
+
14
+ ## Why a CLI as well as MCP
15
+
16
+ They do different jobs and neither replaces the other.
17
+
18
+ MCP gives an agent tools inside its session. It cannot read your disk, it needs a
19
+ session to exist, and its tool schemas ride along in context on every turn.
20
+
21
+ The CLI reaches local files, runs the same operation over hundreds of items, works
22
+ in a script with no agent at all, and costs nothing in context until it's used.
23
+
24
+ Both are the same account and the same workspace. Their credentials are separate:
25
+ signing out of one leaves the other working.
26
+
27
+ ## With the desktop app on this computer
28
+
29
+ When the Eversince desktop app is installed on the same computer, commands go
30
+ through it rather than to eversince.ai, and what the app does is free. The app
31
+ opens if it is closed, the CLI connects itself the first time, and it shows in
32
+ the app under Settings, Your agents, where it can be disconnected. No sign-in is
33
+ needed for this; the app's own is used, in the workspace the app has open.
34
+
35
+ A command stays on eversince.ai when it is run with `--cloud`, `--base-url` or
36
+ `--workspace`, when `ES_API_KEY` or `ES_BASE_URL` is set, or when a workspace was
37
+ chosen with `eversince workspace use`. `login`, `logout`, `workspace` and `init`
38
+ always work against eversince.ai. `eversince status` says whether the app is used.
39
+
40
+ ## Commands
41
+
42
+ ```
43
+ eversince login sign in through the browser
44
+ eversince login --key es_live_… or with an API key (CI, no browser)
45
+ eversince logout
46
+ eversince status
47
+ eversince init connect the agents on this machine
48
+ eversince init --agent codex connect one agent
49
+ eversince mcp --agent codex the desktop app as a stdio MCP server (init writes this)
50
+
51
+ eversince tools [name] what this workspace can do, live
52
+ eversince run <tool> '<json>' call any tool (--wait to follow async work)
53
+ eversince upload <files|folder> local files into the library
54
+ eversince download <refs…> library items onto disk
55
+ eversince jobs <ids…> check async work (--wait to follow)
56
+ eversince jobs cancel <ids…>
57
+ eversince workspace [use <name>] which workspace the CLI acts in
58
+ ```
59
+
60
+ Every command takes `--json`, on success and on failure, in the envelope the API
61
+ uses — `{"ok":true,"data":…}` or `{"ok":false,"error":…}` — so an agent reads one
62
+ field to know which it got rather than inferring it from the shape.
63
+
64
+ ## Examples
65
+
66
+ ```bash
67
+ # A shoot folder into the library, described and tagged on arrival.
68
+ # Describing and tagging draws on cloud processing, so it runs only with `--enrich`.
69
+ eversince upload ~/Desktop/shoot --enrich
70
+
71
+ # What can this workspace do, and what does one tool take
72
+ eversince tools
73
+ eversince tools generate_video
74
+
75
+ # Generate and wait for it
76
+ eversince run generate_video '{"prompt":"slow orbit around the bottle"}' --wait
77
+
78
+ # Pull the results down for ffmpeg
79
+ eversince download ab12cd ef34gh --out ./renders
80
+
81
+ # Everything the library knows about an item, piped into jq
82
+ eversince run get_items '{"refs":["ab12cd"]}' --json | jq '.data.items[0].tags'
83
+
84
+ # Arguments from a file or another command — `-` means read stdin
85
+ jq -n '{refs:["ab12cd"]}' | eversince run get_items -
86
+ ```
87
+
88
+ ## Async work
89
+
90
+ Generation and render return a job rather than a finished file. `--wait`
91
+ follows it to completion using the server's long-poll, and exits non-zero if
92
+ anything failed. Without `--wait` you get the job id back and can follow it later
93
+ with `eversince jobs <id> --wait`.
94
+
95
+ ## Authentication
96
+
97
+ Browser sign-in is the default. It uses OAuth with PKCE against the workspace's
98
+ own authorization server — discovered, never hardcoded — and registers this CLI as
99
+ its own client, so it holds a credential that renews itself and can be revoked
100
+ independently of any other connection.
101
+
102
+ An API key works where a browser doesn't:
103
+
104
+ ```bash
105
+ eversince login --key - # read the key from stdin, stays out of shell history
106
+ eversince login --key es_live_… # stored
107
+ ES_API_KEY=es_live_… eversince … # this shell only, overrides the stored one
108
+ ```
109
+
110
+ A key given as `--key es_live_…` lands in your shell history and, briefly, in the
111
+ machine's process list. On anything shared, pipe it instead.
112
+
113
+ Credentials are kept per deployment, in the system keychain where there is one and
114
+ in a `0600` file otherwise.
115
+
116
+ ## Workspaces
117
+
118
+ ```bash
119
+ eversince workspace # what this account can reach
120
+ eversince workspace use "Studio" # the CLI acts here from now on
121
+ eversince workspace clear # back to the account default
122
+ ```
123
+
124
+ The choice is the CLI's own and travels on each request. It does not move the
125
+ workspace that connected apps are using. An API key is bound to one workspace by
126
+ the server and cannot switch.
127
+
128
+ ## Options
129
+
130
+ ```
131
+ --json machine-readable output, on success and failure
132
+ --wait follow async work to completion
133
+ --timeout <seconds> ceiling on a request, and on --wait (default 1800)
134
+ --out <dir> where downloads land
135
+ --describe <text> description for an upload
136
+ --enrich describe and tag each image upload
137
+ --concurrency <n> parallel uploads (default 3, max 8)
138
+ --workspace <id> act in this workspace, this once
139
+ --cloud use eversince.ai even with the desktop app here
140
+ --base-url <url> point at another deployment
141
+ --debug print each request and response
142
+ ```
143
+
144
+ ## Environment
145
+
146
+ ```
147
+ ES_API_KEY use this key instead of the stored credential
148
+ ES_WORKSPACE workspace for this shell
149
+ ES_BASE_URL deployment for this shell
150
+ ES_DEBUG=1 same as --debug
151
+ ```
152
+
153
+ ## Exit codes
154
+
155
+ `0` success · `1` anything failed, including a partial batch. With `--json` the
156
+ failure is on stdout as `{"ok":false,"error":{…}}` with the request id where the
157
+ server gave one.
158
+
159
+ ## Licence
160
+
161
+ Apache-2.0. This covers the client in this package — not the Eversince service it
162
+ talks to, which needs an account, and not the Eversince name, which the licence
163
+ explicitly does not grant rights to.
164
+
165
+ ## What `init` writes
166
+
167
+ On a computer with the Eversince desktop app, `init` connects the agent through
168
+ the app: the app adds `eversince mcp` from this installed CLI to the agent's own
169
+ settings as a local server, by the absolute paths of Node and the CLI, so the
170
+ work it does there is free, and replaces an eversince.ai entry of the same name.
171
+ The agent is the one named with `--agent` (`claude-code`, `codex`, `cursor`,
172
+ `vscode`, `claude-desktop` or `other`), else the one running `init`, else Claude
173
+ Code and Codex where they are installed. Run `init` again after moving Node or
174
+ the CLI. `--cloud` sets it up on eversince.ai instead.
175
+
176
+ Without the app, `init --agent` writes only that agent's settings: `.mcp.json`
177
+ for Claude Code, `.cursor/mcp.json` for Cursor, `.vscode/mcp.json` for VS Code
178
+ (the user-wide files with `--scope user`), and prints what to add for Codex,
179
+ Claude Desktop and anything else. With no agent named, `init` merges an `eversince` entry into the MCP config of the agents on this
180
+ machine — `.mcp.json` for Claude Code, `.cursor/mcp.json` for Cursor — backing up
181
+ anything it edits and keeping settings that were already there. Codex keeps its
182
+ servers in TOML, so that one is printed for you to paste rather than parsed.
183
+
184
+ It also installs a skill at `.claude/skills/eversince-cli/SKILL.md` teaching an
185
+ agent these commands. That is the CLI's skill and is separate from the Eversince
186
+ plugin skill, which covers the MCP tools. `--no-mcp` and `--no-skills` turn either
187
+ half off; `--dry-run` shows what would change.
@@ -0,0 +1,209 @@
1
+ import { createServer } from 'node:http';
2
+ import { randomBytes, createHash } from 'node:crypto';
3
+ import { spawn } from 'node:child_process';
4
+ import { USER_AGENT } from '../version.js';
5
+ const CLIENT_NAME = 'Eversince CLI';
6
+ const CLIENT_URI = 'https://eversince.ai';
7
+ function base64url(input) {
8
+ return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
9
+ }
10
+ async function getJson(url, init) {
11
+ const res = await fetch(url, {
12
+ ...init,
13
+ headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...(init?.headers ?? {}) },
14
+ });
15
+ const text = await res.text();
16
+ if (!res.ok) {
17
+ throw new Error(`${url} responded ${res.status}: ${text.slice(0, 200)}`);
18
+ }
19
+ try {
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ throw new Error(`${url} did not return JSON`);
24
+ }
25
+ }
26
+ export async function discoverAuthorizationServer(baseUrl) {
27
+ const metadata = (await getJson(new URL('/.well-known/oauth-protected-resource', baseUrl).toString()));
28
+ const issuer = metadata.authorization_servers?.[0];
29
+ if (!issuer)
30
+ throw new Error(`${baseUrl} does not advertise an authorization server.`);
31
+ const issuerUrl = new URL(issuer);
32
+ const wellKnown = new URL(`/.well-known/oauth-authorization-server${issuerUrl.pathname.replace(/\/$/, '')}`, issuerUrl.origin).toString();
33
+ let server;
34
+ try {
35
+ server = (await getJson(wellKnown));
36
+ }
37
+ catch {
38
+ server = (await getJson(new URL('.well-known/oauth-authorization-server', `${issuer}/`).toString()));
39
+ }
40
+ if (!server.authorization_endpoint || !server.token_endpoint) {
41
+ throw new Error('Authorization server metadata is missing its endpoints.');
42
+ }
43
+ return { server, resource: metadata.resource ?? baseUrl };
44
+ }
45
+ export async function registerClient(server, redirectUri) {
46
+ if (!server.registration_endpoint) {
47
+ throw new Error('This authorization server does not support dynamic client registration. Sign in with an API key instead: eversince login --key es_live_…');
48
+ }
49
+ const registered = (await getJson(server.registration_endpoint, {
50
+ method: 'POST',
51
+ headers: { 'content-type': 'application/json' },
52
+ body: JSON.stringify({
53
+ client_name: CLIENT_NAME,
54
+ client_uri: CLIENT_URI,
55
+ redirect_uris: [redirectUri],
56
+ grant_types: ['authorization_code', 'refresh_token'],
57
+ response_types: ['code'],
58
+ token_endpoint_auth_method: 'none',
59
+ application_type: 'native',
60
+ }),
61
+ }));
62
+ if (!registered.client_id)
63
+ throw new Error('Registration did not return a client_id.');
64
+ return registered.client_id;
65
+ }
66
+ function openBrowser(url) {
67
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
68
+ try {
69
+ const child = spawn(command, [url], { stdio: 'ignore', detached: true, shell: process.platform === 'win32' });
70
+ child.unref();
71
+ }
72
+ catch {
73
+ }
74
+ }
75
+ const DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>Signed in</title>
76
+ <style>body{font:16px/1.6 -apple-system,system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;color:#111}
77
+ @media(prefers-color-scheme:dark){body{background:#111;color:#eee}}</style>
78
+ <body><div><p><strong>Signed in to Eversince.</strong></p><p>You can close this tab and go back to the terminal.</p></div>`;
79
+ const PREFERRED_PORTS = [51703, 51704, 51705, 0];
80
+ async function awaitCallback(timeoutMs) {
81
+ let settle = null;
82
+ const received = new Promise((resolve) => {
83
+ settle = resolve;
84
+ });
85
+ const server = createServer((req, res) => {
86
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
87
+ if (url.pathname !== '/callback') {
88
+ res.writeHead(404).end();
89
+ return;
90
+ }
91
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(DONE_PAGE);
92
+ settle?.({
93
+ code: url.searchParams.get('code') ?? undefined,
94
+ state: url.searchParams.get('state') ?? undefined,
95
+ error: url.searchParams.get('error') ?? undefined,
96
+ errorDescription: url.searchParams.get('error_description') ?? undefined,
97
+ });
98
+ });
99
+ let listening = false;
100
+ for (const port of PREFERRED_PORTS) {
101
+ try {
102
+ await new Promise((resolve, reject) => {
103
+ const onError = (error) => reject(error);
104
+ server.once('error', onError);
105
+ server.listen(port, '127.0.0.1', () => {
106
+ server.removeListener('error', onError);
107
+ resolve();
108
+ });
109
+ });
110
+ listening = true;
111
+ break;
112
+ }
113
+ catch {
114
+ }
115
+ }
116
+ if (!listening)
117
+ throw new Error('Could not open a local port to receive the sign-in. Use `eversince login --key es_live_…`.');
118
+ const timer = setTimeout(() => settle?.({ error: 'timeout' }), timeoutMs);
119
+ timer.unref();
120
+ return {
121
+ port: server.address().port,
122
+ wait: () => received,
123
+ close: () => {
124
+ clearTimeout(timer);
125
+ server.close();
126
+ },
127
+ };
128
+ }
129
+ export async function browserLogin(baseUrl, opts) {
130
+ const { server, resource } = await discoverAuthorizationServer(baseUrl);
131
+ const methods = server.code_challenge_methods_supported ?? [];
132
+ if (methods.length && !methods.includes('S256')) {
133
+ throw new Error('Authorization server does not support PKCE S256 — refusing to sign in without it.');
134
+ }
135
+ const callback = await awaitCallback(opts.timeoutMs ?? 5 * 60_000);
136
+ const redirectUri = `http://127.0.0.1:${callback.port}/callback`;
137
+ try {
138
+ const clientId = opts.existingClientId && opts.existingRedirectUri === redirectUri
139
+ ? opts.existingClientId
140
+ : await registerClient(server, redirectUri);
141
+ const verifier = base64url(randomBytes(32));
142
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
143
+ const state = base64url(randomBytes(16));
144
+ const authUrl = new URL(server.authorization_endpoint);
145
+ authUrl.searchParams.set('response_type', 'code');
146
+ authUrl.searchParams.set('client_id', clientId);
147
+ authUrl.searchParams.set('redirect_uri', redirectUri);
148
+ authUrl.searchParams.set('scope', 'openid email profile');
149
+ authUrl.searchParams.set('state', state);
150
+ authUrl.searchParams.set('code_challenge', challenge);
151
+ authUrl.searchParams.set('code_challenge_method', 'S256');
152
+ authUrl.searchParams.set('resource', resource);
153
+ opts.onUrl(authUrl.toString());
154
+ openBrowser(authUrl.toString());
155
+ const result = await callback.wait();
156
+ if (result.error === 'timeout')
157
+ throw new Error('Timed out waiting for the browser. Nothing was changed.');
158
+ if (result.error)
159
+ throw new Error(result.errorDescription || result.error);
160
+ if (!result.code)
161
+ throw new Error('No authorization code came back.');
162
+ if (result.state !== state)
163
+ throw new Error('The sign-in came back with a state we did not send. Try again.');
164
+ const tokens = await exchange(server, {
165
+ grant_type: 'authorization_code',
166
+ code: result.code,
167
+ redirect_uri: redirectUri,
168
+ client_id: clientId,
169
+ code_verifier: verifier,
170
+ resource,
171
+ });
172
+ return { ...tokens, clientId, redirectUri };
173
+ }
174
+ finally {
175
+ callback.close();
176
+ }
177
+ }
178
+ async function exchange(server, params) {
179
+ const res = await fetch(server.token_endpoint, {
180
+ method: 'POST',
181
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', 'user-agent': USER_AGENT },
182
+ body: new URLSearchParams(params).toString(),
183
+ });
184
+ const text = await res.text();
185
+ let payload;
186
+ try {
187
+ payload = JSON.parse(text);
188
+ }
189
+ catch {
190
+ throw new Error(`Token endpoint returned non-JSON (${res.status}).`);
191
+ }
192
+ if (!res.ok || !payload.access_token) {
193
+ throw new Error(payload.error_description || payload.error || `Token exchange failed (${res.status}).`);
194
+ }
195
+ return {
196
+ accessToken: payload.access_token,
197
+ refreshToken: payload.refresh_token,
198
+ expiresAt: payload.expires_in ? Date.now() + (payload.expires_in - 60) * 1000 : undefined,
199
+ };
200
+ }
201
+ export async function refreshTokens(baseUrl, clientId, refreshToken) {
202
+ const { server, resource } = await discoverAuthorizationServer(baseUrl);
203
+ return exchange(server, {
204
+ grant_type: 'refresh_token',
205
+ refresh_token: refreshToken,
206
+ client_id: clientId,
207
+ resource,
208
+ });
209
+ }