@wirecat/cli-core 0.647.0 → 0.649.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 (80) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.d.ts +5 -0
  4. package/dist/cli/account-remove.js +6 -1
  5. package/dist/cli/app-doctor-command.js +15 -57
  6. package/dist/cli/app-store.d.ts +12 -0
  7. package/dist/cli/app-store.js +25 -0
  8. package/dist/cli/commands-command.js +10 -3
  9. package/dist/cli/doctor-reports-command.d.ts +22 -0
  10. package/dist/cli/doctor-reports-command.js +82 -0
  11. package/dist/cli/help/command-help.d.ts +1 -0
  12. package/dist/cli/help/command-help.js +7 -8
  13. package/dist/cli/index.d.ts +3 -1
  14. package/dist/cli/index.js +3 -1
  15. package/dist/cli/messenger/doctor-command.js +21 -64
  16. package/dist/cli/messenger/stats-command.js +1 -1
  17. package/dist/cli/messenger/store-maintenance-command.js +3 -3
  18. package/dist/cli/messenger/tasks-command.js +1 -3
  19. package/dist/cli/permission-keys.js +4 -2
  20. package/dist/cli/program.js +26 -10
  21. package/dist/cli/settings.d.ts +2 -0
  22. package/dist/cli/settings.js +3 -2
  23. package/dist/cli/store-recover.js +2 -2
  24. package/dist/cli/unknown-profile.d.ts +9 -0
  25. package/dist/cli/unknown-profile.js +23 -0
  26. package/dist/crm/cli/search-all.js +4 -4
  27. package/dist/domain/providers.d.ts +4 -1
  28. package/dist/domain/providers.js +9 -2
  29. package/dist/domain/record-types.d.ts +24 -3
  30. package/dist/domain/record-types.js +23 -2
  31. package/dist/domain/records-table.js +4 -3
  32. package/dist/domain/records.d.ts +1 -1
  33. package/dist/domain/records.js +3 -2
  34. package/dist/errors/failures.d.ts +2 -0
  35. package/dist/errors/failures.js +6 -0
  36. package/dist/errors/reasons.js +17 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +1 -0
  39. package/dist/kit/index.d.ts +1 -0
  40. package/dist/kit/index.js +1 -0
  41. package/dist/kit/own-catalogue.d.ts +7 -0
  42. package/dist/kit/own-catalogue.js +21 -0
  43. package/dist/oauth/index.d.ts +2 -2
  44. package/dist/oauth/index.js +2 -1
  45. package/dist/oauth/provider.d.ts +4 -0
  46. package/dist/oauth/provider.js +16 -1
  47. package/dist/oauth/storage.d.ts +5 -0
  48. package/dist/oauth/storage.js +20 -0
  49. package/dist/runs/error-detail.d.ts +1 -1
  50. package/dist/runs/error-detail.js +5 -2
  51. package/dist/runs/events.d.ts +1 -1
  52. package/dist/runs/secrets.d.ts +5 -4
  53. package/dist/runs/secrets.js +8 -4
  54. package/dist/sends/permissions.d.ts +2 -0
  55. package/dist/sends/permissions.js +4 -1
  56. package/dist/services/document-source.js +9 -1
  57. package/dist/services/notes-search.d.ts +10 -5
  58. package/dist/services/notes-search.js +19 -7
  59. package/dist/services/search-all.js +19 -11
  60. package/dist/sftp/index.d.ts +1 -0
  61. package/dist/sftp/index.js +1 -0
  62. package/dist/sftp/session.d.ts +61 -0
  63. package/dist/sftp/session.js +230 -0
  64. package/dist/sftp/ssh2.d.ts +38 -0
  65. package/dist/sftp/ssh2.js +306 -0
  66. package/dist/store/index.d.ts +1 -0
  67. package/dist/store/index.js +1 -0
  68. package/dist/store/sqlite/added-sources.d.ts +38 -0
  69. package/dist/store/sqlite/added-sources.js +80 -50
  70. package/dist/store/sqlite/crm-activities.d.ts +2 -0
  71. package/dist/store/sqlite/crm-activities.js +17 -0
  72. package/dist/store/sqlite/deals.d.ts +4 -3
  73. package/dist/store/sqlite/deals.js +8 -2
  74. package/dist/store/sqlite/open-store.js +14 -1
  75. package/dist/store/sqlite/record-projectors-document.d.ts +12 -0
  76. package/dist/store/sqlite/record-projectors-document.js +81 -0
  77. package/dist/store/sqlite/record-projectors.js +2 -0
  78. package/package.json +14 -4
  79. package/parity.json +2 -11
  80. package/schemas/records-envelope.v1.schema.json +57 -2
