@wirecat/cli-core 1.0.0 → 1.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/THIRD_PARTY_NOTICES +43 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +3 -0
  5. package/dist/cli/account-remove.js +1 -1
  6. package/dist/cli/documents/index.d.ts +2 -1
  7. package/dist/cli/documents/index.js +4 -1
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/domain-lists-command.d.ts +16 -0
  10. package/dist/cli/domain-lists-command.js +88 -0
  11. package/dist/cli/index.d.ts +4 -3
  12. package/dist/cli/index.js +4 -3
  13. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  14. package/dist/cli/messenger/message-answers.d.ts +2 -0
  15. package/dist/cli/messenger/message-items.js +2 -0
  16. package/dist/cli/messenger/message-writes.d.ts +4 -0
  17. package/dist/cli/messenger/search-answers.js +2 -0
  18. package/dist/cli/model-catalogue-command.d.ts +6 -0
  19. package/dist/cli/model-catalogue-command.js +1 -1
  20. package/dist/cli/oauth-session.d.ts +38 -4
  21. package/dist/cli/oauth-session.js +72 -25
  22. package/dist/cli/shared-command-exports.d.ts +4 -0
  23. package/dist/cli/shared-command-exports.js +6 -0
  24. package/dist/cli/token-session.d.ts +9 -3
  25. package/dist/cli/token-session.js +34 -3
  26. package/dist/domain/domain-lists.d.ts +86 -0
  27. package/dist/domain/domain-lists.js +110 -0
  28. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  29. package/dist/domain/free-mail-domains.generated.js +4 -0
  30. package/dist/domain/models.d.ts +5 -0
  31. package/dist/domain/organization-sectors.d.ts +9 -3
  32. package/dist/domain/organization-sectors.generated.d.ts +1 -0
  33. package/dist/domain/organization-sectors.generated.js +1 -0
  34. package/dist/domain/organization-sectors.js +16 -3
  35. package/dist/domain/person-kinds.d.ts +6 -1
  36. package/dist/domain/person-kinds.js +5 -0
  37. package/dist/entities/contact-context.d.ts +4 -0
  38. package/dist/entities/conversation-results.d.ts +4 -0
  39. package/dist/entities/domain-list.d.ts +27 -0
  40. package/dist/entities/domain-list.js +28 -0
  41. package/dist/entities/evidence.d.ts +16 -0
  42. package/dist/entities/index.d.ts +56 -2
  43. package/dist/entities/index.js +3 -1
  44. package/dist/entities/knowledge-lists.d.ts +1 -1
  45. package/dist/entities/listener.d.ts +8 -0
  46. package/dist/entities/message-change.d.ts +2 -0
  47. package/dist/entities/message-context.d.ts +6 -0
  48. package/dist/entities/message-write.d.ts +8 -0
  49. package/dist/entities/message.d.ts +4 -0
  50. package/dist/entities/message.js +4 -0
  51. package/dist/entities/store-records.d.ts +2 -0
  52. package/dist/errors/reasons.js +20 -2
  53. package/dist/mail/cli/index.js +1 -1
  54. package/dist/mail/headers.d.ts +2 -0
  55. package/dist/mail/headers.js +2 -1
  56. package/dist/mail/mail-types.d.ts +48 -0
  57. package/dist/mail/mail-types.js +218 -0
  58. package/dist/mail/read.js +1 -0
  59. package/dist/mail/sort-rules.d.ts +58 -0
  60. package/dist/mail/sort-rules.js +79 -0
  61. package/dist/oauth/index.d.ts +1 -1
  62. package/dist/oauth/storage.d.ts +10 -2
  63. package/dist/oauth/storage.js +23 -9
  64. package/dist/search/lucene/registry.js +24 -0
  65. package/dist/services/domain-lists-download.d.ts +26 -0
  66. package/dist/services/domain-lists-download.js +155 -0
  67. package/dist/services/messages-search.js +1 -1
  68. package/dist/services/metadata.d.ts +1 -1
  69. package/dist/store/areas.d.ts +3 -1
  70. package/dist/store/areas.js +2 -0
  71. package/dist/store/index.d.ts +2 -2
  72. package/dist/store/index.js +1 -1
  73. package/dist/store/people.d.ts +18 -9
  74. package/dist/store/people.js +8 -7
  75. package/dist/store/public.d.ts +1 -1
  76. package/dist/store/public.js +1 -1
  77. package/dist/store/queries.js +9 -2
  78. package/dist/store/sqlite/accounts.js +3 -1
  79. package/dist/store/sqlite/domain-organizations.d.ts +7 -4
  80. package/dist/store/sqlite/domain-organizations.js +94 -36
  81. package/dist/store/sqlite/email-types.d.ts +87 -0
  82. package/dist/store/sqlite/email-types.js +296 -0
  83. package/dist/store/sqlite/emails.d.ts +14 -2
  84. package/dist/store/sqlite/emails.js +32 -12
  85. package/dist/store/sqlite/identities.d.ts +4 -1
  86. package/dist/store/sqlite/identities.js +11 -2
  87. package/dist/store/sqlite/identity-rekey.js +2 -0
  88. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  89. package/dist/store/sqlite/lucene-fields.js +10 -0
  90. package/dist/store/sqlite/lucene.js +6 -0
  91. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  92. package/dist/store/sqlite/mail-sorting.js +482 -0
  93. package/dist/store/sqlite/manifest.js +6 -0
  94. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  95. package/dist/store/sqlite/merged-persons.js +5 -3
  96. package/dist/store/sqlite/migrations.generated.js +76 -0
  97. package/dist/store/sqlite/people-list.d.ts +1 -6
  98. package/dist/store/sqlite/people-list.js +97 -42
  99. package/dist/store/sqlite/person-links.js +13 -3
  100. package/dist/store/sqlite/person-match-scan.js +5 -2
  101. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  102. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  103. package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
  104. package/dist/store/sqlite/schema/sender-bots.js +9 -1
  105. package/dist/store/sqlite/schema.d.ts +66 -1
  106. package/dist/store/sqlite/schema.js +9 -1
  107. package/dist/store/sqlite/sender-bots.d.ts +89 -15
  108. package/dist/store/sqlite/sender-bots.js +417 -136
  109. package/dist/store/sqlite/sender-signals.d.ts +11 -4
  110. package/dist/store/sqlite/sender-signals.js +14 -10
  111. package/package.json +2 -2
