literarywormai 1.0.0 → 1.0.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/README.md CHANGED
@@ -30,8 +30,10 @@ sign-in, enter your code when you sign in, or your books stay hidden.
30
30
 
31
31
  The sign-in is kept in one file only you can read (`~/.config/literarywormai/credentials.json`, or
32
32
  `%APPDATA%\literarywormai\credentials.json` on Windows) and renews itself. `logout` forgets it here; to end its
33
- access everywhere, **Disconnect** "LiteraryWorm AI command line on <your computer>" in
34
- **Settings › Connected AI apps** on literaryworm.net.
33
+ access everywhere, **Disconnect** "LiteraryWorm AI command line (a1b2)" in **Settings › Connected AI apps** on
34
+ literaryworm.net. The four letters and digits are a random code made once for this computer and kept in the same
35
+ file; `whoami` shows it. The tool never sends your computer's name, your user name or any other device detail:
36
+ LiteraryWorm AI's sign-in keeps an app's name even after you disconnect it.
35
37
 
36
38
  ## Read
37
39
 
package/lib/client.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // keeps this computer's sign-in in one small file readable only by you. The connector decides what the tokens can
4
4
  // reach (row-level security, "No AI" books, locked books, the demo and guest rules): this tool adds nothing.
5
5
 
6
+ const crypto = require("node:crypto");
6
7
  const fs = require("node:fs");
7
8
  const os = require("node:os");
8
9
  const path = require("node:path");
@@ -50,6 +51,26 @@ function credentialsPath(env = process.env, platform = process.platform, home =
50
51
  return path.join(base, "literarywormai", "credentials.json");
51
52
  }
52
53
 
54
+ /** The letters and digits a computer's code is made of, and its length. */
55
+ const CODE_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
56
+ const CODE_LENGTH = 4;
57
+ const CODE_RE = /^[a-z0-9]{4}$/;
58
+ /** A saved code is used only if it is a string of the right shape (String(null) would pass the pattern). */
59
+ const isCode = (value) => typeof value === "string" && CODE_RE.test(value);
60
+
61
+ /** A new random code for this computer ("a1b2"), from crypto-random numbers. No device details go into it. */
62
+ function newComputerCode(randomInt = crypto.randomInt) {
63
+ let code = "";
64
+ for (let i = 0; i < CODE_LENGTH; i++) code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
65
+ return code;
66
+ }
67
+
68
+ /**
69
+ * The name this computer registers under, which Settings › Connected AI apps shows. Only the random code tells
70
+ * computers apart: Supabase keeps a registration even after Disconnect, so it never names the computer or its user.
71
+ */
72
+ const appNameFor = (code) => `LiteraryWorm AI command line (${code})`;
73
+
53
74
  /** The connector's host when it isn't literaryworm.net's, for the warning every command prints; else null. */
