@okhay-p/mivra 0.1.2 → 0.1.4

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.
Files changed (48) hide show
  1. package/README.md +1 -0
  2. package/THIRD_PARTY_NOTICES.md +4 -0
  3. package/dist/chunk-KE5ZEREE.js +212 -0
  4. package/dist/chunk-KE5ZEREE.js.map +7 -0
  5. package/dist/chunk-KUKQU7EQ.js +755 -0
  6. package/dist/chunk-KUKQU7EQ.js.map +7 -0
  7. package/dist/chunk-ODFBAPPH.js +489 -0
  8. package/dist/chunk-ODFBAPPH.js.map +7 -0
  9. package/dist/chunk-PZ5AY32C.js +10 -0
  10. package/dist/chunk-PZ5AY32C.js.map +7 -0
  11. package/dist/chunk-TBAR47I6.js +32 -0
  12. package/dist/chunk-TBAR47I6.js.map +7 -0
  13. package/dist/chunk-YACRW47X.js +1203 -0
  14. package/dist/chunk-YACRW47X.js.map +7 -0
  15. package/dist/cli.js +256 -11188
  16. package/dist/cli.js.map +4 -4
  17. package/dist/client-5YDLS4KV.js +12 -0
  18. package/dist/client-5YDLS4KV.js.map +7 -0
  19. package/dist/extract-child.js +107 -173
  20. package/dist/extract-child.js.map +3 -3
  21. package/dist/key-check-WJ4CVZV5.js +8 -0
  22. package/dist/key-check-WJ4CVZV5.js.map +7 -0
  23. package/dist/start-76LKE3DL.js +13906 -0
  24. package/dist/start-76LKE3DL.js.map +7 -0
  25. package/drizzle/0012_overconfident_the_santerians.sql +66 -0
  26. package/drizzle/0013_next_dormammu.sql +1 -0
  27. package/drizzle/0014_furry_inertia.sql +1 -0
  28. package/drizzle/0015_spotty_warstar.sql +1 -0
  29. package/drizzle/0016_fresh_wiccan.sql +1 -0
  30. package/drizzle/0017_amusing_james_howlett.sql +28 -0
  31. package/drizzle/0018_happy_hairball.sql +43 -0
  32. package/drizzle/meta/0012_snapshot.json +1741 -0
  33. package/drizzle/meta/0013_snapshot.json +1749 -0
  34. package/drizzle/meta/0014_snapshot.json +1756 -0
  35. package/drizzle/meta/0015_snapshot.json +1763 -0
  36. package/drizzle/meta/0016_snapshot.json +1770 -0
  37. package/drizzle/meta/0017_snapshot.json +1956 -0
  38. package/drizzle/meta/0018_snapshot.json +2280 -0
  39. package/drizzle/meta/_journal.json +49 -0
  40. package/package.json +2 -1
  41. package/web/assets/index-C_DsRKCc.css +1 -0
  42. package/web/assets/index-DbKDW1xS.js +413 -0
  43. package/web/assets/notes-graph.worker-DaVQvftJ.js +1 -0
  44. package/web/assets/render.worker-BAfybD27.js +416 -0
  45. package/web/index.html +2 -2
  46. package/web/assets/index-BfT-sp3_.js +0 -406
  47. package/web/assets/index-FIC4B_yh.css +0 -1
  48. package/web/assets/render.worker-Bw6rO7Qu.js +0 -413