@@ -1,8 +1,10 @@
1
1
  import type { OAuthFlow } from "@wirecat/cli-base/codegen/runtime";
2
- import { Command } from "commander";
2
+ import { Command, type Option } from "commander";
3
3
  import type { OAuthClient, OAuthProvider } from "../oauth/provider.js";
4
+ import { type LegacyAccount, type TokenCodec } from "../oauth/storage.js";
4
5
  import type { AppIdentity } from "../ports/app.js";
5
6
  import type { EventSink } from "../runs/events.js";
7
+ import { type SignInSteps } from "../terminal/sign-in-steps.js";
6
8
  import { type BaseEnvironment } from "./context.js";
7
9
  import type { ServiceApiManifest } from "./service-api-manifest.js";
8
10
  import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
@@ -44,6 +46,17 @@ export interface OAuthEnvironment extends BaseEnvironment {
44
46
  /** Gets the command, so the entry opens nothing under `--json`, `--no-input`, CI or without a terminal. */
45
47
  openBrowser?: (url: string, command?: Command) => Promise<void>;
46
48
  }
49
+ /** What `afterSignIn` gets once the sign-in is kept. @experimental */
50
+ export interface OAuthSignedIn {
51
+ env: NodeJS.ProcessEnv;
52
+ profile: string;
53
+ /** `verify`'s `id` and `account`. */
54
+ id: string;
55
+ account: Readonly<Record<string, unknown>>;
56
+ /** The client the preset gave this sign-in, which its refreshes need. */
57
+ client: OAuthClient;
58
+ scopes: readonly string[];
59
+ }
47
60
  /** @experimental */