54
75
  function overriddenHost(url) {
55
76
  return url === DEFAULT_URL ? null : new URL(url).host;
@@ -127,7 +148,7 @@ function tokensFrom(body, now) {
127
148
  * Makes the calls. `store` keeps the sign-in (the file, or a stand-in in tests) and `fetcher` is fetch. Nothing
128
149
  * here ever prints or returns a token.
129
150
  */
130
- function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store = fileStore(), now = Date.now, timeoutMs = TIMEOUT_MS, env = process.env } = {}) {
151
+ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store = fileStore(), now = Date.now, timeoutMs = TIMEOUT_MS, env = process.env, randomInt = crypto.randomInt } = {}) {
131
152
  let rpcId = 0;
132
153
 
133
154
  async function send(target, init = {}) {
@@ -159,17 +180,37 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
159
180
  return oauth.checkServer(await getJson(oauth.serverMetadataUrl(issuer), "the sign-in server's details"), issuer);
160
181
  }
161
182
 
183
+ /** Writes the file, keeping this computer's code whatever else changes. */
184
+ function put(value) {
185
+ const current = store.read();
186
+ const code = current && isCode(current.code) ? current.code : undefined;
187
+ store.write(code && value.code === undefined ? { ...value, code } : value);
188
+ }
189
+
190
+ /** This computer's code: made once (crypto-random) and kept in the file, so it stays the same across logins. */
191
+ function computerCode() {
192
+ const current = store.read();
193
+ if (current && isCode(current.code)) return current.code;
194
+ const code = newComputerCode(randomInt);
195
+ store.write({ ...(current || {}), code });
196
+ return code;
197
+ }
198
+
162
199
  /** The saved sign-in for this address, or null. */
163
200
  function saved() {
164
201
  const all = store.read();
165
202
  return all && all.url === url ? all : null;
166
203
  }
167
204
 
168
- /** This computer's app registration ({ clientId, redirectUri }), kept apart from the tokens; or null. */
205
+ /**
206
+ * This computer's app registration ({ clientId, redirectUri, name }), kept apart from the tokens; or null. One
207
+ * registered under any other name (1.0.0 named it after the computer) doesn't count, so login registers again.
208
+ */
169
209
  function registration() {
170
210
  const all = saved();
171
211
  const reg = all && all.registration;
172
- return reg && typeof reg.clientId === "string" && typeof reg.redirectUri === "string" ? reg : null;
212
+ const code = all && isCode(all.code) ? all.code : null;
213
+ return reg && typeof reg.clientId === "string" && typeof reg.redirectUri === "string" && code && reg.name === appNameFor(code) ? reg : null;
173
214
  }
174
215
 
175
216
  /** The saved file with its tokens dropped, keeping the registration. */
@@ -177,21 +218,21 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
177
218
 
178
219
  async function refresh(current) {
179
220
  if (!current.refreshToken || !current.tokenEndpoint) {
180
- store.write(withoutTokens());
221
+ put(withoutTokens());
181
222
  throw new NotConnected('Your sign-in has run out. Run "literarywormai login" to sign in again.');
182
223
  }
183
224
  const { res, body } = await postForm(current.tokenEndpoint, { grant_type: "refresh_token", refresh_token: current.refreshToken, client_id: current.clientId });
184
225
  if (!res.ok) {
185
226
  if (res.status === 400 || res.status === 401) {
186
227
  // The connection ended: disconnected in Settings, or the refresh token is no longer valid.
187
- store.write(withoutTokens());
228
+ put(withoutTokens());
188
229
  throw new NotConnected('This computer\'s sign-in has ended (it may have been disconnected in Settings › Connected AI apps). Run "literarywormai login" to sign in again.');
189
230
  }
190
231
  throw new Error(`Couldn't renew the sign-in (${res.status}). Try again later.`);
191
232
  }
192
233
  const next = { ...current, ...tokensFrom(body, now()) };
193
234
  if (!next.refreshToken) next.refreshToken = current.refreshToken;
194
- store.write(next);
235
+ put(next);
195
236
  return next;
196
237
  }
197
238
 
@@ -247,6 +288,9 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
247
288
  discover,
248
289
  saved,
249
290
  registration,
291
+ computerCode,
292
+ /** The name this computer registers under: "LiteraryWorm AI command line (a1b2)". */
293
+ appName: () => appNameFor(computerCode()),
250
294
  ready,
251
295
 
252
296
  /** The connector's tools: name, title, description, and whether each only reads. */
@@ -276,7 +320,7 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
276
320
  */
277
321
  async register(meta, name, redirectUri) {
278
322
  const reg = registration();
279
- if (reg && reg.redirectUri === redirectUri) return reg.clientId;
323
+ if (reg && reg.redirectUri === redirectUri && reg.name === name) return reg.clientId;
280
324
  const res = await send(meta.registration_endpoint, {
281
325
  method: "POST",
282
326
  headers: { "Content-Type": "application/json", Accept: "application/json" },
@@ -284,7 +328,7 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
284
328
  });
285
329
  const body = await readJson(res);
286
330
  if (!res.ok || !body || typeof body.client_id !== "string") throw new Error((body && (body.error_description || body.msg)) || `Couldn't register this computer with LiteraryWorm AI (${res.status}). Try again later.`);
287
- store.write({ ...(saved() || { url }), registration: { clientId: body.client_id, redirectUri } });
331
+ put({ ...(saved() || { url }), registration: { clientId: body.client_id, redirectUri, name } });
288
332
  return body.client_id;
289
333
  },
290
334
 
@@ -293,24 +337,31 @@ function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store =
293
337
  const { res, body } = await postForm(meta.token_endpoint, { grant_type: "authorization_code", code, code_verifier: verifier, client_id: clientId, redirect_uri: redirectUri });
294
338
  if (!res.ok) throw new Error((body && body.error_description) || `Couldn't finish signing in (${res.status}). Run "literarywormai login" again.`);
295
339
  const tokens = tokensFrom(body, now());
296
- store.write({ url, registration: { clientId, redirectUri }, clientId, redirectUri, tokenEndpoint: meta.token_endpoint, issuer: meta.issuer, ...tokens });
340
+ const reg = registration();
341
+ put({ url, registration: reg && reg.clientId === clientId ? reg : { clientId, redirectUri }, clientId, redirectUri, tokenEndpoint: meta.token_endpoint, issuer: meta.issuer, ...tokens });
297
342
  },
298
343
 
299
344
  /** Who the saved sign-in belongs to (from the access token, renewed first if needed). Never the token itself. */