@@ -0,0 +1,755 @@
1
+ // ../server/src/chatgpt/oauth.ts
2
+ import { createHash, createPublicKey, randomBytes, timingSafeEqual, verify } from "node:crypto";
3
+ import { z } from "zod";
4
+ var ISSUER = "https://auth.openai.com";
5
+ var CHATGPT_API = "https://api.openai.com/v1";
6
+ var SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
7
+ var DIRECT_SCOPE = "chatgpt.tokens.use.direct";
8
+ var REGISTRATION_CLIENT = "dynamic_agent_client";
9
+ var CALLBACK_PATH = "/auth/callback";
10
+ var APP_NAME = "Mivra";
11
+ var TIMEOUT_MS = 15e3;
12
+ var CLOCK_TOLERANCE_S = 30;
13
+ var ChatGptError = class extends Error {
14
+ constructor(code, message, retryable = false) {
15
+ super(message);
16
+ this.code = code;
17
+ this.retryable = retryable;
18
+ this.name = "ChatGptError";
19
+ }
20
+ code;
21
+ retryable;
22
+ };
23
+ var TERMINAL_REFRESH_ERRORS = /* @__PURE__ */ new Set([
24
+ "invalid_grant",
25
+ "invalid_refresh_token",
26
+ "token_expired",
27
+ "refresh_token_expired",
28
+ "refresh_token_invalidated",
29
+ "refresh_token_reused"
30
+ ]);
31
+ var MESSAGES = {
32
+ access_denied: "Sign-in wasn't completed. You can try again when you're ready.",
33
+ invalid_client: "ChatGPT didn't accept Mivra's registration. Sign in again with a different account to register afresh.",
34
+ subscription_sharing_user_not_eligible: "This ChatGPT account or workspace can't share its plan with apps. Sign-in with ChatGPT needs an eligible Plus or Pro plan."
35
+ };
36
+ var SIGN_IN_AGAIN = "Your ChatGPT sign-in has expired. Sign in again under Model providers.";
37
+ function oauthError(body, status) {
38
+ const code = errorCode(body) ?? (status ? `http_${status}` : "unknown_error");
39
+ if (TERMINAL_REFRESH_ERRORS.has(code)) return new ChatGptError(code, SIGN_IN_AGAIN);
40
+ const message = MESSAGES[code];
41
+ if (message) return new ChatGptError(code, message);
42
+ const retryable = status === void 0 || status >= 500 || status === 429;
43
+ return new ChatGptError(code, retryable ? "ChatGPT's sign-in service is unavailable. Try again shortly." : "ChatGPT sign-in failed. Try again.", retryable);
44
+ }
45
+ function errorCode(body) {
46
+ if (!body || typeof body !== "object") return void 0;
47
+ const error = body.error;
48
+ const code = typeof error === "string" ? error : error && typeof error === "object" ? error.code : void 0;
49
+ return typeof code === "string" && /^[a-z0-9_.-]{1,100}$/i.test(code) ? code : void 0;
50
+ }
51
+ var randomValue = () => randomBytes(32).toString("base64url");
52
+ var sha256 = (value) => createHash("sha256").update(value).digest("base64url");
53
+ function sameSecret(a, b) {
54
+ const left = Buffer.from(a);
55
+ const right = Buffer.from(b);
56
+ return left.length === right.length && timingSafeEqual(left, right);
57
+ }
58
+ var Discovery = z.object({
59
+ issuer: z.literal(ISSUER),
60
+ authorization_endpoint: z.string().url(),
61
+ token_endpoint: z.string().url(),
62
+ jwks_uri: z.string().url(),
63
+ revocation_endpoint: z.string().url().optional()
64
+ });
65
+ var TokenResponse = z.object({
66
+ access_token: z.string().min(1).max(2e4),
67
+ token_type: z.string().refine((t) => t.toLowerCase() === "bearer"),
68
+ expires_in: z.number().positive().max(366 * 24 * 3600),
69
+ refresh_token: z.string().min(1).max(2e4).optional(),
70
+ id_token: z.string().min(1).max(2e4).optional(),
71
+ scope: z.string().max(2e3).optional()
72
+ });
73
+ function createOAuthClient({ fetch: fetchImpl = fetch, clock = Date.now } = {}) {
74
+ let discovery;
75
+ let jwks;
76
+ async function request(url, init = {}) {
77
+ let response;
78
+ try {
79
+ response = await fetchImpl(url, { ...init, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
80
+ } catch {
81
+ throw new ChatGptError("network_error", "Couldn't reach ChatGPT. Check your connection and try again.", true);
82
+ }
83
+ const text = await response.text().catch(() => "");
84
+ let body;
85
+ try {
86
+ body = text ? JSON.parse(text) : void 0;
87
+ } catch {
88
+ body = void 0;
89
+ }
90
+ return { status: response.status, body };
91
+ }
92
+ function config() {
93
+ discovery ??= (async () => {
94
+ const { status, body } = await request(`${ISSUER}/.well-known/openid-configuration`, { headers: { accept: "application/json" } });
95
+ const parsed = Discovery.safeParse(body);
96
+ const sameOrigin = parsed.success && [parsed.data.authorization_endpoint, parsed.data.token_endpoint, parsed.data.jwks_uri, parsed.data.revocation_endpoint].every((url) => url === void 0 || new URL(url).origin === ISSUER);
97
+ if (status !== 200 || !parsed.success || !sameOrigin) {
98
+ throw new ChatGptError("discovery_failed", "ChatGPT's sign-in configuration couldn't be verified. Try again shortly.", true);
99
+ }
100
+ return parsed.data;
101
+ })().catch((error) => {
102
+ discovery = void 0;
103
+ throw error;
104
+ });
105
+ return discovery;
106
+ }
107
+ async function tokenRequest(params) {
108
+ const { token_endpoint } = await config();
109
+ const { status, body } = await request(token_endpoint, {
110
+ method: "POST",
111
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
112
+ body: new URLSearchParams(params)
113
+ });
114
+ if (status !== 200) throw oauthError(body, status);
115
+ const parsed = TokenResponse.safeParse(body);
116
+ if (!parsed.success) throw new ChatGptError("invalid_token_response", "ChatGPT returned incomplete credentials. Sign in again.");
117
+ return parsed.data;
118
+ }
119
+ async function signingKey(kid) {
120
+ const { jwks_uri } = await config();
121
+ const find = () => jwks?.keys.find((k) => k.kty === "RSA" && (kid === void 0 || k.kid === kid));
122
+ if (!jwks || jwks.uri !== jwks_uri || !find() && clock() - jwks.loadedAt > 6e4) {
123
+ const { status, body } = await request(jwks_uri, { headers: { accept: "application/json" } });
124
+ const keys = body?.keys;
125
+ if (status !== 200 || !Array.isArray(keys)) {
126
+ throw new ChatGptError("identity_unavailable", "ChatGPT's identity check is unavailable. Try again shortly.", true);
127
+ }
128
+ jwks = { uri: jwks_uri, keys, loadedAt: clock() };
129
+ }
130
+ const key = find();
131
+ if (!key) throw invalidIdentity();
132
+ return key;
133
+ }
134
+ async function verifyIdToken(idToken, clientId, nonce) {
135
+ const parts = idToken.split(".");
136
+ if (parts.length !== 3) throw invalidIdentity();
137
+ const [headerPart, payloadPart, signaturePart] = parts;
138
+ let header;
139
+ let claims;
140
+ try {
141
+ header = JSON.parse(Buffer.from(headerPart, "base64url").toString("utf8"));
142
+ claims = JSON.parse(Buffer.from(payloadPart, "base64url").toString("utf8"));
143
+ } catch {
144
+ throw invalidIdentity();
145
+ }
146
+ if (header.alg !== "RS256" || !claims || typeof claims !== "object") throw invalidIdentity();
147
+ const jwk = await signingKey(typeof header.kid === "string" ? header.kid : void 0);
148
+ let valid;
149
+ try {
150
+ valid = verify("RSA-SHA256", Buffer.from(`${headerPart}.${payloadPart}`), createPublicKey({ key: jwk, format: "jwk" }), Buffer.from(signaturePart, "base64url"));
151
+ } catch {
152
+ valid = false;
153
+ }
154
+ const now = clock() / 1e3;
155
+ const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
156
+ if (!valid || claims.iss !== ISSUER || !audience.includes(clientId) || audience.length > 1 && claims.azp !== clientId || claims.azp !== void 0 && claims.azp !== clientId || typeof claims.exp !== "number" || claims.exp + CLOCK_TOLERANCE_S < now || typeof claims.iat !== "number" || typeof claims.sub !== "string" || !claims.sub || nonce !== void 0 && (typeof claims.nonce !== "string" || !sameSecret(claims.nonce, nonce))) {
157
+ throw invalidIdentity();
158
+ }
159
+ const text = (value) => typeof value === "string" && value.length <= 320 ? value : null;
160
+ return { subject: claims.sub, email: text(claims.email), name: text(claims.name) };
161
+ }
162
+ const tokensFrom = (data, fallback = {}) => {
163
+ const refreshToken = data.refresh_token ?? fallback.refreshToken;
164
+ const idToken = data.id_token ?? fallback.idToken;
165
+ const scopes = data.scope !== void 0 ? data.scope.split(/\s+/).filter(Boolean) : fallback.scopes ?? [];
166
+ if (!refreshToken || !idToken) throw new ChatGptError("invalid_token_response", "ChatGPT returned incomplete credentials. Sign in again.");
167
+ if (!scopes.includes(DIRECT_SCOPE)) {
168
+ throw new ChatGptError("scope_not_granted", "ChatGPT didn't grant Mivra use of your plan. Sign in again and allow it.");
169
+ }
170
+ return { accessToken: data.access_token, refreshToken, expiresAt: clock() + data.expires_in * 1e3, scopes, idToken };
171
+ };
172
+ return {
173
+ /** The authorize URL for a new sign-in, with fresh state, nonce and PKCE verifier. */
174
+ async authorize({ redirectUri, hostId, clientId, loginHint }) {
175
+ const { authorization_endpoint } = await config();
176
+ const state = randomValue();
177
+ const nonce = randomValue();
178
+ const verifier = randomValue();
179
+ const url = new URL(authorization_endpoint);
180
+ url.search = new URLSearchParams({
181
+ client_id: clientId ?? REGISTRATION_CLIENT,
182
+ response_type: "code",
183
+ redirect_uri: redirectUri,
184
+ scope: SCOPES,
185
+ resource: CHATGPT_API,
186
+ state,
187
+ nonce,
188
+ code_challenge_method: "S256",
189
+ code_challenge: sha256(verifier),
190
+ ext_agent_host_id: hostId
191
+ }).toString();
192
+ if (!clientId) url.searchParams.set("agent_name_hint", APP_NAME);
193
+ if (clientId && loginHint) url.searchParams.set("login_hint", loginHint);
194
+ return { url: url.toString(), state, nonce, verifier, redirectUri, clientId: clientId ?? null };
195
+ },
196
+ /** Exchanges the code from a validated callback, and verifies who signed in. */
197
+ async exchange(pending, callback) {
198
+ const data = await tokenRequest({
199
+ grant_type: "authorization_code",
200
+ client_id: callback.clientId,
201
+ code: callback.code,
202
+ code_verifier: pending.verifier,
203
+ redirect_uri: pending.redirectUri,
204
+ resource: CHATGPT_API
205
+ });
206
+ if (!data.id_token) throw new ChatGptError("invalid_token_response", "ChatGPT didn't say which account signed in. Try again.");
207
+ const identity = await verifyIdToken(data.id_token, callback.clientId, pending.nonce);
208
+ return { tokens: tokensFrom(data), identity };
209
+ },
210
+ /** Renews a session. The refresh token rotates: the old one stops working once this succeeds. */
211
+ async refresh(clientId, tokens) {
212
+ const data = await tokenRequest({ grant_type: "refresh_token", client_id: clientId, refresh_token: tokens.refreshToken, resource: CHATGPT_API });
213
+ return tokensFrom(data, tokens);
214
+ },
215
+ verifyIdToken,
216
+ /** Ends a session at OpenAI. Resolves false when that couldn't be confirmed. */
217
+ async revoke(clientId, refreshToken) {
218
+ try {
219
+ const { revocation_endpoint } = await config();
220
+ if (!revocation_endpoint) return false;
221
+ const { status } = await request(revocation_endpoint, {
222
+ method: "POST",
223
+ headers: { "content-type": "application/x-www-form-urlencoded" },
224
+ body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token", client_id: clientId })
225
+ });
226
+ return status === 200;
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+ };
232
+ }
233
+ var invalidIdentity = () => new ChatGptError("invalid_id_token", "ChatGPT's answer about who signed in couldn't be verified. Sign in again.");
234
+ var CLIENT_ID = /^[A-Za-z0-9_-]{1,200}$/;
235
+ function readCallback(params, pending) {
236
+ const state = params.getAll("state");
237
+ if (state.length !== 1 || !sameSecret(state[0], pending.state)) return "wrong-state";
238
+ if (params.has("error")) return { ok: false, error: oauthError({ error: params.get("error") }) };
239
+ const codes = params.getAll("code");
240
+ const clientIds = params.getAll("client_id");
241
+ const clientId = clientIds[0] ?? pending.clientId;
242
+ if (codes.length !== 1 || !codes[0] || clientIds.length > 1 || !clientId || !CLIENT_ID.test(clientId) || clientId === REGISTRATION_CLIENT || pending.clientId !== null && clientIds.length === 1 && clientIds[0] !== pending.clientId) {
243
+ return { ok: false, error: new ChatGptError("registration_incomplete", "ChatGPT didn't finish registering Mivra. Try signing in again.") };
244
+ }
245
+ return { ok: true, code: codes[0], clientId };
246
+ }
247
+
248
+ // ../server/src/chatgpt/session.ts
249
+ import { randomBytes as randomBytes2, randomUUID } from "node:crypto";
250
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
251
+ import { createServer } from "node:http";
252
+ import { join } from "node:path";
253
+ import { z as z2 } from "zod";
254
+ var CHATGPT_FILE = "chatgpt.json";
255
+ var CALLBACK_PORT = 1455;
256
+ var SIGN_IN_TIMEOUT_MS = 10 * 60 * 1e3;
257
+ var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
258
+ var SIGNED_OUT = "Sign in with ChatGPT under Model providers first.";
259
+ var TokensSchema = z2.object({
260
+ accessToken: z2.string().min(1),
261
+ refreshToken: z2.string().min(1),
262
+ expiresAt: z2.number(),
263
+ scopes: z2.array(z2.string()),
264
+ idToken: z2.string().min(1)
265
+ });
266
+ var FileSchema = z2.object({
267
+ version: z2.literal(1),
268
+ /** Sent as `ext_agent_host_id`: made once per install, never a secret. */
269
+ hostId: z2.string().min(1).max(200),
270
+ /** The client id ChatGPT issued for this account, kept after sign-out so signing in again reuses it. */
271
+ registration: z2.object({ clientId: z2.string().min(1), subject: z2.string().min(1), email: z2.string().nullable(), name: z2.string().nullable() }).nullable(),
272
+ tokens: TokensSchema.nullable(),
273
+ /** Why the learner was signed out, when Mivra did it (an expired session, say). */
274
+ notice: z2.string().nullable(),
275
+ /** The one-time "You're using your ChatGPT plan" dialog has been shown (OpenAI's guidelines: once, ever). */
276
+ welcomed: z2.boolean().default(false)
277
+ });
278
+ function chatGptFileStore(dataDir) {
279
+ const path = join(dataDir, CHATGPT_FILE);
280
+ let warned = false;
281
+ return {
282
+ load() {
283
+ let text;
284
+ try {
285
+ text = readFileSync(path, "utf8");
286
+ } catch {
287
+ return void 0;
288
+ }
289
+ const parsed = FileSchema.safeParse((() => {
290
+ try {
291
+ return JSON.parse(text);
292
+ } catch {
293
+ return void 0;
294
+ }
295
+ })());
296
+ if (parsed.success) return parsed.data;
297
+ if (!warned) console.warn(`${path} isn't valid, so the ChatGPT sign-in in it is ignored. Sign in again to replace it.`);
298
+ warned = true;
299
+ return void 0;
300
+ },
301
+ save(file) {
302
+ mkdirSync(dataDir, { recursive: true });
303
+ const temp = `${path}.${randomBytes2(6).toString("hex")}.tmp`;
304
+ try {
305
+ writeFileSync(temp, `${JSON.stringify(file, null, 2)}
306
+ `, { mode: 384 });
307
+ chmodSync(temp, 384);
308
+ renameSync(temp, path);
309
+ } catch (error) {
310
+ rmSync(temp, { force: true });
311
+ throw error;
312
+ }
313
+ }
314
+ };
315
+ }
316
+ function createChatGptSession({ store, oauth = createOAuthClient(), clock = Date.now, callbackPort = CALLBACK_PORT, signInTimeoutMs = SIGN_IN_TIMEOUT_MS }) {
317
+ let pending;
318
+ let refreshing;
319
+ let lastError = null;
320
+ const load = () => store.load() ?? { version: 1, hostId: `urn:uuid:${randomUUID()}`, registration: null, tokens: null, notice: null, welcomed: false };
321
+ const save = (file) => store.save(file);
322
+ function view() {
323
+ const file = store.load();
324
+ const signedIn = Boolean(file?.tokens && file.registration);
325
+ return {
326
+ signedIn,
327
+ email: signedIn ? file.registration.email : null,
328
+ name: signedIn ? file.registration.name : null,
329
+ pending: pending !== void 0 && !pending.settled,
330
+ previous: !signedIn && file?.registration ? file.registration.email ?? "your previous account" : null,
331
+ notice: lastError ?? (signedIn ? null : file?.notice ?? null),
332
+ welcome: signedIn && !file.welcomed
333
+ };
334
+ }
335
+ const stillCurrent = (clientId, refreshToken) => {
336
+ const file = store.load();
337
+ return file?.registration?.clientId === clientId && file.tokens?.refreshToken === refreshToken;
338
+ };
339
+ function endSession(clientId, refreshToken, notice) {
340
+ if (!stillCurrent(clientId, refreshToken)) return;
341
+ save({ ...load(), tokens: null, notice });
342
+ }
343
+ async function refresh() {
344
+ const file = load();
345
+ if (!file.tokens || !file.registration) throw new ChatGptError("signed_out", SIGNED_OUT);
346
+ if (file.tokens.expiresAt - clock() > REFRESH_MARGIN_MS) return file.tokens.accessToken;
347
+ const { clientId, subject } = file.registration;
348
+ const spent = file.tokens.refreshToken;
349
+ let tokens;
350
+ try {
351
+ tokens = await oauth.refresh(clientId, file.tokens);
352
+ } catch (error) {
353
+ if (error instanceof ChatGptError && (TERMINAL_REFRESH_ERRORS.has(error.code) || error.code === "scope_not_granted")) endSession(clientId, spent, error.message);
354
+ throw error;
355
+ }
356
+ if (!stillCurrent(clientId, spent)) {
357
+ void oauth.revoke(clientId, tokens.refreshToken);
358
+ throw new ChatGptError("signed_out", SIGNED_OUT);
359
+ }
360
+ save({ ...load(), tokens, notice: null });
361
+ if (tokens.idToken !== file.tokens.idToken) {
362
+ try {
363
+ const identity = await oauth.verifyIdToken(tokens.idToken, clientId);
364
+ if (identity.subject !== subject) throw new ChatGptError("account_mismatch", "ChatGPT renewed the sign-in for a different account.");
365
+ } catch (error) {
366
+ if (!(error instanceof ChatGptError) || error.retryable) return tokens.accessToken;
367
+ endSession(clientId, tokens.refreshToken, "ChatGPT's renewed sign-in couldn't be verified. Sign in again under Model providers.");
368
+ throw error;
369
+ }
370
+ }
371
+ return tokens.accessToken;
372
+ }
373
+ async function finish(current, callback) {
374
+ try {
375
+ const { tokens, identity } = await oauth.exchange(current.auth, callback);
376
+ if (current.settled) {
377
+ void oauth.revoke(callback.clientId, tokens.refreshToken);
378
+ return { ...view(), pending: false };
379
+ }
380
+ const file = load();
381
+ if (current.auth.clientId && file.registration && file.registration.subject !== identity.subject) {
382
+ throw new ChatGptError("account_mismatch", `You signed in to a different account than ${file.registration.email ?? "before"}. To switch accounts, choose "Use a different account".`);
383
+ }
384
+ save({ ...file, registration: { clientId: callback.clientId, subject: identity.subject, email: identity.email, name: identity.name }, tokens, notice: null });
385
+ lastError = null;
386
+ } catch (error) {
387
+ lastError = error instanceof ChatGptError ? error.message : "Sign-in with ChatGPT failed. Try again.";
388
+ }
389
+ const result = { ...view(), pending: false };
390
+ current.finish(result);
391
+ return result;
392
+ }
393
+ function close(current) {
394
+ current.settled = true;
395
+ clearTimeout(current.timer);
396
+ current.server.close();
397
+ current.server.closeIdleConnections();
398
+ if (pending === current) pending = void 0;
399
+ current.finish({ ...view(), pending: false });
400
+ }
401
+ async function listen(server) {
402
+ for (const port of callbackPort === 0 ? [0] : [callbackPort, 0]) {
403
+ try {
404
+ await new Promise((resolve, reject) => {
405
+ server.once("error", reject);
406
+ server.listen({ port, host: "127.0.0.1" }, () => {
407
+ server.off("error", reject);
408
+ resolve();
409
+ });
410
+ });
411
+ return server.address().port;
412
+ } catch (error) {
413
+ if (error.code !== "EADDRINUSE") throw error;
414
+ }
415
+ }
416
+ throw new ChatGptError("callback_port_unavailable", "Mivra couldn't listen for ChatGPT's answer. Try again.");
417
+ }
418
+ return {
419
+ view,
420
+ /** Changes when the learner signs in to another account or out, so what depends on the account can rebuild. */
421
+ signature() {
422
+ const file = store.load();
423
+ return file?.tokens && file.registration ? file.registration.subject : "";
424
+ },
425
+ /** A valid access token, renewed first when it's close to expiring. Throws a ChatGptError when signed out. */
426
+ accessToken() {
427
+ const file = store.load();
428
+ if (!file?.tokens || !file.registration) return Promise.reject(new ChatGptError("signed_out", SIGNED_OUT));
429
+ if (file.tokens.expiresAt - clock() > REFRESH_MARGIN_MS) return Promise.resolve(file.tokens.accessToken);
430
+ refreshing ??= refresh().finally(() => refreshing = void 0);
431
+ return refreshing;
432
+ },
433
+ /**
434
+ * Starts a sign-in: listens on 127.0.0.1 for the callback and returns the URL to open. A sign-in already
435
+ * waiting is cancelled. `newAccount` registers afresh instead of reusing the saved registration.
436
+ */
437
+ async startSignIn({ newAccount = false } = {}) {
438
+ if (pending) close(pending);
439
+ lastError = null;
440
+ const file = load();
441
+ if (!store.load()) save(file);
442
+ const registration = newAccount ? null : file.registration;
443
+ let resolveDone;
444
+ const done = new Promise((resolve) => resolveDone = resolve);
445
+ const server = createServer();
446
+ server.requestTimeout = 3e4;
447
+ server.headersTimeout = 1e4;
448
+ const port = await listen(server);
449
+ const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`;
450
+ let auth;
451
+ try {
452
+ auth = await oauth.authorize({ redirectUri, hostId: file.hostId, clientId: registration?.clientId, loginHint: registration?.email });
453
+ } catch (error) {
454
+ server.close();
455
+ throw error;
456
+ }
457
+ const current = {
458
+ auth,
459
+ server,
460
+ settled: false,
461
+ claimed: false,
462
+ finish: resolveDone,
463
+ timer: setTimeout(() => {
464
+ if (current.settled || current.claimed) return;
465
+ lastError = "Sign-in timed out. Start it again when you're ready.";
466
+ close(current);
467
+ }, signInTimeoutMs)
468
+ };
469
+ current.timer.unref();
470
+ pending = current;
471
+ server.on("request", (request, response) => {
472
+ response.setHeader("Cache-Control", "no-store");
473
+ response.setHeader("Referrer-Policy", "no-referrer");
474
+ response.setHeader("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'");
475
+ let url;
476
+ try {
477
+ url = new URL(request.url ?? "/", redirectUri);
478
+ } catch {
479
+ }
480
+ if (!url || request.method !== "GET" || request.headers.host !== `127.0.0.1:${port}` || url.pathname !== CALLBACK_PATH || current.settled || current.claimed) {
481
+ response.writeHead(404).end("Not found");
482
+ return;
483
+ }
484
+ const callback = readCallback(url.searchParams, auth);
485
+ if (callback === "wrong-state") {
486
+ response.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(page("This sign-in link is out of date", "Go back to Mivra and start signing in again."));
487
+ return;
488
+ }
489
+ const reply = (result) => response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(
490
+ result.signedIn ? page("Signed in to ChatGPT", "Mivra can now use your ChatGPT plan. You can close this tab and go back to Mivra.") : page("Sign-in didn't finish", `${result.notice ?? "Something went wrong."} Go back to Mivra to try again.`)
491
+ );
492
+ if (!callback.ok) {
493
+ lastError = callback.error.message;
494
+ close(current);
495
+ const result = view();
496
+ resolveDone(result);
497
+ reply(result);
498
+ return;
499
+ }
500
+ current.claimed = true;
501
+ void finish(current, callback).then((result) => {
502
+ reply(result);
503
+ close(current);
504
+ });
505
+ });
506
+ return { url: auth.url, redirectUri, done };
507
+ },
508
+ /**
509
+ * Finishes the pending sign-in from the address the browser ended on, for when the browser can't reach this
510
+ * machine's 127.0.0.1 (Mivra on another computer, or in Docker).
511
+ */
512
+ async completeSignIn(address) {
513
+ const current = pending;
514
+ if (!current || current.settled || current.claimed) throw new ChatGptError("no_sign_in", "No sign-in is waiting. Start one first.");
515
+ let params;
516
+ try {
517
+ const trimmed = address.trim();
518
+ params = trimmed.startsWith("http") ? new URL(trimmed).searchParams : new URLSearchParams(trimmed.replace(/^[^?]*\?/, ""));
519
+ } catch {
520
+ throw new ChatGptError("bad_address", "That isn't the address from the browser. Copy the whole address after approving.");
521
+ }
522
+ const callback = readCallback(params, current.auth);
523
+ if (callback === "wrong-state") {
524
+ throw new ChatGptError("wrong_state", params.has("state") ? "That address is from a different sign-in. Use the one from the sign-in you just started." : "That isn't the address from the browser. Copy the whole address after approving.");
525
+ }
526
+ if (!callback.ok) {
527
+ lastError = callback.error.message;
528
+ close(current);
529
+ const result = view();
530
+ current.finish(result);
531
+ return result;
532
+ }
533
+ current.claimed = true;
534
+ try {
535
+ return await finish(current, callback);
536
+ } finally {
537
+ close(current);
538
+ }
539
+ },
540
+ cancelSignIn() {
541
+ if (pending) close(pending);
542
+ },
543
+ /** Signs out: ends the session at OpenAI and forgets the tokens, keeping the registration for next time. */
544
+ async signOut() {
545
+ const file = store.load();
546
+ if (!file?.tokens || !file.registration) return { revoked: true };
547
+ save({ ...file, tokens: null, notice: null });
548
+ const revoked = await oauth.revoke(file.registration.clientId, file.tokens.refreshToken);
549
+ lastError = revoked ? null : "Signed out of Mivra, but ChatGPT didn't confirm it. To be sure, disconnect Mivra in ChatGPT's settings.";
550
+ return { revoked };
551
+ },
552
+ /** Records that the welcome dialog was shown, so it never shows again. */
553
+ welcomed() {
554
+ const file = store.load();
555
+ if (file && !file.welcomed) save({ ...file, welcomed: true });
556
+ },
557
+ /** Stops listening for a callback; for shutdown and tests. */
558
+ close() {
559
+ if (pending) close(pending);
560
+ }
561
+ };
562
+ }
563
+ var escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
564
+ function page(title, body) {
565
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mivra</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px;color:#1f1b16;background:#faf7f2}h1{font-size:1.4rem}@media (prefers-color-scheme:dark){body{color:#ece6dc;background:#1b1916}}</style></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p></body></html>`;
566
+ }
567
+
568
+ // ../server/src/credentials.ts
569
+ import { randomBytes as randomBytes3 } from "node:crypto";
570
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
571
+ import { join as join2 } from "node:path";
572
+ import { z as z3 } from "zod";
573
+ var providerIds = ["openrouter", "anthropic", "openai"];
574
+ var PROVIDER_LABELS = { openrouter: "OpenRouter", anthropic: "Anthropic", openai: "OpenAI" };
575
+ var PROVIDER_ENV = {
576
+ openrouter: "OPENROUTER_API_KEY",
577
+ anthropic: "ANTHROPIC_API_KEY",
578
+ openai: "OPENAI_API_KEY"
579
+ };
580
+ var CREDENTIALS_FILE = "credentials.json";
581
+ var ApiKey = z3.string().trim().min(8, "That's too short to be an API key").max(500, "That's too long to be an API key").regex(/^[\x21-\x7e]+$/, "An API key has no spaces or special characters");
582
+ var CredentialsFile = z3.object({ keys: z3.record(z3.string(), z3.string()).default({}) });
583
+ var hintFor = (key) => key.length >= 12 ? key.slice(-4) : null;
584
+ function credentialStore(envVar, saved) {
585
+ const fromEnv = (provider) => envVar(PROVIDER_ENV[provider]);
586
+ const customName = (id) => `custom:${id}`;
587
+ return {
588
+ keys() {
589
+ const stored = saved.load();
590
+ return Object.fromEntries(providerIds.flatMap((p) => {
591
+ const key = fromEnv(p) ?? stored[p];
592
+ return key ? [[p, key]] : [];
593
+ }));
594
+ },
595
+ views() {
596
+ const stored = saved.load();
597
+ return providerIds.map((id) => {
598
+ const env = fromEnv(id);
599
+ const key = env ?? stored[id];
600
+ return { id, label: PROVIDER_LABELS[id], source: env ? "env" : key ? "saved" : null, hint: key ? hintFor(key) : null };
601
+ });
602
+ },
603
+ set(provider, key) {
604
+ if (fromEnv(provider)) return { ok: false, reason: "env" };
605
+ saved.save({ ...saved.load(), [provider]: ApiKey.parse(key) });
606
+ return { ok: true };
607
+ },
608
+ remove(provider) {
609
+ if (fromEnv(provider)) return "env";
610
+ const stored = saved.load();
611
+ if (!(provider in stored)) return false;
612
+ delete stored[provider];
613
+ saved.save(stored);
614
+ return true;
615
+ },
616
+ customKey(id, envName) {
617
+ const env = envVar(envName);
618
+ if (env) return { key: env, source: "env" };
619
+ const key = saved.load()[customName(id)];
620
+ return key ? { key, source: "saved" } : { key: void 0, source: null };
621
+ },
622
+ setCustomKey(id, key) {
623
+ saved.save({ ...saved.load(), [customName(id)]: ApiKey.parse(key) });
624
+ },
625
+ removeCustomKey(id) {
626
+ const stored = saved.load();
627
+ if (!(customName(id) in stored)) return false;
628
+ delete stored[customName(id)];
629
+ saved.save(stored);
630
+ return true;
631
+ }
632
+ };
633
+ }
634
+ function createCredentialStore({ dataDir, env = process.env }) {
635
+ const path = join2(dataDir, CREDENTIALS_FILE);
636
+ let warned = false;
637
+ return credentialStore((name) => env[name]?.trim() || void 0, {
638
+ load() {
639
+ let text;
640
+ try {
641
+ text = readFileSync2(path, "utf8");
642
+ } catch {
643
+ return {};
644
+ }
645
+ try {
646
+ return CredentialsFile.parse(JSON.parse(text)).keys;
647
+ } catch {
648
+ if (!warned) console.warn(`${path} isn't valid, so its keys are ignored. Fix or delete it, or set the keys again.`);
649
+ warned = true;
650
+ return {};
651
+ }
652
+ },
653
+ save(keys) {
654
+ mkdirSync2(dataDir, { recursive: true });
655
+ const temp = `${path}.${randomBytes3(6).toString("hex")}.tmp`;
656
+ try {
657
+ writeFileSync2(temp, `${JSON.stringify({ keys }, null, 2)}
658
+ `, { mode: 384 });
659
+ chmodSync2(temp, 384);
660
+ renameSync2(temp, path);
661
+ } catch (error) {
662
+ rmSync2(temp, { force: true });
663
+ throw error;
664
+ }
665
+ }
666
+ });
667
+ }
668
+ function memoryCredentials({ env = {}, saved = {}, vars = {} } = {}) {
669
+ let stored = { ...saved };
670
+ const byName = Object.fromEntries(providerIds.flatMap((p) => env[p] ? [[PROVIDER_ENV[p], env[p]]] : []));
671
+ return credentialStore((name) => byName[name] ?? vars[name], {
672
+ load: () => ({ ...stored }),
673
+ save: (keys) => stored = { ...keys }
674
+ });
675
+ }
676
+ var keysSignature = (keys) => providerIds.map((p) => keys[p] ?? "").join("\n");
677
+
678
+ // ../server/src/security.ts
679
+ import { randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
680
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
681
+ import { join as join3 } from "node:path";
682
+ import { getConnInfo } from "@hono/node-server/conninfo";
683
+ import { createMiddleware } from "hono/factory";
684
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
685
+ var PUBLIC_API_PATHS = /* @__PURE__ */ new Set(["/api/health", "/api/doc"]);
686
+ var TOKEN_FILE = "auth-token";
687
+ function loadOrCreateToken(dataDir) {
688
+ const path = join3(dataDir, TOKEN_FILE);
689
+ try {
690
+ const existing = readFileSync3(path, "utf8").trim();
691
+ if (existing) return existing;
692
+ } catch {
693
+ }
694
+ mkdirSync3(dataDir, { recursive: true });
695
+ const token = randomBytes4(32).toString("base64url");
696
+ writeFileSync3(path, `${token}
697
+ `, { mode: 384 });
698
+ return token;
699
+ }
700
+ function hostGuard(allowedHosts) {
701
+ const allowed = /* @__PURE__ */ new Set([...LOOPBACK_HOSTS, ...allowedHosts.map((h) => h.toLowerCase())]);
702
+ return createMiddleware(async (c, next) => {
703
+ const hostname = new URL(c.req.url).hostname.toLowerCase();
704
+ if (!allowed.has(hostname)) return c.json({ error: "Host not allowed" }, 403);
705
+ await next();
706
+ });
707
+ }
708
+ function tokenGuard(token) {
709
+ const expected = Buffer.from(token);
710
+ return createMiddleware(async (c, next) => {
711
+ if (PUBLIC_API_PATHS.has(c.req.path)) return next();
712
+ const header = c.req.header("authorization") ?? "";
713
+ const given = Buffer.from(header.startsWith("Bearer ") ? header.slice(7) : "");
714
+ if (given.length !== expected.length || !timingSafeEqual2(given, expected)) {
715
+ return c.json({ error: "Missing or invalid API token" }, 401);
716
+ }
717
+ await next();
718
+ });
719
+ }
720
+ function isLoopbackPeer(c) {
721
+ let address;
722
+ try {
723
+ address = getConnInfo(c).remote.address;
724
+ } catch {
725
+ return false;
726
+ }
727
+ if (!address) return false;
728
+ const v4 = address.startsWith("::ffff:") ? address.slice(7) : address;
729
+ if (address !== "::1" && !/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v4)) return false;
730
+ if (!LOOPBACK_HOSTS.includes(new URL(c.req.url).hostname.toLowerCase())) return false;
731
+ return !["forwarded", "x-forwarded-for", "x-forwarded-host", "x-real-ip"].some((name) => c.req.header(name) !== void 0);
732
+ }
733
+
734
+ export {
735
+ CHATGPT_API,
736
+ ChatGptError,
737
+ errorCode,
738
+ CHATGPT_FILE,
739
+ chatGptFileStore,
740
+ createChatGptSession,
741
+ providerIds,
742
+ PROVIDER_LABELS,
743
+ PROVIDER_ENV,
744
+ CREDENTIALS_FILE,
745
+ ApiKey,
746
+ createCredentialStore,
747
+ memoryCredentials,
748
+ keysSignature,
749
+ TOKEN_FILE,
750
+ loadOrCreateToken,
751
+ hostGuard,
752
+ tokenGuard,
753
+ isLoopbackPeer
754
+ };
755
+ //# sourceMappingURL=chunk-KUKQU7EQ.js.map