48
61
  export interface OAuthSessionOptions {
49
62
  app: AppIdentity;
@@ -51,15 +64,36 @@ export interface OAuthSessionOptions {
51
64
  /** The preset's `id` and `name`: `session list` and `status` read the sign-in without choosing a client. */
52
65
  providerId: string;
53
66
  service: string;
54
- /** From `oauthPreset`; the client is the CLI's own choice (a flag, a variable, the config, WireCat's app). */
55
- preset: (command: Command) => OAuthPreset;
56
- /** Asks the service whose the access token is; `id` names the account, `account` is what start and status show. */
67
+ /**
68
+ * From `oauthPreset`; the client is the CLI's own choice (a flag, a variable, the config, WireCat's app). It reads its
69
+ * `startOptions` from `command.opts()`. In `session start` it gets the sign-in's steps too, so with `--answer-stdin`
70
+ * it may ask for what it lacks, such as the client id.
71
+ */
72
+ preset: (command: Command, steps?: SignInSteps) => OAuthPreset | Promise<OAuthPreset>;
73
+ /**
74
+ * Asks the service whose the access token is; `id` names the account, `account` is what start and status show.
75
+ * `extra` is saved in the entry by the codec at sign-in, such as drive's `principal`.
76
+ */
57
77
  verify: (command: Command, accessToken: string, events: EventSink) => Promise<{
58
78
  id: string;
59
79
  account: Readonly<Record<string, unknown>>;
80
+ extra?: Record<string, unknown>;
60
81
  }>;
61
82
  /** Runs before anything is saved; by default only remembers the account. A CLI that refuses a taken one throws. */
62
83
  claim?: (env: NodeJS.ProcessEnv, profile: string, id: string) => void;
84
+ /** The entry's format; `standardCodec` by default. A CLI that kept its sign-ins before passes the format it wrote. */
85
+ codec?: TokenCodec;
86
+ /**
87
+ * Where older versions kept a profile's sign-in. Read when the profile's own entry is empty and copied to it, so
88
+ * nobody signs in again; `session end` removes them too. A run with moved folders only reads them.
89
+ */
90
+ legacyAccounts?: (env: NodeJS.ProcessEnv, profile: string) => readonly LegacyAccount[];
91
+ /** More `session start` options, such as the client or the scopes to ask; `preset` reads them. */
92
+ startOptions?: readonly Option[];
93
+ /** Runs once the sign-in is kept, before the answer: the CLI saves what belongs beside it (WC-SECR-25). */
94
+ afterSignIn?: (command: Command, signedIn: OAuthSignedIn) => void | Promise<void>;
95
+ /** The profiles `session list` names; by default the configured ones and those signed in here before. */
96
+ profiles?: (env: NodeJS.ProcessEnv) => readonly string[];
63
97
  }
64
98
  /**
65
99
  * `session start | status | end | list` for a service signed in in the browser (WC-SECR-22): PKCE on the loopback,
@@ -3,16 +3,16 @@ import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { hostFetch } from "@wirecat/cli-base/http";
4
4
  import { Command } from "commander";
5
5
  import { tokenKeeper } from "../oauth/keeper.js";
6
- import { credentialStorage, oauthAccount, standardCodec } from "../oauth/storage.js";
6
+ import { credentialStorage, oauthAccount, standardCodec, } from "../oauth/storage.js";
7
7
  import { editDistance } from "../search/correct.js";
8
- import { signInSteps } from "../terminal/sign-in-steps.js";
8
+ import { answerStdinOption, signInSteps } from "../terminal/sign-in-steps.js";
9
9
  import { baseContext, environmentOf, outputFor } from "./context.js";
10
10
  import { refuseOffline } from "./early-refusal.js";
11
11
  import { LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, REMOTE_WRITE } from "./effects.js";
12
12
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
13
13
  import { profilesHere, rememberAccount } from "./messenger/accounts.js";
14
14
  import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
15
- import { storageOf } from "./token-session.js";
15
+ import { storageOf, unknownSignIn } from "./token-session.js";
16
16
  /**
17
17
  * The authorization code flow an OpenAPI spec declares; a GraphQL service (Linear) writes the same object by hand.
18
18
  * @experimental
@@ -58,6 +58,7 @@ export const oauthPreset = (flow, options) => {
58
58
  };
59
59
  return { provider, scopes: [...options.scopes], rotating: options.rotating === true };
60
60
  };
61
+ const PASTE_PROMPT = "the address the browser shows after you allow access, when it does not come back here";
61
62
  /**
62
63
  * `session start | status | end | list` for a service signed in in the browser (WC-SECR-22): PKCE on the loopback,
63
64
  * the account checked before the tokens are kept, refreshes under one lock, and a run with moved folders that never
@@ -66,6 +67,7 @@ export const oauthPreset = (flow, options) => {
66
67
  */
67
68
  export const oauthSessionCommand = (options) => {
68
69
  const { app, providerId, service } = options;
70
+ const codec = options.codec ?? standardCodec(providerId);
69
71
  const pathsOf = (env) => ({ appName: app.appName, prefix: app.envPrefix, env });
70
72
  const storageFor = (where, profile, storage = "auto", rotating = false) => credentialStorage({
71
73
  credentials: {
@@ -78,7 +80,8 @@ export const oauthSessionCommand = (options) => {
78
80
  ...(where.warn ? { warn: where.warn } : {}),
79
81
  },
80
82
  account: oauthAccount(providerId, profile),
81
- codec: rotating ? { ...standardCodec(providerId), rotating: true } : standardCodec(providerId),
83
+ ...(options.legacyAccounts ? { legacyAccounts: options.legacyAccounts(where.env, profile) } : {}),
84
+ codec: rotating && !codec.rotating ? { ...codec, rotating: true } : codec,
82
85
  });
83
86
  const contextOf = (command) => {
84
87
  const base = baseContext(command, options.resolveSettings);
@@ -86,8 +89,8 @@ export const oauthSessionCommand = (options) => {
86
89
  const where = { env: base.env, keyring: base.keyring, warn: base.renderer.warn };
87
90
  const { profile } = base.settings;
88
91
  /** The preset is asked only here, after the refusals: a CLI's client choice may fail on its own. */
89
- const keeperOf = (storage) => {
90
- const { provider, scopes, rotating } = options.preset(command);
92
+ const keeperOf = async (storage, steps) => {
93
+ const { provider, scopes, rotating } = await options.preset(command, steps);
91
94
  const keeper = tokenKeeper({
92
95
  provider,
93
96
  storage: storageFor(where, profile, storage ?? "auto", rotating),
@@ -95,14 +98,17 @@ export const oauthSessionCommand = (options) => {
95
98
  // Only the provider's own sign-in hosts: a token request never reaches anything else.
96
99
  fetch: environment.fetch ??
97
100
  hostFetch({
98
- hosts: [provider.authorizeUrl, provider.tokenUrl, provider.revokeUrl]
99
- .filter((url) => url !== undefined)
100
- .map((url) => new URL(url).hostname),
101
+ // Providers often sign in and hand out tokens on one host; hostFetch refuses a host listed twice.
102
+ hosts: [
103
+ ...new Set([provider.authorizeUrl, provider.tokenUrl, provider.revokeUrl]
104
+ .filter((url) => url !== undefined)
105
+ .map((url) => new URL(url).hostname)),
106
+ ],
101
107
  }),
102
108
  signInCommand: `${app.command} ${profile} session start`,
103
109
  ...(environment.signal ? { signal: environment.signal } : {}),
104
110
  });
105
- return { keeper, scopes };
111
+ return { keeper, scopes, client: provider.client };
106
112
  };
107
113
  const saved = () => storageFor(where, profile).read();
108
114
  return { ...base, environment, where, profile, keeperOf, saved };
@@ -112,31 +118,48 @@ export const oauthSessionCommand = (options) => {
112
118
  effects: REMOTE_WRITE,
113
119
  lifetime: "interactive",
114
120
  mcp: false,
115
- examples: [`${app.command} personal session start`, `${app.command} personal session start --no-browser`],
121
+ examples: [
122
+ `${app.command} personal session start`,
123
+ `${app.command} personal session start --no-browser`,
124
+ `${app.command} personal session start --json --answer-stdin`,
125
+ ],
116
126
  }))
117
127
  .summary(`sign in to ${service} in the browser`)
118
128
  .description(`sign this profile in to ${service} in the browser; the account is checked before anything is kept, in the ` +
119
129
  "keyring or, with --credential-storage file, a private file")
120
130
  .option("--no-browser", "print the sign-in URL instead of opening a browser")
121
131
  .option("--credential-storage <storage>", "where the sign-in is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
122
- .action(async function (args) {
132
+ .addOption(answerStdinOption());
133
+ for (const option of options.startOptions ?? [])
134
+ start.addOption(option);
135
+ start.action(async function (args) {
123
136
  const context = contextOf(this);
124
137
  refuseCommandName(context.profile, commandWords(rootOf(this)), app.command);
125
138
  refuseOffline(this, service);
126
- const { keeper, scopes: asked } = context.keeperOf(args.credentialStorage === "file" ? "file" : undefined);
127
139
  const { streams } = outputFor(this);
128
140
  const steps = signInSteps({
129
141
  diagnostic: (line) => streams.diagnostic(`${line}\n`),
130
142
  json: context.format !== "pretty" || context.environment.tty === false,
131
- answers: false,
143
+ answers: args.answerStdin === true,
144
+ ...(context.environment.stdin ? { input: context.environment.stdin } : {}),
132
145
  });
146
+ const { keeper, scopes: asked, client, } = await context.keeperOf(args.credentialStorage === "file" ? "file" : undefined, steps);
133
147
  let shown = {};
148
+ let accountId = "";
134
149
  const { scopes } = await context.run((events) => keeper.signIn({
135
150
  scopes: asked,
136
151
  openBrowser: async (url) => {
137
152
  if (args.browser)
138
153
  await context.environment.openBrowser?.(url, this);
139
154
  },
155
+ ...(steps.answers
156
+ ? {
157
+ readPaste: (stop) => steps
158
+ .ask({ field: "redirect", secret: true, prompt: PASTE_PROMPT }, stop)
159
+ // The browser's callback won the race; the question is withdrawn, not failed.
160
+ .catch((error) => (stop.aborted ? new Promise(() => { }) : Promise.reject(error))),
161
+ }
162
+ : {}),
140
163
  showUrl: (url) => {
141
164
  steps.openUrl(url, `Sign in to ${service} and allow access`);
142
165
  streams.diagnostic(`Open ${service} sign-in: ${url}\n`);
@@ -145,10 +168,11 @@ export const oauthSessionCommand = (options) => {
145
168
  accept: async (tokens) => {
146
169
  if (!tokens.accessToken)
147
170
  throw new CliError("authentication_error", `${service} returned no access token`);
148
- const { id, account } = await options.verify(this, tokens.accessToken, events);
171
+ const { id, account, extra } = await options.verify(this, tokens.accessToken, events);
149
172
  (options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))(context.env, context.profile, id);
150
173
  shown = account;
151
- return undefined;
174
+ accountId = id;
175
+ return extra;
152
176
  },
153
177
  }));
154
178
  // The owner chose the file: an older keyring copy must not outlive it with a live refresh token.
@@ -159,6 +183,14 @@ export const oauthSessionCommand = (options) => {
159
183
  catch {
160
184
  // No keyring on this computer: there is no copy to forget.
161
185
  }
186
+ await options.afterSignIn?.(this, {
187
+ env: context.env,
188
+ profile: context.profile,
189
+ id: accountId,
190
+ account: shown,
191
+ client,
192
+ scopes,
193
+ });
162
194
  answer(this, { ...shown, profile: context.profile, signed_in: true, scopes });
163
195
  });
164
196
  const status = annotate(new Command("status"), {
@@ -173,11 +205,18 @@ export const oauthSessionCommand = (options) => {
173
205
  const saved = context.saved();
174
206
  if (!saved)
175
207
  return answer(this, { profile: context.profile, state: "missing", verified: false });
176
- const state = { profile: context.profile, state: "saved", scopes: saved.tokens.scopes };
208
+ const { expiresAt } = saved.tokens;
209
+ const state = {
210
+ profile: context.profile,
211
+ state: "saved",
212
+ scopes: saved.tokens.scopes,
213
+ // The access token's end, which a refresh moves on; a sign-in itself ends only at session end or in the service.
214
+ expires_at: expiresAt ? new Date(expiresAt).toISOString() : null,
215
+ };
177
216
  if (!args.check)
178
217
  return answer(this, { ...state, verified: false });
179
218
  refuseOffline(this, service);
180
- const { keeper } = context.keeperOf();
219
+ const { keeper } = await context.keeperOf();
181
220
  const { account } = await context.run(async (events) => options.verify(this, await keeper.accessToken(), events));
182
221
  answer(this, { ...account, ...state, verified: true });
183
222
  });
@@ -193,7 +232,7 @@ export const oauthSessionCommand = (options) => {
193
232
  const context = contextOf(this);
194
233
  if (!context.saved())
195
234
  return answer(this, { profile: context.profile, ended: false });
196
- const { removed } = await context.keeperOf().keeper.signOut();
235
+ const { removed } = await (await context.keeperOf()).keeper.signOut();
197
236
  if (!context.saved())
198
237
  return answer(this, { profile: context.profile, ended: true, removed });
199
238
  answer(this, {
@@ -214,12 +253,20 @@ export const oauthSessionCommand = (options) => {
214
253
  .action(function () {
215
254
  const environment = environmentOf(this);
216
255
  const env = environment.env ?? process.env;
217
- const { configuredProfiles } = options.resolveSettings({}, { env, needsProfile: false });
218
- const where = { env, keyring: environment.keyring, warn: outputFor(this).renderer.warn };
219
- const items = profilesHere(app, configuredProfiles, env).map((profile) => ({
220
- profile,
221
- signed_in: storageFor(where, profile).read() !== undefined,
222
- }));
256
+ const { warn } = outputFor(this).renderer;
257
+ const where = { env, keyring: environment.keyring, warn };
258
+ const profiles = options.profiles?.(env) ??
259
+ profilesHere(app, options.resolveSettings({}, { env, needsProfile: false }).configuredProfiles, env);
260
+ const unknown = unknownSignIn(warn);
261
+ const items = profiles.map((profile) => {
262
+ try {
263
+ const saved = storageFor(where, profile).read() !== undefined;
264
+ return { profile, signed_in: saved, state: saved ? "saved" : "missing" };
265
+ }
266
+ catch (error) {
267
+ return unknown(profile, error);
268
+ }
269
+ });
223
270
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
224
271
  });
225
272
  return annotate(new Command("session"), { effects: LOCAL_READ })
@@ -573,6 +573,8 @@ export declare const botMcpCommand: (bot: import("./index.js").BotMessenger) =>
573
573
  /** @experimental */
574
574
  export declare const botMessagesCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
575
575
  export declare const commandsCommand: (app: import("./entry.js").AppIdentity) => import("commander").Command;
576
+ /** @experimental */
577
+ export declare const oauthSessionCommand: (options: import("./oauth-session.js").OAuthSessionOptions) => import("commander").Command;
576
578
  export declare const configCommand: (app: import("./entry.js").AppIdentity, config: {
577
579
  resolveSettings: (flags?: import("./settings.js").GlobalFlags, options?: import("./settings.js").ResolveOptions) => import("./settings.js").Settings & object;
578
580
  configuredProfiles: (options?: import("./settings.js").ResolveOptions) => string[];
@@ -1048,4 +1050,6 @@ export declare const skillCommand: (app: import("./entry.js").AppIdentity, skill
1048
1050
  export declare const upgradeCommand: (app: import("./entry.js").AppIdentity, packageName: string, contextFor: (command: import("commander").Command) => import("./upgrade-command.js").UpgradeContext) => import("commander").Command;
1049
1051
  export declare const modelCatalogueCommand: (app: import("./entry.js").AppIdentity, options: import("./model-catalogue-command.js").ModelCatalogueOptions) => import("commander").Command;
1050
1052
  /** @experimental */
1053
+ export declare const domainListsCommand: (app: import("./entry.js").AppIdentity, options: import("./domain-lists-command.js").DomainListsCommandOptions) => import("commander").Command;
1054
+ /** @experimental */
1051
1055
  export declare const templatesCommand: (app: import("./entry.js").AppIdentity, options: import("./templates-command.js").TemplatesOptions) => import("commander").Command;
@@ -54,6 +54,7 @@ import { tagsCommand as tagsCommandDefinition } from "./messenger/tags-command.j
54
54
  import { tasksCommand as tasksCommandDefinition, tasksStatsCommand as tasksStatsCommandDefinition, } from "./messenger/tasks-command.js";
55
55
  import { topicsCommand as topicsCommandDefinition } from "./messenger/topics-command.js";
56
56
  import { watchCommand as watchCommandDefinition } from "./messenger/watch-command.js";
57
+ import { oauthSessionCommand as oauthSessionCommandDefinition } from "./oauth-session.js";
57
58
  import { runsCommand as runsCommandDefinition } from "./runs/command.js";
58
59
  import { scheduleCommandFor as scheduleCommandForDefinition } from "./schedule/schedule-command.js";
59
60
  import { serviceApiCommand as serviceApiCommandDefinition } from "./service-api.js";
@@ -79,6 +80,8 @@ export const botMcpCommand = sharedCommand(botMcpCommandDefinition);
79
80
  /** @experimental */
80
81
  export const botMessagesCommand = sharedCommand(botMessagesCommandDefinition);
81
82
  export const commandsCommand = sharedCommand(commandsCommandDefinition);
83
+ /** @experimental */
84
+ export const oauthSessionCommand = sharedCommand(oauthSessionCommandDefinition);
82
85
  export const configCommand = sharedCommand(configCommandDefinition);
83
86
  export const setupCommand = sharedCommand(setupCommandDefinition);
84
87
  export const guideCommand = sharedCommand(guideCommandDefinition);
@@ -151,8 +154,11 @@ export const watchCommand = sharedCommand(watchCommandDefinition);
151
154
  export const runsCommand = sharedCommand(runsCommandDefinition);
152
155
  export const skillCommand = sharedCommand(skillCommandDefinition);
153
156
  export const upgradeCommand = sharedCommand(upgradeCommandDefinition);
157
+ import { domainListsCommand as domainListsDefinition } from "./domain-lists-command.js";
154
158
  import { modelCatalogueCommand as modelCatalogueDefinition } from "./model-catalogue-command.js";
155
159
  import { templatesCommand as templatesDefinition } from "./templates-command.js";
156
160
  export const modelCatalogueCommand = sharedCommand(modelCatalogueDefinition);
157
161
  /** @experimental */
162
+ export const domainListsCommand = sharedCommand(domainListsDefinition);
163
+ /** @experimental */
158
164
  export const templatesCommand = sharedCommand(templatesDefinition);
@@ -74,11 +74,17 @@ export interface ManifestVerifyOptions {
74
74
  * answer does not call active is refused, and the account is the id and name the answer holds.
75
75
  */
76
76
  export declare const manifestVerify: ({ manifest, service, verify, fetch }: ManifestVerifyOptions) => TokenSessionOptions["verify"];
77
- export declare const storageOf: (raw: string) => TokenStorage;
78
77
  /**
79
- * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
80
- * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
78
+ * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
79
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
81
80
  */
81
+ export declare const unknownSignIn: (warn: (message: string) => void) => (profile: string, error: unknown) => {
82
+ readonly profile: string;
83
+ readonly signed_in: null;
84
+ readonly state: "unknown";
85
+ };
86
+ export declare const storageOf: (raw: string) => TokenStorage;
87
+ /** cli-core's own command (WC-CMD-34): a CLI changes it only through its options. */
82
88
  export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command;
83
89
  /**
84
90
  * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
@@ -6,6 +6,7 @@ import { plainSetupText } from "../setup/plain.js";
6
6
  import { drawsHyperlinks, hyperlink } from "../terminal/hyperlink.js";
7
7
  import { readSecret } from "../terminal/prompt.js";
8
8
  import { baseContext, environmentOf, outputFor, secretInputOf } from "./context.js";
9
+ import { honoursDryRun } from "./dry-run-guard.js";
9
10
  import { refuseOffline } from "./early-refusal.js";
10
11
  import { FETCH, LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, refuseUnderReadOnly } from "./effects.js";
11
12
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
@@ -14,6 +15,7 @@ import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.
14
15
  import { ProfileTokenStore } from "./profile-token.js";
15
16
  import { serviceApiCall } from "./service-api-call.js";
16
17
  import { siteValue } from "./service-api-manifest.js";
18
+ import { sharedCommand } from "./shared-contracts.js";
17
19
  /**
18
20
  * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the
19
21
  * answer does not call active is refused, and the account is the id and name the answer holds.
@@ -38,6 +40,22 @@ export const manifestVerify = ({ manifest, service, verify, fetch }) => async (c
38
40
  const name = verify.name === undefined ? undefined : valueAt(answer, verify.name);
39
41
  return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } };
40
42
  };
43
+ const UNREADABLE = new Set(["keyring.unreachable", "oauth.not-saved", "oauth.invalid", "session.unreadable"]);
44
+ /**
45
+ * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
46
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
47
+ */
48
+ export const unknownSignIn = (warn) => {
49
+ const warned = new Set();
50
+ return (profile, error) => {
51
+ if (!(error instanceof CliError) || !UNREADABLE.has(String(error.details.reason)))
52
+ throw error;
53
+ if (!warned.has(error.message))
54
+ warn(error.message);
55
+ warned.add(error.message);
56
+ return { profile, signed_in: null, state: "unknown" };
57
+ };
58
+ };
41
59
  export const storageOf = (raw) => {
42
60
  if (raw === "keyring" || raw === "file")
43
61
  return raw;
@@ -47,7 +65,7 @@ export const storageOf = (raw) => {
47
65
  * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
48
66
  * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
49
67
  */
50
- export const tokenSessionCommand = (options) => {
68
+ const tokenSessionCommandDefinition = (options) => {
51
69
  const { app, service } = options;
52
70
  const word = options.token ?? (options.login ? "password" : "API token");
53
71
  const contextOf = (command) => {
@@ -166,9 +184,20 @@ export const tokenSessionCommand = (options) => {
166
184
  ...(environment.keyring ? { keyring: environment.keyring } : {}),
167
185
  warn: outputFor(this).renderer.warn,
168
186
  });
187
+ const unknown = unknownSignIn(outputFor(this).renderer.warn);
169
188
  const items = profilesHere(app, configuredProfiles, env).map((profile) => {
170
- const saved = tokens.read(profile);
171
- return { profile, signed_in: saved !== undefined, token_from: saved?.source ?? null };
189
+ try {
190
+ const saved = tokens.read(profile);
191
+ return {
192
+ profile,
193
+ signed_in: saved !== undefined,
194
+ state: saved ? "saved" : "missing",
195
+ token_from: saved?.source ?? null,
196
+ };
197
+ }
198
+ catch (error) {
199
+ return { ...unknown(profile, error), token_from: null };
200
+ }
172
201
  });
173
202
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
174
203
  });
@@ -179,6 +208,8 @@ export const tokenSessionCommand = (options) => {
179
208
  .addCommand(end)
180
209
  .addCommand(list);
181
210
  };
211
+ /** cli-core's own command (WC-CMD-34): a CLI changes it only through its options. */
212
+ export const tokenSessionCommand = honoursDryRun(sharedCommand(tokenSessionCommandDefinition));
182
213
  const SITE = "site";
183
214
  /**
184
215
  * The account a profile keeps: on a service of the owner's own site, `<site>:<id>`, as bitrix24-cli keeps
@@ -0,0 +1,86 @@
1
+ import { type Sector } from "./organization-sectors.js";
2
+ /**
3
+ * The domain-list pack: lists too big, too often updated or share-alike to build into the package. Published as
4
+ * assets of a WireCat GitHub release, downloaded whole by `domain-lists update` and matched only on this computer:
5
+ * a lookup per sender would tell a third party who writes to the owner.
6
+ */
7
+ export declare const PACK_TAG = "domain-lists";
8
+ export declare const PACK_MANIFEST_URL = "https://github.com/WireCatLabs/cli-core/releases/download/domain-lists/manifest.json";
9
+ /**
10
+ * `commercial-ok`: any use, paid services included. `non-commercial`: WireCat, which is free, may use it; a paid
11
+ * service built around WireCat may not, and leaves it out with `--commercial-only`.
12
+ */
13
+ export type LicenceClass = "commercial-ok" | "non-commercial";
14
+ /**
15
+ * One list. `sector` files give an organization its sector; `freemail` files name mailbox providers, which never
16
+ * make an organization; `bad` files only say a host is known for spam, phishing or malware, and never set a sector. A line is a domain, or a domain, a tab and a sector (or a source's own
17
+ * category, for `bad`). `upstream` lists may not be redistributed: the command fetches them from their source, whole.
18
+ */
19
+ export interface PackSource {
20
+ id: string;
21
+ title: string;
22
+ signal: "sector" | "freemail" | "bad";
23
+ /** The sector or category of a line that names none. */
24
+ tag?: string;
25
+ licence: string;
26
+ licence_url: string;
27
+ class: LicenceClass;
28
+ attribution: string;
29
+ homepage: string;
30
+ /** Where the file is: the release asset, or the source itself for `upstream`. */
31
+ url: string;
32
+ /** The gzip file as published; absent for `upstream`, whose file changes at its source. */
33
+ sha256?: string;
34
+ bytes?: number;
35
+ /** The most an `upstream` file may weigh. */
36
+ max_bytes?: number;
37
+ upstream?: boolean;
38
+ /** Lines in the published file; absent for `upstream`. */
39
+ count?: number;
40
+ /** Lines per tag, for `domain-lists list`. */
41
+ tags?: Record<string, number>;
42
+ fetched_at?: string;
43
+ }
44
+ export interface PackManifest {
45
+ /** The build date, `YYYY-MM-DD`, newest wins. */
46
+ version: string;
47
+ built_at: string;
48
+ sources: PackSource[];
49
+ }
50
+ /** The pack as this computer holds it: what was installed from which manifest. */
51
+ export interface InstalledPack extends PackManifest {
52
+ installed_at: string;
53
+ commercial_only: boolean;
54
+ /** The files in place, by source id: their sha256 as checked, and their lines. */
55
+ files: Record<string, {
56
+ sha256: string;
57
+ lines: number;
58
+ bytes: number;
59
+ }>;
60
+ }
61
+ /** Shared by every CLI of the family, like the models: one pack per computer. */
62
+ export declare const domainListsDirectory: (env?: NodeJS.ProcessEnv) => string;
63
+ export declare const listFile: (directory: string, id: string) => string;
64
+ export declare const installedPack: (env?: NodeJS.ProcessEnv) => InstalledPack | undefined;
65
+ export interface DomainHits {
66
+ /** The pack's sectors of each domain looked up, in list order. */
67
+ sectors: Map<string, Sector[]>;
68
+ /** The `bad` sources that name each host exactly, as `source` or `source:category`. */
69
+ bad: Map<string, string[]>;
70
+ }
71
+ export interface LookupOptions {
72
+ env?: NodeJS.ProcessEnv;
73
+ /** Leave out `non-commercial` sources even when they are installed: a paid service sets it. */
74
+ commercialOnly?: boolean;
75
+ }
76
+ /**
77
+ * Reads each list once from disk, a megabyte at a time, keeping only the lines naming `hosts`. Exact names only: an
78
+ * entry `click.mail.brand.example` says nothing about `brand.example`. The pack's biggest list has millions of lines,
79
+ * so it is never held in memory; the caller passes the few hosts it needs.
80
+ */
81
+ export declare const lookupDomains: (hosts: ReadonlySet<string>, options?: LookupOptions) => DomainHits;
82
+ /**
83
+ * A mailbox provider from the pack's `freemail` lists (UT1 `webmail`). They are small, so they are held in memory and
84
+ * read again only when `domain-lists update` replaced the pack.
85
+ */
86
+ export declare const isPackFreeMailDomain: (domain: string, env?: NodeJS.ProcessEnv) => boolean;
@@ -0,0 +1,110 @@
1
+ import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { wirecatDirectory } from "../store/path.js";
5
+ import { isSector } from "./organization-sectors.js";
6
+ /**
7
+ * The domain-list pack: lists too big, too often updated or share-alike to build into the package. Published as
8
+ * assets of a WireCat GitHub release, downloaded whole by `domain-lists update` and matched only on this computer:
9
+ * a lookup per sender would tell a third party who writes to the owner.
10
+ */
11
+ export const PACK_TAG = "domain-lists";
12
+ export const PACK_MANIFEST_URL = `https://github.com/WireCatLabs/cli-core/releases/download/${PACK_TAG}/manifest.json`;
13
+ /** Shared by every CLI of the family, like the models: one pack per computer. */
14
+ export const domainListsDirectory = (env = process.env) => join(wirecatDirectory(env), "lists", "domains");
15
+ export const listFile = (directory, id) => join(directory, `${id}.txt`);
16
+ export const installedPack = (env = process.env) => {
17
+ try {
18
+ return JSON.parse(readFileSync(join(domainListsDirectory(env), "manifest.json"), "utf8"));
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ };
24
+ const CHUNK = 1 << 20;
25
+ /**
26
+ * Reads each list once from disk, a megabyte at a time, keeping only the lines naming `hosts`. Exact names only: an
27
+ * entry `click.mail.brand.example` says nothing about `brand.example`. The pack's biggest list has millions of lines,
28
+ * so it is never held in memory; the caller passes the few hosts it needs.
29
+ */
30
+ export const lookupDomains = (hosts, options = {}) => {
31
+ const hits = { sectors: new Map(), bad: new Map() };
32
+ const pack = installedPack(options.env);
33
+ if (pack === undefined || hosts.size === 0)
34
+ return hits;
35
+ const directory = domainListsDirectory(options.env);
36
+ for (const source of pack.sources) {
37
+ if (pack.files[source.id] === undefined || source.signal === "freemail")
38
+ continue;
39
+ if (options.commercialOnly && source.class !== "commercial-ok")
40
+ continue;
41
+ scanLines(listFile(directory, source.id), (line) => {
42
+ const tab = line.indexOf("\t");
43
+ const host = tab === -1 ? line : line.slice(0, tab);
44
+ if (!hosts.has(host))
45
+ return;
46
+ const tag = tab === -1 ? source.tag : line.slice(tab + 1);
47
+ if (source.signal === "bad") {
48
+ const name = tag === undefined ? source.id : `${source.id}:${tag}`;
49
+ hits.bad.set(host, [...(hits.bad.get(host) ?? []), name]);
50
+ }
51
+ else if (tag !== undefined && isSector(tag))
52
+ hits.sectors.set(host, [...(hits.sectors.get(host) ?? []), tag]);
53
+ });
54
+ }
55
+ return hits;
56
+ };
57
+ let freeMail;
58
+ const manifestStamp = (env) => {
59
+ try {
60
+ return statSync(join(domainListsDirectory(env), "manifest.json")).mtimeMs;
61
+ }
62
+ catch {
63
+ return 0;
64
+ }
65
+ };
66
+ /**
67
+ * A mailbox provider from the pack's `freemail` lists (UT1 `webmail`). They are small, so they are held in memory and
68
+ * read again only when `domain-lists update` replaced the pack.
69
+ */
70
+ export const isPackFreeMailDomain = (domain, env) => {
71
+ const stamp = manifestStamp(env);
72
+ if (freeMail?.stamp !== stamp) {
73
+ const set = new Set();
74
+ const pack = installedPack(env);
75
+ for (const source of pack?.sources ?? [])
76
+ if (source.signal === "freemail" && pack?.files[source.id] !== undefined)
77
+ scanLines(listFile(domainListsDirectory(env), source.id), (line) => set.add(line.split("\t")[0] ?? line));
78
+ freeMail = { set, stamp };
79
+ }
80
+ return freeMail.set.has(domain);
81
+ };
82
+ const scanLines = (path, line) => {
83
+ let descriptor;
84
+ try {
85
+ descriptor = openSync(path, "r");
86
+ }
87
+ catch {
88
+ return;
89
+ }
90
+ try {
91
+ const buffer = Buffer.allocUnsafe(CHUNK);
92
+ const text = new StringDecoder("utf8");
93
+ let rest = "";
94
+ for (;;) {
95
+ const read = readSync(descriptor, buffer, 0, CHUNK, null);
96
+ if (read === 0)
97
+ break;
98
+ const lines = (rest + text.write(buffer.subarray(0, read))).split("\n");
99
+ rest = lines.pop() ?? "";
100
+ for (const one of lines)
101
+ if (one !== "")
102
+ line(one);
103
+ }
104
+ if (rest !== "")
105
+ line(rest);
106
+ }
107
+ finally {
108
+ closeSync(descriptor);
109
+ }
110
+ };