300
345
  async whoami() {
301
346
  const current = await ready();
302
347
  const claims = oauth.claimsOf(current.accessToken) || {};
303
- return { url, email: typeof claims.email === "string" ? claims.email : null, userId: typeof claims.sub === "string" ? claims.sub : null, expiresAt: new Date(current.expiresAt).toISOString() };
348
+ // The code only once this computer is registered under it (a 1.0.0 sign-in shows null until the next login).
349
+ const reg = registration();
350
+ const code = reg && reg.clientId === current.clientId ? saved().code : null;
351
+ return {
352
+ url, email: typeof claims.email === "string" ? claims.email : null, userId: typeof claims.sub === "string" ? claims.sub : null,
353
+ expiresAt: new Date(current.expiresAt).toISOString(), code, appName: code ? appNameFor(code) : null,
354
+ };
304
355
  },
305
356
 
306
357
  /** Forgets the sign-in here (keeping the app registration, so the next login reuses it). */
307
358
  logout() {
308
359
  const current = saved();
309
360
  if (!current || !current.accessToken) return false;
310
- store.write(withoutTokens());
361
+ put(withoutTokens());
311
362
  return true;
312
363
  },
313
364
  };
314
365
  }
315
366
 
316
- module.exports = { createClient, fileStore, overriddenHost, LITERARYWORM_AUTH_HOSTS, credentialsPath, mcpUrl, tokensFrom, readRpc, NotConnected, Refused, Offline, DEFAULT_URL, PROTOCOL_VERSION, REFRESH_EARLY_MS };
367
+ module.exports = { createClient, fileStore, overriddenHost, newComputerCode, appNameFor, CODE_ALPHABET, CODE_LENGTH, LITERARYWORM_AUTH_HOSTS, credentialsPath, mcpUrl, tokensFrom, readRpc, NotConnected, Refused, Offline, DEFAULT_URL, PROTOCOL_VERSION, REFRESH_EARLY_MS };
package/lib/display.js CHANGED
@@ -152,7 +152,10 @@ function saved(result) {
152
152
  }
153
153
 
154
154
  function whoami(info) {
155
- return [`Signed in to LiteraryWorm AI${info.email ? ` as ${info.email}` : ""}.`, `Connector: ${info.url}`, `This sign-in renews itself; the current one runs until ${info.expiresAt}.`].join("\n");
155
+ const code = info.code
156
+ ? `This computer's code: ${info.code} (shown as "${info.appName}" in Settings › Connected AI apps).`
157
+ : 'This computer has no code yet: run "literarywormai login" again to give it one in Settings › Connected AI apps.';
158
+ return [`Signed in to LiteraryWorm AI${info.email ? ` as ${info.email}` : ""}.`, code, `Connector: ${info.url}`, `This sign-in renews itself; the current one runs until ${info.expiresAt}.`].join("\n");
156
159
  }
157
160
 
158
161
  module.exports = { MAX_CELL, safe, oneLine, table, pageLine, books, book, chapters, partText, bible, notes, readiness, tools, saved, whoami };
package/lib/main.js CHANGED
@@ -4,7 +4,6 @@
4
4
 
5
5
  const fs = require("node:fs");
6
6
  const http = require("node:http");
7
- const os = require("node:os");
8
7
  const readline = require("node:readline");
9
8
  const { spawn } = require("node:child_process");
10
9
  const { HELP, parseArgs, isWrite, UsageError } = require("./args");
@@ -107,7 +106,7 @@ async function login(client, out, { port, browser, minutes }) {
107
106
  const savedPort = reg ? Number(new URL(reg.redirectUri).port) : previous && previous.redirectUri ? Number(new URL(previous.redirectUri).port) : null;
108
107
  let clientId = "";
109
108
  const answer = await waitForAnswer({ attempt, issuer: meta.issuer, port: port ?? savedPort ?? DEFAULT_PORT, fallback: port === undefined, ...(minutes ? { minutes } : {}) }, async (redirectUri) => {
110
- const name = `LiteraryWorm AI command line on ${os.hostname()}`.slice(0, MAX_APP_NAME);
109
+ const name = client.appName().slice(0, MAX_APP_NAME);
111
110
  clientId = await client.register(meta, name, redirectUri);
112
111
  const url = oauth.authorizeUrl(meta, clientId, redirectUri, attempt);
113
112
  out(`Connector: ${new URL(client.url).host}. Sign-in server: ${new URL(meta.issuer).host}.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "literarywormai",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "LiteraryWorm AI from the command line: read your books, chapters, story bible, research notes and readiness, and save drafts when you say so, through the same connector your AI apps use.",
5
5
  "homepage": "https://literaryworm.net/help#command-line",
6
6
  "license": "UNLICENSED",