@wirecat/cli-core 0.647.0 → 0.648.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +85 -0
- package/dist/cli/account-remove.d.ts +5 -0
- package/dist/cli/account-remove.js +6 -1
- package/dist/cli/app-doctor-command.js +15 -57
- package/dist/cli/app-store.d.ts +12 -0
- package/dist/cli/app-store.js +25 -0
- package/dist/cli/commands-command.js +10 -3
- package/dist/cli/doctor-reports-command.d.ts +22 -0
- package/dist/cli/doctor-reports-command.js +82 -0
- package/dist/cli/help/command-help.d.ts +1 -0
- package/dist/cli/help/command-help.js +7 -8
- package/dist/cli/index.d.ts +3 -1
- package/dist/cli/index.js +3 -1
- package/dist/cli/messenger/doctor-command.js +21 -64
- package/dist/cli/messenger/stats-command.js +1 -1
- package/dist/cli/messenger/store-maintenance-command.js +3 -3
- package/dist/cli/messenger/tasks-command.js +1 -3
- package/dist/cli/permission-keys.js +4 -2
- package/dist/cli/program.js +26 -10
- package/dist/cli/settings.d.ts +2 -0
- package/dist/cli/settings.js +3 -2
- package/dist/cli/store-recover.js +2 -2
- package/dist/cli/unknown-profile.d.ts +9 -0
- package/dist/cli/unknown-profile.js +23 -0
- package/dist/crm/cli/search-all.js +4 -4
- package/dist/errors/failures.d.ts +2 -0
- package/dist/errors/failures.js +6 -0
- package/dist/errors/reasons.js +17 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/kit/index.d.ts +1 -0
- package/dist/kit/index.js +1 -0
- package/dist/kit/own-catalogue.d.ts +7 -0
- package/dist/kit/own-catalogue.js +21 -0
- package/dist/oauth/index.d.ts +2 -2
- package/dist/oauth/index.js +2 -1
- package/dist/oauth/provider.d.ts +4 -0
- package/dist/oauth/provider.js +16 -1
- package/dist/oauth/storage.d.ts +5 -0
- package/dist/oauth/storage.js +20 -0
- package/dist/runs/error-detail.d.ts +1 -1
- package/dist/runs/error-detail.js +5 -2
- package/dist/runs/events.d.ts +1 -1
- package/dist/runs/secrets.d.ts +5 -4
- package/dist/runs/secrets.js +8 -4
- package/dist/sends/permissions.d.ts +2 -0
- package/dist/sends/permissions.js +4 -1
- package/dist/services/search-all.js +1 -1
- package/dist/sftp/index.d.ts +1 -0
- package/dist/sftp/index.js +1 -0
- package/dist/sftp/session.d.ts +61 -0
- package/dist/sftp/session.js +230 -0
- package/dist/sftp/ssh2.d.ts +38 -0
- package/dist/sftp/ssh2.js +306 -0
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.js +1 -0
- package/dist/store/sqlite/crm-activities.d.ts +2 -0
- package/dist/store/sqlite/crm-activities.js +17 -0
- package/dist/store/sqlite/deals.d.ts +4 -3
- package/dist/store/sqlite/deals.js +8 -2
- package/dist/store/sqlite/open-store.js +14 -1
- package/package.json +14 -4
- package/parity.json +2 -11
|
@@ -49,7 +49,7 @@ const filtersBeside = (text) => {
|
|
|
49
49
|
* What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
|
|
50
50
|
* so `search all` skips deals with the reason instead of matching a field they do not have.
|
|
51
51
|
*/
|
|
52
|
-
export const titleWords = (text, refused = "deals and leads are found by the words of their title, company and
|
|
52
|
+
export const titleWords = (text, refused = "deals and leads are found by the words of their title, company, contacts and activities only") => {
|
|
53
53
|
const { root } = parseLucene(text, SEARCH_QUERY);
|
|
54
54
|
const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
|
|
55
55
|
const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type HostKey, openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, type SftpAuth, type SftpClient, type SftpEntry, type SftpKind, type SftpOptions, type SftpReadOptions, type SftpTarget, sftpHostKey, } from "./session.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { openSftp, SFTP_CONNECT_TIMEOUT_MS, SFTP_OPERATION_TIMEOUT_MS, SFTP_RETRY, sftpHostKey, } from "./session.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Duplex } from "node:stream";
|
|
2
|
+
import { type RetryConfig, type SleepLike } from "@wirecat/cli-base";
|
|
3
|
+
import type { RequestEvent } from "../runs/events.js";
|
|
4
|
+
import { type HostKey, type SftpEntry } from "./ssh2.js";
|
|
5
|
+
export type SftpAuth = {
|
|
6
|
+
password: string;
|
|
7
|
+
} | {
|
|
8
|
+
privateKey: string | Uint8Array;
|
|
9
|
+
passphrase?: string;
|
|
10
|
+
};
|
|
11
|
+
export interface SftpTarget {
|
|
12
|
+
host: string;
|
|
13
|
+
/** 22 when not given. */
|
|
14
|
+
port?: number;
|
|
15
|
+
/** Seams for a test or a tunnel: a stream already connected to the server, one per connection attempt. */
|
|
16
|
+
socket?: () => Duplex | Promise<Duplex>;
|
|
17
|
+
/** The run's signal: aborting it stops every operation and closes the connection. */
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
/** The run's events (WC-LIFE-17); the current command's run when not given. */
|
|
20
|
+
events?: (event: RequestEvent) => void;
|
|
21
|
+
/** How long a connection may take up to an open SFTP channel. */
|
|
22
|
+
connectTimeoutMs?: number;
|
|
23
|
+
retry?: RetryConfig;
|
|
24
|
+
sleep?: SleepLike;
|
|
25
|
+
random?: () => number;
|
|
26
|
+
}
|
|
27
|
+
export interface SftpOptions extends SftpTarget {
|
|
28
|
+
username: string;
|
|
29
|
+
auth: SftpAuth;
|
|
30
|
+
/** The host key fingerprint the owner confirmed, `SHA256:…` as `sftpHostKey` or `ssh-keygen -lf` print it. */
|
|
31
|
+
hostKey: string;
|
|
32
|
+
/** How long one list or stat may take, and how long a read may go without receiving a byte. */
|
|
33
|
+
operationTimeoutMs?: number;
|
|
34
|
+
}
|
|
35
|
+
export interface SftpReadOptions {
|
|
36
|
+
/** A larger file is refused before its first byte is read, and a file that grows past it while read is too. */
|
|
37
|
+
maxBytes: number;
|
|
38
|
+
}
|
|
39
|
+
export interface SftpClient {
|
|
40
|
+
/** The entries of a folder, without `.` and `..`. */
|
|
41
|
+
list(path: string): Promise<SftpEntry[]>;
|
|
42
|
+
stat(path: string): Promise<SftpEntry>;
|
|
43
|
+
readFile(path: string, options: SftpReadOptions): Promise<Uint8Array>;
|
|
44
|
+
close(): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
export type { HostKey, SftpEntry, SftpKind } from "./ssh2.js";
|
|
47
|
+
export declare const SFTP_CONNECT_TIMEOUT_MS = 20000;
|
|
48
|
+
export declare const SFTP_OPERATION_TIMEOUT_MS = 30000;
|
|
49
|
+
/** Every operation only reads, so a transient failure is tried again: three attempts in all. */
|
|
50
|
+
export declare const SFTP_RETRY: RetryConfig;
|
|
51
|
+
/**
|
|
52
|
+
* The server's host key, for a sign-in to show the owner before the fingerprint is pinned: the connection stops at
|
|
53
|
+
* the key exchange and sends no credential.
|
|
54
|
+
*/
|
|
55
|
+
export declare const sftpHostKey: (target: SftpTarget) => Promise<HostKey>;
|
|
56
|
+
/**
|
|
57
|
+
* A read-only SFTP connection: list, stat and read, nothing that writes. The host key must match the pinned
|
|
58
|
+
* fingerprint before a credential is sent. Each operation is a request in the run's events (host and operation,
|
|
59
|
+
* never a path or file content) and is tried again on a transient failure over a fresh connection.
|
|
60
|
+
*/
|
|
61
|
+
export declare const openSftp: (input: SftpOptions) => Promise<SftpClient>;
|
|
@@ -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
|
+
};
|
package/dist/store/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/store/index.js
CHANGED
|
@@ -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";
|