@@ -0,0 +1,230 @@
1
+ import { backoffMs, CliError, isCliError, realSleep, } from "@wirecat/cli-base";
2
+ import { providerEvent, providerRequest } from "../cli/command-runs.js";
3
+ import { openWire, probeHostKey } from "./ssh2.js";
4
+ export const SFTP_CONNECT_TIMEOUT_MS = 20_000;
5
+ export const SFTP_OPERATION_TIMEOUT_MS = 30_000;
6
+ /** Every operation only reads, so a transient failure is tried again: three attempts in all. */
7
+ export const SFTP_RETRY = { retries: 2, baseDelayMs: 500, maxDelayMs: 5_000, maxRetryAfterMs: 0 };
8
+ const normalized = (fingerprint) => fingerprint
9
+ .trim()
10
+ .replace(/^SHA256:/i, "")
11
+ .replace(/=+$/, "");
12
+ const stoppedBy = (signal) => {
13
+ if (!signal?.aborted)
14
+ return undefined;
15
+ if (isCliError(signal.reason))
16
+ return signal.reason;
17
+ const timeout = signal.reason instanceof Error && signal.reason.name === "TimeoutError";
18
+ return new CliError(timeout ? "timeout" : "cancelled", "the SFTP operation was stopped before it finished", {
19
+ reason: timeout ? "command.timed-out" : "command.cancelled",
20
+ });
21
+ };
22
+ const timedOut = (what, ms) => new CliError("timeout", `the SFTP server did not answer the ${what} within ${Math.ceil(ms / 1000)} s`, {
23
+ reason: "sftp.timeout",
24
+ retryable: true,
25
+ });
26
+ /**
27
+ * Runs `work` until it settles or `ms` pass without a call of `touch`. The wait goes through `sleep` with reason
28
+ * `timeout`, so a test decides when a deadline passes.
29
+ */
30
+ const deadline = async (ms, sleep, expire, work) => {
31
+ let timer = new AbortController();
32
+ let expired = false;
33
+ const arm = () => {
34
+ timer.abort();
35
+ timer = new AbortController();
36
+ sleep(ms, timer.signal, "timeout").then(() => {
37
+ expired = true;
38
+ expire();
39
+ }, () => { });
40
+ };
41
+ arm();
42
+ try {
43
+ return await work(arm);
44
+ }
45
+ catch (error) {
46
+ if (expired)
47
+ throw new Expired();
48
+ throw error;
49
+ }
50
+ finally {
51
+ timer.abort();
52
+ }
53
+ };
54
+ class Expired extends Error {
55
+ }
56
+ const retrying = async (target, job) => {
57
+ const retry = target.retry ?? SFTP_RETRY;
58
+ const events = target.events ?? providerEvent;
59
+ let waitMs;
60
+ for (let attempt = 1;; attempt++) {
61
+ const stop = stoppedBy(target.signal);
62
+ if (stop)
63
+ throw stop;
64
+ const answered = providerRequest(job.operation, events, {
65
+ transport: "sftp",
66
+ attempt,
67
+ ...(waitMs === undefined ? {} : { waitMs }),
68
+ });
69
+ try {
70
+ const value = await job.run(attempt);
71
+ answered({ ids: { host: target.host }, ...job.answer?.(value) });
72
+ return value;
73
+ }
74
+ catch (caught) {
75
+ const error = stoppedBy(target.signal) ?? caught;
76
+ answered({ ids: { host: target.host }, error, ...(isCliError(error) ? { errorCode: error.code } : {}) });
77
+ const again = isCliError(error) && error.details.retryable === true && !target.signal?.aborted;
78
+ if (!again || attempt > retry.retries) {
79
+ if (isCliError(error) && error.details.retryable === true)
80
+ throw new CliError(error.code, error.message, { ...error.details, attempts: attempt });
81
+ throw error;
82
+ }
83
+ waitMs = backoffMs(attempt, retry, target.random);
84
+ try {
85
+ await target.sleep(waitMs, target.signal, "retry");
86
+ }
87
+ catch {
88
+ throw stoppedBy(target.signal) ?? error;
89
+ }
90
+ }
91
+ }
92
+ };
93
+ const wireOptions = (target, credentials = {}) => ({
94
+ host: target.host,
95
+ port: target.port ?? 22,
96
+ username: credentials.username ?? "wirecat",
97
+ password: credentials.password,
98
+ privateKey: credentials.privateKey,
99
+ passphrase: credentials.passphrase,
100
+ socket: target.socket,
101
+ });
102
+ /** Opens the connection once, under the connect deadline and the run's signal. */
103
+ const connectOnce = async (target, open) => {
104
+ const ms = target.connectTimeoutMs ?? SFTP_CONNECT_TIMEOUT_MS;
105
+ const attempt = new AbortController();
106
+ const signal = target.signal ? AbortSignal.any([target.signal, attempt.signal]) : attempt.signal;
107
+ try {
108
+ return await deadline(ms, target.sleep, () => attempt.abort(), () => open(signal));
109
+ }
110
+ catch (error) {
111
+ if (error instanceof Expired)
112
+ throw timedOut("connection", ms);
113
+ throw error;
114
+ }
115
+ };
116
+ const seams = (target) => ({
117
+ ...target,
118
+ sleep: target.sleep ?? realSleep,
119
+ random: target.random ?? Math.random,
120
+ });
121
+ /**
122
+ * The server's host key, for a sign-in to show the owner before the fingerprint is pinned: the connection stops at
123
+ * the key exchange and sends no credential.
124
+ */
125
+ export const sftpHostKey = async (target) => {
126
+ const options = seams(target);
127
+ return retrying(options, {
128
+ operation: "sftp.host-key",
129
+ run: () => connectOnce(options, async (signal) => probeHostKey(wireOptions(options), signal)),
130
+ });
131
+ };
132
+ const closedError = () => new CliError("validation_error", "the SFTP connection is closed", { reason: "sftp.closed" });
133
+ const refuseOptions = (options) => {
134
+ if (!options.hostKey?.trim())
135
+ throw new CliError("configuration_error", "no host key is pinned for this SFTP server: show the owner its fingerprint (sftpHostKey) and pin the one confirmed", { reason: "sftp.host-key-missing" });
136
+ const auth = options.auth;
137
+ if (!auth?.password && !auth?.privateKey)
138
+ throw new CliError("configuration_error", "an SFTP connection needs a password or a private key", {
139
+ reason: "sftp.auth-missing",
140
+ });
141
+ };
142
+ /**
143
+ * A read-only SFTP connection: list, stat and read, nothing that writes. The host key must match the pinned
144
+ * fingerprint before a credential is sent. Each operation is a request in the run's events (host and operation,
145
+ * never a path or file content) and is tried again on a transient failure over a fresh connection.
146
+ */
147
+ export const openSftp = async (input) => {
148
+ refuseOptions(input);
149
+ const options = seams(input);
150
+ const pinned = normalized(options.hostKey);
151
+ const operationMs = options.operationTimeoutMs ?? SFTP_OPERATION_TIMEOUT_MS;
152
+ const credentials = {
153
+ username: options.username,
154
+ ...("password" in options.auth
155
+ ? { password: options.auth.password }
156
+ : { privateKey: options.auth.privateKey, passphrase: options.auth.passphrase }),
157
+ };
158
+ let wire;
159
+ let connecting;
160
+ let closed = false;
161
+ const drop = (failed = wire) => {
162
+ if (wire === failed)
163
+ wire = undefined;
164
+ failed?.close();
165
+ };
166
+ const abort = () => drop();
167
+ options.signal?.addEventListener("abort", abort, { once: true });
168
+ const open = async () => {
169
+ const opened = await connectOnce(options, async (signal) => openWire(wireOptions(options, credentials), (key) => normalized(key.fingerprint) === pinned, signal));
170
+ if (options.signal?.aborted || closed) {
171
+ opened.close();
172
+ throw stoppedBy(options.signal) ?? closedError();
173
+ }
174
+ wire = opened;
175
+ return opened;
176
+ };
177
+ // Operations started together share one connection attempt, so none opens a connection that close() cannot reach.
178
+ const connected = async () => {
179
+ if (closed)
180
+ throw closedError();
181
+ if (wire)
182
+ return wire;
183
+ connecting ??= open().finally(() => {
184
+ connecting = undefined;
185
+ });
186
+ return connecting;
187
+ };
188
+ const operation = (name, work, answer) => retrying(options, {
189
+ operation: name,
190
+ run: async () => {
191
+ const current = await connected();
192
+ try {
193
+ return await deadline(operationMs, options.sleep, () => current.close(), (touch) => work(current, touch));
194
+ }
195
+ catch (error) {
196
+ if (error instanceof Expired) {
197
+ drop(current);
198
+ throw timedOut("request", operationMs);
199
+ }
200
+ if (isCliError(error) && error.details.retryable === true)
201
+ drop(current);
202
+ throw error;
203
+ }
204
+ },
205
+ ...(answer ? { answer } : {}),
206
+ });
207
+ try {
208
+ await retrying(options, { operation: "sftp.connect", run: () => connected() });
209
+ }
210
+ catch (error) {
211
+ options.signal?.removeEventListener("abort", abort);
212
+ throw error;
213
+ }
214
+ return {
215
+ list: (path) => operation("sftp.list", (current) => current.list(path), (entries) => ({ counts: { entries: entries.length } })),
216
+ stat: (path) => operation("sftp.stat", (current) => current.stat(path)),
217
+ readFile: (path, { maxBytes }) => {
218
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
219
+ return Promise.reject(new CliError("validation_error", "maxBytes must be a whole number of bytes, 0 or more", {
220
+ reason: "input.invalid",
221
+ }));
222
+ return operation("sftp.read", (current, touch) => current.read(path, maxBytes, touch), (bytes) => ({ bytes: bytes.length }));
223
+ },
224
+ close: async () => {
225
+ closed = true;
226
+ options.signal?.removeEventListener("abort", abort);
227
+ drop();
228
+ },
229
+ };
230
+ };
@@ -0,0 +1,38 @@
1
+ import type { Duplex } from "node:stream";
2
+ /** What a server's host key is, as `ssh-keygen -lf` prints it: `SHA256:` and unpadded base64. */
3
+ export interface HostKey {
4
+ algorithm: string;
5
+ fingerprint: string;
6
+ }
7
+ export type SftpKind = "file" | "directory" | "symlink" | "other";
8
+ export interface SftpEntry {
9
+ name: string;
10
+ kind: SftpKind;
11
+ size: number;
12
+ /** ISO 8601, from the server's whole-second modification time. */
13
+ modifiedAt: string;
14
+ }
15
+ export interface WireOptions {
16
+ host: string;
17
+ port: number;
18
+ username: string;
19
+ password?: string | undefined;
20
+ privateKey?: string | Uint8Array | undefined;
21
+ passphrase?: string | undefined;
22
+ /** Opens a stream already connected to the server, instead of a TCP connection to `host`. */
23
+ socket?: (() => Duplex | Promise<Duplex>) | undefined;
24
+ }
25
+ export interface Wire {
26
+ list(path: string): Promise<SftpEntry[]>;
27
+ stat(path: string): Promise<SftpEntry>;
28
+ read(path: string, maxBytes: number, progress: () => void): Promise<Uint8Array>;
29
+ close(): void;
30
+ }
31
+ export declare const hostKeyOf: (blob: Buffer) => HostKey;
32
+ /**
33
+ * Connects, checks the host key with `accept` before any credential is sent, and opens the SFTP channel. `signal`
34
+ * ends the attempt and destroys the connection.
35
+ */
36
+ export declare const openWire: (options: WireOptions, accept: (key: HostKey) => boolean, signal: AbortSignal) => Promise<Wire>;
37
+ /** Connects only as far as the server's host key, and returns it; no credential is sent. */
38
+ export declare const probeHostKey: (options: WireOptions, signal: AbortSignal) => Promise<HostKey>;
@@ -0,0 +1,306 @@
1
+ import { createHash } from "node:crypto";
2
+ import { basename } from "node:path";
3
+ import { CliError, isCliError } from "@wirecat/cli-base";
4
+ let library;
5
+ /** ssh2 is an optional peer: a CLI that never speaks SFTP neither installs nor loads it. */
6
+ const ssh2 = () => {
7
+ library ??= import("ssh2").then((module) => (module.default ?? module), () => {
8
+ library = undefined;
9
+ throw new CliError("configuration_error", "SFTP needs the ssh2 package: add ssh2 to this CLI's dependencies", {
10
+ reason: "sftp.library-missing",
11
+ });
12
+ });
13
+ return library;
14
+ };
15
+ export const hostKeyOf = (blob) => {
16
+ const length = blob.length >= 4 ? blob.readUInt32BE(0) : 0;
17
+ const algorithm = /^[\w@.-]{1,64}$/.test(blob.toString("latin1", 4, 4 + length))
18
+ ? blob.toString("latin1", 4, 4 + length)
19
+ : "unknown";
20
+ const fingerprint = `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`;
21
+ return { algorithm, fingerprint };
22
+ };
23
+ const TRANSIENT_CODES = new Set([
24
+ "ECONNRESET",
25
+ "ECONNREFUSED",
26
+ "ECONNABORTED",
27
+ "ETIMEDOUT",
28
+ "EPIPE",
29
+ "EHOSTUNREACH",
30
+ "ENETUNREACH",
31
+ "ENETDOWN",
32
+ "EAI_AGAIN",
33
+ ]);
34
+ /** SFTP status codes (draft-ietf-secsh-filexfer-02, section 7). */
35
+ const NO_SUCH_FILE = 2;
36
+ const PERMISSION_DENIED = 3;
37
+ const NO_CONNECTION = 6;
38
+ const CONNECTION_LOST = 7;
39
+ /** SSH disconnect reasons (RFC 4253, section 11.1) a busy or restarting server sends: service not available, connection
40
+ * lost, too many connections. */
41
+ const DISCONNECTS_TO_RETRY = new Set([7, 10, 12]);
42
+ const lost = () => new CliError("network_error", "the connection to the SFTP server broke", {
43
+ reason: "network.failed",
44
+ retryable: true,
45
+ });
46
+ /**
47
+ * The vendor's error as a CliError with fixed wording: an SFTP server's message and the path asked can name a caller's
48
+ * phone number, and a key error can quote the key (WC-SECR-6).
49
+ */
50
+ const failureOf = (error, from = "sftp") => {
51
+ if (isCliError(error))
52
+ return error;
53
+ const { code, level, message } = (error ?? {});
54
+ if (level === "client-authentication")
55
+ return new CliError("authentication_error", "the SFTP server refused the user name and password or key", {
56
+ reason: "auth.failed",
57
+ });
58
+ if (from === "ssh" && typeof code === "number")
59
+ return new CliError(DISCONNECTS_TO_RETRY.has(code) ? "provider_unavailable" : "provider_error", `the SFTP server ended the connection (SSH disconnect reason ${code})`, {
60
+ reason: DISCONNECTS_TO_RETRY.has(code) ? "provider.unavailable" : "provider.refused",
61
+ ...(DISCONNECTS_TO_RETRY.has(code) ? { retryable: true } : {}),
62
+ });
63
+ if (code === NO_SUCH_FILE)
64
+ return new CliError("not_found", "no such file or folder on the SFTP server", { reason: "file.not-found" });
65
+ if (code === PERMISSION_DENIED)
66
+ return new CliError("permission_error", "the SFTP server denied access to the path", { reason: "file.denied" });
67
+ if (code === NO_CONNECTION || code === CONNECTION_LOST || message === "No response from server")
68
+ return lost();
69
+ if (level === "client-dns" || code === "ENOTFOUND")
70
+ return new CliError("network_error", "the SFTP server's host name was not found", { reason: "network.failed" });
71
+ if ((typeof code === "string" && TRANSIENT_CODES.has(code)) ||
72
+ level === "client-socket" ||
73
+ level === "client-timeout" ||
74
+ level === "protocol")
75
+ return lost();
76
+ if (typeof code === "number")
77
+ return new CliError("provider_error", `the SFTP server refused the request (status ${code})`, {
78
+ reason: "provider.refused",
79
+ });
80
+ return new CliError("provider_unavailable", "the SFTP server failed the request", {
81
+ reason: "provider.unavailable",
82
+ retryable: true,
83
+ });
84
+ };
85
+ const KIND_BITS = 0o170000;
86
+ const kindOf = (mode) => {
87
+ const bits = mode & KIND_BITS;
88
+ if (bits === 0o100000)
89
+ return "file";
90
+ if (bits === 0o040000)
91
+ return "directory";
92
+ if (bits === 0o120000)
93
+ return "symlink";
94
+ return "other";
95
+ };
96
+ const entryOf = (name, attrs) => ({
97
+ name,
98
+ kind: kindOf(attrs.mode),
99
+ size: Number(attrs.size),
100
+ modifiedAt: new Date(attrs.mtime * 1000).toISOString(),
101
+ });
102
+ const tooLarge = (maxBytes) => new CliError("validation_error", `the file is larger than the read's limit of ${maxBytes} bytes`, {
103
+ reason: "sftp.too-large",
104
+ max_bytes: maxBytes,
105
+ });
106
+ const CHUNK = 64 * 1024;
107
+ const IN_FLIGHT = 16;
108
+ const readAll = async (sftp, path, maxBytes, progress) => {
109
+ const call = (work) => new Promise((resolve, reject) => work((error, value) => (error ? reject(failureOf(error)) : resolve(value))));
110
+ const handle = await call((done) => sftp.open(path, "r", (error, value) => done(error, value)));
111
+ const readAt = (position, length) => call((done) => {
112
+ const into = Buffer.alloc(length);
113
+ sftp.read(handle, into, 0, length, position, (error, bytes) => done(error, into.subarray(0, bytes)));
114
+ });
115
+ // A server may answer a read with fewer bytes than asked; only an empty answer is the end of the file.
116
+ const fill = async (position, length) => {
117
+ const parts = [];
118
+ let got = 0;
119
+ while (got < length) {
120
+ const part = await readAt(position + got, length - got);
121
+ if (part.length === 0)
122
+ break;
123
+ parts.push(part);
124
+ got += part.length;
125
+ progress();
126
+ }
127
+ return Buffer.concat(parts, got);
128
+ };
129
+ try {
130
+ const stats = await call((done) => sftp.fstat(handle, (error, value) => done(error, value)));
131
+ if (kindOf(stats.mode) !== "file")
132
+ throw new CliError("validation_error", "the path names a folder or another thing that is not a file", {
133
+ reason: "file.not-a-file",
134
+ });
135
+ if (stats.size > maxBytes)
136
+ throw tooLarge(maxBytes);
137
+ const size = Number(stats.size);
138
+ const pieces = [];
139
+ let next = 0;
140
+ const worker = async () => {
141
+ for (let index = next++; index * CHUNK < size; index = next++)
142
+ pieces[index] = await fill(index * CHUNK, Math.min(CHUNK, size - index * CHUNK));
143
+ };
144
+ await Promise.all(Array.from({ length: Math.min(IN_FLIGHT, Math.ceil(size / CHUNK)) }, worker));
145
+ const short = pieces.findIndex((piece, index) => piece.length < Math.min(CHUNK, size - index * CHUNK));
146
+ const parts = short === -1 ? pieces : pieces.slice(0, short + 1);
147
+ let total = parts.reduce((sum, part) => sum + part.length, 0);
148
+ // The size came from a stat; a file still being written can be longer by now, so read on to its end.
149
+ for (let tail = short === -1 ? await fill(total, CHUNK) : Buffer.alloc(0); tail.length > 0;) {
150
+ parts.push(tail);
151
+ total += tail.length;
152
+ if (total > maxBytes)
153
+ throw tooLarge(maxBytes);
154
+ tail = await fill(total, CHUNK);
155
+ }
156
+ return new Uint8Array(Buffer.concat(parts, total));
157
+ }
158
+ finally {
159
+ sftp.close(handle, () => { });
160
+ }
161
+ };
162
+ const validKey = (library, options) => {
163
+ if (options.privateKey === undefined)
164
+ return;
165
+ const key = typeof options.privateKey === "string" ? options.privateKey : Buffer.from(options.privateKey);
166
+ const parsed = library.utils.parseKey(key, options.passphrase);
167
+ if (parsed instanceof Error)
168
+ throw new CliError("configuration_error", "the SFTP private key cannot be read: check the key and its passphrase", {
169
+ reason: "sftp.key-invalid",
170
+ });
171
+ };
172
+ const configOf = async (options, verify) => ({
173
+ host: options.host,
174
+ port: options.port,
175
+ username: options.username,
176
+ ...(options.password === undefined ? {} : { password: options.password }),
177
+ ...(options.privateKey === undefined
178
+ ? {}
179
+ : {
180
+ privateKey: typeof options.privateKey === "string" ? options.privateKey : Buffer.from(options.privateKey),
181
+ }),
182
+ ...(options.passphrase === undefined ? {} : { passphrase: options.passphrase }),
183
+ ...(options.socket ? { sock: await options.socket() } : {}),
184
+ // The caller's own deadline bounds the handshake; ssh2's timer would be a second, unseen clock.
185
+ readyTimeout: 0,
186
+ keepaliveInterval: 10_000,
187
+ keepaliveCountMax: 3,
188
+ tryKeyboard: false,
189
+ hostVerifier: verify,
190
+ });
191
+ /**
192
+ * Connects, checks the host key with `accept` before any credential is sent, and opens the SFTP channel. `signal`
193
+ * ends the attempt and destroys the connection.
194
+ */
195
+ export const openWire = async (options, accept, signal) => {
196
+ const library = await ssh2();
197
+ validKey(library, options);
198
+ signal.throwIfAborted();
199
+ const client = new library.Client();
200
+ let refused;
201
+ const verify = (blob) => {
202
+ const key = hostKeyOf(blob);
203
+ if (accept(key))
204
+ return true;
205
+ refused = key;
206
+ return false;
207
+ };
208
+ const config = await configOf(options, verify);
209
+ signal.throwIfAborted();
210
+ const sftp = await new Promise((resolve, reject) => {
211
+ const stop = () => {
212
+ client.destroy();
213
+ reject(signal.reason);
214
+ };
215
+ signal.addEventListener("abort", stop, { once: true });
216
+ const fail = (error) => {
217
+ signal.removeEventListener("abort", stop);
218
+ client.destroy();
219
+ reject(refused
220
+ ? new CliError("authentication_error", `the SFTP server's host key (${refused.algorithm} ${refused.fingerprint}) is not the pinned one; ` +
221
+ "check it with the server's owner before pinning it again", { reason: "sftp.host-key-mismatch" })
222
+ : failureOf(error, "ssh"));
223
+ };
224
+ client.once("error", fail);
225
+ client.once("close", () => fail(lost()));
226
+ client.once("ready", () => client.sftp((error, channel) => {
227
+ if (error)
228
+ return fail(error);
229
+ signal.removeEventListener("abort", stop);
230
+ client.removeListener("error", fail);
231
+ client.on("error", () => { });
232
+ resolve(channel);
233
+ }));
234
+ client.connect(config);
235
+ });
236
+ return wireOf(client, sftp);
237
+ };
238
+ const wireOf = (client, sftp) => {
239
+ const pending = new Set();
240
+ let closed = false;
241
+ const close = () => {
242
+ if (closed)
243
+ return;
244
+ closed = true;
245
+ for (const reject of pending)
246
+ reject(lost());
247
+ pending.clear();
248
+ client.destroy();
249
+ };
250
+ client.once("close", close);
251
+ const guarded = (work) => {
252
+ if (closed)
253
+ return Promise.reject(lost());
254
+ return new Promise((resolve, reject) => {
255
+ const settle = (error) => reject(error);
256
+ pending.add(settle);
257
+ work().then((value) => {
258
+ pending.delete(settle);
259
+ resolve(value);
260
+ }, (error) => {
261
+ pending.delete(settle);
262
+ reject(failureOf(error));
263
+ });
264
+ });
265
+ };
266
+ return {
267
+ list: (path) => guarded(() => new Promise((resolve, reject) => sftp.readdir(path, (error, list) => error
268
+ ? reject(error)
269
+ : resolve(list
270
+ .filter((one) => one.filename !== "." && one.filename !== "..")
271
+ .map((one) => entryOf(one.filename, one.attrs)))))),
272
+ stat: (path) => guarded(() => new Promise((resolve, reject) => sftp.stat(path, (error, attrs) => (error ? reject(error) : resolve(entryOf(basename(path), attrs)))))),
273
+ read: (path, maxBytes, progress) => guarded(() => readAll(sftp, path, maxBytes, progress)),
274
+ close,
275
+ };
276
+ };
277
+ /** Connects only as far as the server's host key, and returns it; no credential is sent. */
278
+ export const probeHostKey = async (options, signal) => {
279
+ const library = await ssh2();
280
+ signal.throwIfAborted();
281
+ const client = new library.Client();
282
+ let seen;
283
+ const config = await configOf(options, (blob) => {
284
+ seen = hostKeyOf(blob);
285
+ return false;
286
+ });
287
+ signal.throwIfAborted();
288
+ return new Promise((resolve, reject) => {
289
+ const stop = () => {
290
+ client.destroy();
291
+ reject(signal.reason);
292
+ };
293
+ signal.addEventListener("abort", stop, { once: true });
294
+ const done = (error) => {
295
+ signal.removeEventListener("abort", stop);
296
+ client.destroy();
297
+ if (seen)
298
+ resolve(seen);
299
+ else
300
+ reject(failureOf(error ?? lost(), "ssh"));
301
+ };
302
+ client.once("error", done);
303
+ client.once("close", () => done());
304
+ client.connect(config);
305
+ });
306
+ };
@@ -35,6 +35,7 @@ export { type ProjectAnnotationPreview, type ProjectAnnotationPreviewOptions, pr
35
35
  export { decodeProjectAnnotationSnapshot, type ProjectAnnotationSnapshot, type ProjectAnnotationSnapshotOptions, type ProjectAnnotationSnapshotResult, projectAnnotationSnapshotFingerprint, projectAnnotationSnapshotSchema, snapshotProjectAnnotations, } from "./project-transfer/snapshot.js";
36
36
  export { planProjectAnnotationSnapshot } from "./project-transfer/snapshot-plan.js";
37
37
  export type { ProjectAnnotationRestoreReceipt, ProjectAnnotationRestoreRequest, ProjectAnnotationStore, ProjectAnnotationTargetRequest, } from "./project-transfer/store.js";
38
+ export { registerProvider } from "./providers.js";
38
39
  export { type ChangedSource, SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, type SourceCheck, type SourceReviewCause, type SourceReviewChallenge, type SourceReviewMarker, type SourceReviewPayload, type SourceReviewSource, type SourceReviewText, } from "./source-review.js";
39
40
  export { ADDED_KINDS, type AddedSource, type AddedSourceContent, type AddedSourceDetails, type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js";
40
41
  export type { AgentAction, AgentActionInput, AgentActionsStore } from "./sqlite/agent-actions.js";
@@ -25,6 +25,7 @@ export { planProjectAnnotations, } from "./project-transfer/plan.js";
25
25
  export { previewProjectAnnotationSnapshot, } from "./project-transfer/preview.js";
26
26
  export { decodeProjectAnnotationSnapshot, projectAnnotationSnapshotFingerprint, projectAnnotationSnapshotSchema, snapshotProjectAnnotations, } from "./project-transfer/snapshot.js";
27
27
  export { planProjectAnnotationSnapshot } from "./project-transfer/snapshot-plan.js";
28
+ export { registerProvider } from "./providers.js";
28
29
  export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, } from "./source-review.js";
29
30
  export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
30
31
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
@@ -97,6 +97,43 @@ export interface AddedSourceDetails {
97
97
  /** Where the caller keeps the copy, when one was kept. */
98
98
  copy: string | null;
99
99
  }
100
+ type Row = Record<string, unknown>;
101
+ /** What a document's text and description write, whichever account holds it. */
102
+ export interface DocumentText {
103
+ kind: string;
104
+ title: string | null;
105
+ fileName: string | null;
106
+ extension: string | null;
107
+ url: string | null;
108
+ mime: string | null;
109
+ size: number | null;
110
+ /** `null` keeps it out of every match by content: an imported document is its source's, never a folder file's. */
111
+ hash: string | null;
112
+ text: string;
113
+ extraction: "text" | "none";
114
+ metadata: string | null;
115
+ language: string | null;
116
+ }
117
+ /** Where a copy of the file is kept, when one is: `text` keeps the text alone. */
118
+ export interface DocumentStorage {
119
+ storage: "text" | "copy";
120
+ localPath: string | null;
121
+ }
122
+ /**
123
+ * The writes of a document in a given account: the added sources' (`added:owner`) and a records import's (the
124
+ * envelope's own account) go through the same columns.
125
+ */
126
+ export declare const documentWritesOver: ({ database }: Pick<StoreContext, "database">) => {
127
+ insert: (accountId: number, externalId: string, document: DocumentText, kept: DocumentStorage, at: number) => number;
128
+ /** Its next revision, the text before kept; `revised: false` changes what describes it and keeps the revision. */
129
+ update: (row: Row, document: DocumentText, at: number, revised?: boolean) => void;
130
+ /** A removed document back, as written now. */
131
+ revive: (id: number, document: DocumentText, kept: DocumentStorage, at: number) => void;
132
+ /** Its `files` row, named as its source names it, not by a hash or a key. */
133
+ place: (id: number, at: number, name: string) => void;
134
+ /** Its text goes, its row stays as deleted: what a folder file's removal does. */
135
+ remove: (id: number, at: number) => void;
136
+ };
100
137
  /**
101
138
  * The key an added source is stored under: its source key, else `sha256:<hash>` (a file's bytes; pasted text or a page
102
139
  * by its normalized text, or its address when it has none), and every hash a folder or Drive document of the same
@@ -108,3 +145,4 @@ export declare const addedSourceKeyOf: (content: AddedSourceContent) => {
108
145
  hashes: string[];
109
146
  };
110
147
  export declare const addedSourcesOver: (context: StoreContext) => AddedSources;
148
+ export {};