@heywavie/cli 0.2.4 → 0.3.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 +24 -5
- package/bin/heywavie.mjs +41 -9
- package/package.json +2 -2
- package/src/chatgpt-relay.mjs +146 -0
- package/src/chatgpt-tokens.mjs +154 -0
- package/src/chatgpt.mjs +330 -0
- package/src/claude.mjs +187 -39
- package/src/host.mjs +99 -24
- package/src/link.mjs +93 -21
- package/src/service.mjs +52 -13
- package/src/wavie.mjs +17 -0
package/src/chatgpt.mjs
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { createHash, createPublicKey, randomBytes, randomUUID, verify } from 'node:crypto';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import {
|
|
4
|
+
AUTH,
|
|
5
|
+
appVersion,
|
|
6
|
+
discovery,
|
|
7
|
+
dropTokens,
|
|
8
|
+
OPENAI_API,
|
|
9
|
+
readClient,
|
|
10
|
+
readTokens,
|
|
11
|
+
revoke,
|
|
12
|
+
tokenCall,
|
|
13
|
+
writeClient,
|
|
14
|
+
writeTokens,
|
|
15
|
+
} from './chatgpt-tokens.mjs';
|
|
16
|
+
import { readLink } from './home.mjs';
|
|
17
|
+
import { Stop } from './link.mjs';
|
|
18
|
+
import { CLIENT_HEADER, routesOf, updateLine, VERSION } from './wavie.mjs';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Their ChatGPT plan on this computer: OpenAI's open-source "Sign in with ChatGPT" (developers.openai.com/siwc). The
|
|
22
|
+
* sign-in runs here on 127.0.0.1, OpenAI issues this person a client id of their own at first sign-in (no secret), and
|
|
23
|
+
* the tokens stay in heywavie's folder, readable by them only. Wavie hears only that it is connected, who, and the models.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const AUTHORIZE = `${AUTH}/api/accounts/authorize`;
|
|
27
|
+
export const SCOPE = 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct';
|
|
28
|
+
const PLAN_SCOPE = 'chatgpt.tokens.use.direct';
|
|
29
|
+
// The first sign-in's client id: OpenAI issues the real one in the callback. Never saved.
|
|
30
|
+
const FIRST = 'dynamic_agent_client';
|
|
31
|
+
const PORT = 1455;
|
|
32
|
+
const CALLBACK = '/auth/callback';
|
|
33
|
+
const WAIT_MS = 10 * 60_000;
|
|
34
|
+
|
|
35
|
+
const b64url = (buf) => Buffer.from(buf).toString('base64url');
|
|
36
|
+
|
|
37
|
+
/** OpenAI's sign-in page for this attempt: the saved issued client id, else a first registration. */
|
|
38
|
+
export function authorizeUrl({ clientId, hostId, redirectUri, state, nonce, challenge }) {
|
|
39
|
+
const q = new URLSearchParams({
|
|
40
|
+
response_type: 'code',
|
|
41
|
+
client_id: clientId ?? FIRST,
|
|
42
|
+
// Only on the first registration, as OpenAI asks.
|
|
43
|
+
...(clientId ? {} : { agent_name_hint: 'heywavie' }),
|
|
44
|
+
ext_agent_host_id: hostId,
|
|
45
|
+
redirect_uri: redirectUri,
|
|
46
|
+
scope: SCOPE,
|
|
47
|
+
resource: OPENAI_API,
|
|
48
|
+
state,
|
|
49
|
+
nonce,
|
|
50
|
+
code_challenge: challenge,
|
|
51
|
+
code_challenge_method: 'S256',
|
|
52
|
+
});
|
|
53
|
+
return `${AUTHORIZE}?${q}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The client id this sign-in goes on with: the one OpenAI issued in the callback on a first registration (an answer
|
|
58
|
+
* without one is an incomplete registration), else the saved one, which a callback may leave out but never change.
|
|
59
|
+
*/
|
|
60
|
+
export function issuedClientId(saved, callback) {
|
|
61
|
+
const sent = callback.get('client_id');
|
|
62
|
+
if (!saved) {
|
|
63
|
+
if (!sent || sent === FIRST)
|
|
64
|
+
throw new Stop("ChatGPT's sign-in didn't finish registering heywavie for you. Run this again.");
|
|
65
|
+
return sent;
|
|
66
|
+
}
|
|
67
|
+
if (sent && sent !== saved) throw new Stop("ChatGPT answered for another registration than this computer's. Run this again.");
|
|
68
|
+
return saved;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The ID token checked as OpenAI asks (its signature by OpenAI's keys, issuer, audience, expiry, nonce): its claims. */
|
|
72
|
+
export async function checkIdToken(idToken, { clientId, nonce, fetch, now = Date.now() }) {
|
|
73
|
+
const [h, p, s] = String(idToken ?? '').split('.');
|
|
74
|
+
if (!h || !p || !s) throw new Stop("ChatGPT's sign-in sent no identity. Run this again.");
|
|
75
|
+
const header = JSON.parse(Buffer.from(h, 'base64url').toString('utf8'));
|
|
76
|
+
const claims = JSON.parse(Buffer.from(p, 'base64url').toString('utf8'));
|
|
77
|
+
const conf = await discovery(fetch);
|
|
78
|
+
const keys = (await (await fetch(conf.jwks_uri, { signal: AbortSignal.timeout(15_000) })).json())?.keys ?? [];
|
|
79
|
+
const jwk = keys.find((k) => k.kid === header.kid) ?? (keys.length === 1 ? keys[0] : null);
|
|
80
|
+
const data = Buffer.from(`${h}.${p}`);
|
|
81
|
+
const sig = Buffer.from(s, 'base64url');
|
|
82
|
+
let good = false;
|
|
83
|
+
if (jwk && header.alg === 'RS256') good = verify('sha256', data, createPublicKey({ key: jwk, format: 'jwk' }), sig);
|
|
84
|
+
else if (jwk && header.alg === 'ES256')
|
|
85
|
+
good = verify('sha256', data, { key: createPublicKey({ key: jwk, format: 'jwk' }), dsaEncoding: 'ieee-p1363' }, sig);
|
|
86
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
87
|
+
if (
|
|
88
|
+
!good ||
|
|
89
|
+
claims.iss !== (conf.issuer ?? AUTH) ||
|
|
90
|
+
!aud.includes(clientId) ||
|
|
91
|
+
!(claims.exp * 1000 > now) ||
|
|
92
|
+
claims.nonce !== nonce
|
|
93
|
+
)
|
|
94
|
+
throw new Stop("ChatGPT's sign-in came back with an identity heywavie can't trust. Run this again.");
|
|
95
|
+
return claims;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Waits on 127.0.0.1 (port 1455, else any free one) for OpenAI to send the browser back. A callback of another attempt
|
|
100
|
+
* (a wrong state) is refused and the wait goes on. Resolves `{ query, reply }`: `reply(words)` answers the browser.
|
|
101
|
+
*/
|
|
102
|
+
export async function callbackServer({ state, signal = null, port = PORT, waitMs = WAIT_MS }) {
|
|
103
|
+
let done;
|
|
104
|
+
let failed;
|
|
105
|
+
const got = new Promise((resolve, reject) => {
|
|
106
|
+
done = resolve;
|
|
107
|
+
failed = reject;
|
|
108
|
+
});
|
|
109
|
+
const server = http.createServer((req, res) => {
|
|
110
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
111
|
+
if (url.pathname !== CALLBACK) {
|
|
112
|
+
res.writeHead(404).end();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (url.searchParams.get('state') !== state) {
|
|
116
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
|
|
117
|
+
res.end("This isn't the sign-in heywavie started. Close this tab.");
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const reply = (words) => {
|
|
121
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
122
|
+
res.end(`<!doctype html><meta charset="utf-8"><title>heywavie</title><p style="font:15px system-ui;margin:40px">${words.replace(/</g, '<')}</p>`);
|
|
123
|
+
};
|
|
124
|
+
done({ query: url.searchParams, reply });
|
|
125
|
+
});
|
|
126
|
+
const listen = (p) =>
|
|
127
|
+
new Promise((resolve, reject) => {
|
|
128
|
+
server.once('error', reject);
|
|
129
|
+
server.listen(p, '127.0.0.1', () => {
|
|
130
|
+
server.off('error', reject);
|
|
131
|
+
resolve(server.address().port);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
let at;
|
|
135
|
+
try {
|
|
136
|
+
at = await listen(port);
|
|
137
|
+
} catch {
|
|
138
|
+
at = await listen(0);
|
|
139
|
+
}
|
|
140
|
+
const timer = setTimeout(() => failed(new Stop("ChatGPT's sign-in took too long. Run this again.")), waitMs);
|
|
141
|
+
const stop = () => failed(new Stop('The ChatGPT sign-in was stopped.'));
|
|
142
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
143
|
+
const close = () => {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
signal?.removeEventListener('abort', stop);
|
|
146
|
+
server.close();
|
|
147
|
+
server.closeAllConnections?.();
|
|
148
|
+
};
|
|
149
|
+
return { redirectUri: `http://127.0.0.1:${at}${CALLBACK}`, next: got, close };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The models this ChatGPT plan offers, in OpenAI's order: the slugs it lists. */
|
|
153
|
+
export async function planModels(fetch, access) {
|
|
154
|
+
const res = await fetch(`${OPENAI_API}/models`, {
|
|
155
|
+
headers: { authorization: `Bearer ${access}` },
|
|
156
|
+
signal: AbortSignal.timeout(30_000),
|
|
157
|
+
});
|
|
158
|
+
if (!res.ok) throw new Stop(`OpenAI didn't list your ChatGPT plan's models (${res.status}). Run this again.`);
|
|
159
|
+
const body = await res.json().catch(() => ({}));
|
|
160
|
+
return (body?.models ?? [])
|
|
161
|
+
.filter((m) => m?.visibility === 'list')
|
|
162
|
+
.map((m) => m.slug)
|
|
163
|
+
.filter((m) => typeof m === 'string');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Which of this computer's keys Wavie last heard ChatGPT from: a relink makes a new key, which Wavie must hear again. */
|
|
167
|
+
export const keyMark = (key) => createHash('sha256').update(String(key)).digest('base64url').slice(0, 16);
|
|
168
|
+
|
|
169
|
+
/** Wavie told this computer holds their ChatGPT plan, by its key: true once saved, else the Stop that says why. */
|
|
170
|
+
export async function tellWavie({ link, fetch, email, kind, models }) {
|
|
171
|
+
let res;
|
|
172
|
+
try {
|
|
173
|
+
res = await fetch(deviceChatgpt(link), {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: wavieHeaders(link),
|
|
176
|
+
body: JSON.stringify({ device: link.device, email, kind, models }),
|
|
177
|
+
signal: AbortSignal.timeout(30_000),
|
|
178
|
+
});
|
|
179
|
+
} catch (err) {
|
|
180
|
+
throw new Stop(`Failed to reach Wavie at ${link.api} (${err?.cause?.code ?? err?.message ?? err}). Run this again.`);
|
|
181
|
+
}
|
|
182
|
+
if (res.ok) return true;
|
|
183
|
+
const body = await res.json().catch(() => ({}));
|
|
184
|
+
if (res.status === 426) throw new Stop(updateLine(body));
|
|
185
|
+
if (res.status === 401)
|
|
186
|
+
throw new Stop('Wavie no longer knows this computer. Connect it again from Wavie (Thinks with, Claude).');
|
|
187
|
+
throw new Stop(`Wavie refused the ChatGPT plan (${res.status}${body?.message ? `: ${body.message}` : ''}).`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const wavieHeaders = (link) => ({ authorization: `Bearer ${link.key}`, 'content-type': 'application/json', ...CLIENT_HEADER });
|
|
191
|
+
const deviceChatgpt = (link) => `${routesOf(link.api)}/device/chatgpt`;
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Signs in with ChatGPT here and tells Wavie: on a computer linked already. `open(url)` opens their browser. The tokens
|
|
195
|
+
* are written only once Wavie took it, so a web disconnect check never finds a half-made sign-in.
|
|
196
|
+
*/
|
|
197
|
+
export async function chatgptSignIn({
|
|
198
|
+
home,
|
|
199
|
+
open,
|
|
200
|
+
fetch = globalThis.fetch,
|
|
201
|
+
log = console.log,
|
|
202
|
+
signal = null,
|
|
203
|
+
port = PORT,
|
|
204
|
+
waitMs = WAIT_MS,
|
|
205
|
+
installer = null,
|
|
206
|
+
now = Date.now,
|
|
207
|
+
}) {
|
|
208
|
+
const link = readLink(home);
|
|
209
|
+
if (!link)
|
|
210
|
+
throw new Stop(
|
|
211
|
+
'This computer is not connected to Wavie yet. Connect it first (Thinks with, Claude, in Wavie), then run this again.',
|
|
212
|
+
);
|
|
213
|
+
const client = readClient(home);
|
|
214
|
+
const hostId = client?.hostId ?? `urn:uuid:${randomUUID()}`;
|
|
215
|
+
if (!client?.hostId) writeClient(home, { hostId, clientId: null });
|
|
216
|
+
const saved = client?.clientId ?? null;
|
|
217
|
+
const state = b64url(randomBytes(24));
|
|
218
|
+
const nonce = b64url(randomBytes(24));
|
|
219
|
+
const verifier = b64url(randomBytes(48));
|
|
220
|
+
const challenge = b64url(createHash('sha256').update(verifier).digest());
|
|
221
|
+
|
|
222
|
+
const cb = await callbackServer({ state, signal, port, waitMs });
|
|
223
|
+
let reply = () => {};
|
|
224
|
+
try {
|
|
225
|
+
const url = authorizeUrl({ clientId: saved, hostId, redirectUri: cb.redirectUri, state, nonce, challenge });
|
|
226
|
+
log('Opening ChatGPT in your browser to sign in.');
|
|
227
|
+
log(`If it didn't open, go to: ${url}`);
|
|
228
|
+
await Promise.resolve(open(url)).catch(() => {});
|
|
229
|
+
const back = await cb.next;
|
|
230
|
+
reply = back.reply;
|
|
231
|
+
const q = back.query;
|
|
232
|
+
if (q.get('error') === 'access_denied') throw new Stop('You declined in ChatGPT, so nothing was connected.');
|
|
233
|
+
if (q.get('error')) throw new Stop(`ChatGPT's sign-in failed (${q.get('error')}). Run this again.`);
|
|
234
|
+
const clientId = issuedClientId(saved, q);
|
|
235
|
+
writeClient(home, { hostId, clientId });
|
|
236
|
+
const code = q.get('code');
|
|
237
|
+
if (!code) throw new Stop("ChatGPT's sign-in sent no code. Run this again.");
|
|
238
|
+
|
|
239
|
+
let tokens;
|
|
240
|
+
try {
|
|
241
|
+
tokens = await tokenCall(fetch, {
|
|
242
|
+
grant_type: 'authorization_code',
|
|
243
|
+
client_id: clientId,
|
|
244
|
+
code,
|
|
245
|
+
code_verifier: verifier,
|
|
246
|
+
redirect_uri: cb.redirectUri,
|
|
247
|
+
resource: OPENAI_API,
|
|
248
|
+
});
|
|
249
|
+
} catch (err) {
|
|
250
|
+
throw new Stop(`${err.message}. Run this again.`);
|
|
251
|
+
}
|
|
252
|
+
const scopes = String(tokens.scope ?? q.get('scope') ?? '').split(/\s+/).filter(Boolean);
|
|
253
|
+
if (!scopes.includes(PLAN_SCOPE))
|
|
254
|
+
throw new Stop(
|
|
255
|
+
"This ChatGPT account didn't allow its plan to be used by heywavie. Turn it on when ChatGPT asks, or use another account, then run this again.",
|
|
256
|
+
);
|
|
257
|
+
const claims = tokens.id_token ? await checkIdToken(tokens.id_token, { clientId, nonce, fetch, now: now() }) : {};
|
|
258
|
+
const before = readTokens(home);
|
|
259
|
+
if (before?.sub && claims.sub && before.sub !== claims.sub)
|
|
260
|
+
throw new Stop('This computer has another ChatGPT account connected. Run heywavie chatgpt --off first.');
|
|
261
|
+
const email = typeof claims.email === 'string' ? claims.email : null;
|
|
262
|
+
const kind = claims['https://api.openai.com/auth']?.chatgpt_plan_type ?? null;
|
|
263
|
+
const models = await planModels(fetch, tokens.access_token);
|
|
264
|
+
|
|
265
|
+
await tellWavie({ link, fetch, email, kind, models });
|
|
266
|
+
writeTokens(home, {
|
|
267
|
+
clientId,
|
|
268
|
+
hostId,
|
|
269
|
+
sub: claims.sub ?? null,
|
|
270
|
+
email,
|
|
271
|
+
kind,
|
|
272
|
+
idToken: tokens.id_token ?? null,
|
|
273
|
+
access: tokens.access_token,
|
|
274
|
+
refresh: tokens.refresh_token,
|
|
275
|
+
expiresAt: now() + Number(tokens.expires_in ?? 3600) * 1000,
|
|
276
|
+
scopes,
|
|
277
|
+
models,
|
|
278
|
+
wavieKey: keyMark(link.key),
|
|
279
|
+
savedAt: new Date(now()).toISOString(),
|
|
280
|
+
});
|
|
281
|
+
reply('ChatGPT is connected to Wavie on this computer. You can close this tab.');
|
|
282
|
+
|
|
283
|
+
// The service relays ChatGPT only from this version on: an older copy of it is replaced.
|
|
284
|
+
if (installer && appVersion(home) && appVersion(home) !== VERSION) {
|
|
285
|
+
const s = await installer({ home });
|
|
286
|
+
if (!s.ok) log(`The heywavie service couldn't be updated (${s.reason}). Run heywavie run, or connect again.`);
|
|
287
|
+
}
|
|
288
|
+
log(
|
|
289
|
+
`Your ChatGPT plan is connected to Wavie${email ? ` (${email})` : ''}. Sign-in and plan stay on this computer; Wavie uses it while this computer is on.`,
|
|
290
|
+
);
|
|
291
|
+
return { email, kind, models };
|
|
292
|
+
} catch (err) {
|
|
293
|
+
reply(err instanceof Stop ? err.message : "ChatGPT couldn't be connected. Run heywavie chatgpt again.");
|
|
294
|
+
throw err;
|
|
295
|
+
} finally {
|
|
296
|
+
cb.close();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** ChatGPT off this computer: revoked at OpenAI, the tokens gone, Wavie told (`tellWavie`). */
|
|
301
|
+
export async function chatgptOff({ home, fetch = globalThis.fetch, log = console.log, tellWavie = true, waitMs = 1000 }) {
|
|
302
|
+
const t = readTokens(home);
|
|
303
|
+
const confirmed = t ? await revoke(t, { fetch, waitMs }) : true;
|
|
304
|
+
dropTokens(home);
|
|
305
|
+
const link = readLink(home);
|
|
306
|
+
if (link && tellWavie) {
|
|
307
|
+
await fetch(deviceChatgpt(link), {
|
|
308
|
+
method: 'DELETE',
|
|
309
|
+
headers: wavieHeaders(link),
|
|
310
|
+
signal: AbortSignal.timeout(15_000),
|
|
311
|
+
}).catch(() => null);
|
|
312
|
+
}
|
|
313
|
+
if (!t) log('ChatGPT was not signed in on this computer.');
|
|
314
|
+
else if (confirmed) log('ChatGPT is signed out on this computer and disconnected from Wavie.');
|
|
315
|
+
else
|
|
316
|
+
log(
|
|
317
|
+
"ChatGPT's sign-in is gone from this computer, but OpenAI didn't confirm it ended. To be sure, remove heywavie under Connected apps in ChatGPT's settings.",
|
|
318
|
+
);
|
|
319
|
+
return { revoked: confirmed };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Whether Wavie still has this computer's ChatGPT plan: false only when it said so. */
|
|
323
|
+
export async function wavieHasChatgpt({ link, fetch = globalThis.fetch }) {
|
|
324
|
+
const res = await fetch(deviceChatgpt(link), { headers: wavieHeaders(link), signal: AbortSignal.timeout(15_000) }).catch(
|
|
325
|
+
() => null,
|
|
326
|
+
);
|
|
327
|
+
if (!res?.ok) return null;
|
|
328
|
+
const body = await res.json().catch(() => null);
|
|
329
|
+
return typeof body?.connected === 'boolean' ? body.connected : null;
|
|
330
|
+
}
|