pinggy 0.6.10 → 0.7.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/ARCHITECTURE.md +36 -21
- package/CLAUDE.md +8 -5
- package/README.md +32 -4
- package/dist/{chunk-AYU3GM4D.js → chunk-2IPBK3RG.js} +173 -133
- package/dist/{chunk-3IPMFCEF.js → chunk-QUVQ7ODD.js} +1 -0
- package/dist/{chunk-G3NF35JY.js → chunk-ZSED6OIR.js} +3050 -266
- package/dist/{configStore-6LCHFPQX.js → configStore-VDPOPFLJ.js} +1 -1
- package/dist/{daemonChild-4ZZ3YQDL.js → daemonChild-5HZFQLQR.js} +3 -3
- package/dist/index.cjs +3417 -459
- package/dist/index.js +4 -4
- package/dist/{main-3D7R75PR.js → main-M4BTDE2A.js} +3 -3
- package/dist/{updateChild-ZOC3VGJL.js → updateChild-CEVYCBED.js} +1 -1
- package/package.json +2 -1
- package/scripts/install/install.ps1 +12 -10
- package/scripts/install/install.sh +21 -14
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
upsertConfig,
|
|
29
29
|
validateName,
|
|
30
30
|
validateNameStrict
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-QUVQ7ODD.js";
|
|
32
32
|
import {
|
|
33
33
|
createQrCodes
|
|
34
34
|
} from "./chunk-XZ64ZAGO.js";
|
|
@@ -42,11 +42,14 @@ import {
|
|
|
42
42
|
setTunnelLoggingEnabled
|
|
43
43
|
} from "./chunk-5HBGVJSW.js";
|
|
44
44
|
import {
|
|
45
|
+
AUTOSTART_OFF_COMMAND,
|
|
46
|
+
AUTOSTART_ON_COMMAND,
|
|
45
47
|
InstallKind,
|
|
46
48
|
NPM_INSTALL_COMMAND,
|
|
47
49
|
UpdateError,
|
|
48
50
|
acquireUpdateLock,
|
|
49
51
|
assetNameFor,
|
|
52
|
+
autostartFilePath,
|
|
50
53
|
backgroundInstallKind,
|
|
51
54
|
canReplaceItself,
|
|
52
55
|
createInstallProbe,
|
|
@@ -61,8 +64,8 @@ import {
|
|
|
61
64
|
getInProcessDaemonHandle,
|
|
62
65
|
hasExecutableSpawnHelper,
|
|
63
66
|
hasPathSegment,
|
|
67
|
+
installBootEntry,
|
|
64
68
|
installCommandFor,
|
|
65
|
-
installService,
|
|
66
69
|
installerBinaryPath,
|
|
67
70
|
ipcMismatchMessage,
|
|
68
71
|
isDaemonRunning,
|
|
@@ -72,6 +75,7 @@ import {
|
|
|
72
75
|
isProcessAlive,
|
|
73
76
|
isReleaseComplete,
|
|
74
77
|
isUpdateLockHeld,
|
|
78
|
+
machineServiceInstallContext,
|
|
75
79
|
makeSpawnHelperExecutable,
|
|
76
80
|
nowEpochSeconds,
|
|
77
81
|
parseVersion,
|
|
@@ -79,26 +83,31 @@ import {
|
|
|
79
83
|
printDaemonVersionNoticeOnce,
|
|
80
84
|
readBinaryIpcVersion,
|
|
81
85
|
readBinaryVersion,
|
|
86
|
+
readBootEntry,
|
|
82
87
|
readLinkVersion,
|
|
83
88
|
readUpdateState,
|
|
84
89
|
recordLatestVersion,
|
|
85
90
|
releaseUpdateLock,
|
|
91
|
+
removeBootEntry,
|
|
86
92
|
removeQuietly,
|
|
87
93
|
removeStaleUpdateFiles,
|
|
88
94
|
requireNodePty,
|
|
89
95
|
resolveLatestTag,
|
|
90
96
|
resolveNodePtyRoot,
|
|
91
97
|
runPinggyBinary,
|
|
98
|
+
sameProgram,
|
|
99
|
+
serviceInstallRefusal,
|
|
100
|
+
serviceProgramPath,
|
|
92
101
|
startDaemon,
|
|
93
102
|
startDaemonFromInstalledBinary,
|
|
94
103
|
startedInEarlierBoot,
|
|
104
|
+
startsBeforeSignIn,
|
|
95
105
|
stopDaemon,
|
|
96
|
-
uninstallService,
|
|
97
106
|
unixLayoutPaths,
|
|
98
107
|
versionFromTag,
|
|
99
108
|
windowsInstallPaths,
|
|
100
109
|
writeUpdateState
|
|
101
|
-
} from "./chunk-
|
|
110
|
+
} from "./chunk-2IPBK3RG.js";
|
|
102
111
|
import {
|
|
103
112
|
DaemonHost,
|
|
104
113
|
DeviceAgentState,
|
|
@@ -192,6 +201,8 @@ var cliOptions = {
|
|
|
192
201
|
all: { type: "boolean", description: "Start all auto-start tunnels" },
|
|
193
202
|
// `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
|
|
194
203
|
foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
|
|
204
|
+
// `pinggy device login`, `connect` and `start` only: on or off, the answer to the file access question.
|
|
205
|
+
files: { type: "string", description: "Allow file access from the dashboard: on or off", hidden: true },
|
|
195
206
|
// `pinggy update` only.
|
|
196
207
|
check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
|
|
197
208
|
rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
|
|
@@ -275,6 +286,7 @@ function printHelpMessage() {
|
|
|
275
286
|
console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
|
|
276
287
|
console.log(" pinggy device status # Show this device and its agent");
|
|
277
288
|
console.log(" pinggy device stop # Stop the background agent");
|
|
289
|
+
console.log(" pinggy autostart on # Bring this device online each time this computer starts");
|
|
278
290
|
console.log("\nUpdates:");
|
|
279
291
|
console.log(" pinggy update --check # Print the latest version");
|
|
280
292
|
console.log(" pinggy update # Update to the latest version now");
|
|
@@ -284,8 +296,6 @@ function printHelpMessage() {
|
|
|
284
296
|
console.log(" pinggy daemon start # Start the background daemon");
|
|
285
297
|
console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
|
|
286
298
|
console.log(" pinggy daemon status # Show daemon PID and uptime");
|
|
287
|
-
console.log(" pinggy daemon service-install # Run the daemon at login as a system service");
|
|
288
|
-
console.log(" pinggy daemon service-uninstall # Stop the daemon and remove the system service");
|
|
289
299
|
}
|
|
290
300
|
|
|
291
301
|
// src/utils/parseArgs.ts
|
|
@@ -2981,10 +2991,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
|
|
|
2981
2991
|
}
|
|
2982
2992
|
function storeJson(config, saveconf) {
|
|
2983
2993
|
if (saveconf) {
|
|
2984
|
-
const
|
|
2994
|
+
const path9 = saveconf;
|
|
2985
2995
|
try {
|
|
2986
|
-
fs4.writeFileSync(
|
|
2987
|
-
logger.info(`Configuration saved to ${
|
|
2996
|
+
fs4.writeFileSync(path9, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
|
|
2997
|
+
logger.info(`Configuration saved to ${path9}`);
|
|
2988
2998
|
} catch (err) {
|
|
2989
2999
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2990
3000
|
logger.error("Error loading configuration:", msg);
|
|
@@ -4246,7 +4256,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
|
|
|
4246
4256
|
client.close();
|
|
4247
4257
|
}
|
|
4248
4258
|
async function startAutoStartTunnels() {
|
|
4249
|
-
const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-
|
|
4259
|
+
const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-VDPOPFLJ.js");
|
|
4250
4260
|
const configs = getAutoStartConfigs2();
|
|
4251
4261
|
if (configs.length === 0) {
|
|
4252
4262
|
printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
|
|
@@ -4377,8 +4387,6 @@ function printDaemonHelp() {
|
|
|
4377
4387
|
console.log(" start Start the daemon process");
|
|
4378
4388
|
console.log(" stop Stop the daemon (stops all tunnels)");
|
|
4379
4389
|
console.log(" status Show daemon PID and uptime");
|
|
4380
|
-
console.log(" service-install Run the daemon at login as a system service");
|
|
4381
|
-
console.log(" service-uninstall Stop the daemon and remove the system service");
|
|
4382
4390
|
console.log("Tunnel operations:");
|
|
4383
4391
|
console.log(" pinggy ps List running tunnels");
|
|
4384
4392
|
console.log(" pinggy stop <name|id> Stop a specific tunnel");
|
|
@@ -4428,17 +4436,34 @@ function printDeviceHelp() {
|
|
|
4428
4436
|
console.log(" The device stays in the dashboard\n");
|
|
4429
4437
|
console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
|
|
4430
4438
|
console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
|
|
4439
|
+
console.log("Start on boot:");
|
|
4440
|
+
console.log(" pinggy autostart on Bring this device online each time this computer starts");
|
|
4441
|
+
console.log(" pinggy autostart off Stop that. The device stays online until the next restart");
|
|
4442
|
+
console.log(" pinggy autostart status Show whether it is on");
|
|
4443
|
+
console.log("On macOS and Windows it starts when you sign in. On Linux it starts at boot.\n");
|
|
4431
4444
|
console.log("Options:");
|
|
4432
4445
|
console.log(" --foreground login, connect and start: run the agent in this terminal until Ctrl+C");
|
|
4433
4446
|
console.log(" -b login, connect and start: run the agent in the background. The default");
|
|
4434
4447
|
console.log(" --token <TOKEN> Device token from the dashboard");
|
|
4435
4448
|
console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
|
|
4436
4449
|
console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
|
|
4450
|
+
console.log(" --files on|off login, connect and start: allow or refuse file access from the");
|
|
4451
|
+
console.log(" dashboard. Without it, the first run in a terminal asks");
|
|
4437
4452
|
console.log(" -f remove only: remove without asking\n");
|
|
4438
4453
|
console.log("Environment:");
|
|
4439
4454
|
console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
|
|
4440
4455
|
console.log(" With no --manage, it dials dashboard.pinggy.io. Removed once read\n");
|
|
4441
4456
|
}
|
|
4457
|
+
function printAutostartHelp() {
|
|
4458
|
+
console.log("\nUsage: pinggy autostart [on | off | status]\n");
|
|
4459
|
+
console.log("Bring this device online each time this computer starts.");
|
|
4460
|
+
console.log("On macOS and Windows it starts when you sign in. On Linux it starts at boot.\n");
|
|
4461
|
+
console.log("Commands:");
|
|
4462
|
+
console.log(" on Turn it on. Asks first when the device agent does not run in the");
|
|
4463
|
+
console.log(" background");
|
|
4464
|
+
console.log(" off Turn it off. The device stays online until the next restart");
|
|
4465
|
+
console.log(" status Show whether it is on. The default\n");
|
|
4466
|
+
}
|
|
4442
4467
|
function printUpdateHelp() {
|
|
4443
4468
|
console.log("\nUsage: pinggy update [--check | --rollback]\n");
|
|
4444
4469
|
console.log("Commands:");
|
|
@@ -4466,14 +4491,21 @@ function readDeviceIdentity() {
|
|
|
4466
4491
|
}
|
|
4467
4492
|
}
|
|
4468
4493
|
function writeDeviceIdentity(identity) {
|
|
4494
|
+
const written = keepStoredFileManager(identity, readDeviceIdentity());
|
|
4469
4495
|
ensurePinggyConfigDir();
|
|
4470
4496
|
const filePath = getDeviceConfigPath();
|
|
4471
|
-
fs5.writeFileSync(filePath, JSON.stringify(
|
|
4497
|
+
fs5.writeFileSync(filePath, JSON.stringify(written, null, 2), {
|
|
4472
4498
|
encoding: "utf-8",
|
|
4473
4499
|
mode: SECRET_FILE_MODE
|
|
4474
4500
|
});
|
|
4475
4501
|
fs5.chmodSync(filePath, SECRET_FILE_MODE);
|
|
4476
4502
|
}
|
|
4503
|
+
function keepStoredFileManager(identity, stored) {
|
|
4504
|
+
if (identity.file_manager !== void 0 || !stored || stored.token !== identity.token || typeof stored.file_manager !== "boolean") {
|
|
4505
|
+
return identity;
|
|
4506
|
+
}
|
|
4507
|
+
return { ...identity, file_manager: stored.file_manager };
|
|
4508
|
+
}
|
|
4477
4509
|
function clearDeviceIdentity() {
|
|
4478
4510
|
const filePath = getDeviceConfigPath();
|
|
4479
4511
|
if (!fs5.existsSync(filePath)) {
|
|
@@ -4488,7 +4520,7 @@ function maskToken(token) {
|
|
|
4488
4520
|
|
|
4489
4521
|
// src/devices/deviceAgent.ts
|
|
4490
4522
|
import WebSocket3 from "ws";
|
|
4491
|
-
import
|
|
4523
|
+
import os11 from "os";
|
|
4492
4524
|
|
|
4493
4525
|
// src/devices/envelope.ts
|
|
4494
4526
|
import { randomUUID } from "crypto";
|
|
@@ -4516,8 +4548,8 @@ function request(ch, op, payload) {
|
|
|
4516
4548
|
function response(to, op, payload) {
|
|
4517
4549
|
return { v: PROTOCOL_VERSION, kind: "res", ch: to.ch, op, id: to.id, seq: 0, ts: nowSeconds(), payload };
|
|
4518
4550
|
}
|
|
4519
|
-
function event(ch, op, payload) {
|
|
4520
|
-
return { v: PROTOCOL_VERSION, kind: "event", ch, op, id
|
|
4551
|
+
function event(ch, op, payload, id = "") {
|
|
4552
|
+
return { v: PROTOCOL_VERSION, kind: "event", ch, op, id, seq: 0, ts: nowSeconds(), payload };
|
|
4521
4553
|
}
|
|
4522
4554
|
function parseEnvelope(raw) {
|
|
4523
4555
|
try {
|
|
@@ -4549,6 +4581,12 @@ var WelcomeSchema = z3.object({
|
|
|
4549
4581
|
terminal_idle_timeout_seconds: z3.number().optional(),
|
|
4550
4582
|
// Optional: without it the agent keeps the window brake and never skips output.
|
|
4551
4583
|
terminal_resync: z3.boolean().optional(),
|
|
4584
|
+
// Optional: a dashboard that predates the file manager sends none, and every file request is refused.
|
|
4585
|
+
file_manager_enabled: z3.boolean().optional(),
|
|
4586
|
+
// No default on the agent. Without it, every copy, move and delete answers file_busy rather than running unbounded.
|
|
4587
|
+
file_max_concurrent_operations: z3.number().optional(),
|
|
4588
|
+
// Optional: without it nothing waits, and a copy, move or delete past the running limit answers file_busy.
|
|
4589
|
+
file_max_queued_operations: z3.number().optional(),
|
|
4552
4590
|
// Optional: a dashboard older than these sends neither, and the agent prints only the device id.
|
|
4553
4591
|
email: z3.string().optional(),
|
|
4554
4592
|
device_url: z3.string().optional()
|
|
@@ -4605,6 +4643,19 @@ var printingReporter = {
|
|
|
4605
4643
|
// src/devices/collectors/systemInfo.ts
|
|
4606
4644
|
import os4 from "os";
|
|
4607
4645
|
var UNKNOWN_CPU_MODEL = "unknown";
|
|
4646
|
+
function agentUser() {
|
|
4647
|
+
const uid = process.getuid?.();
|
|
4648
|
+
let username;
|
|
4649
|
+
try {
|
|
4650
|
+
username = os4.userInfo().username || void 0;
|
|
4651
|
+
} catch {
|
|
4652
|
+
username = void 0;
|
|
4653
|
+
}
|
|
4654
|
+
return {
|
|
4655
|
+
...username === void 0 ? {} : { username },
|
|
4656
|
+
...uid === void 0 ? {} : { uid }
|
|
4657
|
+
};
|
|
4658
|
+
}
|
|
4608
4659
|
function collectSystemInfo() {
|
|
4609
4660
|
const cpus = os4.cpus();
|
|
4610
4661
|
return {
|
|
@@ -4618,7 +4669,8 @@ function collectSystemInfo() {
|
|
|
4618
4669
|
// os.cpus() is empty on some Android and container builds.
|
|
4619
4670
|
cpu_model: cpus[0]?.model?.trim() || UNKNOWN_CPU_MODEL,
|
|
4620
4671
|
cpu_cores: cpus.length,
|
|
4621
|
-
total_memory_bytes: os4.totalmem()
|
|
4672
|
+
total_memory_bytes: os4.totalmem(),
|
|
4673
|
+
...agentUser()
|
|
4622
4674
|
};
|
|
4623
4675
|
}
|
|
4624
4676
|
|
|
@@ -5068,50 +5120,2553 @@ function backoffCeilingMillis(attempt) {
|
|
|
5068
5120
|
const uncapped = INITIAL_DELAY_MILLIS * 2 ** Math.max(0, attempt);
|
|
5069
5121
|
return Math.min(uncapped, MAX_DELAY_MILLIS);
|
|
5070
5122
|
}
|
|
5071
|
-
function fullJitterMillis(ceilingMillis, random) {
|
|
5072
|
-
return Math.floor(random() * ceilingMillis);
|
|
5123
|
+
function fullJitterMillis(ceilingMillis, random) {
|
|
5124
|
+
return Math.floor(random() * ceilingMillis);
|
|
5125
|
+
}
|
|
5126
|
+
var ReconnectPolicy = class {
|
|
5127
|
+
constructor(options = {}) {
|
|
5128
|
+
this.attemptCount = 0;
|
|
5129
|
+
this.connectedAtMillis = null;
|
|
5130
|
+
this.now = options.now ?? Date.now;
|
|
5131
|
+
this.random = options.random ?? Math.random;
|
|
5132
|
+
}
|
|
5133
|
+
/** Attempts taken since the last reset. Exposed for logging and for tests. */
|
|
5134
|
+
get attempt() {
|
|
5135
|
+
return this.attemptCount;
|
|
5136
|
+
}
|
|
5137
|
+
/** The ceiling the next delay will be drawn from, before jitter. */
|
|
5138
|
+
get nextCeilingMillis() {
|
|
5139
|
+
return backoffCeilingMillis(this.attemptCount);
|
|
5140
|
+
}
|
|
5141
|
+
markConnected() {
|
|
5142
|
+
this.connectedAtMillis = this.now();
|
|
5143
|
+
}
|
|
5144
|
+
/**
|
|
5145
|
+
* Ends the current connection. Returns true when it had held long enough to reset the
|
|
5146
|
+
* schedule, which the caller logs.
|
|
5147
|
+
*/
|
|
5148
|
+
markDisconnected() {
|
|
5149
|
+
const heldMillis = this.connectedAtMillis === null ? 0 : this.now() - this.connectedAtMillis;
|
|
5150
|
+
this.connectedAtMillis = null;
|
|
5151
|
+
const wasStable = heldMillis >= STABLE_CONNECTION_MILLIS;
|
|
5152
|
+
if (wasStable) {
|
|
5153
|
+
this.attemptCount = 0;
|
|
5154
|
+
}
|
|
5155
|
+
return wasStable;
|
|
5156
|
+
}
|
|
5157
|
+
/** The delay before the next dial, and advances the schedule. */
|
|
5158
|
+
nextDelayMillis() {
|
|
5159
|
+
const delay = fullJitterMillis(this.nextCeilingMillis, this.random);
|
|
5160
|
+
this.attemptCount = Math.min(this.attemptCount + 1, MAX_ATTEMPT);
|
|
5161
|
+
return delay;
|
|
5162
|
+
}
|
|
5163
|
+
};
|
|
5164
|
+
|
|
5165
|
+
// src/devices/files/file_schema.ts
|
|
5166
|
+
import { z as z4 } from "zod";
|
|
5167
|
+
var CHANNEL_FILE = "file";
|
|
5168
|
+
var OP_LIST = "list";
|
|
5169
|
+
var OP_STAT = "stat";
|
|
5170
|
+
var OP_DELETE = "delete";
|
|
5171
|
+
var OP_MKDIR = "mkdir";
|
|
5172
|
+
var OP_COPY = "copy";
|
|
5173
|
+
var OP_MOVE = "move";
|
|
5174
|
+
var OP_PROGRESS = "progress";
|
|
5175
|
+
var ERROR_INVALID_PAYLOAD2 = "invalid_payload";
|
|
5176
|
+
var ERROR_UNSUPPORTED_OP2 = "unsupported_op";
|
|
5177
|
+
var ERROR_FILE_MANAGER_DISABLED = "file_manager_disabled";
|
|
5178
|
+
var ERROR_FILE_ACCESS_OFF = "file_access_off";
|
|
5179
|
+
var ERROR_INVALID_PATH = "invalid_path";
|
|
5180
|
+
var ERROR_PATH_NOT_FOUND = "path_not_found";
|
|
5181
|
+
var ERROR_NOT_A_DIRECTORY = "not_a_directory";
|
|
5182
|
+
var ERROR_PERMISSION_DENIED = "permission_denied";
|
|
5183
|
+
var ERROR_FILE_TIMEOUT = "file_timeout";
|
|
5184
|
+
var ERROR_FILE_OPERATION_FAILED = "file_operation_failed";
|
|
5185
|
+
var ERROR_PROTECTED_PATH = "protected_path";
|
|
5186
|
+
var ERROR_MOUNT_POINT = "mount_point";
|
|
5187
|
+
var ERROR_FILE_BUSY = "file_busy";
|
|
5188
|
+
var ERROR_FILE_EXISTS = "file_exists";
|
|
5189
|
+
var ERROR_INVALID_NAME = "invalid_name";
|
|
5190
|
+
var ERROR_INVALID_DESTINATION = "invalid_destination";
|
|
5191
|
+
var ERROR_NO_SPACE = "no_space";
|
|
5192
|
+
var ERROR_SPECIAL_FILE = "special_file";
|
|
5193
|
+
var SORT_BY_NAME = "name";
|
|
5194
|
+
var SORT_BY_SIZE = "size";
|
|
5195
|
+
var SORT_BY_MODIFIED = "modified";
|
|
5196
|
+
var SORT_BY_CREATED = "created";
|
|
5197
|
+
var SORT_ORDER_ASC = "asc";
|
|
5198
|
+
var SORT_ORDER_DESC = "desc";
|
|
5199
|
+
var DEFAULT_LIST_LIMIT = 200;
|
|
5200
|
+
var MAX_LIST_LIMIT = 500;
|
|
5201
|
+
var MAX_PATH_BYTES = 4096;
|
|
5202
|
+
var MAX_NAME_BYTES = 255;
|
|
5203
|
+
var ON_CONFLICT_FAIL = "fail";
|
|
5204
|
+
var ON_CONFLICT_SKIP = "skip";
|
|
5205
|
+
var ON_CONFLICT_KEEP_BOTH = "keep_both";
|
|
5206
|
+
var ON_CONFLICT_REPLACE = "replace";
|
|
5207
|
+
var FileListRequestSchema = z4.object({
|
|
5208
|
+
path: z4.string().optional(),
|
|
5209
|
+
offset: z4.number().int().min(0).optional(),
|
|
5210
|
+
limit: z4.number().int().min(1).max(MAX_LIST_LIMIT).optional(),
|
|
5211
|
+
sort_by: z4.enum([SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED]).optional(),
|
|
5212
|
+
sort_order: z4.enum([SORT_ORDER_ASC, SORT_ORDER_DESC]).optional(),
|
|
5213
|
+
include_hidden: z4.boolean().optional()
|
|
5214
|
+
});
|
|
5215
|
+
var FileStatRequestSchema = z4.object({
|
|
5216
|
+
path: z4.string(),
|
|
5217
|
+
include_hidden: z4.boolean().optional()
|
|
5218
|
+
});
|
|
5219
|
+
var FileDeleteRequestSchema = z4.object({
|
|
5220
|
+
path: z4.string()
|
|
5221
|
+
});
|
|
5222
|
+
var FileMkdirRequestSchema = z4.object({
|
|
5223
|
+
path: z4.string()
|
|
5224
|
+
});
|
|
5225
|
+
var FileCopyRequestSchema = z4.object({
|
|
5226
|
+
source_path: z4.string(),
|
|
5227
|
+
destination_path: z4.string(),
|
|
5228
|
+
on_conflict: z4.enum([ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE]).optional()
|
|
5229
|
+
});
|
|
5230
|
+
function fileError(code, message) {
|
|
5231
|
+
return { error: { code, message } };
|
|
5232
|
+
}
|
|
5233
|
+
|
|
5234
|
+
// src/devices/files/fileSystem.ts
|
|
5235
|
+
import fs6 from "fs";
|
|
5236
|
+
import os6 from "os";
|
|
5237
|
+
import path4 from "path";
|
|
5238
|
+
var machineFileSystem = {
|
|
5239
|
+
readdir: (folder) => fs6.promises.readdir(folder, { withFileTypes: true }),
|
|
5240
|
+
lstat: (target) => fs6.promises.lstat(target),
|
|
5241
|
+
stat: (target) => fs6.promises.stat(target),
|
|
5242
|
+
readlink: (target) => fs6.promises.readlink(target),
|
|
5243
|
+
access: (target, mode) => fs6.promises.access(target, mode),
|
|
5244
|
+
homedir: () => os6.homedir()
|
|
5245
|
+
};
|
|
5246
|
+
var machineFileSystemDependencies = {
|
|
5247
|
+
fs: machineFileSystem,
|
|
5248
|
+
platform: process.platform
|
|
5249
|
+
};
|
|
5250
|
+
var machineFileSystemRemover = {
|
|
5251
|
+
lstat: (target) => fs6.promises.lstat(target, { bigint: true }),
|
|
5252
|
+
stat: (target) => fs6.promises.stat(target, { bigint: true }),
|
|
5253
|
+
readdir: (folder) => fs6.promises.readdir(folder),
|
|
5254
|
+
unlink: (target) => fs6.promises.unlink(target),
|
|
5255
|
+
rmdir: (target) => fs6.promises.rmdir(target),
|
|
5256
|
+
chmod: (target, mode) => fs6.promises.chmod(target, mode),
|
|
5257
|
+
realpath: (target) => fs6.promises.realpath(target)
|
|
5258
|
+
};
|
|
5259
|
+
var machineFileSystemMaker = {
|
|
5260
|
+
mkdir: async (target) => {
|
|
5261
|
+
await fs6.promises.mkdir(target);
|
|
5262
|
+
}
|
|
5263
|
+
};
|
|
5264
|
+
var NEW_FILE_MODE = 384;
|
|
5265
|
+
var CREATE_ONLY_IF_FREE = "wx";
|
|
5266
|
+
var machineFileSystemCopier = {
|
|
5267
|
+
lstat: (target) => fs6.promises.lstat(target, { bigint: true }),
|
|
5268
|
+
stat: (target) => fs6.promises.stat(target, { bigint: true }),
|
|
5269
|
+
realpath: (target) => fs6.promises.realpath(target),
|
|
5270
|
+
readdir: (folder) => fs6.promises.readdir(folder),
|
|
5271
|
+
mkdir: async (target) => {
|
|
5272
|
+
await fs6.promises.mkdir(target);
|
|
5273
|
+
},
|
|
5274
|
+
openToRead: (target) => fs6.promises.open(target, "r"),
|
|
5275
|
+
createFile: (target) => fs6.promises.open(target, CREATE_ONLY_IF_FREE, NEW_FILE_MODE),
|
|
5276
|
+
read: async (handle, buffer) => (await handle.read(buffer, 0, buffer.length, null)).bytesRead,
|
|
5277
|
+
write: async (handle, buffer, length) => {
|
|
5278
|
+
let written = 0;
|
|
5279
|
+
while (written < length) {
|
|
5280
|
+
written += (await handle.write(buffer, written, length - written, null)).bytesWritten;
|
|
5281
|
+
}
|
|
5282
|
+
},
|
|
5283
|
+
close: (handle) => handle.close(),
|
|
5284
|
+
readlink: (target) => fs6.promises.readlink(target),
|
|
5285
|
+
symlink: (linkText, target, type) => fs6.promises.symlink(linkText, target, type),
|
|
5286
|
+
chmod: (target, mode) => fs6.promises.chmod(target, mode),
|
|
5287
|
+
utimes: (target, accessed, modified) => fs6.promises.utimes(target, accessed, modified),
|
|
5288
|
+
rename: (from, to) => fs6.promises.rename(from, to),
|
|
5289
|
+
unlink: (target) => fs6.promises.unlink(target),
|
|
5290
|
+
freeBytes: async (folder) => {
|
|
5291
|
+
const stats = await fs6.promises.statfs(folder, { bigint: true });
|
|
5292
|
+
return stats.bavail * stats.bsize;
|
|
5293
|
+
}
|
|
5294
|
+
};
|
|
5295
|
+
var HIDDEN_NAME_PREFIX = ".";
|
|
5296
|
+
var MILLIS_PER_SECOND = 1e3;
|
|
5297
|
+
function pathsFor(platform3) {
|
|
5298
|
+
return platform3 === "win32" ? path4.win32 : path4.posix;
|
|
5299
|
+
}
|
|
5300
|
+
function pathProblem(requested, paths) {
|
|
5301
|
+
if (requested.includes("\0")) {
|
|
5302
|
+
return "The path holds a NUL byte.";
|
|
5303
|
+
}
|
|
5304
|
+
if (Buffer.byteLength(requested, "utf8") > MAX_PATH_BYTES) {
|
|
5305
|
+
return `The path is longer than ${MAX_PATH_BYTES} bytes.`;
|
|
5306
|
+
}
|
|
5307
|
+
if (!paths.isAbsolute(requested)) {
|
|
5308
|
+
return "The path must be absolute.";
|
|
5309
|
+
}
|
|
5310
|
+
return null;
|
|
5311
|
+
}
|
|
5312
|
+
function nameProblem(name, platform3) {
|
|
5313
|
+
if (name.length === 0) {
|
|
5314
|
+
return "A name is empty.";
|
|
5315
|
+
}
|
|
5316
|
+
if (Buffer.byteLength(name, "utf8") > MAX_NAME_BYTES) {
|
|
5317
|
+
return `A name is longer than ${MAX_NAME_BYTES} bytes.`;
|
|
5318
|
+
}
|
|
5319
|
+
if (name === "." || name === "..") {
|
|
5320
|
+
return "A name cannot be . or ..";
|
|
5321
|
+
}
|
|
5322
|
+
if (name.includes("\0")) {
|
|
5323
|
+
return "A name holds a NUL byte.";
|
|
5324
|
+
}
|
|
5325
|
+
if (name.includes("/") || platform3 === "win32" && name.includes("\\")) {
|
|
5326
|
+
return "A name holds a path separator.";
|
|
5327
|
+
}
|
|
5328
|
+
return null;
|
|
5329
|
+
}
|
|
5330
|
+
var WINDOWS_FORBIDDEN_CHARACTERS = /[:*?"<>|]/;
|
|
5331
|
+
var WINDOWS_TRAILING_DOT_OR_SPACE = /[. ]$/;
|
|
5332
|
+
var WINDOWS_NUMBERED_DEVICES = ["COM", "LPT"];
|
|
5333
|
+
var WINDOWS_DEVICE_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
|
5334
|
+
var WINDOWS_DEVICE_NAMES = /* @__PURE__ */ new Set([
|
|
5335
|
+
"CON",
|
|
5336
|
+
"PRN",
|
|
5337
|
+
"AUX",
|
|
5338
|
+
"NUL",
|
|
5339
|
+
...WINDOWS_NUMBERED_DEVICES.flatMap((device) => WINDOWS_DEVICE_NUMBERS.map((number) => `${device}${number}`))
|
|
5340
|
+
]);
|
|
5341
|
+
var EXTENSION_SEPARATOR = ".";
|
|
5342
|
+
function windowsNameProblem(name, subject = "A folder name") {
|
|
5343
|
+
if (WINDOWS_FORBIDDEN_CHARACTERS.test(name)) {
|
|
5344
|
+
return `${subject} on Windows cannot hold : * ? " < > |`;
|
|
5345
|
+
}
|
|
5346
|
+
if (WINDOWS_TRAILING_DOT_OR_SPACE.test(name)) {
|
|
5347
|
+
return `${subject} on Windows cannot end with a dot or a space.`;
|
|
5348
|
+
}
|
|
5349
|
+
const stem = name.split(EXTENSION_SEPARATOR)[0].toUpperCase();
|
|
5350
|
+
if (WINDOWS_DEVICE_NAMES.has(stem)) {
|
|
5351
|
+
return `${stem} is a device name on Windows.`;
|
|
5352
|
+
}
|
|
5353
|
+
return null;
|
|
5354
|
+
}
|
|
5355
|
+
function isRoot(resolved, paths) {
|
|
5356
|
+
return paths.dirname(resolved) === resolved;
|
|
5357
|
+
}
|
|
5358
|
+
function resolvedItem(requested, paths) {
|
|
5359
|
+
const resolved = paths.resolve(requested);
|
|
5360
|
+
return { path: resolved, parent: paths.dirname(resolved), name: paths.basename(resolved) };
|
|
5361
|
+
}
|
|
5362
|
+
function withTrimmedName(item) {
|
|
5363
|
+
const name = item.name.trim();
|
|
5364
|
+
if (name === item.name || name.length === 0) {
|
|
5365
|
+
return { ...item, name };
|
|
5366
|
+
}
|
|
5367
|
+
return { ...item, name, path: item.path.slice(0, item.path.length - item.name.length) + name };
|
|
5368
|
+
}
|
|
5369
|
+
var MESSAGE_NAME_TAKEN = "A file or folder with this name already exists.";
|
|
5370
|
+
function errorCodeOf(err) {
|
|
5371
|
+
return typeof err === "object" && err !== null && "code" in err && typeof err.code === "string" ? err.code : void 0;
|
|
5372
|
+
}
|
|
5373
|
+
function failureMessage(err, fallback) {
|
|
5374
|
+
return sanitizeErrorMessage(err instanceof Error ? err.message : String(err)) ?? fallback;
|
|
5375
|
+
}
|
|
5376
|
+
function entryTypeOf(stats) {
|
|
5377
|
+
if (stats.isSymbolicLink()) return "symlink";
|
|
5378
|
+
if (stats.isDirectory()) return "directory";
|
|
5379
|
+
if (stats.isFile()) return "file";
|
|
5380
|
+
return "other";
|
|
5381
|
+
}
|
|
5382
|
+
function targetTypeOf(stats) {
|
|
5383
|
+
if (stats.isDirectory()) return "directory";
|
|
5384
|
+
if (stats.isFile()) return "file";
|
|
5385
|
+
return "other";
|
|
5386
|
+
}
|
|
5387
|
+
function epochSeconds(millis) {
|
|
5388
|
+
return Math.floor(millis / MILLIS_PER_SECOND);
|
|
5389
|
+
}
|
|
5390
|
+
function utf8Bytes(value) {
|
|
5391
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
5392
|
+
}
|
|
5393
|
+
async function readLinkTarget(linkPath, reader) {
|
|
5394
|
+
const target = {};
|
|
5395
|
+
try {
|
|
5396
|
+
target.linkTarget = await reader.readlink(linkPath);
|
|
5397
|
+
} catch {
|
|
5398
|
+
}
|
|
5399
|
+
try {
|
|
5400
|
+
target.targetStats = await reader.stat(linkPath);
|
|
5401
|
+
target.targetType = targetTypeOf(target.targetStats);
|
|
5402
|
+
} catch (err) {
|
|
5403
|
+
const code = errorCodeOf(err);
|
|
5404
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
5405
|
+
target.targetType = "missing";
|
|
5406
|
+
}
|
|
5407
|
+
}
|
|
5408
|
+
return target;
|
|
5409
|
+
}
|
|
5410
|
+
var FileCallTimeoutError = class extends Error {
|
|
5411
|
+
};
|
|
5412
|
+
function callTimeoutError(millis) {
|
|
5413
|
+
const seconds = Math.round(millis / MILLIS_PER_SECOND);
|
|
5414
|
+
return new FileCallTimeoutError(`A filesystem call took longer than ${seconds} s.`);
|
|
5415
|
+
}
|
|
5416
|
+
function callWithTimeout(work, millis) {
|
|
5417
|
+
return new Promise((resolve, reject) => {
|
|
5418
|
+
const timer = setTimeout(() => reject(callTimeoutError(millis)), millis);
|
|
5419
|
+
work.then((value) => {
|
|
5420
|
+
clearTimeout(timer);
|
|
5421
|
+
resolve(value);
|
|
5422
|
+
}, (err) => {
|
|
5423
|
+
clearTimeout(timer);
|
|
5424
|
+
reject(err);
|
|
5425
|
+
});
|
|
5426
|
+
});
|
|
5427
|
+
}
|
|
5428
|
+
function withTimeout(work, millis, fallback) {
|
|
5429
|
+
return new Promise((resolve) => {
|
|
5430
|
+
const timer = setTimeout(() => resolve(fallback), millis);
|
|
5431
|
+
work.then((value) => {
|
|
5432
|
+
clearTimeout(timer);
|
|
5433
|
+
resolve(value);
|
|
5434
|
+
}, () => {
|
|
5435
|
+
clearTimeout(timer);
|
|
5436
|
+
resolve(fallback);
|
|
5437
|
+
});
|
|
5438
|
+
});
|
|
5439
|
+
}
|
|
5440
|
+
|
|
5441
|
+
// src/devices/files/fileCallGate.ts
|
|
5442
|
+
var MESSAGE_DRIVE_STOPPED = "A drive on the device stopped answering. Try again once it is back.";
|
|
5443
|
+
var FileCallsStuckError = class extends FileCallTimeoutError {
|
|
5444
|
+
constructor() {
|
|
5445
|
+
super(MESSAGE_DRIVE_STOPPED);
|
|
5446
|
+
}
|
|
5447
|
+
};
|
|
5448
|
+
var FileCallGate = class {
|
|
5449
|
+
constructor(places) {
|
|
5450
|
+
this.places = places;
|
|
5451
|
+
this.running = 0;
|
|
5452
|
+
this.abandoned = 0;
|
|
5453
|
+
/** In arrival order: a Set iterates as it was filled. */
|
|
5454
|
+
this.waiting = /* @__PURE__ */ new Set();
|
|
5455
|
+
if (!Number.isInteger(places) || places < 1) {
|
|
5456
|
+
throw new Error(`The file call gate needs at least 1 place, not ${places}.`);
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
/** `work`'s outcome, or a {@link FileCallTimeoutError} once `timeoutMillis` pass from now. */
|
|
5460
|
+
run(work, timeoutMillis) {
|
|
5461
|
+
if (this.isStuck()) {
|
|
5462
|
+
return Promise.reject(new FileCallsStuckError());
|
|
5463
|
+
}
|
|
5464
|
+
return new Promise((resolve, reject) => {
|
|
5465
|
+
let answered = false;
|
|
5466
|
+
let holdsPlace = false;
|
|
5467
|
+
let isAbandoned = false;
|
|
5468
|
+
const answer = (outcome) => {
|
|
5469
|
+
if (!answered) {
|
|
5470
|
+
answered = true;
|
|
5471
|
+
clearTimeout(timer);
|
|
5472
|
+
outcome();
|
|
5473
|
+
}
|
|
5474
|
+
};
|
|
5475
|
+
const call = {
|
|
5476
|
+
begin: () => {
|
|
5477
|
+
holdsPlace = true;
|
|
5478
|
+
this.running += 1;
|
|
5479
|
+
let pending;
|
|
5480
|
+
try {
|
|
5481
|
+
pending = work();
|
|
5482
|
+
} catch (err) {
|
|
5483
|
+
pending = Promise.reject(err);
|
|
5484
|
+
}
|
|
5485
|
+
pending.then((value) => answer(() => resolve(value)), (err) => answer(() => reject(err))).finally(() => this.release(isAbandoned));
|
|
5486
|
+
},
|
|
5487
|
+
refuse: (err) => answer(() => reject(err))
|
|
5488
|
+
};
|
|
5489
|
+
const timer = setTimeout(() => {
|
|
5490
|
+
if (holdsPlace) {
|
|
5491
|
+
isAbandoned = true;
|
|
5492
|
+
this.abandoned += 1;
|
|
5493
|
+
} else {
|
|
5494
|
+
this.waiting.delete(call);
|
|
5495
|
+
}
|
|
5496
|
+
answer(() => reject(callTimeoutError(timeoutMillis)));
|
|
5497
|
+
if (this.isStuck()) {
|
|
5498
|
+
this.refuseWaiting();
|
|
5499
|
+
}
|
|
5500
|
+
}, timeoutMillis);
|
|
5501
|
+
if (this.running < this.places) {
|
|
5502
|
+
call.begin();
|
|
5503
|
+
} else {
|
|
5504
|
+
this.waiting.add(call);
|
|
5505
|
+
}
|
|
5506
|
+
});
|
|
5507
|
+
}
|
|
5508
|
+
release(wasAbandoned) {
|
|
5509
|
+
this.running -= 1;
|
|
5510
|
+
if (wasAbandoned) {
|
|
5511
|
+
this.abandoned -= 1;
|
|
5512
|
+
}
|
|
5513
|
+
for (const call of this.waiting) {
|
|
5514
|
+
if (this.running >= this.places) {
|
|
5515
|
+
return;
|
|
5516
|
+
}
|
|
5517
|
+
this.waiting.delete(call);
|
|
5518
|
+
call.begin();
|
|
5519
|
+
}
|
|
5520
|
+
}
|
|
5521
|
+
isStuck() {
|
|
5522
|
+
return this.abandoned >= this.places;
|
|
5523
|
+
}
|
|
5524
|
+
refuseWaiting() {
|
|
5525
|
+
const refused = [...this.waiting];
|
|
5526
|
+
this.waiting.clear();
|
|
5527
|
+
refused.forEach((call) => call.refuse(new FileCallsStuckError()));
|
|
5528
|
+
}
|
|
5529
|
+
};
|
|
5530
|
+
function gatedReader(reader, gate, timeoutMillis) {
|
|
5531
|
+
return {
|
|
5532
|
+
readdir: (folder) => gate.run(() => reader.readdir(folder), timeoutMillis),
|
|
5533
|
+
lstat: (target) => gate.run(() => reader.lstat(target), timeoutMillis),
|
|
5534
|
+
stat: (target) => gate.run(() => reader.stat(target), timeoutMillis),
|
|
5535
|
+
readlink: (target) => gate.run(() => reader.readlink(target), timeoutMillis),
|
|
5536
|
+
access: (target, mode) => gate.run(() => reader.access(target, mode), timeoutMillis),
|
|
5537
|
+
homedir: () => reader.homedir()
|
|
5538
|
+
};
|
|
5539
|
+
}
|
|
5540
|
+
function gatedRemover(remover, gate, timeoutMillis) {
|
|
5541
|
+
return {
|
|
5542
|
+
lstat: (target) => gate.run(() => remover.lstat(target), timeoutMillis),
|
|
5543
|
+
stat: (target) => gate.run(() => remover.stat(target), timeoutMillis),
|
|
5544
|
+
readdir: (folder) => gate.run(() => remover.readdir(folder), timeoutMillis),
|
|
5545
|
+
unlink: (target) => gate.run(() => remover.unlink(target), timeoutMillis),
|
|
5546
|
+
rmdir: (target) => gate.run(() => remover.rmdir(target), timeoutMillis),
|
|
5547
|
+
chmod: (target, mode) => gate.run(() => remover.chmod(target, mode), timeoutMillis),
|
|
5548
|
+
realpath: (target) => gate.run(() => remover.realpath(target), timeoutMillis)
|
|
5549
|
+
};
|
|
5550
|
+
}
|
|
5551
|
+
function gatedMaker(maker, gate, timeoutMillis) {
|
|
5552
|
+
return {
|
|
5553
|
+
mkdir: (target) => gate.run(() => maker.mkdir(target), timeoutMillis)
|
|
5554
|
+
};
|
|
5555
|
+
}
|
|
5556
|
+
function gatedCopier(copier, gate, timeoutMillis) {
|
|
5557
|
+
return {
|
|
5558
|
+
lstat: (target) => gate.run(() => copier.lstat(target), timeoutMillis),
|
|
5559
|
+
stat: (target) => gate.run(() => copier.stat(target), timeoutMillis),
|
|
5560
|
+
realpath: (target) => gate.run(() => copier.realpath(target), timeoutMillis),
|
|
5561
|
+
readdir: (folder) => gate.run(() => copier.readdir(folder), timeoutMillis),
|
|
5562
|
+
mkdir: (target) => gate.run(() => copier.mkdir(target), timeoutMillis),
|
|
5563
|
+
openToRead: (target) => gate.run(() => copier.openToRead(target), timeoutMillis),
|
|
5564
|
+
createFile: (target) => gate.run(() => copier.createFile(target), timeoutMillis),
|
|
5565
|
+
read: (handle, buffer) => gate.run(() => copier.read(handle, buffer), timeoutMillis),
|
|
5566
|
+
write: (handle, buffer, length) => gate.run(() => copier.write(handle, buffer, length), timeoutMillis),
|
|
5567
|
+
close: (handle) => gate.run(() => copier.close(handle), timeoutMillis),
|
|
5568
|
+
readlink: (target) => gate.run(() => copier.readlink(target), timeoutMillis),
|
|
5569
|
+
symlink: (linkText, target, type) => gate.run(() => copier.symlink(linkText, target, type), timeoutMillis),
|
|
5570
|
+
chmod: (target, mode) => gate.run(() => copier.chmod(target, mode), timeoutMillis),
|
|
5571
|
+
utimes: (target, accessed, modified) => gate.run(
|
|
5572
|
+
() => copier.utimes(target, accessed, modified),
|
|
5573
|
+
timeoutMillis
|
|
5574
|
+
),
|
|
5575
|
+
rename: (from, to) => gate.run(() => copier.rename(from, to), timeoutMillis),
|
|
5576
|
+
unlink: (target) => gate.run(() => copier.unlink(target), timeoutMillis),
|
|
5577
|
+
freeBytes: (folder) => gate.run(() => copier.freeBytes(folder), timeoutMillis)
|
|
5578
|
+
};
|
|
5579
|
+
}
|
|
5580
|
+
|
|
5581
|
+
// src/devices/files/fileCopy.ts
|
|
5582
|
+
import crypto from "crypto";
|
|
5583
|
+
|
|
5584
|
+
// src/devices/files/fileProtectedPaths.ts
|
|
5585
|
+
import os7 from "os";
|
|
5586
|
+
import path5 from "path";
|
|
5587
|
+
var MESSAGE_PINGGY_FOLDER = "Pinggy keeps this folder so the device stays connected.";
|
|
5588
|
+
var MESSAGE_PINGGY_PROGRAM = "Pinggy needs this to keep the device connected.";
|
|
5589
|
+
var MESSAGE_SYSTEM_FOLDER = "This is a system folder.";
|
|
5590
|
+
var MESSAGE_ACCOUNTS_FOLDER = "This folder holds the accounts on this device.";
|
|
5591
|
+
var MESSAGE_ACCOUNT_FOLDER = "This is an account's home folder.";
|
|
5592
|
+
var LINUX_SYSTEM_FOLDERS = ["/bin", "/boot", "/etc", "/lib", "/lib64", "/sbin", "/usr", "/var"];
|
|
5593
|
+
var MACOS_SYSTEM_FOLDERS = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/private"];
|
|
5594
|
+
var WINDOWS_SYSTEM_FOLDER_VARIABLES = [
|
|
5595
|
+
["SystemRoot", "C:\\Windows"],
|
|
5596
|
+
["ProgramFiles", "C:\\Program Files"],
|
|
5597
|
+
["ProgramFiles(x86)", "C:\\Program Files (x86)"],
|
|
5598
|
+
["ProgramData", "C:\\ProgramData"]
|
|
5599
|
+
];
|
|
5600
|
+
var POSIX_ACCOUNTS_FOLDER = "/home";
|
|
5601
|
+
var MACOS_ACCOUNTS_FOLDER = "/Users";
|
|
5602
|
+
var WINDOWS_ACCOUNTS_FOLDER = "C:\\Users";
|
|
5603
|
+
var WINDOWS_PUBLIC_FOLDER_VARIABLE = "PUBLIC";
|
|
5604
|
+
function systemFoldersFor(platform3, environment) {
|
|
5605
|
+
if (platform3 === "win32") {
|
|
5606
|
+
return WINDOWS_SYSTEM_FOLDER_VARIABLES.map(([variable, fallback]) => environment[variable] || fallback);
|
|
5607
|
+
}
|
|
5608
|
+
return platform3 === "darwin" ? MACOS_SYSTEM_FOLDERS : LINUX_SYSTEM_FOLDERS;
|
|
5609
|
+
}
|
|
5610
|
+
function accountsFolderFor(platform3, environment) {
|
|
5611
|
+
if (platform3 === "win32") {
|
|
5612
|
+
const publicFolder = environment[WINDOWS_PUBLIC_FOLDER_VARIABLE];
|
|
5613
|
+
return publicFolder ? path5.win32.dirname(publicFolder) : WINDOWS_ACCOUNTS_FOLDER;
|
|
5614
|
+
}
|
|
5615
|
+
return platform3 === "darwin" ? MACOS_ACCOUNTS_FOLDER : POSIX_ACCOUNTS_FOLDER;
|
|
5616
|
+
}
|
|
5617
|
+
function agentFilesFor(platform3, home, environment, runningProgram, script) {
|
|
5618
|
+
const files = [installerBinaryPath(platform3, home, environment), runningProgram];
|
|
5619
|
+
if (script) {
|
|
5620
|
+
files.push(script);
|
|
5621
|
+
}
|
|
5622
|
+
const autostartFile = autostartFilePath(platform3, home);
|
|
5623
|
+
if (autostartFile) {
|
|
5624
|
+
files.push(autostartFile);
|
|
5625
|
+
}
|
|
5626
|
+
return [...new Set(files)];
|
|
5627
|
+
}
|
|
5628
|
+
function machineProtectedSources() {
|
|
5629
|
+
const home = os7.homedir();
|
|
5630
|
+
const script = isPackagedBinary() ? void 0 : process.argv[1];
|
|
5631
|
+
return {
|
|
5632
|
+
home,
|
|
5633
|
+
configFolder: getPinggyConfigDir(),
|
|
5634
|
+
systemFolders: systemFoldersFor(process.platform, process.env),
|
|
5635
|
+
accountsFolder: accountsFolderFor(process.platform, process.env),
|
|
5636
|
+
agentFiles: agentFilesFor(process.platform, home, process.env, process.execPath, script)
|
|
5637
|
+
};
|
|
5638
|
+
}
|
|
5639
|
+
function identityOf(stats) {
|
|
5640
|
+
return `${stats.dev}:${stats.ino}`;
|
|
5641
|
+
}
|
|
5642
|
+
function selfAndAncestors(target, paths) {
|
|
5643
|
+
const chain = [];
|
|
5644
|
+
let current = paths.resolve(target);
|
|
5645
|
+
for (; ; ) {
|
|
5646
|
+
chain.push(current);
|
|
5647
|
+
const parent = paths.dirname(current);
|
|
5648
|
+
if (parent === current) {
|
|
5649
|
+
return chain;
|
|
5650
|
+
}
|
|
5651
|
+
current = parent;
|
|
5652
|
+
}
|
|
5653
|
+
}
|
|
5654
|
+
function identityOrNull(read, callTimeoutMillis) {
|
|
5655
|
+
return callWithTimeout(read, callTimeoutMillis).then(identityOf, (err) => {
|
|
5656
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5657
|
+
throw err;
|
|
5658
|
+
}
|
|
5659
|
+
return null;
|
|
5660
|
+
});
|
|
5661
|
+
}
|
|
5662
|
+
async function identitiesOf(target, remover, callTimeoutMillis) {
|
|
5663
|
+
const identities = await Promise.all([remover.lstat(target), remover.stat(target)].map((read) => identityOrNull(read, callTimeoutMillis)));
|
|
5664
|
+
return identities.filter((identity) => identity !== null);
|
|
5665
|
+
}
|
|
5666
|
+
async function realPathOrNull(target, remover, callTimeoutMillis) {
|
|
5667
|
+
try {
|
|
5668
|
+
return await callWithTimeout(remover.realpath(target), callTimeoutMillis);
|
|
5669
|
+
} catch (err) {
|
|
5670
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5671
|
+
throw err;
|
|
5672
|
+
}
|
|
5673
|
+
return null;
|
|
5674
|
+
}
|
|
5675
|
+
}
|
|
5676
|
+
async function agentFileChains(files, paths, remover, callTimeoutMillis) {
|
|
5677
|
+
const realPaths = await Promise.all(files.map((file) => realPathOrNull(file, remover, callTimeoutMillis)));
|
|
5678
|
+
return files.flatMap((file, index) => {
|
|
5679
|
+
const realPath = realPaths[index];
|
|
5680
|
+
return realPath === null ? [] : [...selfAndAncestors(file, paths), ...selfAndAncestors(realPath, paths)];
|
|
5681
|
+
});
|
|
5682
|
+
}
|
|
5683
|
+
async function addFolders(reasons, folders, message, remover, callTimeoutMillis) {
|
|
5684
|
+
const identities = await Promise.all(folders.map((folder) => identitiesOf(folder, remover, callTimeoutMillis)));
|
|
5685
|
+
for (const identity of identities.flat()) {
|
|
5686
|
+
reasons.set(identity, message);
|
|
5687
|
+
}
|
|
5688
|
+
}
|
|
5689
|
+
async function readProtectedSet(sources, paths, remover, callTimeoutMillis) {
|
|
5690
|
+
const reasons = /* @__PURE__ */ new Map();
|
|
5691
|
+
const agentChains = await agentFileChains(sources.agentFiles, paths, remover, callTimeoutMillis);
|
|
5692
|
+
await addFolders(reasons, agentChains, MESSAGE_PINGGY_PROGRAM, remover, callTimeoutMillis);
|
|
5693
|
+
const systemChains = sources.systemFolders.flatMap((folder) => selfAndAncestors(folder, paths));
|
|
5694
|
+
await addFolders(reasons, systemChains, MESSAGE_SYSTEM_FOLDER, remover, callTimeoutMillis);
|
|
5695
|
+
await addFolders(
|
|
5696
|
+
reasons,
|
|
5697
|
+
selfAndAncestors(sources.accountsFolder, paths),
|
|
5698
|
+
MESSAGE_ACCOUNTS_FOLDER,
|
|
5699
|
+
remover,
|
|
5700
|
+
callTimeoutMillis
|
|
5701
|
+
);
|
|
5702
|
+
const pinggyChains = [...selfAndAncestors(sources.home, paths), ...selfAndAncestors(sources.configFolder, paths)];
|
|
5703
|
+
await addFolders(reasons, pinggyChains, MESSAGE_PINGGY_FOLDER, remover, callTimeoutMillis);
|
|
5704
|
+
const [configFolder, accountsFolder] = await Promise.all([sources.configFolder, sources.accountsFolder].map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
|
|
5705
|
+
return { reasons, configFolder, accountsFolder };
|
|
5706
|
+
}
|
|
5707
|
+
async function isInsideConfigFolder(directory, protectedSet, paths, remover, callTimeoutMillis) {
|
|
5708
|
+
if (protectedSet.configFolder === null) {
|
|
5709
|
+
return false;
|
|
5710
|
+
}
|
|
5711
|
+
const chain = selfAndAncestors(directory, paths);
|
|
5712
|
+
const identities = await Promise.all(chain.map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
|
|
5713
|
+
return identities.includes(protectedSet.configFolder);
|
|
5714
|
+
}
|
|
5715
|
+
|
|
5716
|
+
// src/devices/files/fileDelete.ts
|
|
5717
|
+
var WINDOWS_WRITABLE_MODE = 438;
|
|
5718
|
+
var MESSAGE_DELETE_FAILED = "The item could not be deleted.";
|
|
5719
|
+
var MESSAGE_PROTECTED_UNREAD = "The protected folders could not be read in time.";
|
|
5720
|
+
var MESSAGE_SELECTED_MOUNT = "This folder is a mounted disk. Open it to delete what is inside.";
|
|
5721
|
+
var MESSAGE_MOUNT_INSIDE = "Another disk is mounted inside. Pinggy left it in place.";
|
|
5722
|
+
var ProtectedEntryError = class extends Error {
|
|
5723
|
+
};
|
|
5724
|
+
async function prepareDelete(request2, dependencies) {
|
|
5725
|
+
const paths = pathsFor(dependencies.platform);
|
|
5726
|
+
const pathIssue = pathProblem(request2.path, paths);
|
|
5727
|
+
if (pathIssue) {
|
|
5728
|
+
return fileError(ERROR_INVALID_PATH, pathIssue);
|
|
5729
|
+
}
|
|
5730
|
+
const item = resolvedItem(request2.path, paths);
|
|
5731
|
+
const { remover, callTimeoutMillis } = dependencies;
|
|
5732
|
+
let stats;
|
|
5733
|
+
let parentStats;
|
|
5734
|
+
try {
|
|
5735
|
+
stats = await callWithTimeout(remover.lstat(item.path), callTimeoutMillis);
|
|
5736
|
+
parentStats = await callWithTimeout(remover.stat(item.parent), callTimeoutMillis);
|
|
5737
|
+
} catch (err) {
|
|
5738
|
+
return { error: deleteFailure(err) };
|
|
5739
|
+
}
|
|
5740
|
+
let protectedSet;
|
|
5741
|
+
let insideConfigFolder;
|
|
5742
|
+
try {
|
|
5743
|
+
protectedSet = await readProtectedSet(dependencies.protectedSources, paths, remover, callTimeoutMillis);
|
|
5744
|
+
insideConfigFolder = await isInsideConfigFolder(item.parent, protectedSet, paths, remover, callTimeoutMillis);
|
|
5745
|
+
} catch (err) {
|
|
5746
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
5747
|
+
return fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD));
|
|
5748
|
+
}
|
|
5749
|
+
if (insideConfigFolder) {
|
|
5750
|
+
return fileError(ERROR_PROTECTED_PATH, MESSAGE_PINGGY_FOLDER);
|
|
5751
|
+
}
|
|
5752
|
+
if (protectedSet.accountsFolder !== null && identityOf(parentStats) === protectedSet.accountsFolder) {
|
|
5753
|
+
return fileError(ERROR_PROTECTED_PATH, MESSAGE_ACCOUNT_FOLDER);
|
|
5754
|
+
}
|
|
5755
|
+
const reason = protectedSet.reasons.get(identityOf(stats));
|
|
5756
|
+
if (reason) {
|
|
5757
|
+
return fileError(ERROR_PROTECTED_PATH, reason);
|
|
5758
|
+
}
|
|
5759
|
+
if (stats.dev !== parentStats.dev) {
|
|
5760
|
+
return fileError(ERROR_MOUNT_POINT, MESSAGE_SELECTED_MOUNT);
|
|
5761
|
+
}
|
|
5762
|
+
return { target: item.path, name: item.name, stats, protectedSet };
|
|
5763
|
+
}
|
|
5764
|
+
async function runDelete(prepared, progress, dependencies) {
|
|
5765
|
+
const context = {
|
|
5766
|
+
device: prepared.stats.dev,
|
|
5767
|
+
protectedSet: prepared.protectedSet,
|
|
5768
|
+
progress,
|
|
5769
|
+
dependencies,
|
|
5770
|
+
paths: pathsFor(dependencies.platform)
|
|
5771
|
+
};
|
|
5772
|
+
let result = {};
|
|
5773
|
+
try {
|
|
5774
|
+
if (!await removeEntry(prepared.target, prepared.stats, context)) {
|
|
5775
|
+
result = fileError(ERROR_MOUNT_POINT, MESSAGE_MOUNT_INSIDE);
|
|
5776
|
+
}
|
|
5777
|
+
} catch (err) {
|
|
5778
|
+
result = { error: deleteFailure(err) };
|
|
5779
|
+
}
|
|
5780
|
+
progress.items_done += 1;
|
|
5781
|
+
return result;
|
|
5782
|
+
}
|
|
5783
|
+
function removeTree(target, stats, protectedSet, dependencies) {
|
|
5784
|
+
const context = {
|
|
5785
|
+
device: stats.dev,
|
|
5786
|
+
protectedSet,
|
|
5787
|
+
progress: { files_done: 0 },
|
|
5788
|
+
dependencies,
|
|
5789
|
+
paths: pathsFor(dependencies.platform)
|
|
5790
|
+
};
|
|
5791
|
+
return removeEntry(target, stats, context);
|
|
5792
|
+
}
|
|
5793
|
+
async function removeEntry(target, stats, context) {
|
|
5794
|
+
if (!stats.isDirectory()) {
|
|
5795
|
+
if (await removeWith(target, (entry) => context.dependencies.remover.unlink(entry), context)) {
|
|
5796
|
+
context.progress.files_done += 1;
|
|
5797
|
+
}
|
|
5798
|
+
return true;
|
|
5799
|
+
}
|
|
5800
|
+
return removeFolder(target, context);
|
|
5801
|
+
}
|
|
5802
|
+
async function removeFolder(folder, context) {
|
|
5803
|
+
const { remover, callTimeoutMillis } = context.dependencies;
|
|
5804
|
+
const removeFolderItself = (entry) => remover.rmdir(entry);
|
|
5805
|
+
try {
|
|
5806
|
+
if (await removeWith(folder, removeFolderItself, context)) {
|
|
5807
|
+
context.progress.files_done += 1;
|
|
5808
|
+
}
|
|
5809
|
+
return true;
|
|
5810
|
+
} catch (err) {
|
|
5811
|
+
if (!isNotEmpty(err)) {
|
|
5812
|
+
throw err;
|
|
5813
|
+
}
|
|
5814
|
+
}
|
|
5815
|
+
let names;
|
|
5816
|
+
try {
|
|
5817
|
+
names = await callWithTimeout(remover.readdir(folder), callTimeoutMillis);
|
|
5818
|
+
} catch (err) {
|
|
5819
|
+
if (isGone(err)) {
|
|
5820
|
+
return true;
|
|
5821
|
+
}
|
|
5822
|
+
throw err;
|
|
5823
|
+
}
|
|
5824
|
+
let removedAll = true;
|
|
5825
|
+
for (const name of names) {
|
|
5826
|
+
if (!await removeChild(context.paths.join(folder, name), context)) {
|
|
5827
|
+
removedAll = false;
|
|
5828
|
+
}
|
|
5829
|
+
}
|
|
5830
|
+
if (!removedAll) {
|
|
5831
|
+
return false;
|
|
5832
|
+
}
|
|
5833
|
+
if (await removeWith(folder, removeFolderItself, context)) {
|
|
5834
|
+
context.progress.files_done += 1;
|
|
5835
|
+
}
|
|
5836
|
+
return true;
|
|
5837
|
+
}
|
|
5838
|
+
async function removeChild(child, context) {
|
|
5839
|
+
let stats;
|
|
5840
|
+
try {
|
|
5841
|
+
stats = await callWithTimeout(
|
|
5842
|
+
context.dependencies.remover.lstat(child),
|
|
5843
|
+
context.dependencies.callTimeoutMillis
|
|
5844
|
+
);
|
|
5845
|
+
} catch (err) {
|
|
5846
|
+
if (isGone(err)) {
|
|
5847
|
+
return true;
|
|
5848
|
+
}
|
|
5849
|
+
throw err;
|
|
5850
|
+
}
|
|
5851
|
+
const reason = context.protectedSet.reasons.get(identityOf(stats));
|
|
5852
|
+
if (reason) {
|
|
5853
|
+
throw new ProtectedEntryError(reason);
|
|
5854
|
+
}
|
|
5855
|
+
if (stats.isDirectory() && stats.dev !== context.device) {
|
|
5856
|
+
return false;
|
|
5857
|
+
}
|
|
5858
|
+
return removeEntry(child, stats, context);
|
|
5859
|
+
}
|
|
5860
|
+
async function removeWith(target, remove, context) {
|
|
5861
|
+
const { remover, callTimeoutMillis, platform: platform3 } = context.dependencies;
|
|
5862
|
+
try {
|
|
5863
|
+
await callWithTimeout(remove(target), callTimeoutMillis);
|
|
5864
|
+
return true;
|
|
5865
|
+
} catch (err) {
|
|
5866
|
+
if (isGone(err)) {
|
|
5867
|
+
return false;
|
|
5868
|
+
}
|
|
5869
|
+
if (platform3 !== "win32" || errorCodeOf(err) !== "EPERM") {
|
|
5870
|
+
throw err;
|
|
5871
|
+
}
|
|
5872
|
+
try {
|
|
5873
|
+
await callWithTimeout(remover.chmod(target, WINDOWS_WRITABLE_MODE), callTimeoutMillis);
|
|
5874
|
+
} catch {
|
|
5875
|
+
throw err;
|
|
5876
|
+
}
|
|
5877
|
+
}
|
|
5878
|
+
try {
|
|
5879
|
+
await callWithTimeout(remove(target), callTimeoutMillis);
|
|
5880
|
+
return true;
|
|
5881
|
+
} catch (err) {
|
|
5882
|
+
if (isGone(err)) {
|
|
5883
|
+
return false;
|
|
5884
|
+
}
|
|
5885
|
+
throw err;
|
|
5886
|
+
}
|
|
5887
|
+
}
|
|
5888
|
+
function isGone(err) {
|
|
5889
|
+
return errorCodeOf(err) === "ENOENT";
|
|
5890
|
+
}
|
|
5891
|
+
function isNotEmpty(err) {
|
|
5892
|
+
const code = errorCodeOf(err);
|
|
5893
|
+
return code === "ENOTEMPTY" || code === "EEXIST";
|
|
5894
|
+
}
|
|
5895
|
+
function deleteFailure(err) {
|
|
5896
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5897
|
+
return { code: ERROR_FILE_TIMEOUT, message: err.message };
|
|
5898
|
+
}
|
|
5899
|
+
if (err instanceof ProtectedEntryError) {
|
|
5900
|
+
return { code: ERROR_PROTECTED_PATH, message: err.message };
|
|
5901
|
+
}
|
|
5902
|
+
const message = failureMessage(err, MESSAGE_DELETE_FAILED);
|
|
5903
|
+
switch (errorCodeOf(err)) {
|
|
5904
|
+
case "ENOENT":
|
|
5905
|
+
case "ENOTDIR":
|
|
5906
|
+
return { code: ERROR_PATH_NOT_FOUND, message };
|
|
5907
|
+
case "EACCES":
|
|
5908
|
+
case "EPERM":
|
|
5909
|
+
case "EROFS":
|
|
5910
|
+
return { code: ERROR_PERMISSION_DENIED, message };
|
|
5911
|
+
default:
|
|
5912
|
+
return { code: ERROR_FILE_OPERATION_FAILED, message };
|
|
5913
|
+
}
|
|
5914
|
+
}
|
|
5915
|
+
|
|
5916
|
+
// src/devices/files/fileCopy.ts
|
|
5917
|
+
var COPY_PIECE_BYTES = 1024 * 1024;
|
|
5918
|
+
var SMALL_PIECE_BYTES = 4096;
|
|
5919
|
+
var PERMISSION_BITS = 0o777n;
|
|
5920
|
+
var MAX_KEEP_BOTH_NUMBER = 1e3;
|
|
5921
|
+
var EXTENSION_SEPARATOR2 = ".";
|
|
5922
|
+
var HIDDEN_NAME_PREFIX2 = ".";
|
|
5923
|
+
var HIDDEN_COPY_MARK = "copy";
|
|
5924
|
+
var HIDDEN_OLD_MARK = "old";
|
|
5925
|
+
var HIDDEN_SUFFIX_BYTES = 4;
|
|
5926
|
+
var LINK_TYPE_FILE = "file";
|
|
5927
|
+
var LINK_TYPE_FOLDER = "dir";
|
|
5928
|
+
var BYTES_PER_UNIT = 1e3;
|
|
5929
|
+
var BYTE_UNITS = ["bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
5930
|
+
var BYTE_UNIT_SINGULAR = "byte";
|
|
5931
|
+
var MESSAGE_FOLDER_UNREADABLE = "The folder could not be read.";
|
|
5932
|
+
var MESSAGE_NOT_A_FOLDER = "The path is not a folder.";
|
|
5933
|
+
var MESSAGE_ROOT = "A drive or filesystem root cannot be copied or moved.";
|
|
5934
|
+
var MESSAGE_INTO_ITSELF = "A folder cannot be copied into itself.";
|
|
5935
|
+
var MESSAGE_REPLACE_ITSELF = "An item cannot replace itself.";
|
|
5936
|
+
var MESSAGE_REPLACE_HOLDER = "An item cannot replace a folder that holds it.";
|
|
5937
|
+
var MESSAGE_TARGET_TAKEN = "1 item already exists in the destination.";
|
|
5938
|
+
var MESSAGE_PROTECTED_UNREAD2 = "The protected folders could not be read in time.";
|
|
5939
|
+
var MESSAGE_SPECIAL_SELECTED = "This is a socket, pipe or device file. Pinggy cannot copy it.";
|
|
5940
|
+
var MESSAGE_REPLACE_MOUNT = "This item is a mounted disk. Pinggy does not replace it.";
|
|
5941
|
+
var MESSAGE_COPY_FAILED = "The item could not be copied.";
|
|
5942
|
+
var MESSAGE_COPY_IN_PLACE = "The copy is in place. The old one stays as";
|
|
5943
|
+
var REASON_MOUNT_INSIDE = "a disk is mounted inside it.";
|
|
5944
|
+
var TakenError = class extends Error {
|
|
5945
|
+
};
|
|
5946
|
+
var RequestRefusal = class extends Error {
|
|
5947
|
+
constructor(refusal) {
|
|
5948
|
+
super(refusal.error.message);
|
|
5949
|
+
this.refusal = refusal;
|
|
5950
|
+
}
|
|
5951
|
+
};
|
|
5952
|
+
var SKIPPED = "skipped";
|
|
5953
|
+
function randomHiddenNameSuffix() {
|
|
5954
|
+
return crypto.randomBytes(HIDDEN_SUFFIX_BYTES).toString("hex");
|
|
5955
|
+
}
|
|
5956
|
+
async function prepareCopy(request2, dependencies) {
|
|
5957
|
+
try {
|
|
5958
|
+
return await checkedCopy(request2, dependencies);
|
|
5959
|
+
} catch (err) {
|
|
5960
|
+
return refusalOf(err);
|
|
5961
|
+
}
|
|
5962
|
+
}
|
|
5963
|
+
function refusalOf(err) {
|
|
5964
|
+
if (err instanceof RequestRefusal) {
|
|
5965
|
+
return err.refusal;
|
|
5966
|
+
}
|
|
5967
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
5968
|
+
return fileError(code, failureMessage(err, MESSAGE_FOLDER_UNREADABLE));
|
|
5969
|
+
}
|
|
5970
|
+
async function checkedCopy(request2, dependencies) {
|
|
5971
|
+
const { copier, platform: platform3 } = dependencies;
|
|
5972
|
+
const paths = pathsFor(platform3);
|
|
5973
|
+
const { source, destination } = resolvedItems(request2, paths);
|
|
5974
|
+
checkTargetName(destination.name, platform3);
|
|
5975
|
+
const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_COPY_FAILED);
|
|
5976
|
+
if (isSpecial(sourceStats)) {
|
|
5977
|
+
throw new RequestRefusal(fileError(ERROR_SPECIAL_FILE, MESSAGE_SPECIAL_SELECTED));
|
|
5978
|
+
}
|
|
5979
|
+
const destinationStats = await folderStats(destination.parent, copier);
|
|
5980
|
+
await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF);
|
|
5981
|
+
const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
|
|
5982
|
+
if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
|
|
5983
|
+
const target = await lstatOrNull(destination.path, copier);
|
|
5984
|
+
if (onConflict === ON_CONFLICT_FAIL && target !== null) {
|
|
5985
|
+
throw new RequestRefusal(targetTakenRefusal());
|
|
5986
|
+
}
|
|
5987
|
+
if (onConflict === ON_CONFLICT_REPLACE && target !== null && identityOf(target) === identityOf(sourceStats)) {
|
|
5988
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
|
|
5989
|
+
}
|
|
5990
|
+
if (onConflict === ON_CONFLICT_REPLACE) {
|
|
5991
|
+
await refuseReplacingAHolder(target, source.parent, dependencies);
|
|
5992
|
+
}
|
|
5993
|
+
}
|
|
5994
|
+
const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(
|
|
5995
|
+
destination.parent,
|
|
5996
|
+
destinationStats,
|
|
5997
|
+
await readProtectedFolders(dependencies),
|
|
5998
|
+
dependencies
|
|
5999
|
+
) : null;
|
|
6000
|
+
return {
|
|
6001
|
+
source: source.path,
|
|
6002
|
+
sourceStats,
|
|
6003
|
+
sourceName: source.name,
|
|
6004
|
+
destinationDirectory: destination.parent,
|
|
6005
|
+
targetName: destination.name,
|
|
6006
|
+
onConflict,
|
|
6007
|
+
destinationDevice: destinationStats.dev,
|
|
6008
|
+
replaceGuard
|
|
6009
|
+
};
|
|
6010
|
+
}
|
|
6011
|
+
function resolvedItems(request2, paths) {
|
|
6012
|
+
for (const requested of [request2.source_path, request2.destination_path]) {
|
|
6013
|
+
const issue = pathProblem(requested, paths);
|
|
6014
|
+
if (issue) {
|
|
6015
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PATH, issue));
|
|
6016
|
+
}
|
|
6017
|
+
}
|
|
6018
|
+
const source = resolvedItem(request2.source_path, paths);
|
|
6019
|
+
const requestedDestination = resolvedItem(request2.destination_path, paths);
|
|
6020
|
+
const destination = requestedDestination.name === source.name ? requestedDestination : withTrimmedName(requestedDestination);
|
|
6021
|
+
if (isRoot(source.path, paths) || isRoot(destination.path, paths)) {
|
|
6022
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PATH, MESSAGE_ROOT));
|
|
6023
|
+
}
|
|
6024
|
+
return { source, destination };
|
|
6025
|
+
}
|
|
6026
|
+
function checkTargetName(targetName, platform3) {
|
|
6027
|
+
const nameIssue = nameProblem(targetName, platform3);
|
|
6028
|
+
if (nameIssue) {
|
|
6029
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PAYLOAD2, nameIssue));
|
|
6030
|
+
}
|
|
6031
|
+
const windowsIssue = platform3 === "win32" ? windowsNameProblem(targetName, "A name") : null;
|
|
6032
|
+
if (windowsIssue) {
|
|
6033
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_NAME, windowsIssue));
|
|
6034
|
+
}
|
|
6035
|
+
}
|
|
6036
|
+
async function sourceItemStats(source, copier, fallbackMessage) {
|
|
6037
|
+
try {
|
|
6038
|
+
return await copier.lstat(source);
|
|
6039
|
+
} catch (err) {
|
|
6040
|
+
throw new RequestRefusal({ error: copyFailure(err, fallbackMessage) });
|
|
6041
|
+
}
|
|
6042
|
+
}
|
|
6043
|
+
async function folderStats(folder, copier) {
|
|
6044
|
+
let stats;
|
|
6045
|
+
try {
|
|
6046
|
+
stats = await copier.stat(folder);
|
|
6047
|
+
} catch (err) {
|
|
6048
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6049
|
+
throw err;
|
|
6050
|
+
}
|
|
6051
|
+
throw new RequestRefusal(folderFailure(err));
|
|
6052
|
+
}
|
|
6053
|
+
if (!stats.isDirectory()) {
|
|
6054
|
+
throw new RequestRefusal(fileError(ERROR_NOT_A_DIRECTORY, MESSAGE_NOT_A_FOLDER));
|
|
6055
|
+
}
|
|
6056
|
+
return stats;
|
|
6057
|
+
}
|
|
6058
|
+
function folderFailure(err) {
|
|
6059
|
+
const message = failureMessage(err, MESSAGE_FOLDER_UNREADABLE);
|
|
6060
|
+
switch (errorCodeOf(err)) {
|
|
6061
|
+
case "ENOENT":
|
|
6062
|
+
case "ENOTDIR":
|
|
6063
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6064
|
+
case "EACCES":
|
|
6065
|
+
case "EPERM":
|
|
6066
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6067
|
+
default:
|
|
6068
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6069
|
+
}
|
|
6070
|
+
}
|
|
6071
|
+
async function refuseIntoItself(source, destinationDirectory, dependencies, message) {
|
|
6072
|
+
if (await folderHolds(source, destinationDirectory, dependencies)) {
|
|
6073
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, message));
|
|
6074
|
+
}
|
|
6075
|
+
}
|
|
6076
|
+
async function refuseReplacingAHolder(target, sourceDirectory, dependencies) {
|
|
6077
|
+
if (await folderHolds(target, sourceDirectory, dependencies)) {
|
|
6078
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_HOLDER));
|
|
6079
|
+
}
|
|
6080
|
+
}
|
|
6081
|
+
async function folderHolds(candidate, folder, dependencies) {
|
|
6082
|
+
if (candidate === null || !candidate.isDirectory()) {
|
|
6083
|
+
return false;
|
|
6084
|
+
}
|
|
6085
|
+
const { copier } = dependencies;
|
|
6086
|
+
const paths = pathsFor(dependencies.platform);
|
|
6087
|
+
const realFolder = await copier.realpath(folder);
|
|
6088
|
+
const chain = new Set(await Promise.all(selfAndAncestors(realFolder, paths).map((each) => identityOrNull2(copier.stat(each)))));
|
|
6089
|
+
return chain.has(identityOf(candidate));
|
|
6090
|
+
}
|
|
6091
|
+
function targetTakenRefusal() {
|
|
6092
|
+
return fileError(ERROR_FILE_EXISTS, MESSAGE_TARGET_TAKEN);
|
|
6093
|
+
}
|
|
6094
|
+
async function readProtectedFolders(dependencies) {
|
|
6095
|
+
const { remover, callTimeoutMillis, protectedSources } = dependencies;
|
|
6096
|
+
try {
|
|
6097
|
+
return await readProtectedSet(protectedSources, pathsFor(dependencies.platform), remover, callTimeoutMillis);
|
|
6098
|
+
} catch (err) {
|
|
6099
|
+
throw protectedUnread(err);
|
|
6100
|
+
}
|
|
6101
|
+
}
|
|
6102
|
+
async function removalGuard(folder, stats, protectedSet, dependencies) {
|
|
6103
|
+
const { remover, callTimeoutMillis } = dependencies;
|
|
6104
|
+
try {
|
|
6105
|
+
const insideConfigFolder = await isInsideConfigFolder(
|
|
6106
|
+
folder,
|
|
6107
|
+
protectedSet,
|
|
6108
|
+
pathsFor(dependencies.platform),
|
|
6109
|
+
remover,
|
|
6110
|
+
callTimeoutMillis
|
|
6111
|
+
);
|
|
6112
|
+
const inAccountsFolder = protectedSet.accountsFolder !== null && identityOf(stats) === protectedSet.accountsFolder;
|
|
6113
|
+
return { protectedSet, insideConfigFolder, inAccountsFolder };
|
|
6114
|
+
} catch (err) {
|
|
6115
|
+
throw protectedUnread(err);
|
|
6116
|
+
}
|
|
6117
|
+
}
|
|
6118
|
+
function protectedUnread(err) {
|
|
6119
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
6120
|
+
return new RequestRefusal(fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD2)));
|
|
6121
|
+
}
|
|
6122
|
+
async function runCopy(prepared, progress, dependencies) {
|
|
6123
|
+
const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
|
|
6124
|
+
const totals = await countSource(prepared, dependencies);
|
|
6125
|
+
counted.files_total = totals.files;
|
|
6126
|
+
counted.bytes_total = totals.bytes;
|
|
6127
|
+
const noSpace = await noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
|
|
6128
|
+
if (noSpace) {
|
|
6129
|
+
return noSpace;
|
|
6130
|
+
}
|
|
6131
|
+
const walk = {
|
|
6132
|
+
copier: dependencies.copier,
|
|
6133
|
+
paths: pathsFor(dependencies.platform),
|
|
6134
|
+
platform: dependencies.platform,
|
|
6135
|
+
progress: counted,
|
|
6136
|
+
specialFilesLeftOut: 0
|
|
6137
|
+
};
|
|
6138
|
+
const outcome = await copyItem(prepared, walk, dependencies);
|
|
6139
|
+
counted.items_done += 1;
|
|
6140
|
+
return outcomeAnswer(outcome);
|
|
6141
|
+
}
|
|
6142
|
+
function outcomeAnswer(outcome) {
|
|
6143
|
+
if (outcome === SKIPPED) {
|
|
6144
|
+
return { skipped: true };
|
|
6145
|
+
}
|
|
6146
|
+
return outcome === null ? {} : { error: outcome };
|
|
6147
|
+
}
|
|
6148
|
+
async function noSpaceRefusal(neededBytes, destinationDirectory, copier) {
|
|
6149
|
+
const freeBytes = await copier.freeBytes(destinationDirectory).catch(() => null);
|
|
6150
|
+
if (freeBytes === null || BigInt(neededBytes) <= freeBytes) {
|
|
6151
|
+
return null;
|
|
6152
|
+
}
|
|
6153
|
+
return fileError(ERROR_NO_SPACE, `The copy needs ${formatBytes(neededBytes)}. The destination disk has ${formatBytes(freeBytes)} free.`);
|
|
6154
|
+
}
|
|
6155
|
+
async function countSource(prepared, dependencies) {
|
|
6156
|
+
const { copier } = dependencies;
|
|
6157
|
+
const paths = pathsFor(dependencies.platform);
|
|
6158
|
+
const totals = newCountTotals();
|
|
6159
|
+
const target = paths.join(prepared.destinationDirectory, prepared.targetName);
|
|
6160
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, copier).catch(() => null)) {
|
|
6161
|
+
return totals;
|
|
6162
|
+
}
|
|
6163
|
+
await countEntry(prepared.source, totals, copier, paths, null);
|
|
6164
|
+
return totals;
|
|
6165
|
+
}
|
|
6166
|
+
function newCountTotals() {
|
|
6167
|
+
return { files: 0, bytes: 0, specialFiles: 0, mountedDisks: 0 };
|
|
6168
|
+
}
|
|
6169
|
+
async function countEntry(entry, totals, copier, paths, stopAtDevice) {
|
|
6170
|
+
let stats;
|
|
6171
|
+
try {
|
|
6172
|
+
stats = await copier.lstat(entry);
|
|
6173
|
+
} catch {
|
|
6174
|
+
return;
|
|
6175
|
+
}
|
|
6176
|
+
if (isSpecial(stats)) {
|
|
6177
|
+
totals.specialFiles += 1;
|
|
6178
|
+
return;
|
|
6179
|
+
}
|
|
6180
|
+
if (stats.isDirectory() && stopAtDevice !== null && stats.dev !== stopAtDevice) {
|
|
6181
|
+
totals.mountedDisks += 1;
|
|
6182
|
+
return;
|
|
6183
|
+
}
|
|
6184
|
+
totals.files += 1;
|
|
6185
|
+
if (stats.isFile()) {
|
|
6186
|
+
totals.bytes += Number(stats.size);
|
|
6187
|
+
return;
|
|
6188
|
+
}
|
|
6189
|
+
if (!stats.isDirectory()) {
|
|
6190
|
+
return;
|
|
6191
|
+
}
|
|
6192
|
+
let children;
|
|
6193
|
+
try {
|
|
6194
|
+
children = await copier.readdir(entry);
|
|
6195
|
+
} catch {
|
|
6196
|
+
return;
|
|
6197
|
+
}
|
|
6198
|
+
for (const child of children) {
|
|
6199
|
+
await countEntry(paths.join(entry, child), totals, copier, paths, stopAtDevice);
|
|
6200
|
+
}
|
|
6201
|
+
}
|
|
6202
|
+
async function copyItem(prepared, walk, dependencies) {
|
|
6203
|
+
try {
|
|
6204
|
+
if (prepared.onConflict === ON_CONFLICT_REPLACE) {
|
|
6205
|
+
const refusal = await replaceTarget(prepared, walk, dependencies);
|
|
6206
|
+
if (refusal) {
|
|
6207
|
+
return refusal;
|
|
6208
|
+
}
|
|
6209
|
+
} else if (await copyToFreeName(
|
|
6210
|
+
prepared.source,
|
|
6211
|
+
prepared.sourceStats,
|
|
6212
|
+
prepared.targetName,
|
|
6213
|
+
prepared,
|
|
6214
|
+
walk
|
|
6215
|
+
) === SKIPPED) {
|
|
6216
|
+
return SKIPPED;
|
|
6217
|
+
}
|
|
6218
|
+
} catch (err) {
|
|
6219
|
+
return copyFailure(err, MESSAGE_COPY_FAILED);
|
|
6220
|
+
}
|
|
6221
|
+
return walk.specialFilesLeftOut > 0 ? specialFilesLeftOut(walk.specialFilesLeftOut) : null;
|
|
6222
|
+
}
|
|
6223
|
+
async function copyToFreeName(source, stats, targetName, prepared, walk) {
|
|
6224
|
+
let candidate = targetName;
|
|
6225
|
+
for (let number = 1; ; number++) {
|
|
6226
|
+
try {
|
|
6227
|
+
await copyEntry(source, stats, walk.paths.join(prepared.destinationDirectory, candidate), walk, true);
|
|
6228
|
+
return null;
|
|
6229
|
+
} catch (err) {
|
|
6230
|
+
if (!(err instanceof TakenError)) {
|
|
6231
|
+
throw err;
|
|
6232
|
+
}
|
|
6233
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP) {
|
|
6234
|
+
return SKIPPED;
|
|
6235
|
+
}
|
|
6236
|
+
if (prepared.onConflict !== ON_CONFLICT_KEEP_BOTH || number > MAX_KEEP_BOTH_NUMBER) {
|
|
6237
|
+
throw err;
|
|
6238
|
+
}
|
|
6239
|
+
candidate = keepBothName(targetName, stats.isDirectory(), number);
|
|
6240
|
+
}
|
|
6241
|
+
}
|
|
6242
|
+
}
|
|
6243
|
+
async function replaceTarget(prepared, walk, dependencies) {
|
|
6244
|
+
const { copier, paths } = walk;
|
|
6245
|
+
const { source, sourceStats: stats, targetName } = prepared;
|
|
6246
|
+
const guard = prepared.replaceGuard;
|
|
6247
|
+
const target = paths.join(prepared.destinationDirectory, targetName);
|
|
6248
|
+
const existing = await lstatOrNull(target, copier);
|
|
6249
|
+
if (existing === null) {
|
|
6250
|
+
await copyEntry(source, stats, target, walk, true);
|
|
6251
|
+
return null;
|
|
6252
|
+
}
|
|
6253
|
+
const refusal = replaceRefusal(existing, stats, prepared.destinationDevice, guard);
|
|
6254
|
+
if (refusal) {
|
|
6255
|
+
return refusal;
|
|
6256
|
+
}
|
|
6257
|
+
const suffix = dependencies.hiddenNameSuffix();
|
|
6258
|
+
const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(targetName, HIDDEN_COPY_MARK, suffix));
|
|
6259
|
+
try {
|
|
6260
|
+
await copyEntry(source, stats, hiddenCopy, walk, true);
|
|
6261
|
+
} catch (err) {
|
|
6262
|
+
if (!(err instanceof TakenError)) {
|
|
6263
|
+
await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
|
|
6264
|
+
}
|
|
6265
|
+
throw err;
|
|
6266
|
+
}
|
|
6267
|
+
let oldName;
|
|
6268
|
+
try {
|
|
6269
|
+
oldName = await swapIn(
|
|
6270
|
+
hiddenCopy,
|
|
6271
|
+
prepared.destinationDirectory,
|
|
6272
|
+
targetName,
|
|
6273
|
+
existing,
|
|
6274
|
+
stats.isDirectory(),
|
|
6275
|
+
suffix,
|
|
6276
|
+
copier,
|
|
6277
|
+
paths
|
|
6278
|
+
);
|
|
6279
|
+
} catch (err) {
|
|
6280
|
+
await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
|
|
6281
|
+
throw err;
|
|
6282
|
+
}
|
|
6283
|
+
if (oldName === null) {
|
|
6284
|
+
return null;
|
|
6285
|
+
}
|
|
6286
|
+
return removeOld(
|
|
6287
|
+
paths.join(prepared.destinationDirectory, oldName),
|
|
6288
|
+
oldName,
|
|
6289
|
+
existing,
|
|
6290
|
+
guard.protectedSet,
|
|
6291
|
+
dependencies,
|
|
6292
|
+
MESSAGE_COPY_IN_PLACE
|
|
6293
|
+
);
|
|
6294
|
+
}
|
|
6295
|
+
async function swapIn(incoming, folder, targetName, existing, incomingIsFolder, suffix, copier, paths) {
|
|
6296
|
+
const target = paths.join(folder, targetName);
|
|
6297
|
+
if (!existing.isDirectory() && !incomingIsFolder) {
|
|
6298
|
+
await copier.rename(incoming, target);
|
|
6299
|
+
return null;
|
|
6300
|
+
}
|
|
6301
|
+
const oldName = hiddenName(targetName, HIDDEN_OLD_MARK, suffix);
|
|
6302
|
+
const hiddenOld = paths.join(folder, oldName);
|
|
6303
|
+
await copier.rename(target, hiddenOld);
|
|
6304
|
+
try {
|
|
6305
|
+
await copier.rename(incoming, target);
|
|
6306
|
+
} catch (err) {
|
|
6307
|
+
await copier.rename(hiddenOld, target).catch(() => void 0);
|
|
6308
|
+
throw err;
|
|
6309
|
+
}
|
|
6310
|
+
return oldName;
|
|
6311
|
+
}
|
|
6312
|
+
function replaceRefusal(existing, source, destinationDevice, guard) {
|
|
6313
|
+
if (identityOf(existing) === identityOf(source)) {
|
|
6314
|
+
return { code: ERROR_INVALID_DESTINATION, message: MESSAGE_REPLACE_ITSELF };
|
|
6315
|
+
}
|
|
6316
|
+
return protectedRefusal(existing, destinationDevice, guard, MESSAGE_REPLACE_MOUNT);
|
|
6317
|
+
}
|
|
6318
|
+
function protectedRefusal(stats, folderDevice, guard, mountMessage) {
|
|
6319
|
+
if (guard.insideConfigFolder) {
|
|
6320
|
+
return { code: ERROR_PROTECTED_PATH, message: MESSAGE_PINGGY_FOLDER };
|
|
6321
|
+
}
|
|
6322
|
+
if (guard.inAccountsFolder) {
|
|
6323
|
+
return { code: ERROR_PROTECTED_PATH, message: MESSAGE_ACCOUNT_FOLDER };
|
|
6324
|
+
}
|
|
6325
|
+
const reason = guard.protectedSet.reasons.get(identityOf(stats));
|
|
6326
|
+
if (reason) {
|
|
6327
|
+
return { code: ERROR_PROTECTED_PATH, message: reason };
|
|
6328
|
+
}
|
|
6329
|
+
if (stats.dev !== folderDevice) {
|
|
6330
|
+
return { code: ERROR_MOUNT_POINT, message: mountMessage };
|
|
6331
|
+
}
|
|
6332
|
+
return null;
|
|
6333
|
+
}
|
|
6334
|
+
async function removeOld(hiddenOld, oldName, existing, protectedSet, dependencies, inPlaceMessage) {
|
|
6335
|
+
try {
|
|
6336
|
+
if (await removeTree(hiddenOld, existing, protectedSet, deleteDependencies(dependencies))) {
|
|
6337
|
+
return null;
|
|
6338
|
+
}
|
|
6339
|
+
return { code: ERROR_MOUNT_POINT, message: `${inPlaceMessage} ${oldName}: ${REASON_MOUNT_INSIDE}` };
|
|
6340
|
+
} catch (err) {
|
|
6341
|
+
const failure2 = deleteFailure(err);
|
|
6342
|
+
const message = sanitizeErrorMessage(`${inPlaceMessage} ${oldName}: ${failure2.message}`) ?? failure2.message;
|
|
6343
|
+
return { code: failure2.code, message };
|
|
6344
|
+
}
|
|
6345
|
+
}
|
|
6346
|
+
async function removeQuietly2(entry, protectedSet, dependencies) {
|
|
6347
|
+
try {
|
|
6348
|
+
const stats = await dependencies.remover.lstat(entry);
|
|
6349
|
+
await removeTree(entry, stats, protectedSet, deleteDependencies(dependencies));
|
|
6350
|
+
} catch {
|
|
6351
|
+
}
|
|
6352
|
+
}
|
|
6353
|
+
function deleteDependencies(dependencies) {
|
|
6354
|
+
const { remover, platform: platform3, protectedSources, callTimeoutMillis } = dependencies;
|
|
6355
|
+
return { remover, platform: platform3, protectedSources, callTimeoutMillis };
|
|
6356
|
+
}
|
|
6357
|
+
async function copyEntry(source, stats, target, walk, top) {
|
|
6358
|
+
if (stats.isSymbolicLink()) {
|
|
6359
|
+
await copyLink(source, target, walk, top);
|
|
6360
|
+
} else if (stats.isDirectory()) {
|
|
6361
|
+
await copyFolder(source, stats, target, walk, top);
|
|
6362
|
+
} else if (stats.isFile()) {
|
|
6363
|
+
await copyFile(source, stats, target, walk, top);
|
|
6364
|
+
} else {
|
|
6365
|
+
walk.specialFilesLeftOut += 1;
|
|
6366
|
+
}
|
|
6367
|
+
}
|
|
6368
|
+
async function copyFile(source, stats, target, walk, top) {
|
|
6369
|
+
const { copier, progress } = walk;
|
|
6370
|
+
const reader = await copier.openToRead(source);
|
|
6371
|
+
let writer;
|
|
6372
|
+
try {
|
|
6373
|
+
writer = await created(copier.createFile(target), top);
|
|
6374
|
+
} catch (err) {
|
|
6375
|
+
await closeQuietly(reader, copier);
|
|
6376
|
+
throw err;
|
|
6377
|
+
}
|
|
6378
|
+
const buffer = Buffer.allocUnsafe(Math.min(COPY_PIECE_BYTES, Math.max(SMALL_PIECE_BYTES, Number(stats.size) + 1)));
|
|
6379
|
+
try {
|
|
6380
|
+
for (; ; ) {
|
|
6381
|
+
const bytesRead = await copier.read(reader, buffer);
|
|
6382
|
+
if (bytesRead === 0) {
|
|
6383
|
+
break;
|
|
6384
|
+
}
|
|
6385
|
+
await copier.write(writer, buffer, bytesRead);
|
|
6386
|
+
progress.bytes_done += bytesRead;
|
|
6387
|
+
}
|
|
6388
|
+
await copier.close(writer);
|
|
6389
|
+
} catch (err) {
|
|
6390
|
+
await closeQuietly(writer, copier);
|
|
6391
|
+
await copier.unlink(target).catch(() => void 0);
|
|
6392
|
+
throw err;
|
|
6393
|
+
} finally {
|
|
6394
|
+
await closeQuietly(reader, copier);
|
|
6395
|
+
}
|
|
6396
|
+
await keepModeAndTimes(target, stats, copier);
|
|
6397
|
+
progress.files_done += 1;
|
|
6398
|
+
}
|
|
6399
|
+
async function copyFolder(source, stats, target, walk, top) {
|
|
6400
|
+
const { copier, paths } = walk;
|
|
6401
|
+
await created(copier.mkdir(target), top);
|
|
6402
|
+
walk.progress.files_done += 1;
|
|
6403
|
+
for (const child of await copier.readdir(source)) {
|
|
6404
|
+
const childSource = paths.join(source, child);
|
|
6405
|
+
let childStats;
|
|
6406
|
+
try {
|
|
6407
|
+
childStats = await copier.lstat(childSource);
|
|
6408
|
+
} catch (err) {
|
|
6409
|
+
if (errorCodeOf(err) === "ENOENT") {
|
|
6410
|
+
continue;
|
|
6411
|
+
}
|
|
6412
|
+
throw err;
|
|
6413
|
+
}
|
|
6414
|
+
await copyEntry(childSource, childStats, paths.join(target, child), walk, false);
|
|
6415
|
+
}
|
|
6416
|
+
await keepModeAndTimes(target, stats, copier);
|
|
6417
|
+
}
|
|
6418
|
+
async function copyLink(source, target, walk, top) {
|
|
6419
|
+
const { copier } = walk;
|
|
6420
|
+
const linkText = await copier.readlink(source);
|
|
6421
|
+
const type = walk.platform === "win32" ? await linkTypeOf(source, copier) : LINK_TYPE_FILE;
|
|
6422
|
+
await created(copier.symlink(linkText, target, type), top);
|
|
6423
|
+
walk.progress.files_done += 1;
|
|
6424
|
+
}
|
|
6425
|
+
async function linkTypeOf(link, copier) {
|
|
6426
|
+
try {
|
|
6427
|
+
return (await copier.stat(link)).isDirectory() ? LINK_TYPE_FOLDER : LINK_TYPE_FILE;
|
|
6428
|
+
} catch (err) {
|
|
6429
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6430
|
+
throw err;
|
|
6431
|
+
}
|
|
6432
|
+
return LINK_TYPE_FILE;
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
async function keepModeAndTimes(target, stats, copier) {
|
|
6436
|
+
await copier.utimes(target, stats.atime, stats.mtime).catch(() => void 0);
|
|
6437
|
+
await copier.chmod(target, Number(stats.mode & PERMISSION_BITS)).catch(() => void 0);
|
|
6438
|
+
}
|
|
6439
|
+
async function created(making, top) {
|
|
6440
|
+
try {
|
|
6441
|
+
return await making;
|
|
6442
|
+
} catch (err) {
|
|
6443
|
+
if (top && errorCodeOf(err) === "EEXIST") {
|
|
6444
|
+
throw new TakenError(MESSAGE_NAME_TAKEN);
|
|
6445
|
+
}
|
|
6446
|
+
throw err;
|
|
6447
|
+
}
|
|
6448
|
+
}
|
|
6449
|
+
async function closeQuietly(handle, copier) {
|
|
6450
|
+
await copier.close(handle).catch(() => void 0);
|
|
6451
|
+
}
|
|
6452
|
+
function keepBothName(name, isFolder, number) {
|
|
6453
|
+
const suffix = ` (${number})`;
|
|
6454
|
+
const dot = isFolder ? -1 : name.lastIndexOf(EXTENSION_SEPARATOR2);
|
|
6455
|
+
let stem = dot > 0 ? name.slice(0, dot) : name;
|
|
6456
|
+
let extension = dot > 0 ? name.slice(dot) : "";
|
|
6457
|
+
if (Buffer.byteLength(suffix + extension, "utf8") >= MAX_NAME_BYTES) {
|
|
6458
|
+
stem = name;
|
|
6459
|
+
extension = "";
|
|
6460
|
+
}
|
|
6461
|
+
const room = MAX_NAME_BYTES - Buffer.byteLength(suffix + extension, "utf8");
|
|
6462
|
+
return `${cutToBytes(stem, room)}${suffix}${extension}`;
|
|
6463
|
+
}
|
|
6464
|
+
function hiddenName(targetName, mark, suffix) {
|
|
6465
|
+
const tail = `.pinggy-${mark}-${suffix}`;
|
|
6466
|
+
const room = MAX_NAME_BYTES - Buffer.byteLength(HIDDEN_NAME_PREFIX2 + tail, "utf8");
|
|
6467
|
+
return `${HIDDEN_NAME_PREFIX2}${cutToBytes(targetName, room)}${tail}`;
|
|
6468
|
+
}
|
|
6469
|
+
function cutToBytes(text, maxBytes) {
|
|
6470
|
+
let bytes = 0;
|
|
6471
|
+
let kept = "";
|
|
6472
|
+
for (const character of text) {
|
|
6473
|
+
const characterBytes = Buffer.byteLength(character, "utf8");
|
|
6474
|
+
if (bytes + characterBytes > maxBytes) {
|
|
6475
|
+
break;
|
|
6476
|
+
}
|
|
6477
|
+
kept += character;
|
|
6478
|
+
bytes += characterBytes;
|
|
6479
|
+
}
|
|
6480
|
+
return kept;
|
|
6481
|
+
}
|
|
6482
|
+
function formatBytes(bytes) {
|
|
6483
|
+
let value = Number(bytes);
|
|
6484
|
+
let unit = 0;
|
|
6485
|
+
while (value >= BYTES_PER_UNIT && unit < BYTE_UNITS.length - 1) {
|
|
6486
|
+
value /= BYTES_PER_UNIT;
|
|
6487
|
+
unit += 1;
|
|
6488
|
+
}
|
|
6489
|
+
if (unit > 0) {
|
|
6490
|
+
return `${value.toFixed(1)} ${BYTE_UNITS[unit]}`;
|
|
6491
|
+
}
|
|
6492
|
+
return value === 1 ? `1 ${BYTE_UNIT_SINGULAR}` : `${value} ${BYTE_UNITS[0]}`;
|
|
6493
|
+
}
|
|
6494
|
+
function isSpecial(stats) {
|
|
6495
|
+
return !stats.isFile() && !stats.isDirectory() && !stats.isSymbolicLink();
|
|
6496
|
+
}
|
|
6497
|
+
function specialFilesLeftOut(count) {
|
|
6498
|
+
const message = count === 1 ? "1 socket, pipe or device file inside was left out." : `${count} sockets, pipes or device files inside were left out.`;
|
|
6499
|
+
return { code: ERROR_SPECIAL_FILE, message };
|
|
6500
|
+
}
|
|
6501
|
+
async function lstatOrNull(target, copier) {
|
|
6502
|
+
try {
|
|
6503
|
+
return await copier.lstat(target);
|
|
6504
|
+
} catch (err) {
|
|
6505
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6506
|
+
throw err;
|
|
6507
|
+
}
|
|
6508
|
+
return null;
|
|
6509
|
+
}
|
|
6510
|
+
}
|
|
6511
|
+
async function identityOrNull2(read) {
|
|
6512
|
+
try {
|
|
6513
|
+
return identityOf(await read);
|
|
6514
|
+
} catch (err) {
|
|
6515
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6516
|
+
throw err;
|
|
6517
|
+
}
|
|
6518
|
+
return null;
|
|
6519
|
+
}
|
|
6520
|
+
}
|
|
6521
|
+
function copyFailure(err, fallbackMessage) {
|
|
6522
|
+
if (err instanceof TakenError) {
|
|
6523
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
6524
|
+
}
|
|
6525
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6526
|
+
return { code: ERROR_FILE_TIMEOUT, message: err.message };
|
|
6527
|
+
}
|
|
6528
|
+
const message = failureMessage(err, fallbackMessage);
|
|
6529
|
+
switch (errorCodeOf(err)) {
|
|
6530
|
+
case "ENOENT":
|
|
6531
|
+
case "ENOTDIR":
|
|
6532
|
+
return { code: ERROR_PATH_NOT_FOUND, message };
|
|
6533
|
+
case "EEXIST":
|
|
6534
|
+
return { code: ERROR_FILE_EXISTS, message };
|
|
6535
|
+
case "EACCES":
|
|
6536
|
+
case "EPERM":
|
|
6537
|
+
case "EROFS":
|
|
6538
|
+
return { code: ERROR_PERMISSION_DENIED, message };
|
|
6539
|
+
case "ENOSPC":
|
|
6540
|
+
case "EDQUOT":
|
|
6541
|
+
return { code: ERROR_NO_SPACE, message };
|
|
6542
|
+
default:
|
|
6543
|
+
return { code: ERROR_FILE_OPERATION_FAILED, message };
|
|
6544
|
+
}
|
|
6545
|
+
}
|
|
6546
|
+
|
|
6547
|
+
// src/devices/files/fileList.ts
|
|
6548
|
+
var ROOT_PROBE_TIMEOUT_MILLIS = 2e3;
|
|
6549
|
+
var WINDOWS_DRIVE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
6550
|
+
var POSIX_ROOT = "/";
|
|
6551
|
+
var WIDEST_NEXT_OFFSET = Number.MAX_SAFE_INTEGER;
|
|
6552
|
+
var NAME_COLLATOR = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
|
|
6553
|
+
var MESSAGE_LIST_FAILED = "The folder could not be read.";
|
|
6554
|
+
function folderReadFailure(err) {
|
|
6555
|
+
const message = failureMessage(err, MESSAGE_LIST_FAILED);
|
|
6556
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6557
|
+
return fileError(ERROR_FILE_TIMEOUT, message);
|
|
6558
|
+
}
|
|
6559
|
+
switch (errorCodeOf(err)) {
|
|
6560
|
+
case "ENOENT":
|
|
6561
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6562
|
+
case "ENOTDIR":
|
|
6563
|
+
return fileError(ERROR_NOT_A_DIRECTORY, message);
|
|
6564
|
+
case "EACCES":
|
|
6565
|
+
case "EPERM":
|
|
6566
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6567
|
+
default:
|
|
6568
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6569
|
+
}
|
|
6570
|
+
}
|
|
6571
|
+
function compareNames(left, right) {
|
|
6572
|
+
const byCollator = NAME_COLLATOR.compare(left, right);
|
|
6573
|
+
if (byCollator !== 0) return byCollator;
|
|
6574
|
+
if (left === right) return 0;
|
|
6575
|
+
return left < right ? -1 : 1;
|
|
6576
|
+
}
|
|
6577
|
+
async function readSortKeys(folder, dirents, dependencies, paths) {
|
|
6578
|
+
const keys = /* @__PURE__ */ new Map();
|
|
6579
|
+
await Promise.all(dirents.map(async (dirent) => {
|
|
6580
|
+
try {
|
|
6581
|
+
const stats = await dependencies.fs.lstat(paths.join(folder, dirent.name));
|
|
6582
|
+
keys.set(dirent.name, {
|
|
6583
|
+
sizeBytes: stats.isFile() ? stats.size : 0,
|
|
6584
|
+
modifiedMillis: stats.mtimeMs,
|
|
6585
|
+
createdMillis: stats.birthtimeMs
|
|
6586
|
+
});
|
|
6587
|
+
} catch {
|
|
6588
|
+
keys.set(dirent.name, { sizeBytes: 0, modifiedMillis: 0, createdMillis: 0 });
|
|
6589
|
+
}
|
|
6590
|
+
}));
|
|
6591
|
+
return keys;
|
|
6592
|
+
}
|
|
6593
|
+
function sortDirents(dirents, sortBy, descending, keys) {
|
|
6594
|
+
const direction = descending ? -1 : 1;
|
|
6595
|
+
return [...dirents].sort((left, right) => {
|
|
6596
|
+
const leftIsFolder = left.isDirectory();
|
|
6597
|
+
if (leftIsFolder !== right.isDirectory()) {
|
|
6598
|
+
return leftIsFolder ? -1 : 1;
|
|
6599
|
+
}
|
|
6600
|
+
let order = 0;
|
|
6601
|
+
if (keys && sortBy === SORT_BY_SIZE && !leftIsFolder) {
|
|
6602
|
+
order = keys.get(left.name).sizeBytes - keys.get(right.name).sizeBytes;
|
|
6603
|
+
} else if (keys && sortBy === SORT_BY_MODIFIED) {
|
|
6604
|
+
order = keys.get(left.name).modifiedMillis - keys.get(right.name).modifiedMillis;
|
|
6605
|
+
} else if (keys && sortBy === SORT_BY_CREATED) {
|
|
6606
|
+
order = keys.get(left.name).createdMillis - keys.get(right.name).createdMillis;
|
|
6607
|
+
}
|
|
6608
|
+
if (order === 0) {
|
|
6609
|
+
order = compareNames(left.name, right.name);
|
|
6610
|
+
}
|
|
6611
|
+
return order * direction;
|
|
6612
|
+
});
|
|
6613
|
+
}
|
|
6614
|
+
async function describeEntry(folder, dirent, dependencies, paths) {
|
|
6615
|
+
const fullPath = paths.join(folder, dirent.name);
|
|
6616
|
+
let stats;
|
|
6617
|
+
try {
|
|
6618
|
+
stats = await dependencies.fs.lstat(fullPath);
|
|
6619
|
+
} catch {
|
|
6620
|
+
return { name: dirent.name, type: "unknown" };
|
|
6621
|
+
}
|
|
6622
|
+
const type = entryTypeOf(stats);
|
|
6623
|
+
const entry = { name: dirent.name, type, modified_at: epochSeconds(stats.mtimeMs) };
|
|
6624
|
+
if (stats.birthtimeMs > 0) {
|
|
6625
|
+
entry.created_at = epochSeconds(stats.birthtimeMs);
|
|
6626
|
+
}
|
|
6627
|
+
if (type === "file") {
|
|
6628
|
+
entry.size_bytes = stats.size;
|
|
6629
|
+
}
|
|
6630
|
+
if (dirent.name.startsWith(HIDDEN_NAME_PREFIX)) {
|
|
6631
|
+
entry.hidden = true;
|
|
6632
|
+
}
|
|
6633
|
+
if (type === "symlink") {
|
|
6634
|
+
const { linkTarget, targetType } = await readLinkTarget(fullPath, dependencies.fs);
|
|
6635
|
+
if (linkTarget !== void 0) {
|
|
6636
|
+
entry.link_target = linkTarget;
|
|
6637
|
+
}
|
|
6638
|
+
if (targetType !== void 0) {
|
|
6639
|
+
entry.target_type = targetType;
|
|
6640
|
+
}
|
|
6641
|
+
}
|
|
6642
|
+
return entry;
|
|
6643
|
+
}
|
|
6644
|
+
async function listRoots(dependencies) {
|
|
6645
|
+
if (dependencies.platform !== "win32") {
|
|
6646
|
+
return [POSIX_ROOT];
|
|
6647
|
+
}
|
|
6648
|
+
const drives = [...WINDOWS_DRIVE_LETTERS].map((letter) => `${letter}:\\`);
|
|
6649
|
+
const answers = await Promise.all(drives.map((drive) => withTimeout(
|
|
6650
|
+
dependencies.fs.access(drive).then(() => true),
|
|
6651
|
+
ROOT_PROBE_TIMEOUT_MILLIS,
|
|
6652
|
+
false
|
|
6653
|
+
)));
|
|
6654
|
+
return drives.filter((_drive, index) => answers[index]);
|
|
6655
|
+
}
|
|
6656
|
+
async function listFolder(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
|
|
6657
|
+
try {
|
|
6658
|
+
return await listFolderOrThrow(request2, maxPayloadBytes, dependencies);
|
|
6659
|
+
} catch (err) {
|
|
6660
|
+
return folderReadFailure(err);
|
|
6661
|
+
}
|
|
6662
|
+
}
|
|
6663
|
+
async function listFolderOrThrow(request2, maxPayloadBytes, dependencies) {
|
|
6664
|
+
const paths = pathsFor(dependencies.platform);
|
|
6665
|
+
const firstOpen = request2.path === void 0;
|
|
6666
|
+
let folder;
|
|
6667
|
+
if (request2.path === void 0) {
|
|
6668
|
+
folder = paths.resolve(dependencies.fs.homedir());
|
|
6669
|
+
} else {
|
|
6670
|
+
const problem = pathProblem(request2.path, paths);
|
|
6671
|
+
if (problem) {
|
|
6672
|
+
return fileError(ERROR_INVALID_PATH, problem);
|
|
6673
|
+
}
|
|
6674
|
+
folder = paths.resolve(request2.path);
|
|
6675
|
+
}
|
|
6676
|
+
let dirents;
|
|
6677
|
+
try {
|
|
6678
|
+
dirents = await dependencies.fs.readdir(folder);
|
|
6679
|
+
} catch (err) {
|
|
6680
|
+
return folderReadFailure(err);
|
|
6681
|
+
}
|
|
6682
|
+
const visible = request2.include_hidden ? dirents : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX));
|
|
6683
|
+
const sortBy = request2.sort_by ?? SORT_BY_NAME;
|
|
6684
|
+
const keys = sortBy === SORT_BY_NAME ? null : await readSortKeys(folder, visible, dependencies, paths);
|
|
6685
|
+
const sorted = sortDirents(visible, sortBy, request2.sort_order === SORT_ORDER_DESC, keys);
|
|
6686
|
+
const offset = request2.offset ?? 0;
|
|
6687
|
+
const limit = request2.limit ?? DEFAULT_LIST_LIMIT;
|
|
6688
|
+
const page = sorted.slice(offset, offset + limit);
|
|
6689
|
+
const described = await Promise.all(page.map((dirent) => describeEntry(folder, dirent, dependencies, paths)));
|
|
6690
|
+
const parent = paths.dirname(folder);
|
|
6691
|
+
const answer = {
|
|
6692
|
+
path: folder,
|
|
6693
|
+
...parent !== folder ? { parent } : {},
|
|
6694
|
+
separator: paths.sep,
|
|
6695
|
+
total: visible.length,
|
|
6696
|
+
offset,
|
|
6697
|
+
entries: []
|
|
6698
|
+
};
|
|
6699
|
+
if (firstOpen) {
|
|
6700
|
+
answer.home = folder;
|
|
6701
|
+
answer.roots = await listRoots(dependencies);
|
|
6702
|
+
}
|
|
6703
|
+
let payloadBytes = utf8Bytes({ ...answer, next_offset: WIDEST_NEXT_OFFSET });
|
|
6704
|
+
for (const entry of described) {
|
|
6705
|
+
const entryBytes = utf8Bytes(entry) + (answer.entries.length > 0 ? 1 : 0);
|
|
6706
|
+
if (payloadBytes + entryBytes > maxPayloadBytes) {
|
|
6707
|
+
break;
|
|
6708
|
+
}
|
|
6709
|
+
answer.entries.push(entry);
|
|
6710
|
+
payloadBytes += entryBytes;
|
|
6711
|
+
}
|
|
6712
|
+
if (described.length > 0 && answer.entries.length === 0) {
|
|
6713
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, "The next entry does not fit in 1 frame.");
|
|
6714
|
+
}
|
|
6715
|
+
const nextOffset = offset + answer.entries.length;
|
|
6716
|
+
if (nextOffset < visible.length) {
|
|
6717
|
+
answer.next_offset = nextOffset;
|
|
6718
|
+
}
|
|
6719
|
+
return answer;
|
|
6720
|
+
}
|
|
6721
|
+
|
|
6722
|
+
// src/devices/files/fileMkdir.ts
|
|
6723
|
+
var MESSAGE_MKDIR_FAILED = "The folder could not be made.";
|
|
6724
|
+
async function makeFolder(request2, dependencies) {
|
|
6725
|
+
const { maker, platform: platform3, callTimeoutMillis } = dependencies;
|
|
6726
|
+
const paths = pathsFor(platform3);
|
|
6727
|
+
const pathIssue = pathProblem(request2.path, paths);
|
|
6728
|
+
if (pathIssue) {
|
|
6729
|
+
return fileError(ERROR_INVALID_PATH, pathIssue);
|
|
6730
|
+
}
|
|
6731
|
+
const item = withTrimmedName(resolvedItem(request2.path, paths));
|
|
6732
|
+
if (!isRoot(item.path, paths)) {
|
|
6733
|
+
const nameIssue = nameProblem(item.name, platform3);
|
|
6734
|
+
if (nameIssue) {
|
|
6735
|
+
return fileError(ERROR_INVALID_PAYLOAD2, nameIssue);
|
|
6736
|
+
}
|
|
6737
|
+
const windowsIssue = platform3 === "win32" ? windowsNameProblem(item.name) : null;
|
|
6738
|
+
if (windowsIssue) {
|
|
6739
|
+
return fileError(ERROR_INVALID_NAME, windowsIssue);
|
|
6740
|
+
}
|
|
6741
|
+
}
|
|
6742
|
+
try {
|
|
6743
|
+
await callWithTimeout(maker.mkdir(item.path), callTimeoutMillis);
|
|
6744
|
+
} catch (err) {
|
|
6745
|
+
return mkdirFailure(err);
|
|
6746
|
+
}
|
|
6747
|
+
return { path: item.path };
|
|
6748
|
+
}
|
|
6749
|
+
function mkdirFailure(err) {
|
|
6750
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6751
|
+
return fileError(ERROR_FILE_TIMEOUT, err.message);
|
|
6752
|
+
}
|
|
6753
|
+
const message = failureMessage(err, MESSAGE_MKDIR_FAILED);
|
|
6754
|
+
switch (errorCodeOf(err)) {
|
|
6755
|
+
case "EEXIST":
|
|
6756
|
+
return fileError(ERROR_FILE_EXISTS, MESSAGE_NAME_TAKEN);
|
|
6757
|
+
case "ENOENT":
|
|
6758
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6759
|
+
case "ENOTDIR":
|
|
6760
|
+
return fileError(ERROR_NOT_A_DIRECTORY, message);
|
|
6761
|
+
case "EACCES":
|
|
6762
|
+
case "EPERM":
|
|
6763
|
+
case "EROFS":
|
|
6764
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6765
|
+
default:
|
|
6766
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6767
|
+
}
|
|
6768
|
+
}
|
|
6769
|
+
|
|
6770
|
+
// src/devices/files/fileMove.ts
|
|
6771
|
+
var HIDDEN_MOVE_MARK = "move";
|
|
6772
|
+
var MESSAGE_INTO_ITSELF2 = "A folder cannot be moved into itself.";
|
|
6773
|
+
var MESSAGE_ALREADY_HERE = "The item is already in this folder.";
|
|
6774
|
+
var MESSAGE_SELECTED_MOUNT2 = "This folder is a mounted disk. Open it to move what is inside.";
|
|
6775
|
+
var MESSAGE_MOUNT_INSIDE2 = "Another disk is mounted inside. Pinggy does not move it to another disk.";
|
|
6776
|
+
var MESSAGE_SPECIAL_SELECTED2 = "This is a socket, pipe or device file. Pinggy cannot move it to another disk.";
|
|
6777
|
+
var MESSAGE_MOVED_IN_PLACE = "The item is in place. The old one stays as";
|
|
6778
|
+
var MESSAGE_ORIGINAL_STAYS = "The item is in its new place. The original could not be fully removed:";
|
|
6779
|
+
var MESSAGE_MOVE_FAILED = "The item could not be moved.";
|
|
6780
|
+
var PLACED = { placed: true, oldStays: null };
|
|
6781
|
+
async function prepareMove(request2, dependencies) {
|
|
6782
|
+
try {
|
|
6783
|
+
return await checkedMove(request2, dependencies);
|
|
6784
|
+
} catch (err) {
|
|
6785
|
+
return refusalOf(err);
|
|
6786
|
+
}
|
|
6787
|
+
}
|
|
6788
|
+
async function checkedMove(request2, dependencies) {
|
|
6789
|
+
const { copier, platform: platform3 } = dependencies;
|
|
6790
|
+
const paths = pathsFor(platform3);
|
|
6791
|
+
const { source, destination } = resolvedItems(request2, paths);
|
|
6792
|
+
checkTargetName(destination.name, platform3);
|
|
6793
|
+
const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_MOVE_FAILED);
|
|
6794
|
+
const sourceFolderStats = await folderStats(source.parent, copier);
|
|
6795
|
+
const destinationStats = await folderStats(destination.parent, copier);
|
|
6796
|
+
const sameFolder = identityOf(sourceFolderStats) === identityOf(destinationStats);
|
|
6797
|
+
await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF2);
|
|
6798
|
+
if (sameFolder && destination.name === source.name) {
|
|
6799
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_ALREADY_HERE));
|
|
6800
|
+
}
|
|
6801
|
+
const protectedSet = await readProtectedFolders(dependencies);
|
|
6802
|
+
const sourceGuard = await removalGuard(source.parent, sourceFolderStats, protectedSet, dependencies);
|
|
6803
|
+
const sourceRefusal = protectedRefusal(sourceStats, sourceFolderStats.dev, sourceGuard, MESSAGE_SELECTED_MOUNT2);
|
|
6804
|
+
if (sourceRefusal) {
|
|
6805
|
+
throw new RequestRefusal({ error: sourceRefusal });
|
|
6806
|
+
}
|
|
6807
|
+
const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
|
|
6808
|
+
if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
|
|
6809
|
+
await checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies);
|
|
6810
|
+
}
|
|
6811
|
+
const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(destination.parent, destinationStats, protectedSet, dependencies) : null;
|
|
6812
|
+
return {
|
|
6813
|
+
source: source.path,
|
|
6814
|
+
sourceStats,
|
|
6815
|
+
sourceName: source.name,
|
|
6816
|
+
destinationDirectory: destination.parent,
|
|
6817
|
+
targetName: destination.name,
|
|
6818
|
+
onConflict,
|
|
6819
|
+
destinationDevice: destinationStats.dev,
|
|
6820
|
+
sameFolder,
|
|
6821
|
+
acrossDisks: sourceFolderStats.dev !== destinationStats.dev,
|
|
6822
|
+
sourceGuard,
|
|
6823
|
+
replaceGuard
|
|
6824
|
+
};
|
|
6825
|
+
}
|
|
6826
|
+
async function checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies) {
|
|
6827
|
+
const target = await lstatOrNull(destination.path, dependencies.copier);
|
|
6828
|
+
if (target === null || isCaseOnlyRename(sameFolder, source.name, destination.name, sourceStats, target)) {
|
|
6829
|
+
return;
|
|
6830
|
+
}
|
|
6831
|
+
if (onConflict === ON_CONFLICT_REPLACE) {
|
|
6832
|
+
if (identityOf(target) === identityOf(sourceStats)) {
|
|
6833
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
|
|
6834
|
+
}
|
|
6835
|
+
await refuseReplacingAHolder(target, source.parent, dependencies);
|
|
6836
|
+
return;
|
|
6837
|
+
}
|
|
6838
|
+
throw new RequestRefusal(targetTakenRefusal());
|
|
6839
|
+
}
|
|
6840
|
+
function isCaseOnlyRename(sameFolder, name, targetName, source, target) {
|
|
6841
|
+
return sameFolder && source !== null && name !== targetName && foldedName(name) === foldedName(targetName) && identityOf(source) === identityOf(target);
|
|
6842
|
+
}
|
|
6843
|
+
function foldedName(name) {
|
|
6844
|
+
return name.normalize("NFC").toLowerCase();
|
|
6845
|
+
}
|
|
6846
|
+
function moveProgress(prepared) {
|
|
6847
|
+
const progress = {
|
|
6848
|
+
items_done: 0,
|
|
6849
|
+
items_total: 1,
|
|
6850
|
+
files_done: 0,
|
|
6851
|
+
bytes_done: 0,
|
|
6852
|
+
current_name: prepared.sourceName
|
|
6853
|
+
};
|
|
6854
|
+
if (!prepared.acrossDisks) {
|
|
6855
|
+
progress.files_total = 1;
|
|
6856
|
+
progress.bytes_total = 0;
|
|
6857
|
+
}
|
|
6858
|
+
return progress;
|
|
6859
|
+
}
|
|
6860
|
+
async function runMove(prepared, progress, dependencies) {
|
|
6861
|
+
const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
|
|
6862
|
+
const item = {
|
|
6863
|
+
name: prepared.sourceName,
|
|
6864
|
+
targetName: prepared.targetName,
|
|
6865
|
+
source: prepared.source,
|
|
6866
|
+
stats: prepared.sourceStats
|
|
6867
|
+
};
|
|
6868
|
+
if (prepared.acrossDisks) {
|
|
6869
|
+
const refusal = await countAcross(item, prepared, counted, dependencies);
|
|
6870
|
+
if (refusal) {
|
|
6871
|
+
return refusal;
|
|
6872
|
+
}
|
|
6873
|
+
}
|
|
6874
|
+
const outcome = await moveItem(item, prepared, counted, dependencies);
|
|
6875
|
+
counted.items_done += 1;
|
|
6876
|
+
return outcomeAnswer(outcome);
|
|
6877
|
+
}
|
|
6878
|
+
async function countAcross(item, prepared, progress, dependencies) {
|
|
6879
|
+
const paths = pathsFor(dependencies.platform);
|
|
6880
|
+
const target = paths.join(prepared.destinationDirectory, item.targetName);
|
|
6881
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, dependencies.copier).catch(() => null)) {
|
|
6882
|
+
progress.files_total = 0;
|
|
6883
|
+
progress.bytes_total = 0;
|
|
6884
|
+
return null;
|
|
6885
|
+
}
|
|
6886
|
+
const totals = await countItem(item, dependencies);
|
|
6887
|
+
const refusal = countRefusal(totals, item.stats);
|
|
6888
|
+
if (refusal) {
|
|
6889
|
+
return { error: refusal };
|
|
6890
|
+
}
|
|
6891
|
+
progress.files_total = totals.files;
|
|
6892
|
+
progress.bytes_total = totals.bytes;
|
|
6893
|
+
return noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
|
|
6894
|
+
}
|
|
6895
|
+
async function countItem(item, dependencies) {
|
|
6896
|
+
const totals = newCountTotals();
|
|
6897
|
+
await countEntry(item.source, totals, dependencies.copier, pathsFor(dependencies.platform), item.stats.dev);
|
|
6898
|
+
return totals;
|
|
6899
|
+
}
|
|
6900
|
+
function countRefusal(totals, stats) {
|
|
6901
|
+
if (totals.mountedDisks > 0) {
|
|
6902
|
+
return { code: ERROR_MOUNT_POINT, message: MESSAGE_MOUNT_INSIDE2 };
|
|
6903
|
+
}
|
|
6904
|
+
if (isSpecial(stats)) {
|
|
6905
|
+
return { code: ERROR_SPECIAL_FILE, message: MESSAGE_SPECIAL_SELECTED2 };
|
|
6906
|
+
}
|
|
6907
|
+
return totals.specialFiles > 0 ? specialInside(totals.specialFiles) : null;
|
|
6908
|
+
}
|
|
6909
|
+
function specialInside(count) {
|
|
6910
|
+
const message = count === 1 ? "This folder holds 1 socket, pipe or device file, which cannot be moved to another disk." : `This folder holds ${count} sockets, pipes or device files, which cannot be moved to another disk.`;
|
|
6911
|
+
return { code: ERROR_SPECIAL_FILE, message };
|
|
6912
|
+
}
|
|
6913
|
+
async function moveItem(item, prepared, progress, dependencies) {
|
|
6914
|
+
if (prepared.acrossDisks) {
|
|
6915
|
+
return moveAcross(item, prepared, progress, dependencies);
|
|
6916
|
+
}
|
|
6917
|
+
try {
|
|
6918
|
+
const placement = await placeAt(item.source, item, prepared, dependencies, dependencies.hiddenNameSuffix());
|
|
6919
|
+
if (!placement.placed) {
|
|
6920
|
+
return placement.outcome;
|
|
6921
|
+
}
|
|
6922
|
+
progress.files_done += 1;
|
|
6923
|
+
return placement.oldStays;
|
|
6924
|
+
} catch (err) {
|
|
6925
|
+
if (errorCodeOf(err) !== "EXDEV") {
|
|
6926
|
+
return moveFailure(err);
|
|
6927
|
+
}
|
|
6928
|
+
}
|
|
6929
|
+
const totals = await countItem(item, dependencies);
|
|
6930
|
+
const refusal = countRefusal(totals, item.stats);
|
|
6931
|
+
if (refusal) {
|
|
6932
|
+
return refusal;
|
|
6933
|
+
}
|
|
6934
|
+
progress.files_total = (progress.files_total ?? 0) + totals.files - 1;
|
|
6935
|
+
progress.bytes_total = (progress.bytes_total ?? 0) + totals.bytes;
|
|
6936
|
+
return moveAcross(item, prepared, progress, dependencies);
|
|
6937
|
+
}
|
|
6938
|
+
async function moveAcross(item, prepared, progress, dependencies) {
|
|
6939
|
+
const { copier, platform: platform3 } = dependencies;
|
|
6940
|
+
const paths = pathsFor(platform3);
|
|
6941
|
+
const { protectedSet } = prepared.sourceGuard;
|
|
6942
|
+
try {
|
|
6943
|
+
const settledFirst = await targetBeforeCopy(item, prepared, dependencies);
|
|
6944
|
+
if (settledFirst) {
|
|
6945
|
+
return settledFirst;
|
|
6946
|
+
}
|
|
6947
|
+
} catch (err) {
|
|
6948
|
+
return moveFailure(err);
|
|
6949
|
+
}
|
|
6950
|
+
const suffix = dependencies.hiddenNameSuffix();
|
|
6951
|
+
const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(item.targetName, HIDDEN_MOVE_MARK, suffix));
|
|
6952
|
+
const walk = { copier, paths, platform: platform3, progress, specialFilesLeftOut: 0 };
|
|
6953
|
+
let placement;
|
|
6954
|
+
try {
|
|
6955
|
+
await copyEntry(item.source, item.stats, hiddenCopy, walk, true);
|
|
6956
|
+
if (walk.specialFilesLeftOut > 0) {
|
|
6957
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6958
|
+
return specialInside(walk.specialFilesLeftOut);
|
|
6959
|
+
}
|
|
6960
|
+
placement = await placeAt(hiddenCopy, item, prepared, dependencies, suffix);
|
|
6961
|
+
} catch (err) {
|
|
6962
|
+
if (!(err instanceof TakenError)) {
|
|
6963
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6964
|
+
}
|
|
6965
|
+
return moveFailure(err);
|
|
6966
|
+
}
|
|
6967
|
+
if (!placement.placed) {
|
|
6968
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6969
|
+
return placement.outcome;
|
|
6970
|
+
}
|
|
6971
|
+
return await removeOriginal(item, protectedSet, dependencies) ?? placement.oldStays;
|
|
6972
|
+
}
|
|
6973
|
+
async function targetBeforeCopy(item, prepared, dependencies) {
|
|
6974
|
+
if (prepared.onConflict === ON_CONFLICT_KEEP_BOTH) {
|
|
6975
|
+
return null;
|
|
6976
|
+
}
|
|
6977
|
+
const paths = pathsFor(dependencies.platform);
|
|
6978
|
+
const existing = await lstatOrNull(
|
|
6979
|
+
paths.join(prepared.destinationDirectory, item.targetName),
|
|
6980
|
+
dependencies.copier
|
|
6981
|
+
);
|
|
6982
|
+
if (existing === null) {
|
|
6983
|
+
return null;
|
|
6984
|
+
}
|
|
6985
|
+
switch (prepared.onConflict) {
|
|
6986
|
+
case ON_CONFLICT_SKIP:
|
|
6987
|
+
return SKIPPED;
|
|
6988
|
+
case ON_CONFLICT_REPLACE:
|
|
6989
|
+
return replaceRefusal(existing, item.stats, prepared.destinationDevice, prepared.replaceGuard);
|
|
6990
|
+
default:
|
|
6991
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
6992
|
+
}
|
|
6993
|
+
}
|
|
6994
|
+
async function placeAt(incoming, item, prepared, dependencies, suffix) {
|
|
6995
|
+
const { copier } = dependencies;
|
|
6996
|
+
const paths = pathsFor(dependencies.platform);
|
|
6997
|
+
const target = paths.join(prepared.destinationDirectory, item.targetName);
|
|
6998
|
+
const existing = await lstatOrNull(target, copier);
|
|
6999
|
+
if (existing === null || isCaseOnlyRename(prepared.sameFolder, item.name, item.targetName, item.stats, existing)) {
|
|
7000
|
+
await copier.rename(incoming, target);
|
|
7001
|
+
return PLACED;
|
|
7002
|
+
}
|
|
7003
|
+
switch (prepared.onConflict) {
|
|
7004
|
+
case ON_CONFLICT_SKIP:
|
|
7005
|
+
return { placed: false, outcome: SKIPPED };
|
|
7006
|
+
case ON_CONFLICT_KEEP_BOTH:
|
|
7007
|
+
return placeUnderFreeName(incoming, item, prepared, dependencies);
|
|
7008
|
+
case ON_CONFLICT_REPLACE:
|
|
7009
|
+
return replaceAt(incoming, existing, item, prepared, dependencies, suffix);
|
|
7010
|
+
default:
|
|
7011
|
+
return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
|
|
7012
|
+
}
|
|
7013
|
+
}
|
|
7014
|
+
async function placeUnderFreeName(incoming, item, prepared, dependencies) {
|
|
7015
|
+
const paths = pathsFor(dependencies.platform);
|
|
7016
|
+
for (let number = 1; number <= MAX_KEEP_BOTH_NUMBER; number++) {
|
|
7017
|
+
const candidate = paths.join(
|
|
7018
|
+
prepared.destinationDirectory,
|
|
7019
|
+
keepBothName(item.targetName, item.stats.isDirectory(), number)
|
|
7020
|
+
);
|
|
7021
|
+
if (await lstatOrNull(candidate, dependencies.copier) === null) {
|
|
7022
|
+
await dependencies.copier.rename(incoming, candidate);
|
|
7023
|
+
return PLACED;
|
|
7024
|
+
}
|
|
7025
|
+
}
|
|
7026
|
+
return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
|
|
7027
|
+
}
|
|
7028
|
+
async function replaceAt(incoming, existing, item, prepared, dependencies, suffix) {
|
|
7029
|
+
const guard = prepared.replaceGuard;
|
|
7030
|
+
const refusal = replaceRefusal(existing, item.stats, prepared.destinationDevice, guard);
|
|
7031
|
+
if (refusal) {
|
|
7032
|
+
return { placed: false, outcome: refusal };
|
|
7033
|
+
}
|
|
7034
|
+
const paths = pathsFor(dependencies.platform);
|
|
7035
|
+
const oldName = await swapIn(
|
|
7036
|
+
incoming,
|
|
7037
|
+
prepared.destinationDirectory,
|
|
7038
|
+
item.targetName,
|
|
7039
|
+
existing,
|
|
7040
|
+
item.stats.isDirectory(),
|
|
7041
|
+
suffix,
|
|
7042
|
+
dependencies.copier,
|
|
7043
|
+
paths
|
|
7044
|
+
);
|
|
7045
|
+
if (oldName === null) {
|
|
7046
|
+
return PLACED;
|
|
7047
|
+
}
|
|
7048
|
+
const oldStays = await removeOld(
|
|
7049
|
+
paths.join(prepared.destinationDirectory, oldName),
|
|
7050
|
+
oldName,
|
|
7051
|
+
existing,
|
|
7052
|
+
guard.protectedSet,
|
|
7053
|
+
dependencies,
|
|
7054
|
+
MESSAGE_MOVED_IN_PLACE
|
|
7055
|
+
);
|
|
7056
|
+
return { placed: true, oldStays };
|
|
7057
|
+
}
|
|
7058
|
+
async function removeOriginal(item, protectedSet, dependencies) {
|
|
7059
|
+
try {
|
|
7060
|
+
if (await removeTree(item.source, item.stats, protectedSet, deleteDependencies(dependencies))) {
|
|
7061
|
+
return null;
|
|
7062
|
+
}
|
|
7063
|
+
return { code: ERROR_MOUNT_POINT, message: `${MESSAGE_ORIGINAL_STAYS} ${REASON_MOUNT_INSIDE}` };
|
|
7064
|
+
} catch (err) {
|
|
7065
|
+
const failure2 = deleteFailure(err);
|
|
7066
|
+
const message = sanitizeErrorMessage(`${MESSAGE_ORIGINAL_STAYS} ${failure2.message}`) ?? failure2.message;
|
|
7067
|
+
return { code: failure2.code, message };
|
|
7068
|
+
}
|
|
7069
|
+
}
|
|
7070
|
+
function moveFailure(err) {
|
|
7071
|
+
switch (errorCodeOf(err)) {
|
|
7072
|
+
case "EBUSY":
|
|
7073
|
+
return { code: ERROR_PERMISSION_DENIED, message: failureMessage(err, MESSAGE_MOVE_FAILED) };
|
|
7074
|
+
case "ENOTEMPTY":
|
|
7075
|
+
case "EISDIR":
|
|
7076
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
7077
|
+
default:
|
|
7078
|
+
return copyFailure(err, MESSAGE_MOVE_FAILED);
|
|
7079
|
+
}
|
|
7080
|
+
}
|
|
7081
|
+
|
|
7082
|
+
// src/devices/files/fileStat.ts
|
|
7083
|
+
import fs7 from "fs";
|
|
7084
|
+
var PERMISSION_BITS_MASK = 4095;
|
|
7085
|
+
var OCTAL_RADIX = 8;
|
|
7086
|
+
var MODE_DIGITS = 4;
|
|
7087
|
+
var MESSAGE_STAT_FAILED = "The path could not be read.";
|
|
7088
|
+
var MESSAGE_TOO_LARGE = "The details are too large to send.";
|
|
7089
|
+
function lstatFailure(err) {
|
|
7090
|
+
const message = failureMessage(err, MESSAGE_STAT_FAILED);
|
|
7091
|
+
if (err instanceof FileCallTimeoutError) {
|
|
7092
|
+
return fileError(ERROR_FILE_TIMEOUT, message);
|
|
7093
|
+
}
|
|
7094
|
+
switch (errorCodeOf(err)) {
|
|
7095
|
+
case "ENOENT":
|
|
7096
|
+
case "ENOTDIR":
|
|
7097
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
7098
|
+
case "EACCES":
|
|
7099
|
+
case "EPERM":
|
|
7100
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
7101
|
+
default:
|
|
7102
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
7103
|
+
}
|
|
7104
|
+
}
|
|
7105
|
+
function modeDigits(mode) {
|
|
7106
|
+
return (mode & PERMISSION_BITS_MASK).toString(OCTAL_RADIX).padStart(MODE_DIGITS, "0");
|
|
7107
|
+
}
|
|
7108
|
+
async function hasAccess(target, mode, dependencies) {
|
|
7109
|
+
try {
|
|
7110
|
+
await dependencies.fs.access(target, mode);
|
|
7111
|
+
return true;
|
|
7112
|
+
} catch {
|
|
7113
|
+
return false;
|
|
7114
|
+
}
|
|
7115
|
+
}
|
|
7116
|
+
async function countEntries(folder, includeHidden, dependencies) {
|
|
7117
|
+
try {
|
|
7118
|
+
const dirents = await dependencies.fs.readdir(folder);
|
|
7119
|
+
return includeHidden ? dirents.length : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX)).length;
|
|
7120
|
+
} catch {
|
|
7121
|
+
return void 0;
|
|
7122
|
+
}
|
|
7123
|
+
}
|
|
7124
|
+
async function statPath(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
|
|
7125
|
+
try {
|
|
7126
|
+
return await statPathOrThrow(request2, maxPayloadBytes, dependencies);
|
|
7127
|
+
} catch (err) {
|
|
7128
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, failureMessage(err, MESSAGE_STAT_FAILED));
|
|
7129
|
+
}
|
|
7130
|
+
}
|
|
7131
|
+
async function statPathOrThrow(request2, maxPayloadBytes, dependencies) {
|
|
7132
|
+
const paths = pathsFor(dependencies.platform);
|
|
7133
|
+
const problem = pathProblem(request2.path, paths);
|
|
7134
|
+
if (problem) {
|
|
7135
|
+
return fileError(ERROR_INVALID_PATH, problem);
|
|
7136
|
+
}
|
|
7137
|
+
const target = paths.resolve(request2.path);
|
|
7138
|
+
let stats;
|
|
7139
|
+
try {
|
|
7140
|
+
stats = await dependencies.fs.lstat(target);
|
|
7141
|
+
} catch (err) {
|
|
7142
|
+
return lstatFailure(err);
|
|
7143
|
+
}
|
|
7144
|
+
const type = entryTypeOf(stats);
|
|
7145
|
+
const name = paths.basename(target) || target;
|
|
7146
|
+
const onWindows = dependencies.platform === "win32";
|
|
7147
|
+
const answer = {
|
|
7148
|
+
path: target,
|
|
7149
|
+
name,
|
|
7150
|
+
type,
|
|
7151
|
+
...type === "file" ? { size_bytes: stats.size } : {},
|
|
7152
|
+
modified_at: epochSeconds(stats.mtimeMs),
|
|
7153
|
+
accessed_at: epochSeconds(stats.atimeMs),
|
|
7154
|
+
// 0 is a filesystem with no birth time. Some report the change time instead, which cannot be told apart.
|
|
7155
|
+
...stats.birthtimeMs > 0 ? { created_at: epochSeconds(stats.birthtimeMs) } : {},
|
|
7156
|
+
...name.startsWith(HIDDEN_NAME_PREFIX) ? { hidden: true } : {}
|
|
7157
|
+
};
|
|
7158
|
+
if (!onWindows) {
|
|
7159
|
+
answer.mode = modeDigits(stats.mode);
|
|
7160
|
+
answer.uid = stats.uid;
|
|
7161
|
+
answer.gid = stats.gid;
|
|
7162
|
+
}
|
|
7163
|
+
if (!onWindows && type !== "symlink") {
|
|
7164
|
+
const [readable, writable, executable] = await Promise.all([
|
|
7165
|
+
hasAccess(target, fs7.constants.R_OK, dependencies),
|
|
7166
|
+
hasAccess(target, fs7.constants.W_OK, dependencies),
|
|
7167
|
+
hasAccess(target, fs7.constants.X_OK, dependencies)
|
|
7168
|
+
]);
|
|
7169
|
+
Object.assign(answer, { readable, writable, executable });
|
|
7170
|
+
}
|
|
7171
|
+
if (type === "directory") {
|
|
7172
|
+
const entryCount = await countEntries(target, request2.include_hidden === true, dependencies);
|
|
7173
|
+
if (entryCount !== void 0) {
|
|
7174
|
+
answer.entry_count = entryCount;
|
|
7175
|
+
}
|
|
7176
|
+
}
|
|
7177
|
+
if (type === "symlink") {
|
|
7178
|
+
const { linkTarget, targetType, targetStats } = await readLinkTarget(target, dependencies.fs);
|
|
7179
|
+
if (linkTarget !== void 0) {
|
|
7180
|
+
answer.link_target = linkTarget;
|
|
7181
|
+
}
|
|
7182
|
+
if (targetType !== void 0) {
|
|
7183
|
+
answer.target_type = targetType;
|
|
7184
|
+
}
|
|
7185
|
+
if (targetStats?.isFile()) {
|
|
7186
|
+
answer.target_size_bytes = targetStats.size;
|
|
7187
|
+
}
|
|
7188
|
+
}
|
|
7189
|
+
if (utf8Bytes(answer) > maxPayloadBytes) {
|
|
7190
|
+
delete answer.link_target;
|
|
7191
|
+
}
|
|
7192
|
+
if (utf8Bytes(answer) > maxPayloadBytes) {
|
|
7193
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, MESSAGE_TOO_LARGE);
|
|
7194
|
+
}
|
|
7195
|
+
return answer;
|
|
7196
|
+
}
|
|
7197
|
+
|
|
7198
|
+
// src/devices/files/fileHandler.ts
|
|
7199
|
+
var DEFAULT_READ_TIMEOUT_MILLIS = 2e4;
|
|
7200
|
+
var DEFAULT_DELETE_CALL_TIMEOUT_MILLIS = 2e4;
|
|
7201
|
+
var DEFAULT_MKDIR_TIMEOUT_MILLIS = 2e4;
|
|
7202
|
+
var DEFAULT_COPY_CALL_TIMEOUT_MILLIS = 2e4;
|
|
7203
|
+
var DEFAULT_FILE_CALL_PLACES = 2;
|
|
7204
|
+
var MILLIS_PER_SECOND2 = 1e3;
|
|
7205
|
+
var PROGRESS_TICK_MILLIS = 1e3;
|
|
7206
|
+
var PROGRESS_KEEPALIVE_TICKS = 5;
|
|
7207
|
+
var QUEUED_KEEPALIVE_MILLIS = PROGRESS_TICK_MILLIS * PROGRESS_KEEPALIVE_TICKS;
|
|
7208
|
+
var NULL_PAYLOAD_BYTES = Buffer.byteLength("null", "utf8");
|
|
7209
|
+
var OUTCOME_ANSWERED = "answered";
|
|
7210
|
+
var FILE_ACCESS_OFF_MESSAGE = "File access is off on this device. To allow it, run on the device: pinggy device connect --files on";
|
|
7211
|
+
var HANDLED_OPS = /* @__PURE__ */ new Set([OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE]);
|
|
7212
|
+
var FileHandler = class {
|
|
7213
|
+
constructor(dependencies) {
|
|
7214
|
+
this.dependencies = dependencies;
|
|
7215
|
+
this.enabled = false;
|
|
7216
|
+
this.maxFrameBytes = 0;
|
|
7217
|
+
this.maxConcurrentOperations = 0;
|
|
7218
|
+
this.maxQueuedOperations = 0;
|
|
7219
|
+
this.runningOperations = 0;
|
|
7220
|
+
/** Oldest first. The first is the next to start. */
|
|
7221
|
+
this.waitingOperations = [];
|
|
7222
|
+
this.queuedKeepalive = null;
|
|
7223
|
+
const gate = new FileCallGate(dependencies.fileCallPlaces ?? DEFAULT_FILE_CALL_PLACES);
|
|
7224
|
+
const fileSystem = dependencies.fileSystem ?? machineFileSystemDependencies;
|
|
7225
|
+
this.gatedFileSystem = {
|
|
7226
|
+
platform: fileSystem.platform,
|
|
7227
|
+
fs: gatedReader(fileSystem.fs, gate, this.readTimeoutMillis())
|
|
7228
|
+
};
|
|
7229
|
+
this.gatedRemover = gatedRemover(
|
|
7230
|
+
dependencies.remover ?? machineFileSystemRemover,
|
|
7231
|
+
gate,
|
|
7232
|
+
this.deleteCallTimeoutMillis()
|
|
7233
|
+
);
|
|
7234
|
+
this.gatedMaker = gatedMaker(dependencies.maker ?? machineFileSystemMaker, gate, this.mkdirTimeoutMillis());
|
|
7235
|
+
this.gatedCopier = gatedCopier(
|
|
7236
|
+
dependencies.copier ?? machineFileSystemCopier,
|
|
7237
|
+
gate,
|
|
7238
|
+
this.copyCallTimeoutMillis()
|
|
7239
|
+
);
|
|
7240
|
+
}
|
|
7241
|
+
/**
|
|
7242
|
+
* From each `welcome`. `max_frame_bytes` is the dashboard's cap on 1 frame from this agent. Without
|
|
7243
|
+
* `file_max_concurrent_operations`, no delete, copy or move runs, and without `file_max_queued_operations`, none
|
|
7244
|
+
* waits. Requests already waiting keep their place: more slots start them, and no slot at all refuses them with
|
|
7245
|
+
* `file_busy`, since none would ever start.
|
|
7246
|
+
*/
|
|
7247
|
+
configure(fileManagerEnabled, maxFrameBytes, maxConcurrentOperations, maxQueuedOperations) {
|
|
7248
|
+
this.enabled = fileManagerEnabled === true;
|
|
7249
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
7250
|
+
this.maxConcurrentOperations = maxConcurrentOperations ?? 0;
|
|
7251
|
+
this.maxQueuedOperations = maxQueuedOperations ?? 0;
|
|
7252
|
+
this.admitWaiting();
|
|
7253
|
+
}
|
|
7254
|
+
async handle(envelope) {
|
|
7255
|
+
if (envelope.kind !== "req") {
|
|
7256
|
+
return;
|
|
7257
|
+
}
|
|
7258
|
+
if (!HANDLED_OPS.has(envelope.op)) {
|
|
7259
|
+
this.answer(envelope, fileError(ERROR_UNSUPPORTED_OP2, `Unsupported operation: file/${envelope.op}`));
|
|
7260
|
+
return;
|
|
7261
|
+
}
|
|
7262
|
+
if (!this.enabled) {
|
|
7263
|
+
this.answer(envelope, fileError(ERROR_FILE_MANAGER_DISABLED, "The file manager is disabled."));
|
|
7264
|
+
return;
|
|
7265
|
+
}
|
|
7266
|
+
if (this.dependencies.fileAccessAllowed?.() === false) {
|
|
7267
|
+
this.answer(envelope, fileError(ERROR_FILE_ACCESS_OFF, FILE_ACCESS_OFF_MESSAGE));
|
|
7268
|
+
return;
|
|
7269
|
+
}
|
|
7270
|
+
this.answer(envelope, await this.run(envelope));
|
|
7271
|
+
}
|
|
7272
|
+
run(envelope) {
|
|
7273
|
+
switch (envelope.op) {
|
|
7274
|
+
case OP_LIST:
|
|
7275
|
+
return this.list(envelope);
|
|
7276
|
+
case OP_STAT:
|
|
7277
|
+
return this.stat(envelope);
|
|
7278
|
+
case OP_MKDIR:
|
|
7279
|
+
return this.mkdir(envelope);
|
|
7280
|
+
case OP_COPY:
|
|
7281
|
+
return this.copy(envelope);
|
|
7282
|
+
case OP_MOVE:
|
|
7283
|
+
return this.move(envelope);
|
|
7284
|
+
default:
|
|
7285
|
+
return this.delete(envelope);
|
|
7286
|
+
}
|
|
7287
|
+
}
|
|
7288
|
+
list(envelope) {
|
|
7289
|
+
const parsed = FileListRequestSchema.safeParse(envelope.payload);
|
|
7290
|
+
if (!parsed.success) {
|
|
7291
|
+
return Promise.resolve(invalidPayload());
|
|
7292
|
+
}
|
|
7293
|
+
const listing = afterThisTurn(() => listFolder(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
|
|
7294
|
+
return withTimeout(listing, this.readTimeoutMillis(), this.timedOut("The folder"));
|
|
7295
|
+
}
|
|
7296
|
+
stat(envelope) {
|
|
7297
|
+
const parsed = FileStatRequestSchema.safeParse(envelope.payload);
|
|
7298
|
+
if (!parsed.success) {
|
|
7299
|
+
return Promise.resolve(invalidPayload());
|
|
7300
|
+
}
|
|
7301
|
+
const details = afterThisTurn(() => statPath(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
|
|
7302
|
+
return withTimeout(details, this.readTimeoutMillis(), this.timedOut("The path"));
|
|
7303
|
+
}
|
|
7304
|
+
mkdir(envelope) {
|
|
7305
|
+
const parsed = FileMkdirRequestSchema.safeParse(envelope.payload);
|
|
7306
|
+
if (!parsed.success) {
|
|
7307
|
+
return Promise.resolve(invalidPayload());
|
|
7308
|
+
}
|
|
7309
|
+
return makeFolder(parsed.data, {
|
|
7310
|
+
maker: this.gatedMaker,
|
|
7311
|
+
platform: this.fileSystem().platform,
|
|
7312
|
+
callTimeoutMillis: this.mkdirTimeoutMillis()
|
|
7313
|
+
});
|
|
7314
|
+
}
|
|
7315
|
+
delete(envelope) {
|
|
7316
|
+
const parsed = FileDeleteRequestSchema.safeParse(envelope.payload);
|
|
7317
|
+
if (!parsed.success) {
|
|
7318
|
+
return Promise.resolve(invalidPayload());
|
|
7319
|
+
}
|
|
7320
|
+
return this.inSlot(envelope, "delete", () => this.deleteInSlot(envelope, parsed.data));
|
|
7321
|
+
}
|
|
7322
|
+
copy(envelope) {
|
|
7323
|
+
const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
|
|
7324
|
+
if (!parsed.success) {
|
|
7325
|
+
return Promise.resolve(invalidPayload());
|
|
7326
|
+
}
|
|
7327
|
+
return this.inSlot(envelope, "copy", () => this.copyInSlot(envelope, parsed.data));
|
|
7328
|
+
}
|
|
7329
|
+
move(envelope) {
|
|
7330
|
+
const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
|
|
7331
|
+
if (!parsed.success) {
|
|
7332
|
+
return Promise.resolve(invalidPayload());
|
|
7333
|
+
}
|
|
7334
|
+
return this.inSlot(envelope, "move", () => this.moveInSlot(envelope, parsed.data));
|
|
7335
|
+
}
|
|
7336
|
+
/** Holds 1 slot from {@link takeSlot} to the answer. */
|
|
7337
|
+
async inSlot(envelope, operation, work) {
|
|
7338
|
+
const refusal = await this.takeSlot(envelope);
|
|
7339
|
+
if (refusal) {
|
|
7340
|
+
return refusal;
|
|
7341
|
+
}
|
|
7342
|
+
try {
|
|
7343
|
+
return await work();
|
|
7344
|
+
} catch (err) {
|
|
7345
|
+
logger.warn(`Device agent file ${operation} stopped`, { id: envelope.id, code: errorCodeOf(err) });
|
|
7346
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, `The ${operation} stopped unexpectedly.`);
|
|
7347
|
+
} finally {
|
|
7348
|
+
this.runningOperations -= 1;
|
|
7349
|
+
this.admitWaiting();
|
|
7350
|
+
}
|
|
7351
|
+
}
|
|
7352
|
+
/**
|
|
7353
|
+
* Null once this request holds a slot: at once when 1 is free and nobody waits, else when its turn in line
|
|
7354
|
+
* comes. `file_busy` at once when the line is full, or no slot is allowed.
|
|
7355
|
+
*/
|
|
7356
|
+
takeSlot(envelope) {
|
|
7357
|
+
if (this.runningOperations < this.maxConcurrentOperations && this.waitingOperations.length === 0) {
|
|
7358
|
+
this.runningOperations += 1;
|
|
7359
|
+
return Promise.resolve(null);
|
|
7360
|
+
}
|
|
7361
|
+
if (this.maxConcurrentOperations <= 0 || this.waitingOperations.length >= this.maxQueuedOperations) {
|
|
7362
|
+
return Promise.resolve(busy(this.maxConcurrentOperations, this.waitingOperations.length));
|
|
7363
|
+
}
|
|
7364
|
+
return new Promise((admit) => {
|
|
7365
|
+
this.waitingOperations.push({ envelope, admit });
|
|
7366
|
+
this.sendQueuedPosition(envelope, this.waitingOperations.length);
|
|
7367
|
+
this.startQueuedKeepalive();
|
|
7368
|
+
});
|
|
7369
|
+
}
|
|
7370
|
+
/**
|
|
7371
|
+
* Hands each free slot to the oldest request waiting, and counts it as running at once, so a request that
|
|
7372
|
+
* arrives before the waiting one resumes cannot take its slot. Those still waiting hear their new place.
|
|
7373
|
+
*/
|
|
7374
|
+
admitWaiting() {
|
|
7375
|
+
if (this.waitingOperations.length === 0) {
|
|
7376
|
+
return;
|
|
7377
|
+
}
|
|
7378
|
+
if (this.maxConcurrentOperations <= 0) {
|
|
7379
|
+
const refusal = busy(this.maxConcurrentOperations, 0);
|
|
7380
|
+
this.waitingOperations.splice(0).forEach((waiting) => waiting.admit(refusal));
|
|
7381
|
+
this.stopQueuedKeepalive();
|
|
7382
|
+
return;
|
|
7383
|
+
}
|
|
7384
|
+
let admitted = 0;
|
|
7385
|
+
while (this.waitingOperations.length > 0 && this.runningOperations < this.maxConcurrentOperations) {
|
|
7386
|
+
this.runningOperations += 1;
|
|
7387
|
+
this.waitingOperations.shift().admit(null);
|
|
7388
|
+
admitted += 1;
|
|
7389
|
+
}
|
|
7390
|
+
if (this.waitingOperations.length === 0) {
|
|
7391
|
+
this.stopQueuedKeepalive();
|
|
7392
|
+
} else if (admitted > 0) {
|
|
7393
|
+
this.sendQueuedPositions();
|
|
7394
|
+
}
|
|
7395
|
+
}
|
|
7396
|
+
sendQueuedPosition(envelope, position) {
|
|
7397
|
+
const payload = { queued_position: position };
|
|
7398
|
+
this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, payload, envelope.id));
|
|
7399
|
+
}
|
|
7400
|
+
sendQueuedPositions() {
|
|
7401
|
+
this.waitingOperations.forEach((waiting, index) => this.sendQueuedPosition(waiting.envelope, index + 1));
|
|
7402
|
+
}
|
|
7403
|
+
/** 1 timer for the whole line, running only while someone waits. */
|
|
7404
|
+
startQueuedKeepalive() {
|
|
7405
|
+
if (this.queuedKeepalive === null) {
|
|
7406
|
+
this.queuedKeepalive = setInterval(() => this.sendQueuedPositions(), QUEUED_KEEPALIVE_MILLIS);
|
|
7407
|
+
}
|
|
7408
|
+
}
|
|
7409
|
+
stopQueuedKeepalive() {
|
|
7410
|
+
if (this.queuedKeepalive !== null) {
|
|
7411
|
+
clearInterval(this.queuedKeepalive);
|
|
7412
|
+
this.queuedKeepalive = null;
|
|
7413
|
+
}
|
|
7414
|
+
}
|
|
7415
|
+
/** A refusal from the checks sends no counted `progress`: nothing was deleted, and the answer comes at once. */
|
|
7416
|
+
async deleteInSlot(envelope, request2) {
|
|
7417
|
+
const dependencies = this.deleteDependencies();
|
|
7418
|
+
const prepared = await prepareDelete(request2, dependencies);
|
|
7419
|
+
if ("error" in prepared) {
|
|
7420
|
+
return prepared;
|
|
7421
|
+
}
|
|
7422
|
+
const progress = { items_done: 0, items_total: 1, files_done: 0, current_name: prepared.name };
|
|
7423
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7424
|
+
try {
|
|
7425
|
+
return await runDelete(prepared, progress, dependencies);
|
|
7426
|
+
} finally {
|
|
7427
|
+
stopProgress();
|
|
7428
|
+
}
|
|
7429
|
+
}
|
|
7430
|
+
/**
|
|
7431
|
+
* A refusal from the checks sends no counted `progress`: nothing was copied, and the answer comes at once.
|
|
7432
|
+
* `progress` starts before the count, so a large tree keeps the browser's timer alive while it is counted, and a
|
|
7433
|
+
* `no_space` answer follows it.
|
|
7434
|
+
*/
|
|
7435
|
+
async copyInSlot(envelope, request2) {
|
|
7436
|
+
const dependencies = this.copyDependencies();
|
|
7437
|
+
const prepared = await prepareCopy(request2, dependencies);
|
|
7438
|
+
if ("error" in prepared) {
|
|
7439
|
+
return prepared;
|
|
7440
|
+
}
|
|
7441
|
+
const progress = {
|
|
7442
|
+
items_done: 0,
|
|
7443
|
+
items_total: 1,
|
|
7444
|
+
files_done: 0,
|
|
7445
|
+
bytes_done: 0,
|
|
7446
|
+
current_name: prepared.sourceName
|
|
7447
|
+
};
|
|
7448
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7449
|
+
try {
|
|
7450
|
+
return await runCopy(prepared, progress, dependencies);
|
|
7451
|
+
} finally {
|
|
7452
|
+
stopProgress();
|
|
7453
|
+
}
|
|
7454
|
+
}
|
|
7455
|
+
/**
|
|
7456
|
+
* As for a copy. On 1 disk the first `progress` already holds the totals, since there is nothing to count. To
|
|
7457
|
+
* another disk it starts before the count, as a copy's does.
|
|
7458
|
+
*/
|
|
7459
|
+
async moveInSlot(envelope, request2) {
|
|
7460
|
+
const dependencies = this.copyDependencies();
|
|
7461
|
+
const prepared = await prepareMove(request2, dependencies);
|
|
7462
|
+
if ("error" in prepared) {
|
|
7463
|
+
return prepared;
|
|
7464
|
+
}
|
|
7465
|
+
const progress = moveProgress(prepared);
|
|
7466
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7467
|
+
try {
|
|
7468
|
+
return await runMove(prepared, progress, dependencies);
|
|
7469
|
+
} finally {
|
|
7470
|
+
stopProgress();
|
|
7471
|
+
}
|
|
7472
|
+
}
|
|
7473
|
+
/** Sends 1 `progress` now, then from a timer. Returns the stop, which the answer waits for. */
|
|
7474
|
+
startProgress(envelope, progress) {
|
|
7475
|
+
let lastSent = this.sendProgress(envelope, progress);
|
|
7476
|
+
let ticksSinceSent = 0;
|
|
7477
|
+
const timer = setInterval(() => {
|
|
7478
|
+
ticksSinceSent += 1;
|
|
7479
|
+
if (sameProgress(progress, lastSent) && ticksSinceSent < PROGRESS_KEEPALIVE_TICKS) {
|
|
7480
|
+
return;
|
|
7481
|
+
}
|
|
7482
|
+
lastSent = this.sendProgress(envelope, progress);
|
|
7483
|
+
ticksSinceSent = 0;
|
|
7484
|
+
}, PROGRESS_TICK_MILLIS);
|
|
7485
|
+
return () => clearInterval(timer);
|
|
7486
|
+
}
|
|
7487
|
+
/** Sends a snapshot, since the op keeps counting into `progress`. Returns the snapshot sent. */
|
|
7488
|
+
sendProgress(envelope, progress) {
|
|
7489
|
+
const snapshot = { ...progress };
|
|
7490
|
+
this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, snapshot, envelope.id));
|
|
7491
|
+
return snapshot;
|
|
7492
|
+
}
|
|
7493
|
+
deleteDependencies() {
|
|
7494
|
+
return {
|
|
7495
|
+
remover: this.gatedRemover,
|
|
7496
|
+
platform: this.fileSystem().platform,
|
|
7497
|
+
protectedSources: this.dependencies.protectedSources ?? machineProtectedSources(),
|
|
7498
|
+
callTimeoutMillis: this.deleteCallTimeoutMillis()
|
|
7499
|
+
};
|
|
7500
|
+
}
|
|
7501
|
+
copyDependencies() {
|
|
7502
|
+
return {
|
|
7503
|
+
...this.deleteDependencies(),
|
|
7504
|
+
copier: this.gatedCopier,
|
|
7505
|
+
hiddenNameSuffix: this.dependencies.hiddenNameSuffix ?? randomHiddenNameSuffix
|
|
7506
|
+
};
|
|
7507
|
+
}
|
|
7508
|
+
fileSystem() {
|
|
7509
|
+
return this.gatedFileSystem;
|
|
7510
|
+
}
|
|
7511
|
+
deleteCallTimeoutMillis() {
|
|
7512
|
+
return this.dependencies.deleteCallTimeoutMillis ?? DEFAULT_DELETE_CALL_TIMEOUT_MILLIS;
|
|
7513
|
+
}
|
|
7514
|
+
copyCallTimeoutMillis() {
|
|
7515
|
+
return this.dependencies.copyCallTimeoutMillis ?? DEFAULT_COPY_CALL_TIMEOUT_MILLIS;
|
|
7516
|
+
}
|
|
7517
|
+
mkdirTimeoutMillis() {
|
|
7518
|
+
return this.dependencies.mkdirTimeoutMillis ?? DEFAULT_MKDIR_TIMEOUT_MILLIS;
|
|
7519
|
+
}
|
|
7520
|
+
readTimeoutMillis() {
|
|
7521
|
+
return this.dependencies.readTimeoutMillis ?? DEFAULT_READ_TIMEOUT_MILLIS;
|
|
7522
|
+
}
|
|
7523
|
+
/** "The folder took longer than 20 s to read." */
|
|
7524
|
+
timedOut(subject) {
|
|
7525
|
+
const seconds = Math.round(this.readTimeoutMillis() / MILLIS_PER_SECOND2);
|
|
7526
|
+
return fileError(ERROR_FILE_TIMEOUT, `${subject} took longer than ${seconds} s to read.`);
|
|
7527
|
+
}
|
|
7528
|
+
/** What is left of `max_frame_bytes` once the answer's envelope is counted. */
|
|
7529
|
+
payloadBudget(envelope) {
|
|
7530
|
+
const envelopeBytes = Buffer.byteLength(JSON.stringify(response(envelope, envelope.op, null)), "utf8");
|
|
7531
|
+
return this.maxFrameBytes - (envelopeBytes - NULL_PAYLOAD_BYTES);
|
|
7532
|
+
}
|
|
7533
|
+
answer(envelope, result) {
|
|
7534
|
+
logger.debug("Device agent file request", {
|
|
7535
|
+
op: envelope.op,
|
|
7536
|
+
id: envelope.id,
|
|
7537
|
+
outcome: "error" in result ? result.error.code : OUTCOME_ANSWERED
|
|
7538
|
+
});
|
|
7539
|
+
this.dependencies.send(response(envelope, envelope.op, result));
|
|
7540
|
+
}
|
|
7541
|
+
};
|
|
7542
|
+
function afterThisTurn(work) {
|
|
7543
|
+
return Promise.resolve().then(work);
|
|
7544
|
+
}
|
|
7545
|
+
function sameProgress(left, right) {
|
|
7546
|
+
return left.items_done === right.items_done && left.files_done === right.files_done && left.bytes_done === right.bytes_done && left.files_total === right.files_total && left.bytes_total === right.bytes_total && left.current_name === right.current_name;
|
|
7547
|
+
}
|
|
7548
|
+
function invalidPayload() {
|
|
7549
|
+
return fileError(ERROR_INVALID_PAYLOAD2, "The file request could not be read.");
|
|
7550
|
+
}
|
|
7551
|
+
function busy(limit, waiting) {
|
|
7552
|
+
if (limit <= 0) {
|
|
7553
|
+
return fileError(ERROR_FILE_BUSY, "The dashboard allows no file operations on this device.");
|
|
7554
|
+
}
|
|
7555
|
+
const noun = limit === 1 ? "file operation" : "file operations";
|
|
7556
|
+
const running = `The device is already running ${limit} ${noun}`;
|
|
7557
|
+
if (waiting <= 0) {
|
|
7558
|
+
return fileError(ERROR_FILE_BUSY, `${running}.`);
|
|
7559
|
+
}
|
|
7560
|
+
const verb = waiting === 1 ? "is" : "are";
|
|
7561
|
+
return fileError(ERROR_FILE_BUSY, `${running}, and ${waiting} more ${verb} waiting.`);
|
|
7562
|
+
}
|
|
7563
|
+
|
|
7564
|
+
// src/devices/login/prompts.ts
|
|
7565
|
+
import pico4 from "picocolors";
|
|
7566
|
+
import { createInterface as createInterface2 } from "readline/promises";
|
|
7567
|
+
import { Writable } from "stream";
|
|
7568
|
+
var QUESTION_MARKER = pico4.cyan(pico4.bold("\u2192"));
|
|
7569
|
+
function createTerminalPrompter(input, output) {
|
|
7570
|
+
return {
|
|
7571
|
+
async ask(question, signal) {
|
|
7572
|
+
const readline = createInterface2({ input, output, terminal: true });
|
|
7573
|
+
try {
|
|
7574
|
+
return await readline.question(marked(question), signal ? { signal } : {});
|
|
7575
|
+
} finally {
|
|
7576
|
+
readline.close();
|
|
7577
|
+
}
|
|
7578
|
+
},
|
|
7579
|
+
async askHidden(question, signal) {
|
|
7580
|
+
output.write(marked(question));
|
|
7581
|
+
const readline = createInterface2({ input, output: discardingOutput(), terminal: true });
|
|
7582
|
+
try {
|
|
7583
|
+
const answer = await readline.question("", signal ? { signal } : {});
|
|
7584
|
+
output.write("\n");
|
|
7585
|
+
return answer;
|
|
7586
|
+
} finally {
|
|
7587
|
+
readline.close();
|
|
7588
|
+
}
|
|
7589
|
+
}
|
|
7590
|
+
};
|
|
7591
|
+
}
|
|
7592
|
+
var terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
|
|
7593
|
+
function isInteractiveTerminal() {
|
|
7594
|
+
return process.stdin.isTTY === true;
|
|
7595
|
+
}
|
|
7596
|
+
var ABORT_ERROR_NAME = "AbortError";
|
|
7597
|
+
function isCtrlCAtPrompt(err) {
|
|
7598
|
+
return err instanceof Error && err.name === ABORT_ERROR_NAME;
|
|
7599
|
+
}
|
|
7600
|
+
function marked(question) {
|
|
7601
|
+
return `${QUESTION_MARKER} ${question}`;
|
|
7602
|
+
}
|
|
7603
|
+
function discardingOutput() {
|
|
7604
|
+
return new Writable({
|
|
7605
|
+
write(_chunk, _encoding, callback) {
|
|
7606
|
+
callback();
|
|
7607
|
+
}
|
|
7608
|
+
});
|
|
7609
|
+
}
|
|
7610
|
+
|
|
7611
|
+
// src/devices/fileAccess.ts
|
|
7612
|
+
var FILE_ACCESS_QUESTION = "Allow file access from the Pinggy dashboard? Your account can browse, copy, move and delete this machine's files from the browser. [Y/n] ";
|
|
7613
|
+
var INVALID_FILES_FLAG_MESSAGE = "--files takes on or off.";
|
|
7614
|
+
var FILES_FLAG_ON = "on";
|
|
7615
|
+
var FILES_FLAG_OFF = "off";
|
|
7616
|
+
var NO_ANSWER2 = /^n/i;
|
|
7617
|
+
var FILE_ACCESS_ON_MESSAGE = "File access is on. To turn it off, run: pinggy device connect --files off";
|
|
7618
|
+
var FILE_ACCESS_OFF_MESSAGE2 = "File access is off. To allow it, run: pinggy device connect --files on";
|
|
7619
|
+
function machineFileAccessDependencies() {
|
|
7620
|
+
return {
|
|
7621
|
+
prompter: terminalPrompter,
|
|
7622
|
+
isInteractive: isInteractiveTerminal,
|
|
7623
|
+
writeIdentity: writeDeviceIdentity,
|
|
7624
|
+
print: (message) => printer_default.print(message)
|
|
7625
|
+
};
|
|
5073
7626
|
}
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
this.connectedAtMillis = null;
|
|
5078
|
-
this.now = options.now ?? Date.now;
|
|
5079
|
-
this.random = options.random ?? Math.random;
|
|
7627
|
+
function parseFilesFlag(value) {
|
|
7628
|
+
if (value === void 0) {
|
|
7629
|
+
return void 0;
|
|
5080
7630
|
}
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
7631
|
+
switch (value.trim().toLowerCase()) {
|
|
7632
|
+
case FILES_FLAG_ON:
|
|
7633
|
+
return true;
|
|
7634
|
+
case FILES_FLAG_OFF:
|
|
7635
|
+
return false;
|
|
7636
|
+
default:
|
|
7637
|
+
return null;
|
|
5084
7638
|
}
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
7639
|
+
}
|
|
7640
|
+
async function settleFileAccess(flag, token, stored, dependencies) {
|
|
7641
|
+
const storedForToken = stored?.token === token ? stored : null;
|
|
7642
|
+
let answer = flag;
|
|
7643
|
+
if (answer === void 0) {
|
|
7644
|
+
if (typeof storedForToken?.file_manager === "boolean" || !dependencies.isInteractive()) {
|
|
7645
|
+
return void 0;
|
|
7646
|
+
}
|
|
7647
|
+
answer = !NO_ANSWER2.test((await dependencies.prompter.ask(FILE_ACCESS_QUESTION)).trim());
|
|
5088
7648
|
}
|
|
5089
|
-
|
|
5090
|
-
|
|
7649
|
+
if (storedForToken) {
|
|
7650
|
+
dependencies.writeIdentity({ ...storedForToken, file_manager: answer });
|
|
5091
7651
|
}
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
this.attemptCount = 0;
|
|
5102
|
-
}
|
|
5103
|
-
return wasStable;
|
|
7652
|
+
dependencies.print(answer ? FILE_ACCESS_ON_MESSAGE : FILE_ACCESS_OFF_MESSAGE2);
|
|
7653
|
+
return answer;
|
|
7654
|
+
}
|
|
7655
|
+
function fileAccessAllowed() {
|
|
7656
|
+
return readDeviceIdentity()?.file_manager !== false;
|
|
7657
|
+
}
|
|
7658
|
+
function describeFileAccess(identity) {
|
|
7659
|
+
if (identity.file_manager === true) {
|
|
7660
|
+
return "on";
|
|
5104
7661
|
}
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
const delay = fullJitterMillis(this.nextCeilingMillis, this.random);
|
|
5108
|
-
this.attemptCount = Math.min(this.attemptCount + 1, MAX_ATTEMPT);
|
|
5109
|
-
return delay;
|
|
7662
|
+
if (identity.file_manager === false) {
|
|
7663
|
+
return "off";
|
|
5110
7664
|
}
|
|
5111
|
-
|
|
7665
|
+
return "on, not asked yet";
|
|
7666
|
+
}
|
|
5112
7667
|
|
|
5113
7668
|
// src/devices/terminal/terminal_schema.ts
|
|
5114
|
-
import { z as
|
|
7669
|
+
import { z as z5 } from "zod";
|
|
5115
7670
|
var CHANNEL_TERMINAL = "terminal";
|
|
5116
7671
|
var OP_OPEN = "open";
|
|
5117
7672
|
var OP_OPENED = "opened";
|
|
@@ -5130,43 +7685,43 @@ var MIN_GRID = 1;
|
|
|
5130
7685
|
var MAX_GRID = 1e3;
|
|
5131
7686
|
var CLOSE_REASON_USER_CLOSED = "user_closed";
|
|
5132
7687
|
var CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
|
|
5133
|
-
var
|
|
7688
|
+
var ERROR_INVALID_PAYLOAD3 = "invalid_payload";
|
|
5134
7689
|
var ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
|
|
5135
7690
|
var ERROR_TERMINAL_DISABLED = "terminal_disabled";
|
|
5136
7691
|
var ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
|
|
5137
7692
|
var ERROR_SPAWN_FAILED = "spawn_failed";
|
|
5138
|
-
var TerminalOpenSchema =
|
|
5139
|
-
terminal_id:
|
|
5140
|
-
cols:
|
|
5141
|
-
rows:
|
|
5142
|
-
shell:
|
|
5143
|
-
cwd:
|
|
7693
|
+
var TerminalOpenSchema = z5.object({
|
|
7694
|
+
terminal_id: z5.string().min(1),
|
|
7695
|
+
cols: z5.number().int().optional(),
|
|
7696
|
+
rows: z5.number().int().optional(),
|
|
7697
|
+
shell: z5.string().nullable().optional(),
|
|
7698
|
+
cwd: z5.string().nullable().optional()
|
|
5144
7699
|
});
|
|
5145
|
-
var TerminalCloseSchema =
|
|
5146
|
-
terminal_id:
|
|
5147
|
-
reason:
|
|
7700
|
+
var TerminalCloseSchema = z5.object({
|
|
7701
|
+
terminal_id: z5.string().min(1),
|
|
7702
|
+
reason: z5.string().optional()
|
|
5148
7703
|
});
|
|
5149
|
-
var TerminalResizeSchema =
|
|
5150
|
-
terminal_id:
|
|
5151
|
-
cols:
|
|
5152
|
-
rows:
|
|
7704
|
+
var TerminalResizeSchema = z5.object({
|
|
7705
|
+
terminal_id: z5.string().min(1),
|
|
7706
|
+
cols: z5.number().int(),
|
|
7707
|
+
rows: z5.number().int()
|
|
5153
7708
|
});
|
|
5154
|
-
var TerminalInputSchema =
|
|
5155
|
-
terminal_id:
|
|
5156
|
-
data:
|
|
7709
|
+
var TerminalInputSchema = z5.object({
|
|
7710
|
+
terminal_id: z5.string().min(1),
|
|
7711
|
+
data: z5.string()
|
|
5157
7712
|
});
|
|
5158
|
-
var TerminalSignalSchema =
|
|
5159
|
-
terminal_id:
|
|
5160
|
-
signal:
|
|
7713
|
+
var TerminalSignalSchema = z5.object({
|
|
7714
|
+
terminal_id: z5.string().min(1),
|
|
7715
|
+
signal: z5.enum(TERMINAL_SIGNALS)
|
|
5161
7716
|
});
|
|
5162
|
-
var TerminalAckSchema =
|
|
5163
|
-
terminal_id:
|
|
5164
|
-
ack_seq:
|
|
5165
|
-
ack_bytes:
|
|
7717
|
+
var TerminalAckSchema = z5.object({
|
|
7718
|
+
terminal_id: z5.string().min(1),
|
|
7719
|
+
ack_seq: z5.number().optional(),
|
|
7720
|
+
ack_bytes: z5.number()
|
|
5166
7721
|
});
|
|
5167
|
-
var TerminalSnapshotRequestSchema =
|
|
5168
|
-
terminal_id:
|
|
5169
|
-
snapshot_id:
|
|
7722
|
+
var TerminalSnapshotRequestSchema = z5.object({
|
|
7723
|
+
terminal_id: z5.string().min(1),
|
|
7724
|
+
snapshot_id: z5.string().min(1)
|
|
5170
7725
|
});
|
|
5171
7726
|
function clampGrid(requested, fallback) {
|
|
5172
7727
|
if (requested === void 0 || !Number.isFinite(requested)) return fallback;
|
|
@@ -5175,7 +7730,7 @@ function clampGrid(requested, fallback) {
|
|
|
5175
7730
|
|
|
5176
7731
|
// src/devices/terminal/terminalHandler.ts
|
|
5177
7732
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
5178
|
-
import
|
|
7733
|
+
import os9 from "os";
|
|
5179
7734
|
|
|
5180
7735
|
// src/devices/terminal/flowWindow.ts
|
|
5181
7736
|
var FlowWindow = class {
|
|
@@ -5300,8 +7855,8 @@ var FrameSplitter = class {
|
|
|
5300
7855
|
|
|
5301
7856
|
// src/devices/terminal/shellContext.ts
|
|
5302
7857
|
import { execFile as execFile2 } from "child_process";
|
|
5303
|
-
import
|
|
5304
|
-
import
|
|
7858
|
+
import fs8 from "fs";
|
|
7859
|
+
import os8 from "os";
|
|
5305
7860
|
var SHELL_CONTEXT_POLL_MILLIS = 5e3;
|
|
5306
7861
|
var MAX_CWD_CHARACTERS = 1024;
|
|
5307
7862
|
var MAX_COMMAND_CHARACTERS = 64;
|
|
@@ -5332,7 +7887,7 @@ function displayCwd(rawCwd, resolvedHome) {
|
|
|
5332
7887
|
}
|
|
5333
7888
|
function resolvedHomeDirectory() {
|
|
5334
7889
|
try {
|
|
5335
|
-
return
|
|
7890
|
+
return fs8.realpathSync(os8.homedir());
|
|
5336
7891
|
} catch {
|
|
5337
7892
|
return null;
|
|
5338
7893
|
}
|
|
@@ -5384,14 +7939,14 @@ async function readFromProc(shellPids) {
|
|
|
5384
7939
|
await Promise.all(shellPids.map(async (shellPid) => {
|
|
5385
7940
|
const groups = await readProcGroups(shellPid);
|
|
5386
7941
|
if (!groups) return;
|
|
5387
|
-
const cwd = await readOrNull(() =>
|
|
5388
|
-
const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() =>
|
|
7942
|
+
const cwd = await readOrNull(() => fs8.promises.readlink(`/proc/${shellPid}/cwd`));
|
|
7943
|
+
const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => fs8.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
|
|
5389
7944
|
contexts.set(shellPid, { cwd, foregroundName });
|
|
5390
7945
|
}));
|
|
5391
7946
|
return contexts;
|
|
5392
7947
|
}
|
|
5393
7948
|
async function readProcGroups(shellPid) {
|
|
5394
|
-
const stat = await readOrNull(() =>
|
|
7949
|
+
const stat = await readOrNull(() => fs8.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
|
|
5395
7950
|
if (stat === null) return null;
|
|
5396
7951
|
const afterName = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
5397
7952
|
const shellGroupId = Number.parseInt(afterName[2], 10);
|
|
@@ -5573,7 +8128,7 @@ function errorName(err) {
|
|
|
5573
8128
|
var DEFAULT_COLS = 80;
|
|
5574
8129
|
var DEFAULT_ROWS = 24;
|
|
5575
8130
|
var EXPIRY_CHECK_MILLIS = 5e3;
|
|
5576
|
-
var
|
|
8131
|
+
var MILLIS_PER_SECOND3 = 1e3;
|
|
5577
8132
|
var RESYNC_MIN_INTERVAL_MILLIS = 1e3;
|
|
5578
8133
|
var MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
|
|
5579
8134
|
var MIRROR_LOW_WATER_BYTES = 256 * 1024;
|
|
@@ -5779,7 +8334,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
5779
8334
|
open(envelope) {
|
|
5780
8335
|
const parsed = TerminalOpenSchema.safeParse(envelope.payload);
|
|
5781
8336
|
if (!parsed.success) {
|
|
5782
|
-
this.refuse(envelope, null,
|
|
8337
|
+
this.refuse(envelope, null, ERROR_INVALID_PAYLOAD3, "open payload could not be read.");
|
|
5783
8338
|
return;
|
|
5784
8339
|
}
|
|
5785
8340
|
const request2 = parsed.data;
|
|
@@ -6302,7 +8857,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
6302
8857
|
}
|
|
6303
8858
|
};
|
|
6304
8859
|
function positiveMillis(seconds) {
|
|
6305
|
-
return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds *
|
|
8860
|
+
return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND3 : void 0;
|
|
6306
8861
|
}
|
|
6307
8862
|
function splitIntoParts(bytes, partBytes) {
|
|
6308
8863
|
const parts = [];
|
|
@@ -6315,7 +8870,7 @@ function errorName2(err) {
|
|
|
6315
8870
|
return err instanceof Error ? err.name : typeof err;
|
|
6316
8871
|
}
|
|
6317
8872
|
function signalName(signal) {
|
|
6318
|
-
for (const [name, number] of Object.entries(
|
|
8873
|
+
for (const [name, number] of Object.entries(os9.constants.signals)) {
|
|
6319
8874
|
if (number === signal) return name.replace(/^SIG/, "");
|
|
6320
8875
|
}
|
|
6321
8876
|
return String(signal);
|
|
@@ -6376,8 +8931,8 @@ var TerminalRegistry = class {
|
|
|
6376
8931
|
|
|
6377
8932
|
// src/devices/terminal/ptySession.ts
|
|
6378
8933
|
import { execFile as execFile3 } from "child_process";
|
|
6379
|
-
import
|
|
6380
|
-
import
|
|
8934
|
+
import fs9 from "fs";
|
|
8935
|
+
import os10 from "os";
|
|
6381
8936
|
var loadedPty;
|
|
6382
8937
|
var TERM_NAME = "xterm-256color";
|
|
6383
8938
|
function foregroundProcessGroup(shellPid) {
|
|
@@ -6425,11 +8980,11 @@ function ensureSpawnHelperExecutable(packageRoot) {
|
|
|
6425
8980
|
function resolveCwd(requested) {
|
|
6426
8981
|
if (requested) {
|
|
6427
8982
|
try {
|
|
6428
|
-
if (
|
|
8983
|
+
if (fs9.statSync(requested).isDirectory()) return requested;
|
|
6429
8984
|
} catch {
|
|
6430
8985
|
}
|
|
6431
8986
|
}
|
|
6432
|
-
return
|
|
8987
|
+
return os10.homedir();
|
|
6433
8988
|
}
|
|
6434
8989
|
function spawnPty(request2) {
|
|
6435
8990
|
const pty = loadNodePty();
|
|
@@ -6475,14 +9030,14 @@ function spawnPty(request2) {
|
|
|
6475
9030
|
}
|
|
6476
9031
|
|
|
6477
9032
|
// src/devices/terminal/shellAllowlist.ts
|
|
6478
|
-
import
|
|
9033
|
+
import fs10 from "fs";
|
|
6479
9034
|
var FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
|
|
6480
9035
|
var WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
|
|
6481
9036
|
var ETC_SHELLS_PATH = "/etc/shells";
|
|
6482
9037
|
function readShellEnvironment() {
|
|
6483
9038
|
let etcShells = null;
|
|
6484
9039
|
try {
|
|
6485
|
-
etcShells =
|
|
9040
|
+
etcShells = fs10.readFileSync(ETC_SHELLS_PATH, "utf8");
|
|
6486
9041
|
} catch {
|
|
6487
9042
|
etcShells = null;
|
|
6488
9043
|
}
|
|
@@ -6490,9 +9045,9 @@ function readShellEnvironment() {
|
|
|
6490
9045
|
platform: process.platform,
|
|
6491
9046
|
loginShell: process.env.SHELL,
|
|
6492
9047
|
etcShells,
|
|
6493
|
-
exists: (
|
|
9048
|
+
exists: (path9) => {
|
|
6494
9049
|
try {
|
|
6495
|
-
return
|
|
9050
|
+
return fs10.statSync(path9).isFile();
|
|
6496
9051
|
} catch {
|
|
6497
9052
|
return false;
|
|
6498
9053
|
}
|
|
@@ -6525,13 +9080,13 @@ function resolveShell(requested, environment) {
|
|
|
6525
9080
|
}
|
|
6526
9081
|
|
|
6527
9082
|
// src/devices/foregroundAgent.ts
|
|
6528
|
-
import
|
|
9083
|
+
import fs11 from "fs";
|
|
6529
9084
|
var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
|
|
6530
9085
|
var STOP_WAIT_MILLIS = 1e4;
|
|
6531
9086
|
var STOP_POLL_INTERVAL_MILLIS = 200;
|
|
6532
9087
|
function readRecordFile(filePath) {
|
|
6533
9088
|
try {
|
|
6534
|
-
const record = JSON.parse(
|
|
9089
|
+
const record = JSON.parse(fs11.readFileSync(filePath, "utf-8"));
|
|
6535
9090
|
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
6536
9091
|
} catch {
|
|
6537
9092
|
return null;
|
|
@@ -6539,7 +9094,7 @@ function readRecordFile(filePath) {
|
|
|
6539
9094
|
}
|
|
6540
9095
|
function deleteRecordFile(filePath) {
|
|
6541
9096
|
try {
|
|
6542
|
-
|
|
9097
|
+
fs11.unlinkSync(filePath);
|
|
6543
9098
|
} catch (err) {
|
|
6544
9099
|
logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
|
|
6545
9100
|
}
|
|
@@ -6569,7 +9124,7 @@ function recordForegroundAgent(onRecordDeleted) {
|
|
|
6569
9124
|
};
|
|
6570
9125
|
try {
|
|
6571
9126
|
ensurePinggyConfigDir();
|
|
6572
|
-
|
|
9127
|
+
fs11.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
|
|
6573
9128
|
} catch (err) {
|
|
6574
9129
|
logger.warn(
|
|
6575
9130
|
"Could not write device-agent.json. pinggy device remove cannot stop this agent.",
|
|
@@ -6578,7 +9133,7 @@ function recordForegroundAgent(onRecordDeleted) {
|
|
|
6578
9133
|
return () => void 0;
|
|
6579
9134
|
}
|
|
6580
9135
|
const timer = setInterval(() => {
|
|
6581
|
-
if (!
|
|
9136
|
+
if (!fs11.existsSync(filePath)) {
|
|
6582
9137
|
clearInterval(timer);
|
|
6583
9138
|
onRecordDeleted();
|
|
6584
9139
|
}
|
|
@@ -6641,7 +9196,14 @@ var UNAUTHORIZED_STORED_TOKEN_MESSAGE = "The dashboard refused this machine's de
|
|
|
6641
9196
|
var UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
|
|
6642
9197
|
var HANDSHAKE_TIMEOUT_MILLIS = 3e4;
|
|
6643
9198
|
var PONG_GRACE_INTERVALS = 2;
|
|
6644
|
-
var BASE_CAPABILITIES = [
|
|
9199
|
+
var BASE_CAPABILITIES = [
|
|
9200
|
+
"tunnel",
|
|
9201
|
+
"stats",
|
|
9202
|
+
"tunnel_control",
|
|
9203
|
+
"tunnel_update",
|
|
9204
|
+
"saved_config_update",
|
|
9205
|
+
"file_manager"
|
|
9206
|
+
];
|
|
6645
9207
|
var CAPABILITY_TERMINAL = "terminal";
|
|
6646
9208
|
var CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
|
|
6647
9209
|
var CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
|
|
@@ -6672,8 +9234,8 @@ function sleep3(millis, state) {
|
|
|
6672
9234
|
function buildHello(terminalHandler) {
|
|
6673
9235
|
return {
|
|
6674
9236
|
agent_version: getVersion(),
|
|
6675
|
-
os:
|
|
6676
|
-
hostname:
|
|
9237
|
+
os: os11.platform(),
|
|
9238
|
+
hostname: os11.hostname(),
|
|
6677
9239
|
capabilities: buildCapabilities(isTerminalSupported(), isScreenMirrorSupported()),
|
|
6678
9240
|
terminals: terminalHandler.held()
|
|
6679
9241
|
};
|
|
@@ -6692,11 +9254,13 @@ function startMetricsReporting(intervalSeconds, collect, send) {
|
|
|
6692
9254
|
clearInterval(timer);
|
|
6693
9255
|
};
|
|
6694
9256
|
}
|
|
6695
|
-
function identityForRun(token, server, stored) {
|
|
6696
|
-
|
|
6697
|
-
|
|
9257
|
+
function identityForRun(token, server, stored, fileManager) {
|
|
9258
|
+
const identity = stored?.token === token ? { ...stored, server } : { device_agent_id: null, token, server, enrolled_at: null };
|
|
9259
|
+
delete identity.file_manager;
|
|
9260
|
+
if (fileManager !== void 0) {
|
|
9261
|
+
identity.file_manager = fileManager;
|
|
6698
9262
|
}
|
|
6699
|
-
return
|
|
9263
|
+
return identity;
|
|
6700
9264
|
}
|
|
6701
9265
|
function startDeviceAgent(token, manage, options = {}) {
|
|
6702
9266
|
const server = manage || DEFAULT_SERVER;
|
|
@@ -6707,7 +9271,7 @@ function startDeviceAgent(token, manage, options = {}) {
|
|
|
6707
9271
|
const context = {
|
|
6708
9272
|
wsUrl: buildDeviceAgentWsUrl(manage),
|
|
6709
9273
|
server,
|
|
6710
|
-
identity: identityForRun(token, server, stored),
|
|
9274
|
+
identity: identityForRun(token, server, stored, options.fileManager),
|
|
6711
9275
|
reconnectPolicy: options.reconnectPolicy ?? new ReconnectPolicy(),
|
|
6712
9276
|
handshakeTimeoutMillis: options.handshakeTimeoutMillis ?? HANDSHAKE_TIMEOUT_MILLIS,
|
|
6713
9277
|
terminalHandler: new TerminalHandler({
|
|
@@ -6718,6 +9282,7 @@ function startDeviceAgent(token, manage, options = {}) {
|
|
|
6718
9282
|
readShellContexts: processTableReader(),
|
|
6719
9283
|
resolvedHome: resolvedHomeDirectory()
|
|
6720
9284
|
}),
|
|
9285
|
+
fileHandler: new FileHandler({ send: (frame) => connection.send?.(frame), fileAccessAllowed }),
|
|
6721
9286
|
connection,
|
|
6722
9287
|
reporter,
|
|
6723
9288
|
writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
|
|
@@ -6783,7 +9348,7 @@ function fail(context, error) {
|
|
|
6783
9348
|
return "terminal";
|
|
6784
9349
|
}
|
|
6785
9350
|
function connectOnce(context) {
|
|
6786
|
-
const { identity, reconnectPolicy, terminalHandler, connection, reporter, state, options } = context;
|
|
9351
|
+
const { identity, reconnectPolicy, terminalHandler, fileHandler, connection, reporter, state, options } = context;
|
|
6787
9352
|
return new Promise((resolve) => {
|
|
6788
9353
|
const ws = new WebSocket3(context.wsUrl, { headers: { [TOKEN_HEADER]: identity.token } });
|
|
6789
9354
|
let heartbeat = null;
|
|
@@ -6868,7 +9433,7 @@ function connectOnce(context) {
|
|
|
6868
9433
|
const startHeartbeat = (intervalSeconds) => {
|
|
6869
9434
|
heartbeat = setInterval(
|
|
6870
9435
|
() => sendFrame(
|
|
6871
|
-
event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(
|
|
9436
|
+
event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(os11.uptime()) })
|
|
6872
9437
|
),
|
|
6873
9438
|
intervalSeconds * 1e3
|
|
6874
9439
|
);
|
|
@@ -6890,6 +9455,12 @@ function connectOnce(context) {
|
|
|
6890
9455
|
welcome.terminal_resync
|
|
6891
9456
|
);
|
|
6892
9457
|
terminalHandler.resumeAll();
|
|
9458
|
+
fileHandler.configure(
|
|
9459
|
+
welcome.file_manager_enabled,
|
|
9460
|
+
welcome.max_frame_bytes,
|
|
9461
|
+
welcome.file_max_concurrent_operations,
|
|
9462
|
+
welcome.file_max_queued_operations
|
|
9463
|
+
);
|
|
6893
9464
|
startHeartbeat(welcome.heartbeat_interval_seconds);
|
|
6894
9465
|
startPongWatchdog(welcome.heartbeat_interval_seconds);
|
|
6895
9466
|
sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
|
|
@@ -6913,6 +9484,10 @@ function connectOnce(context) {
|
|
|
6913
9484
|
terminalHandler.handle(envelope);
|
|
6914
9485
|
return;
|
|
6915
9486
|
}
|
|
9487
|
+
if (envelope.ch === CHANNEL_FILE) {
|
|
9488
|
+
void fileHandler.handle(envelope);
|
|
9489
|
+
return;
|
|
9490
|
+
}
|
|
6916
9491
|
if (envelope.ch === CHANNEL_TUNNEL) {
|
|
6917
9492
|
void handleTunnelAction(envelope, (frame) => connection.send?.(frame), options.tunnelActions).then(() => stopTunnels?.pollNow());
|
|
6918
9493
|
return;
|
|
@@ -7016,33 +9591,33 @@ function describeDisconnect(reason) {
|
|
|
7016
9591
|
}
|
|
7017
9592
|
|
|
7018
9593
|
// src/devices/login/deviceLogin.ts
|
|
7019
|
-
import
|
|
9594
|
+
import os12 from "os";
|
|
7020
9595
|
import pico5 from "picocolors";
|
|
7021
9596
|
|
|
7022
9597
|
// src/devices/login/login_schema.ts
|
|
7023
|
-
import { z as
|
|
7024
|
-
var LoginStartedSchema =
|
|
7025
|
-
device_code:
|
|
7026
|
-
match_code:
|
|
7027
|
-
expires_in_seconds:
|
|
7028
|
-
poll_interval_seconds:
|
|
9598
|
+
import { z as z6 } from "zod";
|
|
9599
|
+
var LoginStartedSchema = z6.object({
|
|
9600
|
+
device_code: z6.string().min(1),
|
|
9601
|
+
match_code: z6.string().min(1).optional(),
|
|
9602
|
+
expires_in_seconds: z6.number().int().positive(),
|
|
9603
|
+
poll_interval_seconds: z6.number().int().positive()
|
|
7029
9604
|
});
|
|
7030
9605
|
var LoginStatus = {
|
|
7031
9606
|
Pending: "pending",
|
|
7032
9607
|
MfaRequired: "mfa_required",
|
|
7033
9608
|
Approved: "approved"
|
|
7034
9609
|
};
|
|
7035
|
-
var LoginAnswerSchema =
|
|
7036
|
-
status:
|
|
7037
|
-
token:
|
|
7038
|
-
device_agent_id:
|
|
7039
|
-
device_name:
|
|
7040
|
-
open_url:
|
|
7041
|
-
device_url:
|
|
9610
|
+
var LoginAnswerSchema = z6.object({
|
|
9611
|
+
status: z6.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
|
|
9612
|
+
token: z6.string().min(1).optional(),
|
|
9613
|
+
device_agent_id: z6.string().min(1).optional(),
|
|
9614
|
+
device_name: z6.string().optional(),
|
|
9615
|
+
open_url: z6.string().optional(),
|
|
9616
|
+
device_url: z6.string().optional()
|
|
7042
9617
|
});
|
|
7043
|
-
var LoginErrorSchema =
|
|
7044
|
-
error_type:
|
|
7045
|
-
errors:
|
|
9618
|
+
var LoginErrorSchema = z6.object({
|
|
9619
|
+
error_type: z6.string(),
|
|
9620
|
+
errors: z6.array(z6.string()).default([])
|
|
7046
9621
|
});
|
|
7047
9622
|
var LoginErrorType = {
|
|
7048
9623
|
/** A wrong code or authenticator code, with attempts left. Asked again. */
|
|
@@ -7077,8 +9652,8 @@ var DeviceLoginApiError = class extends Error {
|
|
|
7077
9652
|
var UNREADABLE_ANSWER = "invalid_answer";
|
|
7078
9653
|
function createDeviceLoginApi(manage, fetchImpl = fetch) {
|
|
7079
9654
|
const baseUrl = buildDashboardHttpUrl(manage);
|
|
7080
|
-
async function post(
|
|
7081
|
-
const response2 = await fetchImpl(`${baseUrl}/${
|
|
9655
|
+
async function post(path9, body, schema) {
|
|
9656
|
+
const response2 = await fetchImpl(`${baseUrl}/${path9}`, {
|
|
7082
9657
|
method: "POST",
|
|
7083
9658
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
7084
9659
|
body: JSON.stringify(body)
|
|
@@ -7124,49 +9699,6 @@ async function readJson(response2) {
|
|
|
7124
9699
|
}
|
|
7125
9700
|
}
|
|
7126
9701
|
|
|
7127
|
-
// src/devices/login/prompts.ts
|
|
7128
|
-
import pico4 from "picocolors";
|
|
7129
|
-
import { createInterface as createInterface2 } from "readline/promises";
|
|
7130
|
-
import { Writable } from "stream";
|
|
7131
|
-
var QUESTION_MARKER = pico4.cyan(pico4.bold("\u2192"));
|
|
7132
|
-
function createTerminalPrompter(input, output) {
|
|
7133
|
-
return {
|
|
7134
|
-
async ask(question, signal) {
|
|
7135
|
-
const readline = createInterface2({ input, output, terminal: true });
|
|
7136
|
-
try {
|
|
7137
|
-
return await readline.question(marked(question), signal ? { signal } : {});
|
|
7138
|
-
} finally {
|
|
7139
|
-
readline.close();
|
|
7140
|
-
}
|
|
7141
|
-
},
|
|
7142
|
-
async askHidden(question, signal) {
|
|
7143
|
-
output.write(marked(question));
|
|
7144
|
-
const readline = createInterface2({ input, output: discardingOutput(), terminal: true });
|
|
7145
|
-
try {
|
|
7146
|
-
const answer = await readline.question("", signal ? { signal } : {});
|
|
7147
|
-
output.write("\n");
|
|
7148
|
-
return answer;
|
|
7149
|
-
} finally {
|
|
7150
|
-
readline.close();
|
|
7151
|
-
}
|
|
7152
|
-
}
|
|
7153
|
-
};
|
|
7154
|
-
}
|
|
7155
|
-
var terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
|
|
7156
|
-
function isInteractiveTerminal() {
|
|
7157
|
-
return process.stdin.isTTY === true;
|
|
7158
|
-
}
|
|
7159
|
-
function marked(question) {
|
|
7160
|
-
return `${QUESTION_MARKER} ${question}`;
|
|
7161
|
-
}
|
|
7162
|
-
function discardingOutput() {
|
|
7163
|
-
return new Writable({
|
|
7164
|
-
write(_chunk, _encoding, callback) {
|
|
7165
|
-
callback();
|
|
7166
|
-
}
|
|
7167
|
-
});
|
|
7168
|
-
}
|
|
7169
|
-
|
|
7170
9702
|
// src/devices/login/deviceLogin.ts
|
|
7171
9703
|
var EXIT_OK = 0;
|
|
7172
9704
|
var EXIT_FAILED = 1;
|
|
@@ -7174,10 +9706,9 @@ var DEFAULT_SERVER2 = "dashboard.pinggy.io";
|
|
|
7174
9706
|
var YES_ANSWER = /^y(es)?$/i;
|
|
7175
9707
|
var RESULT_MARKER = pico5.green(pico5.bold("\u2192"));
|
|
7176
9708
|
var SECONDS_PER_MINUTE = 60;
|
|
7177
|
-
var
|
|
9709
|
+
var MILLIS_PER_SECOND4 = 1e3;
|
|
7178
9710
|
var FIRST_SERVER_ERROR_STATUS = 500;
|
|
7179
9711
|
var NO_TERMINAL_MESSAGE = "pinggy device login needs a terminal to type the email and the code. On a machine without one, add the device in the dashboard and run: pinggy device connect --token <TOKEN>";
|
|
7180
|
-
var ABORT_ERROR_NAME = "AbortError";
|
|
7181
9712
|
function machineDeviceLoginDependencies() {
|
|
7182
9713
|
return {
|
|
7183
9714
|
createApi: (manage) => createDeviceLoginApi(manage),
|
|
@@ -7188,9 +9719,9 @@ function machineDeviceLoginDependencies() {
|
|
|
7188
9719
|
runAgent: (token, manage) => runDeviceAgent(token, manage),
|
|
7189
9720
|
renderQr: async (url) => (await createQrCodes([url]))[0],
|
|
7190
9721
|
machine: () => ({
|
|
7191
|
-
hostname:
|
|
7192
|
-
os:
|
|
7193
|
-
arch:
|
|
9722
|
+
hostname: os12.hostname(),
|
|
9723
|
+
os: os12.platform(),
|
|
9724
|
+
arch: os12.arch(),
|
|
7194
9725
|
agent_version: getVersion()
|
|
7195
9726
|
}),
|
|
7196
9727
|
print: (message) => printer_default.print(message),
|
|
@@ -7209,9 +9740,6 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
|
|
|
7209
9740
|
return EXIT_FAILED;
|
|
7210
9741
|
}
|
|
7211
9742
|
}
|
|
7212
|
-
function isCtrlCAtPrompt(err) {
|
|
7213
|
-
return err instanceof Error && err.name === ABORT_ERROR_NAME;
|
|
7214
|
-
}
|
|
7215
9743
|
async function signInAndRunAgent(options, dependencies) {
|
|
7216
9744
|
if (!dependencies.isInteractive()) {
|
|
7217
9745
|
dependencies.printError(NO_TERMINAL_MESSAGE);
|
|
@@ -7224,6 +9752,7 @@ async function signInAndRunAgent(options, dependencies) {
|
|
|
7224
9752
|
`This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
|
|
7225
9753
|
);
|
|
7226
9754
|
if (!YES_ANSWER.test(answer.trim())) {
|
|
9755
|
+
await settleFileAccess(options.fileManager, stored.token, stored, dependencies);
|
|
7227
9756
|
return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
|
|
7228
9757
|
}
|
|
7229
9758
|
}
|
|
@@ -7256,13 +9785,25 @@ async function signInAndRunAgent(options, dependencies) {
|
|
|
7256
9785
|
dependencies.printError("The dashboard approved the sign-in without a device token. Update pinggy and try again.");
|
|
7257
9786
|
return EXIT_FAILED;
|
|
7258
9787
|
}
|
|
7259
|
-
|
|
9788
|
+
const identity = {
|
|
7260
9789
|
device_agent_id: approved.device_agent_id,
|
|
7261
9790
|
token: approved.token,
|
|
7262
9791
|
server: manage || DEFAULT_SERVER2,
|
|
7263
9792
|
enrolled_at: null
|
|
7264
|
-
}
|
|
9793
|
+
};
|
|
7265
9794
|
dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
|
|
9795
|
+
let fileManager;
|
|
9796
|
+
try {
|
|
9797
|
+
fileManager = await settleFileAccess(options.fileManager, identity.token, null, dependencies);
|
|
9798
|
+
} catch (err) {
|
|
9799
|
+
if (!isCtrlCAtPrompt(err)) {
|
|
9800
|
+
throw err;
|
|
9801
|
+
}
|
|
9802
|
+
dependencies.writeIdentity(identity);
|
|
9803
|
+
dependencies.print(pico5.yellow("Cancelled. This machine is signed in, and its agent did not start. To start it, run: pinggy device connect"));
|
|
9804
|
+
return EXIT_FAILED;
|
|
9805
|
+
}
|
|
9806
|
+
dependencies.writeIdentity({ ...identity, file_manager: fileManager });
|
|
7266
9807
|
await printDeviceLink(approved, linkMinutes, dependencies);
|
|
7267
9808
|
return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
|
|
7268
9809
|
}
|
|
@@ -7283,7 +9824,7 @@ async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencie
|
|
|
7283
9824
|
const polled = pollUntilApproved(
|
|
7284
9825
|
api,
|
|
7285
9826
|
deviceCode,
|
|
7286
|
-
pollIntervalSeconds *
|
|
9827
|
+
pollIntervalSeconds * MILLIS_PER_SECOND4,
|
|
7287
9828
|
controller.signal,
|
|
7288
9829
|
dependencies
|
|
7289
9830
|
);
|
|
@@ -7447,9 +9988,10 @@ function machineBackgroundAgentDependencies() {
|
|
|
7447
9988
|
forgetSavedAgent: forgetDeviceAgent,
|
|
7448
9989
|
ensureDaemon: ensureDaemonRunning,
|
|
7449
9990
|
client: (port) => new IPCClient(port, "cli"),
|
|
7450
|
-
verify: (token, manage) => startDeviceAgent(token, manage, {
|
|
9991
|
+
verify: (token, manage, fileManager) => startDeviceAgent(token, manage, {
|
|
7451
9992
|
verifyOnly: true,
|
|
7452
|
-
reporter: verifyingReporter
|
|
9993
|
+
reporter: verifyingReporter,
|
|
9994
|
+
fileManager
|
|
7453
9995
|
}).done,
|
|
7454
9996
|
sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
|
|
7455
9997
|
now: () => Date.now(),
|
|
@@ -7487,7 +10029,7 @@ async function readBackgroundAgent(dependencies) {
|
|
|
7487
10029
|
}
|
|
7488
10030
|
async function startAgentInBackground(target, dependencies, options = {}) {
|
|
7489
10031
|
if (differsFromStored(target, dependencies.readIdentity())) {
|
|
7490
|
-
const verified = await dependencies.verify(target.token, target.manage);
|
|
10032
|
+
const verified = await dependencies.verify(target.token, target.manage, options.fileManager);
|
|
7491
10033
|
if (verified.error || !verified.welcomed) {
|
|
7492
10034
|
dependencies.printError(verified.error?.message ?? "The device did not connect. Nothing changed.");
|
|
7493
10035
|
return EXIT_FAILED;
|
|
@@ -7654,6 +10196,14 @@ function printRunning(status, daemon, options, dependencies) {
|
|
|
7654
10196
|
}
|
|
7655
10197
|
|
|
7656
10198
|
// src/cli/subcommand/handlers/daemonCommandsHandler.ts
|
|
10199
|
+
var RENAMED_DAEMON_VERBS = /* @__PURE__ */ new Map([
|
|
10200
|
+
["service-install", AUTOSTART_ON_COMMAND],
|
|
10201
|
+
["service-uninstall", AUTOSTART_OFF_COMMAND]
|
|
10202
|
+
]);
|
|
10203
|
+
function renamedDaemonVerbMessage(verb) {
|
|
10204
|
+
const replacement = RENAMED_DAEMON_VERBS.get(verb);
|
|
10205
|
+
return replacement ? `"pinggy daemon ${verb}" is now "${replacement}".` : null;
|
|
10206
|
+
}
|
|
7657
10207
|
async function handleDaemon(args) {
|
|
7658
10208
|
if (args.length === 0) {
|
|
7659
10209
|
printDaemonHelp();
|
|
@@ -7670,16 +10220,21 @@ async function handleDaemon(args) {
|
|
|
7670
10220
|
case "status":
|
|
7671
10221
|
await handleDaemonStatus();
|
|
7672
10222
|
return;
|
|
7673
|
-
case "
|
|
7674
|
-
|
|
7675
|
-
|
|
7676
|
-
|
|
7677
|
-
await uninstallService();
|
|
10223
|
+
case "help":
|
|
10224
|
+
case "--help":
|
|
10225
|
+
case "-h":
|
|
10226
|
+
printDaemonHelp();
|
|
7678
10227
|
return;
|
|
7679
|
-
default:
|
|
10228
|
+
default: {
|
|
10229
|
+
const renamed = renamedDaemonVerbMessage(verb);
|
|
10230
|
+
if (renamed) {
|
|
10231
|
+
printer_default.error(renamed);
|
|
10232
|
+
process.exit(1);
|
|
10233
|
+
}
|
|
7680
10234
|
printer_default.error(`Unknown daemon command: "${verb}"`);
|
|
7681
10235
|
printDaemonHelp();
|
|
7682
10236
|
return;
|
|
10237
|
+
}
|
|
7683
10238
|
}
|
|
7684
10239
|
}
|
|
7685
10240
|
async function handleDaemonStart() {
|
|
@@ -7936,11 +10491,11 @@ async function handleAttach(args) {
|
|
|
7936
10491
|
}
|
|
7937
10492
|
|
|
7938
10493
|
// src/cli/subcommand/handlers/logsCommand.ts
|
|
7939
|
-
import
|
|
10494
|
+
import fs13 from "fs";
|
|
7940
10495
|
|
|
7941
10496
|
// src/daemon/logPaths.ts
|
|
7942
|
-
import
|
|
7943
|
-
import
|
|
10497
|
+
import fs12 from "fs";
|
|
10498
|
+
import path6 from "path";
|
|
7944
10499
|
var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
|
|
7945
10500
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
7946
10501
|
function parseTunnelLogFilename(filename) {
|
|
@@ -7960,8 +10515,8 @@ function parseTunnelLogFilename(filename) {
|
|
|
7960
10515
|
}
|
|
7961
10516
|
function listTunnelLogFiles() {
|
|
7962
10517
|
const logDir = getTunnelLogDir();
|
|
7963
|
-
if (!
|
|
7964
|
-
return
|
|
10518
|
+
if (!fs12.existsSync(logDir)) return [];
|
|
10519
|
+
return fs12.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
|
|
7965
10520
|
}
|
|
7966
10521
|
function newestLogFile(q) {
|
|
7967
10522
|
const logDir = getTunnelLogDir();
|
|
@@ -7972,8 +10527,8 @@ function newestLogFile(q) {
|
|
|
7972
10527
|
const nameMatch = parsed.name !== void 0 && parsed.name === q;
|
|
7973
10528
|
const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
|
|
7974
10529
|
if (nameMatch || idMatch) {
|
|
7975
|
-
const filePath =
|
|
7976
|
-
matches.push({ ...parsed, path: filePath, mtime:
|
|
10530
|
+
const filePath = path6.join(logDir, file);
|
|
10531
|
+
matches.push({ ...parsed, path: filePath, mtime: fs12.statSync(filePath).mtimeMs });
|
|
7977
10532
|
}
|
|
7978
10533
|
}
|
|
7979
10534
|
if (matches.length === 0) return null;
|
|
@@ -8056,7 +10611,7 @@ async function handleLogs(args, follow) {
|
|
|
8056
10611
|
return;
|
|
8057
10612
|
}
|
|
8058
10613
|
client.close();
|
|
8059
|
-
if (!filePath || !
|
|
10614
|
+
if (!filePath || !fs13.existsSync(filePath)) {
|
|
8060
10615
|
printer_default.error(`Log file not found: ${filePath}`);
|
|
8061
10616
|
process.exit(1);
|
|
8062
10617
|
}
|
|
@@ -8067,18 +10622,18 @@ async function handleLogs(args, follow) {
|
|
|
8067
10622
|
}
|
|
8068
10623
|
}
|
|
8069
10624
|
function printTail(filePath, lines) {
|
|
8070
|
-
const content =
|
|
10625
|
+
const content = fs13.readFileSync(filePath, "utf-8");
|
|
8071
10626
|
const allLines = content.split("\n");
|
|
8072
10627
|
const tail = allLines.slice(-lines).join("\n");
|
|
8073
10628
|
process.stdout.write(tail);
|
|
8074
10629
|
if (!tail.endsWith("\n")) process.stdout.write("\n");
|
|
8075
10630
|
}
|
|
8076
10631
|
async function followFile(filePath) {
|
|
8077
|
-
if (
|
|
8078
|
-
let fileSize =
|
|
10632
|
+
if (fs13.existsSync(filePath)) printTail(filePath, 20);
|
|
10633
|
+
let fileSize = fs13.existsSync(filePath) ? fs13.statSync(filePath).size : 0;
|
|
8079
10634
|
let watcher = null;
|
|
8080
10635
|
const openStream = () => {
|
|
8081
|
-
const stream =
|
|
10636
|
+
const stream = fs13.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
|
|
8082
10637
|
stream.on("data", (chunk) => {
|
|
8083
10638
|
process.stdout.write(chunk);
|
|
8084
10639
|
fileSize += Buffer.byteLength(chunk, "utf-8");
|
|
@@ -8086,9 +10641,9 @@ async function followFile(filePath) {
|
|
|
8086
10641
|
stream.on("error", () => {
|
|
8087
10642
|
});
|
|
8088
10643
|
};
|
|
8089
|
-
watcher =
|
|
10644
|
+
watcher = fs13.watch(filePath, { persistent: true }, (event2) => {
|
|
8090
10645
|
if (event2 === "change") {
|
|
8091
|
-
const stat =
|
|
10646
|
+
const stat = fs13.existsSync(filePath) ? fs13.statSync(filePath) : null;
|
|
8092
10647
|
if (!stat || stat.size < fileSize) {
|
|
8093
10648
|
fileSize = 0;
|
|
8094
10649
|
}
|
|
@@ -8247,16 +10802,17 @@ async function handleRestart(args) {
|
|
|
8247
10802
|
}
|
|
8248
10803
|
|
|
8249
10804
|
// src/cli/subcommand/handlers/deviceCommand.ts
|
|
8250
|
-
import
|
|
10805
|
+
import pico12 from "picocolors";
|
|
8251
10806
|
|
|
8252
10807
|
// src/devices/removeDevice.ts
|
|
8253
10808
|
import pico10 from "picocolors";
|
|
8254
10809
|
var YES_ANSWER2 = /^y(es)?$/i;
|
|
8255
10810
|
var NO_TERMINAL_MESSAGE2 = "pinggy device remove asks before it removes the device. Run it in a terminal, or add -f to remove without asking.";
|
|
8256
|
-
function machineDeviceRemoveDependencies(background) {
|
|
10811
|
+
function machineDeviceRemoveDependencies(background, bootEntry) {
|
|
8257
10812
|
return {
|
|
8258
10813
|
background,
|
|
8259
10814
|
foreground: machineForegroundStopDependencies(),
|
|
10815
|
+
bootEntry,
|
|
8260
10816
|
clearIdentity: clearDeviceIdentity,
|
|
8261
10817
|
isInteractive: isInteractiveTerminal,
|
|
8262
10818
|
prompter: terminalPrompter,
|
|
@@ -8270,11 +10826,12 @@ async function readActivity(dependencies) {
|
|
|
8270
10826
|
return {
|
|
8271
10827
|
identity: dependencies.background.readIdentity(),
|
|
8272
10828
|
background: reading && isAgentRunning(reading.status) ? reading : null,
|
|
8273
|
-
foreground: dependencies.background.readForegroundAgent()
|
|
10829
|
+
foreground: dependencies.background.readForegroundAgent(),
|
|
10830
|
+
autostart: dependencies.bootEntry.read().present
|
|
8274
10831
|
};
|
|
8275
10832
|
}
|
|
8276
10833
|
function describeActivity(activity) {
|
|
8277
|
-
const { identity, background, foreground } = activity;
|
|
10834
|
+
const { identity, background, foreground, autostart } = activity;
|
|
8278
10835
|
const lines = [];
|
|
8279
10836
|
if (identity) {
|
|
8280
10837
|
const deviceAgentId = identity.device_agent_id ?? "(id not yet assigned)";
|
|
@@ -8291,6 +10848,9 @@ function describeActivity(activity) {
|
|
|
8291
10848
|
} else {
|
|
8292
10849
|
lines.push("The device is not connected now.");
|
|
8293
10850
|
}
|
|
10851
|
+
if (autostart) {
|
|
10852
|
+
lines.push("Removing it also turns off autostart.");
|
|
10853
|
+
}
|
|
8294
10854
|
return lines;
|
|
8295
10855
|
}
|
|
8296
10856
|
async function confirmed(options, dependencies) {
|
|
@@ -8326,6 +10886,175 @@ async function runDeviceRemove(options, dependencies) {
|
|
|
8326
10886
|
dependencies.printSuccess("Local device credential removed.");
|
|
8327
10887
|
dependencies.print(pico10.gray("The device still exists in the dashboard. Delete it there to revoke it."));
|
|
8328
10888
|
}
|
|
10889
|
+
if (activity.autostart) {
|
|
10890
|
+
try {
|
|
10891
|
+
dependencies.bootEntry.remove();
|
|
10892
|
+
} catch (err) {
|
|
10893
|
+
dependencies.printError(errorMessage(err));
|
|
10894
|
+
return EXIT_FAILED;
|
|
10895
|
+
}
|
|
10896
|
+
dependencies.printSuccess("Autostart is off.");
|
|
10897
|
+
}
|
|
10898
|
+
return EXIT_OK;
|
|
10899
|
+
}
|
|
10900
|
+
|
|
10901
|
+
// src/devices/autostart.ts
|
|
10902
|
+
import os13 from "os";
|
|
10903
|
+
import pico11 from "picocolors";
|
|
10904
|
+
var AutostartVerb = {
|
|
10905
|
+
On: "on",
|
|
10906
|
+
Off: "off",
|
|
10907
|
+
Status: "status"
|
|
10908
|
+
};
|
|
10909
|
+
var NOT_ENROLLED_MESSAGE = "This machine is not enrolled. Sign it in first: pinggy device login";
|
|
10910
|
+
var NO_SAVED_AGENT_MESSAGE = "The device agent does not run in the background, so a restart would leave this device offline.";
|
|
10911
|
+
var START_AGENT_QUESTION = "Start it now, and each time this computer starts? [Y/n] ";
|
|
10912
|
+
var NO_ANSWER3 = /^n/i;
|
|
10913
|
+
function machineBootEntryDependencies() {
|
|
10914
|
+
const context = machineServiceInstallContext();
|
|
10915
|
+
return {
|
|
10916
|
+
platform: context.platform,
|
|
10917
|
+
read: () => readBootEntry(context.platform),
|
|
10918
|
+
program: () => serviceProgramPath(context),
|
|
10919
|
+
refusal: () => serviceInstallRefusal(context),
|
|
10920
|
+
startsBeforeSignIn: () => startsBeforeSignIn(context.platform),
|
|
10921
|
+
username: () => os13.userInfo().username,
|
|
10922
|
+
install: (program) => installBootEntry(program, context.platform),
|
|
10923
|
+
remove: () => removeBootEntry(context.platform)
|
|
10924
|
+
};
|
|
10925
|
+
}
|
|
10926
|
+
function machineAutostartDependencies(background, bootEntry, startAgent) {
|
|
10927
|
+
return {
|
|
10928
|
+
background,
|
|
10929
|
+
bootEntry,
|
|
10930
|
+
startAgent,
|
|
10931
|
+
isInteractive: isInteractiveTerminal,
|
|
10932
|
+
prompter: terminalPrompter,
|
|
10933
|
+
print: (message) => printer_default.print(message),
|
|
10934
|
+
printSuccess: (message) => printer_default.success(message),
|
|
10935
|
+
printError: (message) => printer_default.error(message)
|
|
10936
|
+
};
|
|
10937
|
+
}
|
|
10938
|
+
function describeBootStart(bootEntry) {
|
|
10939
|
+
return bootEntry.startsBeforeSignIn() ? "each time this computer starts" : "each time you sign in to this computer";
|
|
10940
|
+
}
|
|
10941
|
+
function isAutostartOn(background, bootEntry) {
|
|
10942
|
+
return background.hasSavedAgent() && bootEntry.read().present;
|
|
10943
|
+
}
|
|
10944
|
+
function describeAutostartRow(on, bootEntry) {
|
|
10945
|
+
if (on) {
|
|
10946
|
+
return `on, comes online ${describeBootStart(bootEntry)}`;
|
|
10947
|
+
}
|
|
10948
|
+
return `${pico11.gray("off")}. To turn it on, run: ${AUTOSTART_ON_COMMAND}`;
|
|
10949
|
+
}
|
|
10950
|
+
function printLingerHint(dependencies) {
|
|
10951
|
+
const { bootEntry } = dependencies;
|
|
10952
|
+
if (bootEntry.platform === "linux" && !bootEntry.startsBeforeSignIn()) {
|
|
10953
|
+
dependencies.print(`To bring it online before anyone signs in, run: loginctl enable-linger ${bootEntry.username()}`);
|
|
10954
|
+
}
|
|
10955
|
+
}
|
|
10956
|
+
async function startAgentAfterAsking(dependencies) {
|
|
10957
|
+
const foreground = dependencies.background.readForegroundAgent();
|
|
10958
|
+
if (foreground) {
|
|
10959
|
+
dependencies.printError(`${foregroundAgentRefusal(foreground)} Then run: ${AUTOSTART_ON_COMMAND}`);
|
|
10960
|
+
return EXIT_FAILED;
|
|
10961
|
+
}
|
|
10962
|
+
if (!dependencies.isInteractive()) {
|
|
10963
|
+
dependencies.printError([
|
|
10964
|
+
NO_SAVED_AGENT_MESSAGE,
|
|
10965
|
+
"Start it first, then run this command again:",
|
|
10966
|
+
" pinggy device start",
|
|
10967
|
+
` ${AUTOSTART_ON_COMMAND}`
|
|
10968
|
+
].join("\n"));
|
|
10969
|
+
return EXIT_FAILED;
|
|
10970
|
+
}
|
|
10971
|
+
dependencies.print(NO_SAVED_AGENT_MESSAGE);
|
|
10972
|
+
let answer;
|
|
10973
|
+
try {
|
|
10974
|
+
answer = await dependencies.prompter.ask(START_AGENT_QUESTION);
|
|
10975
|
+
} catch (err) {
|
|
10976
|
+
if (!isCtrlCAtPrompt(err)) throw err;
|
|
10977
|
+
dependencies.print(pico11.yellow("Cancelled. Nothing changed."));
|
|
10978
|
+
return EXIT_FAILED;
|
|
10979
|
+
}
|
|
10980
|
+
if (NO_ANSWER3.test(answer.trim())) {
|
|
10981
|
+
dependencies.print("Nothing changed.");
|
|
10982
|
+
return EXIT_OK;
|
|
10983
|
+
}
|
|
10984
|
+
const exitCode = await dependencies.startAgent();
|
|
10985
|
+
return exitCode === EXIT_OK ? null : exitCode;
|
|
10986
|
+
}
|
|
10987
|
+
async function runAutostartOn(dependencies) {
|
|
10988
|
+
const { background, bootEntry } = dependencies;
|
|
10989
|
+
if (!background.readIdentity()?.token) {
|
|
10990
|
+
dependencies.printError(NOT_ENROLLED_MESSAGE);
|
|
10991
|
+
return EXIT_FAILED;
|
|
10992
|
+
}
|
|
10993
|
+
const refusal = bootEntry.refusal();
|
|
10994
|
+
if (refusal) {
|
|
10995
|
+
dependencies.printError(refusal);
|
|
10996
|
+
return EXIT_FAILED;
|
|
10997
|
+
}
|
|
10998
|
+
let agentStarted = false;
|
|
10999
|
+
if (!background.hasSavedAgent()) {
|
|
11000
|
+
const stopped = await startAgentAfterAsking(dependencies);
|
|
11001
|
+
if (stopped !== null) {
|
|
11002
|
+
return stopped;
|
|
11003
|
+
}
|
|
11004
|
+
agentStarted = true;
|
|
11005
|
+
}
|
|
11006
|
+
const program = bootEntry.program();
|
|
11007
|
+
const reading = bootEntry.read();
|
|
11008
|
+
if (reading.present && reading.program !== null && sameProgram(bootEntry.platform, reading.program, program)) {
|
|
11009
|
+
const state = agentStarted ? "on" : "already on";
|
|
11010
|
+
dependencies.print(`Autostart is ${state}. This device comes online ${describeBootStart(bootEntry)}.`);
|
|
11011
|
+
printLingerHint(dependencies);
|
|
11012
|
+
return EXIT_OK;
|
|
11013
|
+
}
|
|
11014
|
+
try {
|
|
11015
|
+
bootEntry.install(program);
|
|
11016
|
+
} catch (err) {
|
|
11017
|
+
dependencies.printError(errorMessage(err));
|
|
11018
|
+
return EXIT_FAILED;
|
|
11019
|
+
}
|
|
11020
|
+
dependencies.printSuccess(`Autostart is on. This device comes online ${describeBootStart(bootEntry)}.`);
|
|
11021
|
+
printLingerHint(dependencies);
|
|
11022
|
+
return EXIT_OK;
|
|
11023
|
+
}
|
|
11024
|
+
async function runAutostartOff(dependencies) {
|
|
11025
|
+
if (!dependencies.bootEntry.read().present) {
|
|
11026
|
+
dependencies.print("Autostart is already off.");
|
|
11027
|
+
return EXIT_OK;
|
|
11028
|
+
}
|
|
11029
|
+
try {
|
|
11030
|
+
dependencies.bootEntry.remove();
|
|
11031
|
+
} catch (err) {
|
|
11032
|
+
dependencies.printError(errorMessage(err));
|
|
11033
|
+
return EXIT_FAILED;
|
|
11034
|
+
}
|
|
11035
|
+
dependencies.printSuccess("Autostart is off.");
|
|
11036
|
+
const reading = await readBackgroundAgent(dependencies.background);
|
|
11037
|
+
if (reading && isAgentRunning(reading.status)) {
|
|
11038
|
+
dependencies.print("This device stays online until this computer restarts. To take it offline now, run: pinggy device stop");
|
|
11039
|
+
}
|
|
11040
|
+
return EXIT_OK;
|
|
11041
|
+
}
|
|
11042
|
+
function runAutostartStatus(dependencies) {
|
|
11043
|
+
const { background, bootEntry } = dependencies;
|
|
11044
|
+
if (!background.readIdentity()?.token) {
|
|
11045
|
+
dependencies.print(pico11.yellow("This machine is not enrolled. Run: pinggy device login"));
|
|
11046
|
+
if (bootEntry.read().present) {
|
|
11047
|
+
dependencies.print(`pinggy still starts ${describeBootStart(bootEntry)}. To stop that, run: ${AUTOSTART_OFF_COMMAND}`);
|
|
11048
|
+
}
|
|
11049
|
+
return EXIT_OK;
|
|
11050
|
+
}
|
|
11051
|
+
if (isAutostartOn(background, bootEntry)) {
|
|
11052
|
+
dependencies.print(`Autostart is on. This device comes online ${describeBootStart(bootEntry)}.`);
|
|
11053
|
+
printLingerHint(dependencies);
|
|
11054
|
+
return EXIT_OK;
|
|
11055
|
+
}
|
|
11056
|
+
dependencies.print("Autostart is off. After a restart, this device stays offline.");
|
|
11057
|
+
dependencies.print(`To turn it on, run: ${AUTOSTART_ON_COMMAND}`);
|
|
8329
11058
|
return EXIT_OK;
|
|
8330
11059
|
}
|
|
8331
11060
|
|
|
@@ -8356,7 +11085,7 @@ function resolveConnectTarget(flagToken, environmentToken, manage, stored) {
|
|
|
8356
11085
|
}
|
|
8357
11086
|
return null;
|
|
8358
11087
|
}
|
|
8359
|
-
async function handleDevice(args, background = machineBackgroundAgentDependencies()) {
|
|
11088
|
+
async function handleDevice(args, background = machineBackgroundAgentDependencies(), fileAccess = machineFileAccessDependencies(), bootEntry = machineBootEntryDependencies()) {
|
|
8360
11089
|
const environmentToken = takeEnvironmentToken();
|
|
8361
11090
|
if (args.length === 0) {
|
|
8362
11091
|
printDeviceHelp();
|
|
@@ -8371,30 +11100,39 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
|
|
|
8371
11100
|
process.exit(1);
|
|
8372
11101
|
}
|
|
8373
11102
|
const inBackground = !values.foreground;
|
|
11103
|
+
const fileManager = parseFilesFlag(values.files);
|
|
11104
|
+
if (fileManager === null) {
|
|
11105
|
+
printer_default.error(INVALID_FILES_FLAG_MESSAGE);
|
|
11106
|
+
process.exit(1);
|
|
11107
|
+
}
|
|
8374
11108
|
switch (verb) {
|
|
8375
11109
|
case DeviceVerb.Login:
|
|
8376
|
-
exitUnlessOk(await handleDeviceLogin(
|
|
11110
|
+
exitUnlessOk(await handleDeviceLogin(
|
|
11111
|
+
{ manage: values.manage, name: values.name, fileManager },
|
|
11112
|
+
inBackground,
|
|
11113
|
+
background
|
|
11114
|
+
));
|
|
8377
11115
|
return;
|
|
8378
11116
|
case DeviceVerb.Connect:
|
|
8379
11117
|
case DeviceVerb.Start:
|
|
8380
|
-
exitUnlessOk(await handleDeviceConnect(
|
|
8381
|
-
values.token,
|
|
11118
|
+
exitUnlessOk(await handleDeviceConnect({
|
|
11119
|
+
flagToken: values.token,
|
|
8382
11120
|
environmentToken,
|
|
8383
|
-
values.manage,
|
|
11121
|
+
manage: values.manage,
|
|
8384
11122
|
inBackground,
|
|
8385
|
-
|
|
8386
|
-
));
|
|
11123
|
+
fileManager
|
|
11124
|
+
}, background, fileAccess));
|
|
8387
11125
|
return;
|
|
8388
11126
|
case DeviceVerb.Stop:
|
|
8389
11127
|
exitUnlessOk(await stopAgentInBackground(background));
|
|
8390
11128
|
return;
|
|
8391
11129
|
case DeviceVerb.Status:
|
|
8392
|
-
await handleDeviceStatus(background);
|
|
11130
|
+
await handleDeviceStatus(background, bootEntry);
|
|
8393
11131
|
return;
|
|
8394
11132
|
case DeviceVerb.Remove:
|
|
8395
11133
|
exitUnlessOk(await runDeviceRemove(
|
|
8396
11134
|
{ skipConfirmation: Boolean(values.force) },
|
|
8397
|
-
machineDeviceRemoveDependencies(background)
|
|
11135
|
+
machineDeviceRemoveDependencies(background, bootEntry)
|
|
8398
11136
|
));
|
|
8399
11137
|
return;
|
|
8400
11138
|
default:
|
|
@@ -8402,10 +11140,43 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
|
|
|
8402
11140
|
printDeviceHelp();
|
|
8403
11141
|
return;
|
|
8404
11142
|
}
|
|
8405
|
-
printer_default.error(`Unknown command "${verb}". Valid commands:
|
|
11143
|
+
printer_default.error(`Unknown command "${verb}". Valid commands: ${Object.values(DeviceVerb).join(", ")}.`);
|
|
8406
11144
|
process.exit(1);
|
|
8407
11145
|
}
|
|
8408
11146
|
}
|
|
11147
|
+
async function handleAutostart(args, background = machineBackgroundAgentDependencies(), fileAccess = machineFileAccessDependencies(), bootEntry = machineBootEntryDependencies()) {
|
|
11148
|
+
takeEnvironmentToken();
|
|
11149
|
+
const { values, positionals } = parseCliArgs(cliOptions, args);
|
|
11150
|
+
configureLogger(values);
|
|
11151
|
+
if (values.help || positionals[0] === "help") {
|
|
11152
|
+
printAutostartHelp();
|
|
11153
|
+
return;
|
|
11154
|
+
}
|
|
11155
|
+
const startAgent = () => handleDeviceConnect({
|
|
11156
|
+
flagToken: void 0,
|
|
11157
|
+
environmentToken: void 0,
|
|
11158
|
+
manage: void 0,
|
|
11159
|
+
inBackground: true,
|
|
11160
|
+
fileManager: void 0
|
|
11161
|
+
}, background, fileAccess);
|
|
11162
|
+
exitUnlessOk(await runAutostartVerb(
|
|
11163
|
+
positionals[0],
|
|
11164
|
+
machineAutostartDependencies(background, bootEntry, startAgent)
|
|
11165
|
+
));
|
|
11166
|
+
}
|
|
11167
|
+
async function runAutostartVerb(word, dependencies) {
|
|
11168
|
+
switch (word ?? AutostartVerb.Status) {
|
|
11169
|
+
case AutostartVerb.On:
|
|
11170
|
+
return runAutostartOn(dependencies);
|
|
11171
|
+
case AutostartVerb.Off:
|
|
11172
|
+
return runAutostartOff(dependencies);
|
|
11173
|
+
case AutostartVerb.Status:
|
|
11174
|
+
return runAutostartStatus(dependencies);
|
|
11175
|
+
default:
|
|
11176
|
+
dependencies.printError(`Unknown autostart command "${word}". Valid commands: ${Object.values(AutostartVerb).join(", ")}.`);
|
|
11177
|
+
return EXIT_FAILED;
|
|
11178
|
+
}
|
|
11179
|
+
}
|
|
8409
11180
|
function exitUnlessOk(exitCode) {
|
|
8410
11181
|
if (exitCode !== EXIT_OK) {
|
|
8411
11182
|
process.exit(exitCode);
|
|
@@ -8436,46 +11207,56 @@ function mayRunInBackground(background) {
|
|
|
8436
11207
|
}
|
|
8437
11208
|
return true;
|
|
8438
11209
|
}
|
|
8439
|
-
async function handleDeviceLogin(
|
|
11210
|
+
async function handleDeviceLogin(options, inBackground, background) {
|
|
8440
11211
|
if (!inBackground) {
|
|
8441
11212
|
if (!await mayRunInForeground(background)) return EXIT_FAILED;
|
|
8442
|
-
return runDeviceLogin(
|
|
11213
|
+
return runDeviceLogin(options);
|
|
8443
11214
|
}
|
|
8444
11215
|
if (!mayRunInBackground(background)) return EXIT_FAILED;
|
|
8445
|
-
return runDeviceLogin(
|
|
11216
|
+
return runDeviceLogin(options, {
|
|
8446
11217
|
...machineDeviceLoginDependencies(),
|
|
8447
11218
|
runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
|
|
8448
11219
|
});
|
|
8449
11220
|
}
|
|
8450
|
-
async function handleDeviceConnect(
|
|
8451
|
-
const
|
|
11221
|
+
async function handleDeviceConnect(request2, background, fileAccess) {
|
|
11222
|
+
const stored = background.readIdentity();
|
|
11223
|
+
const target = resolveConnectTarget(request2.flagToken, request2.environmentToken, request2.manage, stored);
|
|
8452
11224
|
if (!target) {
|
|
8453
11225
|
printer_default.error("This machine is not enrolled. Sign it in with your email:\n pinggy device login\nOr add a device in the dashboard, then run:\n pinggy device connect --token <TOKEN>");
|
|
8454
11226
|
return EXIT_FAILED;
|
|
8455
11227
|
}
|
|
8456
|
-
|
|
8457
|
-
|
|
8458
|
-
|
|
11228
|
+
const mayRun = request2.inBackground ? mayRunInBackground(background) : await mayRunInForeground(background);
|
|
11229
|
+
if (!mayRun) return EXIT_FAILED;
|
|
11230
|
+
let fileManager;
|
|
11231
|
+
try {
|
|
11232
|
+
fileManager = await settleFileAccess(request2.fileManager, target.token, stored, fileAccess);
|
|
11233
|
+
} catch (err) {
|
|
11234
|
+
if (!isCtrlCAtPrompt(err)) throw err;
|
|
11235
|
+
fileAccess.print(pico12.yellow("Cancelled. Nothing changed."));
|
|
11236
|
+
return EXIT_FAILED;
|
|
11237
|
+
}
|
|
11238
|
+
if (request2.inBackground) {
|
|
11239
|
+
return startAgentInBackground(target, background, { fileManager });
|
|
8459
11240
|
}
|
|
8460
|
-
|
|
8461
|
-
await runDeviceAgent(target.token, target.manage);
|
|
11241
|
+
await runDeviceAgent(target.token, target.manage, { fileManager });
|
|
8462
11242
|
return EXIT_OK;
|
|
8463
11243
|
}
|
|
8464
|
-
async function handleDeviceStatus(background) {
|
|
11244
|
+
async function handleDeviceStatus(background, bootEntry) {
|
|
8465
11245
|
const identity = background.readIdentity();
|
|
8466
11246
|
if (!identity) {
|
|
8467
|
-
printer_default.print(
|
|
11247
|
+
printer_default.print(pico12.yellow("This machine is not enrolled. Run: pinggy device login"));
|
|
8468
11248
|
return;
|
|
8469
11249
|
}
|
|
8470
11250
|
const reading = await readBackgroundAgent(background);
|
|
8471
11251
|
const foreground = background.readForegroundAgent();
|
|
8472
11252
|
const daemonFound = background.findDaemon() !== null;
|
|
8473
11253
|
printer_default.print(` State ${describeDeviceState(reading, daemonFound, foreground)}`);
|
|
8474
|
-
printer_default.print(` Device id ${identity.device_agent_id ??
|
|
11254
|
+
printer_default.print(` Device id ${identity.device_agent_id ?? pico12.gray("not yet assigned")}`);
|
|
8475
11255
|
printer_default.print(` Server ${identity.server}`);
|
|
8476
11256
|
printer_default.print(` Token ${maskToken(identity.token)}`);
|
|
8477
|
-
printer_default.print(` Enrolled ${identity.enrolled_at ??
|
|
8478
|
-
printer_default.print(` Autostart ${background
|
|
11257
|
+
printer_default.print(` Enrolled ${identity.enrolled_at ?? pico12.gray("never")}`);
|
|
11258
|
+
printer_default.print(` Autostart ${describeAutostartRow(isAutostartOn(background, bootEntry), bootEntry)}`);
|
|
11259
|
+
printer_default.print(` Files ${describeFileAccess(identity)}`);
|
|
8479
11260
|
if (foreground) {
|
|
8480
11261
|
printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
|
|
8481
11262
|
}
|
|
@@ -8698,6 +11479,9 @@ async function handleSubcommand(rawArgs) {
|
|
|
8698
11479
|
case Subcommand.Update:
|
|
8699
11480
|
await handleUpdate(rest);
|
|
8700
11481
|
return;
|
|
11482
|
+
case Subcommand.Autostart:
|
|
11483
|
+
await handleAutostart(rest);
|
|
11484
|
+
return;
|
|
8701
11485
|
}
|
|
8702
11486
|
}
|
|
8703
11487
|
function handleConfig(args) {
|
|
@@ -8920,12 +11704,12 @@ async function initRemoteManagementBackground(values) {
|
|
|
8920
11704
|
}
|
|
8921
11705
|
|
|
8922
11706
|
// src/daemon/lifecycle/daemonChild.ts
|
|
8923
|
-
import
|
|
11707
|
+
import fs17 from "fs";
|
|
8924
11708
|
|
|
8925
11709
|
// src/daemon/ipc/ipcServer.ts
|
|
8926
11710
|
import http from "http";
|
|
8927
|
-
import
|
|
8928
|
-
import
|
|
11711
|
+
import fs15 from "fs";
|
|
11712
|
+
import path8 from "path";
|
|
8929
11713
|
import { WebSocketServer, WebSocket as WebSocket4 } from "ws";
|
|
8930
11714
|
|
|
8931
11715
|
// src/daemon/ws/wsProtocol.ts
|
|
@@ -8952,17 +11736,17 @@ function parseClientMessage(raw) {
|
|
|
8952
11736
|
}
|
|
8953
11737
|
|
|
8954
11738
|
// src/daemon/lifecycle/stateStore.ts
|
|
8955
|
-
import
|
|
8956
|
-
import
|
|
11739
|
+
import fs14 from "fs";
|
|
11740
|
+
import path7 from "path";
|
|
8957
11741
|
var STATE_FILENAME = "daemon-state.json";
|
|
8958
11742
|
function getStatePath() {
|
|
8959
|
-
return
|
|
11743
|
+
return path7.join(getPinggyConfigDir(), STATE_FILENAME);
|
|
8960
11744
|
}
|
|
8961
11745
|
function loadDaemonState() {
|
|
8962
11746
|
const statePath = getStatePath();
|
|
8963
11747
|
try {
|
|
8964
|
-
if (!
|
|
8965
|
-
const raw =
|
|
11748
|
+
if (!fs14.existsSync(statePath)) return null;
|
|
11749
|
+
const raw = fs14.readFileSync(statePath, "utf-8");
|
|
8966
11750
|
const state = JSON.parse(raw);
|
|
8967
11751
|
if (!Array.isArray(state.tunnels)) return null;
|
|
8968
11752
|
return state;
|
|
@@ -8976,8 +11760,8 @@ function persistDaemonState(state) {
|
|
|
8976
11760
|
const tmpPath = statePath + ".tmp";
|
|
8977
11761
|
try {
|
|
8978
11762
|
state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
|
|
8979
|
-
|
|
8980
|
-
|
|
11763
|
+
fs14.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
|
|
11764
|
+
fs14.renameSync(tmpPath, statePath);
|
|
8981
11765
|
} catch (err) {
|
|
8982
11766
|
logger.error("Failed to persist daemon state", { error: errorMessage(err) });
|
|
8983
11767
|
}
|
|
@@ -8985,8 +11769,8 @@ function persistDaemonState(state) {
|
|
|
8985
11769
|
function clearDaemonState() {
|
|
8986
11770
|
const statePath = getStatePath();
|
|
8987
11771
|
try {
|
|
8988
|
-
if (
|
|
8989
|
-
|
|
11772
|
+
if (fs14.existsSync(statePath)) {
|
|
11773
|
+
fs14.unlinkSync(statePath);
|
|
8990
11774
|
}
|
|
8991
11775
|
} catch {
|
|
8992
11776
|
}
|
|
@@ -9162,8 +11946,8 @@ var IPCServer = class {
|
|
|
9162
11946
|
if (n) activeNames.add(n);
|
|
9163
11947
|
}
|
|
9164
11948
|
for (const file of files) {
|
|
9165
|
-
const filePath =
|
|
9166
|
-
const stat =
|
|
11949
|
+
const filePath = path8.join(logDir, file);
|
|
11950
|
+
const stat = fs15.statSync(filePath);
|
|
9167
11951
|
const parsed = parseTunnelLogFilename(file);
|
|
9168
11952
|
if (!parsed) continue;
|
|
9169
11953
|
const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
|
|
@@ -9622,7 +12406,7 @@ var SessionTracker = class {
|
|
|
9622
12406
|
};
|
|
9623
12407
|
|
|
9624
12408
|
// src/daemon/deviceAgentHost.ts
|
|
9625
|
-
var
|
|
12409
|
+
var NOT_ENROLLED_MESSAGE2 = "This machine is not enrolled. Sign it in first: pinggy device login";
|
|
9626
12410
|
function stoppedStatus() {
|
|
9627
12411
|
return {
|
|
9628
12412
|
state: DeviceAgentState.Stopped,
|
|
@@ -9662,7 +12446,7 @@ var DeviceAgentHost = class {
|
|
|
9662
12446
|
}
|
|
9663
12447
|
const identity = this.dependencies.readIdentity();
|
|
9664
12448
|
if (!identity?.token) {
|
|
9665
|
-
return newErrorResponse(ErrorCode.DeviceNotEnrolled,
|
|
12449
|
+
return newErrorResponse(ErrorCode.DeviceNotEnrolled, NOT_ENROLLED_MESSAGE2);
|
|
9666
12450
|
}
|
|
9667
12451
|
const current = this.current;
|
|
9668
12452
|
if (current && current.token === identity.token && current.server === identity.server) {
|
|
@@ -9809,11 +12593,11 @@ function machineDeviceAgentHostDependencies(port, record) {
|
|
|
9809
12593
|
}
|
|
9810
12594
|
|
|
9811
12595
|
// src/daemon/lifecycle/daemonLock.ts
|
|
9812
|
-
import
|
|
12596
|
+
import fs16 from "fs";
|
|
9813
12597
|
var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
|
|
9814
12598
|
function readLock(lockPath) {
|
|
9815
12599
|
try {
|
|
9816
|
-
const record = JSON.parse(
|
|
12600
|
+
const record = JSON.parse(fs16.readFileSync(lockPath, "utf-8"));
|
|
9817
12601
|
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
9818
12602
|
} catch {
|
|
9819
12603
|
return null;
|
|
@@ -9821,7 +12605,7 @@ function readLock(lockPath) {
|
|
|
9821
12605
|
}
|
|
9822
12606
|
function isUnreadableLockOld(lockPath) {
|
|
9823
12607
|
try {
|
|
9824
|
-
return Date.now() -
|
|
12608
|
+
return Date.now() - fs16.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
|
|
9825
12609
|
} catch {
|
|
9826
12610
|
return true;
|
|
9827
12611
|
}
|
|
@@ -9832,7 +12616,7 @@ function isStale(lockPath, holder) {
|
|
|
9832
12616
|
}
|
|
9833
12617
|
function createLock(lockPath, record) {
|
|
9834
12618
|
try {
|
|
9835
|
-
|
|
12619
|
+
fs16.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
|
|
9836
12620
|
return true;
|
|
9837
12621
|
} catch (err) {
|
|
9838
12622
|
if (err.code === "EEXIST") return false;
|
|
@@ -9852,13 +12636,13 @@ function acquireDaemonLock() {
|
|
|
9852
12636
|
if (holder?.pid === process.pid) return true;
|
|
9853
12637
|
if (!isStale(lockPath, holder)) return false;
|
|
9854
12638
|
logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
|
|
9855
|
-
|
|
12639
|
+
fs16.rmSync(lockPath, { force: true });
|
|
9856
12640
|
return createLock(lockPath, record);
|
|
9857
12641
|
}
|
|
9858
12642
|
function releaseDaemonLock() {
|
|
9859
12643
|
const lockPath = getDaemonLockPath();
|
|
9860
12644
|
if (readLock(lockPath)?.pid === process.pid) {
|
|
9861
|
-
|
|
12645
|
+
fs16.rmSync(lockPath, { force: true });
|
|
9862
12646
|
}
|
|
9863
12647
|
}
|
|
9864
12648
|
|
|
@@ -9882,14 +12666,14 @@ function writeDaemonInfo(info) {
|
|
|
9882
12666
|
ensurePinggyConfigDir();
|
|
9883
12667
|
const infoPath = getDaemonInfoPath();
|
|
9884
12668
|
const tmpPath = infoPath + ".tmp";
|
|
9885
|
-
|
|
9886
|
-
|
|
12669
|
+
fs17.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
|
|
12670
|
+
fs17.renameSync(tmpPath, infoPath);
|
|
9887
12671
|
}
|
|
9888
12672
|
function removeDaemonInfo() {
|
|
9889
12673
|
try {
|
|
9890
12674
|
const infoPath = getDaemonInfoPath();
|
|
9891
|
-
const info = JSON.parse(
|
|
9892
|
-
if (info.pid === process.pid)
|
|
12675
|
+
const info = JSON.parse(fs17.readFileSync(infoPath, "utf-8"));
|
|
12676
|
+
if (info.pid === process.pid) fs17.unlinkSync(infoPath);
|
|
9893
12677
|
} catch {
|
|
9894
12678
|
}
|
|
9895
12679
|
}
|
|
@@ -10196,7 +12980,7 @@ async function main() {
|
|
|
10196
12980
|
const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
|
|
10197
12981
|
configureLogger(values);
|
|
10198
12982
|
if (values["_daemon-child"]) {
|
|
10199
|
-
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-
|
|
12983
|
+
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-5HZFQLQR.js");
|
|
10200
12984
|
await runDaemonChild2();
|
|
10201
12985
|
return;
|
|
10202
12986
|
}
|
|
@@ -10205,7 +12989,7 @@ async function main() {
|
|
|
10205
12989
|
return;
|
|
10206
12990
|
}
|
|
10207
12991
|
if (values["_update-child"]) {
|
|
10208
|
-
const { runUpdateChild } = await import("./updateChild-
|
|
12992
|
+
const { runUpdateChild } = await import("./updateChild-CEVYCBED.js");
|
|
10209
12993
|
await runUpdateChild();
|
|
10210
12994
|
process.exit(0);
|
|
10211
12995
|
}
|