pinggy 0.6.10 → 0.6.11
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 +9 -4
- package/CLAUDE.md +5 -3
- package/README.md +12 -0
- package/dist/{chunk-AYU3GM4D.js → chunk-RYO5T2JT.js} +35 -19
- package/dist/{chunk-G3NF35JY.js → chunk-W47AYOH2.js} +2819 -278
- package/dist/{daemonChild-4ZZ3YQDL.js → daemonChild-GGG34AOT.js} +2 -2
- package/dist/index.cjs +3070 -378
- package/dist/index.js +3 -3
- package/dist/{main-3D7R75PR.js → main-FCIOVX5I.js} +2 -2
- package/dist/{updateChild-ZOC3VGJL.js → updateChild-RNCLN24C.js} +1 -1
- package/package.json +1 -1
- package/scripts/install/install.ps1 +3 -2
- package/scripts/install/install.sh +13 -7
|
@@ -47,6 +47,7 @@ import {
|
|
|
47
47
|
UpdateError,
|
|
48
48
|
acquireUpdateLock,
|
|
49
49
|
assetNameFor,
|
|
50
|
+
autostartFilePath,
|
|
50
51
|
backgroundInstallKind,
|
|
51
52
|
canReplaceItself,
|
|
52
53
|
createInstallProbe,
|
|
@@ -98,7 +99,7 @@ import {
|
|
|
98
99
|
versionFromTag,
|
|
99
100
|
windowsInstallPaths,
|
|
100
101
|
writeUpdateState
|
|
101
|
-
} from "./chunk-
|
|
102
|
+
} from "./chunk-RYO5T2JT.js";
|
|
102
103
|
import {
|
|
103
104
|
DaemonHost,
|
|
104
105
|
DeviceAgentState,
|
|
@@ -192,6 +193,8 @@ var cliOptions = {
|
|
|
192
193
|
all: { type: "boolean", description: "Start all auto-start tunnels" },
|
|
193
194
|
// `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
|
|
194
195
|
foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
|
|
196
|
+
// `pinggy device login`, `connect` and `start` only: on or off, the answer to the file access question.
|
|
197
|
+
files: { type: "string", description: "Allow file access from the dashboard: on or off", hidden: true },
|
|
195
198
|
// `pinggy update` only.
|
|
196
199
|
check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
|
|
197
200
|
rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
|
|
@@ -2981,10 +2984,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
|
|
|
2981
2984
|
}
|
|
2982
2985
|
function storeJson(config, saveconf) {
|
|
2983
2986
|
if (saveconf) {
|
|
2984
|
-
const
|
|
2987
|
+
const path9 = saveconf;
|
|
2985
2988
|
try {
|
|
2986
|
-
fs4.writeFileSync(
|
|
2987
|
-
logger.info(`Configuration saved to ${
|
|
2989
|
+
fs4.writeFileSync(path9, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
|
|
2990
|
+
logger.info(`Configuration saved to ${path9}`);
|
|
2988
2991
|
} catch (err) {
|
|
2989
2992
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2990
2993
|
logger.error("Error loading configuration:", msg);
|
|
@@ -4434,6 +4437,8 @@ function printDeviceHelp() {
|
|
|
4434
4437
|
console.log(" --token <TOKEN> Device token from the dashboard");
|
|
4435
4438
|
console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
|
|
4436
4439
|
console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
|
|
4440
|
+
console.log(" --files on|off login, connect and start: allow or refuse file access from the");
|
|
4441
|
+
console.log(" dashboard. Without it, the first run in a terminal asks");
|
|
4437
4442
|
console.log(" -f remove only: remove without asking\n");
|
|
4438
4443
|
console.log("Environment:");
|
|
4439
4444
|
console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
|
|
@@ -4466,14 +4471,21 @@ function readDeviceIdentity() {
|
|
|
4466
4471
|
}
|
|
4467
4472
|
}
|
|
4468
4473
|
function writeDeviceIdentity(identity) {
|
|
4474
|
+
const written = keepStoredFileManager(identity, readDeviceIdentity());
|
|
4469
4475
|
ensurePinggyConfigDir();
|
|
4470
4476
|
const filePath = getDeviceConfigPath();
|
|
4471
|
-
fs5.writeFileSync(filePath, JSON.stringify(
|
|
4477
|
+
fs5.writeFileSync(filePath, JSON.stringify(written, null, 2), {
|
|
4472
4478
|
encoding: "utf-8",
|
|
4473
4479
|
mode: SECRET_FILE_MODE
|
|
4474
4480
|
});
|
|
4475
4481
|
fs5.chmodSync(filePath, SECRET_FILE_MODE);
|
|
4476
4482
|
}
|
|
4483
|
+
function keepStoredFileManager(identity, stored) {
|
|
4484
|
+
if (identity.file_manager !== void 0 || !stored || stored.token !== identity.token || typeof stored.file_manager !== "boolean") {
|
|
4485
|
+
return identity;
|
|
4486
|
+
}
|
|
4487
|
+
return { ...identity, file_manager: stored.file_manager };
|
|
4488
|
+
}
|
|
4477
4489
|
function clearDeviceIdentity() {
|
|
4478
4490
|
const filePath = getDeviceConfigPath();
|
|
4479
4491
|
if (!fs5.existsSync(filePath)) {
|
|
@@ -4488,7 +4500,7 @@ function maskToken(token) {
|
|
|
4488
4500
|
|
|
4489
4501
|
// src/devices/deviceAgent.ts
|
|
4490
4502
|
import WebSocket3 from "ws";
|
|
4491
|
-
import
|
|
4503
|
+
import os11 from "os";
|
|
4492
4504
|
|
|
4493
4505
|
// src/devices/envelope.ts
|
|
4494
4506
|
import { randomUUID } from "crypto";
|
|
@@ -4516,8 +4528,8 @@ function request(ch, op, payload) {
|
|
|
4516
4528
|
function response(to, op, payload) {
|
|
4517
4529
|
return { v: PROTOCOL_VERSION, kind: "res", ch: to.ch, op, id: to.id, seq: 0, ts: nowSeconds(), payload };
|
|
4518
4530
|
}
|
|
4519
|
-
function event(ch, op, payload) {
|
|
4520
|
-
return { v: PROTOCOL_VERSION, kind: "event", ch, op, id
|
|
4531
|
+
function event(ch, op, payload, id = "") {
|
|
4532
|
+
return { v: PROTOCOL_VERSION, kind: "event", ch, op, id, seq: 0, ts: nowSeconds(), payload };
|
|
4521
4533
|
}
|
|
4522
4534
|
function parseEnvelope(raw) {
|
|
4523
4535
|
try {
|
|
@@ -4549,6 +4561,12 @@ var WelcomeSchema = z3.object({
|
|
|
4549
4561
|
terminal_idle_timeout_seconds: z3.number().optional(),
|
|
4550
4562
|
// Optional: without it the agent keeps the window brake and never skips output.
|
|
4551
4563
|
terminal_resync: z3.boolean().optional(),
|
|
4564
|
+
// Optional: a dashboard that predates the file manager sends none, and every file request is refused.
|
|
4565
|
+
file_manager_enabled: z3.boolean().optional(),
|
|
4566
|
+
// No default on the agent. Without it, every copy, move and delete answers file_busy rather than running unbounded.
|
|
4567
|
+
file_max_concurrent_operations: z3.number().optional(),
|
|
4568
|
+
// Optional: without it nothing waits, and a copy, move or delete past the running limit answers file_busy.
|
|
4569
|
+
file_max_queued_operations: z3.number().optional(),
|
|
4552
4570
|
// Optional: a dashboard older than these sends neither, and the agent prints only the device id.
|
|
4553
4571
|
email: z3.string().optional(),
|
|
4554
4572
|
device_url: z3.string().optional()
|
|
@@ -4605,6 +4623,19 @@ var printingReporter = {
|
|
|
4605
4623
|
// src/devices/collectors/systemInfo.ts
|
|
4606
4624
|
import os4 from "os";
|
|
4607
4625
|
var UNKNOWN_CPU_MODEL = "unknown";
|
|
4626
|
+
function agentUser() {
|
|
4627
|
+
const uid = process.getuid?.();
|
|
4628
|
+
let username;
|
|
4629
|
+
try {
|
|
4630
|
+
username = os4.userInfo().username || void 0;
|
|
4631
|
+
} catch {
|
|
4632
|
+
username = void 0;
|
|
4633
|
+
}
|
|
4634
|
+
return {
|
|
4635
|
+
...username === void 0 ? {} : { username },
|
|
4636
|
+
...uid === void 0 ? {} : { uid }
|
|
4637
|
+
};
|
|
4638
|
+
}
|
|
4608
4639
|
function collectSystemInfo() {
|
|
4609
4640
|
const cpus = os4.cpus();
|
|
4610
4641
|
return {
|
|
@@ -4618,7 +4649,8 @@ function collectSystemInfo() {
|
|
|
4618
4649
|
// os.cpus() is empty on some Android and container builds.
|
|
4619
4650
|
cpu_model: cpus[0]?.model?.trim() || UNKNOWN_CPU_MODEL,
|
|
4620
4651
|
cpu_cores: cpus.length,
|
|
4621
|
-
total_memory_bytes: os4.totalmem()
|
|
4652
|
+
total_memory_bytes: os4.totalmem(),
|
|
4653
|
+
...agentUser()
|
|
4622
4654
|
};
|
|
4623
4655
|
}
|
|
4624
4656
|
|
|
@@ -5019,99 +5051,2602 @@ async function updateTunnel(config, dependencies) {
|
|
|
5019
5051
|
if (!client) {
|
|
5020
5052
|
return NO_DAEMON;
|
|
5021
5053
|
}
|
|
5022
|
-
const listed = await client.listTunnels();
|
|
5023
|
-
if (!Array.isArray(listed)) {
|
|
5024
|
-
return actionFailed(isErrorResponse(listed) ? listed.message : "The daemon did not list its tunnels.");
|
|
5054
|
+
const listed = await client.listTunnels();
|
|
5055
|
+
if (!Array.isArray(listed)) {
|
|
5056
|
+
return actionFailed(isErrorResponse(listed) ? listed.message : "The daemon did not list its tunnels.");
|
|
5057
|
+
}
|
|
5058
|
+
const running = listed.find((candidate) => candidate.tunnelconfig?.configId === config.configId);
|
|
5059
|
+
if (!running) {
|
|
5060
|
+
return failure(ERROR_TUNNEL_NOT_FOUND, "No tunnel on this machine runs that config.");
|
|
5061
|
+
}
|
|
5062
|
+
return toResult(await client.updateConfigV2(config, true), running.tunnelid);
|
|
5063
|
+
}
|
|
5064
|
+
async function handleTunnelAction(envelope, send, dependencies = machineTunnelActionDependencies) {
|
|
5065
|
+
if (envelope.kind !== "req") {
|
|
5066
|
+
return;
|
|
5067
|
+
}
|
|
5068
|
+
const op = envelope.op;
|
|
5069
|
+
if (op !== OP_START && op !== OP_STOP && op !== OP_RESTART && op !== OP_UPDATE) {
|
|
5070
|
+
send(response(envelope, op, failure(ERROR_UNSUPPORTED_OP, `Unsupported operation: tunnel/${op}`)));
|
|
5071
|
+
return;
|
|
5072
|
+
}
|
|
5073
|
+
const parsed = TunnelActionSchema.safeParse(envelope.payload);
|
|
5074
|
+
if (!parsed.success) {
|
|
5075
|
+
send(response(envelope, op, failure(ERROR_INVALID_PAYLOAD, "The tunnel request could not be read.")));
|
|
5076
|
+
return;
|
|
5077
|
+
}
|
|
5078
|
+
let result;
|
|
5079
|
+
try {
|
|
5080
|
+
result = await perform(op, parsed.data, dependencies);
|
|
5081
|
+
} catch (err) {
|
|
5082
|
+
result = actionFailed(err instanceof Error ? err.message : String(err));
|
|
5083
|
+
}
|
|
5084
|
+
logger.info("Device agent tunnel action", {
|
|
5085
|
+
op,
|
|
5086
|
+
tunnelId: parsed.data.tunnel_id ?? null,
|
|
5087
|
+
configId: parsed.data.config_id ?? null,
|
|
5088
|
+
source: parsed.data.source ?? null,
|
|
5089
|
+
outcome: "error" in result ? result.error.code : "accepted"
|
|
5090
|
+
});
|
|
5091
|
+
send(response(envelope, op, result));
|
|
5092
|
+
}
|
|
5093
|
+
|
|
5094
|
+
// src/devices/reconnect.ts
|
|
5095
|
+
var INITIAL_DELAY_MILLIS = 1e3;
|
|
5096
|
+
var MAX_DELAY_MILLIS = 6e4;
|
|
5097
|
+
var STABLE_CONNECTION_MILLIS = 6e4;
|
|
5098
|
+
var MAX_ATTEMPT = Math.ceil(Math.log2(MAX_DELAY_MILLIS / INITIAL_DELAY_MILLIS));
|
|
5099
|
+
function backoffCeilingMillis(attempt) {
|
|
5100
|
+
const uncapped = INITIAL_DELAY_MILLIS * 2 ** Math.max(0, attempt);
|
|
5101
|
+
return Math.min(uncapped, MAX_DELAY_MILLIS);
|
|
5102
|
+
}
|
|
5103
|
+
function fullJitterMillis(ceilingMillis, random) {
|
|
5104
|
+
return Math.floor(random() * ceilingMillis);
|
|
5105
|
+
}
|
|
5106
|
+
var ReconnectPolicy = class {
|
|
5107
|
+
constructor(options = {}) {
|
|
5108
|
+
this.attemptCount = 0;
|
|
5109
|
+
this.connectedAtMillis = null;
|
|
5110
|
+
this.now = options.now ?? Date.now;
|
|
5111
|
+
this.random = options.random ?? Math.random;
|
|
5112
|
+
}
|
|
5113
|
+
/** Attempts taken since the last reset. Exposed for logging and for tests. */
|
|
5114
|
+
get attempt() {
|
|
5115
|
+
return this.attemptCount;
|
|
5116
|
+
}
|
|
5117
|
+
/** The ceiling the next delay will be drawn from, before jitter. */
|
|
5118
|
+
get nextCeilingMillis() {
|
|
5119
|
+
return backoffCeilingMillis(this.attemptCount);
|
|
5120
|
+
}
|
|
5121
|
+
markConnected() {
|
|
5122
|
+
this.connectedAtMillis = this.now();
|
|
5123
|
+
}
|
|
5124
|
+
/**
|
|
5125
|
+
* Ends the current connection. Returns true when it had held long enough to reset the
|
|
5126
|
+
* schedule, which the caller logs.
|
|
5127
|
+
*/
|
|
5128
|
+
markDisconnected() {
|
|
5129
|
+
const heldMillis = this.connectedAtMillis === null ? 0 : this.now() - this.connectedAtMillis;
|
|
5130
|
+
this.connectedAtMillis = null;
|
|
5131
|
+
const wasStable = heldMillis >= STABLE_CONNECTION_MILLIS;
|
|
5132
|
+
if (wasStable) {
|
|
5133
|
+
this.attemptCount = 0;
|
|
5134
|
+
}
|
|
5135
|
+
return wasStable;
|
|
5136
|
+
}
|
|
5137
|
+
/** The delay before the next dial, and advances the schedule. */
|
|
5138
|
+
nextDelayMillis() {
|
|
5139
|
+
const delay = fullJitterMillis(this.nextCeilingMillis, this.random);
|
|
5140
|
+
this.attemptCount = Math.min(this.attemptCount + 1, MAX_ATTEMPT);
|
|
5141
|
+
return delay;
|
|
5142
|
+
}
|
|
5143
|
+
};
|
|
5144
|
+
|
|
5145
|
+
// src/devices/files/file_schema.ts
|
|
5146
|
+
import { z as z4 } from "zod";
|
|
5147
|
+
var CHANNEL_FILE = "file";
|
|
5148
|
+
var OP_LIST = "list";
|
|
5149
|
+
var OP_STAT = "stat";
|
|
5150
|
+
var OP_DELETE = "delete";
|
|
5151
|
+
var OP_MKDIR = "mkdir";
|
|
5152
|
+
var OP_COPY = "copy";
|
|
5153
|
+
var OP_MOVE = "move";
|
|
5154
|
+
var OP_PROGRESS = "progress";
|
|
5155
|
+
var ERROR_INVALID_PAYLOAD2 = "invalid_payload";
|
|
5156
|
+
var ERROR_UNSUPPORTED_OP2 = "unsupported_op";
|
|
5157
|
+
var ERROR_FILE_MANAGER_DISABLED = "file_manager_disabled";
|
|
5158
|
+
var ERROR_FILE_ACCESS_OFF = "file_access_off";
|
|
5159
|
+
var ERROR_INVALID_PATH = "invalid_path";
|
|
5160
|
+
var ERROR_PATH_NOT_FOUND = "path_not_found";
|
|
5161
|
+
var ERROR_NOT_A_DIRECTORY = "not_a_directory";
|
|
5162
|
+
var ERROR_PERMISSION_DENIED = "permission_denied";
|
|
5163
|
+
var ERROR_FILE_TIMEOUT = "file_timeout";
|
|
5164
|
+
var ERROR_FILE_OPERATION_FAILED = "file_operation_failed";
|
|
5165
|
+
var ERROR_PROTECTED_PATH = "protected_path";
|
|
5166
|
+
var ERROR_MOUNT_POINT = "mount_point";
|
|
5167
|
+
var ERROR_FILE_BUSY = "file_busy";
|
|
5168
|
+
var ERROR_FILE_EXISTS = "file_exists";
|
|
5169
|
+
var ERROR_INVALID_NAME = "invalid_name";
|
|
5170
|
+
var ERROR_INVALID_DESTINATION = "invalid_destination";
|
|
5171
|
+
var ERROR_NO_SPACE = "no_space";
|
|
5172
|
+
var ERROR_SPECIAL_FILE = "special_file";
|
|
5173
|
+
var SORT_BY_NAME = "name";
|
|
5174
|
+
var SORT_BY_SIZE = "size";
|
|
5175
|
+
var SORT_BY_MODIFIED = "modified";
|
|
5176
|
+
var SORT_BY_CREATED = "created";
|
|
5177
|
+
var SORT_ORDER_ASC = "asc";
|
|
5178
|
+
var SORT_ORDER_DESC = "desc";
|
|
5179
|
+
var DEFAULT_LIST_LIMIT = 200;
|
|
5180
|
+
var MAX_LIST_LIMIT = 500;
|
|
5181
|
+
var MAX_PATH_BYTES = 4096;
|
|
5182
|
+
var MAX_NAME_BYTES = 255;
|
|
5183
|
+
var ON_CONFLICT_FAIL = "fail";
|
|
5184
|
+
var ON_CONFLICT_SKIP = "skip";
|
|
5185
|
+
var ON_CONFLICT_KEEP_BOTH = "keep_both";
|
|
5186
|
+
var ON_CONFLICT_REPLACE = "replace";
|
|
5187
|
+
var FileListRequestSchema = z4.object({
|
|
5188
|
+
path: z4.string().optional(),
|
|
5189
|
+
offset: z4.number().int().min(0).optional(),
|
|
5190
|
+
limit: z4.number().int().min(1).max(MAX_LIST_LIMIT).optional(),
|
|
5191
|
+
sort_by: z4.enum([SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED]).optional(),
|
|
5192
|
+
sort_order: z4.enum([SORT_ORDER_ASC, SORT_ORDER_DESC]).optional(),
|
|
5193
|
+
include_hidden: z4.boolean().optional()
|
|
5194
|
+
});
|
|
5195
|
+
var FileStatRequestSchema = z4.object({
|
|
5196
|
+
path: z4.string(),
|
|
5197
|
+
include_hidden: z4.boolean().optional()
|
|
5198
|
+
});
|
|
5199
|
+
var FileDeleteRequestSchema = z4.object({
|
|
5200
|
+
path: z4.string()
|
|
5201
|
+
});
|
|
5202
|
+
var FileMkdirRequestSchema = z4.object({
|
|
5203
|
+
path: z4.string()
|
|
5204
|
+
});
|
|
5205
|
+
var FileCopyRequestSchema = z4.object({
|
|
5206
|
+
source_path: z4.string(),
|
|
5207
|
+
destination_path: z4.string(),
|
|
5208
|
+
on_conflict: z4.enum([ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE]).optional()
|
|
5209
|
+
});
|
|
5210
|
+
function fileError(code, message) {
|
|
5211
|
+
return { error: { code, message } };
|
|
5212
|
+
}
|
|
5213
|
+
|
|
5214
|
+
// src/devices/files/fileSystem.ts
|
|
5215
|
+
import fs6 from "fs";
|
|
5216
|
+
import os6 from "os";
|
|
5217
|
+
import path4 from "path";
|
|
5218
|
+
var machineFileSystem = {
|
|
5219
|
+
readdir: (folder) => fs6.promises.readdir(folder, { withFileTypes: true }),
|
|
5220
|
+
lstat: (target) => fs6.promises.lstat(target),
|
|
5221
|
+
stat: (target) => fs6.promises.stat(target),
|
|
5222
|
+
readlink: (target) => fs6.promises.readlink(target),
|
|
5223
|
+
access: (target, mode) => fs6.promises.access(target, mode),
|
|
5224
|
+
homedir: () => os6.homedir()
|
|
5225
|
+
};
|
|
5226
|
+
var machineFileSystemDependencies = {
|
|
5227
|
+
fs: machineFileSystem,
|
|
5228
|
+
platform: process.platform
|
|
5229
|
+
};
|
|
5230
|
+
var machineFileSystemRemover = {
|
|
5231
|
+
lstat: (target) => fs6.promises.lstat(target, { bigint: true }),
|
|
5232
|
+
stat: (target) => fs6.promises.stat(target, { bigint: true }),
|
|
5233
|
+
readdir: (folder) => fs6.promises.readdir(folder),
|
|
5234
|
+
unlink: (target) => fs6.promises.unlink(target),
|
|
5235
|
+
rmdir: (target) => fs6.promises.rmdir(target),
|
|
5236
|
+
chmod: (target, mode) => fs6.promises.chmod(target, mode),
|
|
5237
|
+
realpath: (target) => fs6.promises.realpath(target)
|
|
5238
|
+
};
|
|
5239
|
+
var machineFileSystemMaker = {
|
|
5240
|
+
mkdir: async (target) => {
|
|
5241
|
+
await fs6.promises.mkdir(target);
|
|
5242
|
+
}
|
|
5243
|
+
};
|
|
5244
|
+
var NEW_FILE_MODE = 384;
|
|
5245
|
+
var CREATE_ONLY_IF_FREE = "wx";
|
|
5246
|
+
var machineFileSystemCopier = {
|
|
5247
|
+
lstat: (target) => fs6.promises.lstat(target, { bigint: true }),
|
|
5248
|
+
stat: (target) => fs6.promises.stat(target, { bigint: true }),
|
|
5249
|
+
realpath: (target) => fs6.promises.realpath(target),
|
|
5250
|
+
readdir: (folder) => fs6.promises.readdir(folder),
|
|
5251
|
+
mkdir: async (target) => {
|
|
5252
|
+
await fs6.promises.mkdir(target);
|
|
5253
|
+
},
|
|
5254
|
+
openToRead: (target) => fs6.promises.open(target, "r"),
|
|
5255
|
+
createFile: (target) => fs6.promises.open(target, CREATE_ONLY_IF_FREE, NEW_FILE_MODE),
|
|
5256
|
+
read: async (handle, buffer) => (await handle.read(buffer, 0, buffer.length, null)).bytesRead,
|
|
5257
|
+
write: async (handle, buffer, length) => {
|
|
5258
|
+
let written = 0;
|
|
5259
|
+
while (written < length) {
|
|
5260
|
+
written += (await handle.write(buffer, written, length - written, null)).bytesWritten;
|
|
5261
|
+
}
|
|
5262
|
+
},
|
|
5263
|
+
close: (handle) => handle.close(),
|
|
5264
|
+
readlink: (target) => fs6.promises.readlink(target),
|
|
5265
|
+
symlink: (linkText, target, type) => fs6.promises.symlink(linkText, target, type),
|
|
5266
|
+
chmod: (target, mode) => fs6.promises.chmod(target, mode),
|
|
5267
|
+
utimes: (target, accessed, modified) => fs6.promises.utimes(target, accessed, modified),
|
|
5268
|
+
rename: (from, to) => fs6.promises.rename(from, to),
|
|
5269
|
+
unlink: (target) => fs6.promises.unlink(target),
|
|
5270
|
+
freeBytes: async (folder) => {
|
|
5271
|
+
const stats = await fs6.promises.statfs(folder, { bigint: true });
|
|
5272
|
+
return stats.bavail * stats.bsize;
|
|
5273
|
+
}
|
|
5274
|
+
};
|
|
5275
|
+
var HIDDEN_NAME_PREFIX = ".";
|
|
5276
|
+
var MILLIS_PER_SECOND = 1e3;
|
|
5277
|
+
function pathsFor(platform3) {
|
|
5278
|
+
return platform3 === "win32" ? path4.win32 : path4.posix;
|
|
5279
|
+
}
|
|
5280
|
+
function pathProblem(requested, paths) {
|
|
5281
|
+
if (requested.includes("\0")) {
|
|
5282
|
+
return "The path holds a NUL byte.";
|
|
5283
|
+
}
|
|
5284
|
+
if (Buffer.byteLength(requested, "utf8") > MAX_PATH_BYTES) {
|
|
5285
|
+
return `The path is longer than ${MAX_PATH_BYTES} bytes.`;
|
|
5286
|
+
}
|
|
5287
|
+
if (!paths.isAbsolute(requested)) {
|
|
5288
|
+
return "The path must be absolute.";
|
|
5289
|
+
}
|
|
5290
|
+
return null;
|
|
5291
|
+
}
|
|
5292
|
+
function nameProblem(name, platform3) {
|
|
5293
|
+
if (name.length === 0) {
|
|
5294
|
+
return "A name is empty.";
|
|
5295
|
+
}
|
|
5296
|
+
if (Buffer.byteLength(name, "utf8") > MAX_NAME_BYTES) {
|
|
5297
|
+
return `A name is longer than ${MAX_NAME_BYTES} bytes.`;
|
|
5298
|
+
}
|
|
5299
|
+
if (name === "." || name === "..") {
|
|
5300
|
+
return "A name cannot be . or ..";
|
|
5301
|
+
}
|
|
5302
|
+
if (name.includes("\0")) {
|
|
5303
|
+
return "A name holds a NUL byte.";
|
|
5304
|
+
}
|
|
5305
|
+
if (name.includes("/") || platform3 === "win32" && name.includes("\\")) {
|
|
5306
|
+
return "A name holds a path separator.";
|
|
5307
|
+
}
|
|
5308
|
+
return null;
|
|
5309
|
+
}
|
|
5310
|
+
var WINDOWS_FORBIDDEN_CHARACTERS = /[:*?"<>|]/;
|
|
5311
|
+
var WINDOWS_TRAILING_DOT_OR_SPACE = /[. ]$/;
|
|
5312
|
+
var WINDOWS_NUMBERED_DEVICES = ["COM", "LPT"];
|
|
5313
|
+
var WINDOWS_DEVICE_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
|
5314
|
+
var WINDOWS_DEVICE_NAMES = /* @__PURE__ */ new Set([
|
|
5315
|
+
"CON",
|
|
5316
|
+
"PRN",
|
|
5317
|
+
"AUX",
|
|
5318
|
+
"NUL",
|
|
5319
|
+
...WINDOWS_NUMBERED_DEVICES.flatMap((device) => WINDOWS_DEVICE_NUMBERS.map((number) => `${device}${number}`))
|
|
5320
|
+
]);
|
|
5321
|
+
var EXTENSION_SEPARATOR = ".";
|
|
5322
|
+
function windowsNameProblem(name, subject = "A folder name") {
|
|
5323
|
+
if (WINDOWS_FORBIDDEN_CHARACTERS.test(name)) {
|
|
5324
|
+
return `${subject} on Windows cannot hold : * ? " < > |`;
|
|
5325
|
+
}
|
|
5326
|
+
if (WINDOWS_TRAILING_DOT_OR_SPACE.test(name)) {
|
|
5327
|
+
return `${subject} on Windows cannot end with a dot or a space.`;
|
|
5328
|
+
}
|
|
5329
|
+
const stem = name.split(EXTENSION_SEPARATOR)[0].toUpperCase();
|
|
5330
|
+
if (WINDOWS_DEVICE_NAMES.has(stem)) {
|
|
5331
|
+
return `${stem} is a device name on Windows.`;
|
|
5332
|
+
}
|
|
5333
|
+
return null;
|
|
5334
|
+
}
|
|
5335
|
+
function isRoot(resolved, paths) {
|
|
5336
|
+
return paths.dirname(resolved) === resolved;
|
|
5337
|
+
}
|
|
5338
|
+
function resolvedItem(requested, paths) {
|
|
5339
|
+
const resolved = paths.resolve(requested);
|
|
5340
|
+
return { path: resolved, parent: paths.dirname(resolved), name: paths.basename(resolved) };
|
|
5341
|
+
}
|
|
5342
|
+
function withTrimmedName(item) {
|
|
5343
|
+
const name = item.name.trim();
|
|
5344
|
+
if (name === item.name || name.length === 0) {
|
|
5345
|
+
return { ...item, name };
|
|
5346
|
+
}
|
|
5347
|
+
return { ...item, name, path: item.path.slice(0, item.path.length - item.name.length) + name };
|
|
5348
|
+
}
|
|
5349
|
+
var MESSAGE_NAME_TAKEN = "A file or folder with this name already exists.";
|
|
5350
|
+
function errorCodeOf(err) {
|
|
5351
|
+
return typeof err === "object" && err !== null && "code" in err && typeof err.code === "string" ? err.code : void 0;
|
|
5352
|
+
}
|
|
5353
|
+
function failureMessage(err, fallback) {
|
|
5354
|
+
return sanitizeErrorMessage(err instanceof Error ? err.message : String(err)) ?? fallback;
|
|
5355
|
+
}
|
|
5356
|
+
function entryTypeOf(stats) {
|
|
5357
|
+
if (stats.isSymbolicLink()) return "symlink";
|
|
5358
|
+
if (stats.isDirectory()) return "directory";
|
|
5359
|
+
if (stats.isFile()) return "file";
|
|
5360
|
+
return "other";
|
|
5361
|
+
}
|
|
5362
|
+
function targetTypeOf(stats) {
|
|
5363
|
+
if (stats.isDirectory()) return "directory";
|
|
5364
|
+
if (stats.isFile()) return "file";
|
|
5365
|
+
return "other";
|
|
5366
|
+
}
|
|
5367
|
+
function epochSeconds(millis) {
|
|
5368
|
+
return Math.floor(millis / MILLIS_PER_SECOND);
|
|
5369
|
+
}
|
|
5370
|
+
function utf8Bytes(value) {
|
|
5371
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
5372
|
+
}
|
|
5373
|
+
async function readLinkTarget(linkPath, reader) {
|
|
5374
|
+
const target = {};
|
|
5375
|
+
try {
|
|
5376
|
+
target.linkTarget = await reader.readlink(linkPath);
|
|
5377
|
+
} catch {
|
|
5378
|
+
}
|
|
5379
|
+
try {
|
|
5380
|
+
target.targetStats = await reader.stat(linkPath);
|
|
5381
|
+
target.targetType = targetTypeOf(target.targetStats);
|
|
5382
|
+
} catch (err) {
|
|
5383
|
+
const code = errorCodeOf(err);
|
|
5384
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
5385
|
+
target.targetType = "missing";
|
|
5386
|
+
}
|
|
5387
|
+
}
|
|
5388
|
+
return target;
|
|
5389
|
+
}
|
|
5390
|
+
var FileCallTimeoutError = class extends Error {
|
|
5391
|
+
};
|
|
5392
|
+
function callTimeoutError(millis) {
|
|
5393
|
+
const seconds = Math.round(millis / MILLIS_PER_SECOND);
|
|
5394
|
+
return new FileCallTimeoutError(`A filesystem call took longer than ${seconds} s.`);
|
|
5395
|
+
}
|
|
5396
|
+
function callWithTimeout(work, millis) {
|
|
5397
|
+
return new Promise((resolve, reject) => {
|
|
5398
|
+
const timer = setTimeout(() => reject(callTimeoutError(millis)), millis);
|
|
5399
|
+
work.then((value) => {
|
|
5400
|
+
clearTimeout(timer);
|
|
5401
|
+
resolve(value);
|
|
5402
|
+
}, (err) => {
|
|
5403
|
+
clearTimeout(timer);
|
|
5404
|
+
reject(err);
|
|
5405
|
+
});
|
|
5406
|
+
});
|
|
5407
|
+
}
|
|
5408
|
+
function withTimeout(work, millis, fallback) {
|
|
5409
|
+
return new Promise((resolve) => {
|
|
5410
|
+
const timer = setTimeout(() => resolve(fallback), millis);
|
|
5411
|
+
work.then((value) => {
|
|
5412
|
+
clearTimeout(timer);
|
|
5413
|
+
resolve(value);
|
|
5414
|
+
}, () => {
|
|
5415
|
+
clearTimeout(timer);
|
|
5416
|
+
resolve(fallback);
|
|
5417
|
+
});
|
|
5418
|
+
});
|
|
5419
|
+
}
|
|
5420
|
+
|
|
5421
|
+
// src/devices/files/fileCallGate.ts
|
|
5422
|
+
var MESSAGE_DRIVE_STOPPED = "A drive on the device stopped answering. Try again once it is back.";
|
|
5423
|
+
var FileCallsStuckError = class extends FileCallTimeoutError {
|
|
5424
|
+
constructor() {
|
|
5425
|
+
super(MESSAGE_DRIVE_STOPPED);
|
|
5426
|
+
}
|
|
5427
|
+
};
|
|
5428
|
+
var FileCallGate = class {
|
|
5429
|
+
constructor(places) {
|
|
5430
|
+
this.places = places;
|
|
5431
|
+
this.running = 0;
|
|
5432
|
+
this.abandoned = 0;
|
|
5433
|
+
/** In arrival order: a Set iterates as it was filled. */
|
|
5434
|
+
this.waiting = /* @__PURE__ */ new Set();
|
|
5435
|
+
if (!Number.isInteger(places) || places < 1) {
|
|
5436
|
+
throw new Error(`The file call gate needs at least 1 place, not ${places}.`);
|
|
5437
|
+
}
|
|
5438
|
+
}
|
|
5439
|
+
/** `work`'s outcome, or a {@link FileCallTimeoutError} once `timeoutMillis` pass from now. */
|
|
5440
|
+
run(work, timeoutMillis) {
|
|
5441
|
+
if (this.isStuck()) {
|
|
5442
|
+
return Promise.reject(new FileCallsStuckError());
|
|
5443
|
+
}
|
|
5444
|
+
return new Promise((resolve, reject) => {
|
|
5445
|
+
let answered = false;
|
|
5446
|
+
let holdsPlace = false;
|
|
5447
|
+
let isAbandoned = false;
|
|
5448
|
+
const answer = (outcome) => {
|
|
5449
|
+
if (!answered) {
|
|
5450
|
+
answered = true;
|
|
5451
|
+
clearTimeout(timer);
|
|
5452
|
+
outcome();
|
|
5453
|
+
}
|
|
5454
|
+
};
|
|
5455
|
+
const call = {
|
|
5456
|
+
begin: () => {
|
|
5457
|
+
holdsPlace = true;
|
|
5458
|
+
this.running += 1;
|
|
5459
|
+
let pending;
|
|
5460
|
+
try {
|
|
5461
|
+
pending = work();
|
|
5462
|
+
} catch (err) {
|
|
5463
|
+
pending = Promise.reject(err);
|
|
5464
|
+
}
|
|
5465
|
+
pending.then((value) => answer(() => resolve(value)), (err) => answer(() => reject(err))).finally(() => this.release(isAbandoned));
|
|
5466
|
+
},
|
|
5467
|
+
refuse: (err) => answer(() => reject(err))
|
|
5468
|
+
};
|
|
5469
|
+
const timer = setTimeout(() => {
|
|
5470
|
+
if (holdsPlace) {
|
|
5471
|
+
isAbandoned = true;
|
|
5472
|
+
this.abandoned += 1;
|
|
5473
|
+
} else {
|
|
5474
|
+
this.waiting.delete(call);
|
|
5475
|
+
}
|
|
5476
|
+
answer(() => reject(callTimeoutError(timeoutMillis)));
|
|
5477
|
+
if (this.isStuck()) {
|
|
5478
|
+
this.refuseWaiting();
|
|
5479
|
+
}
|
|
5480
|
+
}, timeoutMillis);
|
|
5481
|
+
if (this.running < this.places) {
|
|
5482
|
+
call.begin();
|
|
5483
|
+
} else {
|
|
5484
|
+
this.waiting.add(call);
|
|
5485
|
+
}
|
|
5486
|
+
});
|
|
5487
|
+
}
|
|
5488
|
+
release(wasAbandoned) {
|
|
5489
|
+
this.running -= 1;
|
|
5490
|
+
if (wasAbandoned) {
|
|
5491
|
+
this.abandoned -= 1;
|
|
5492
|
+
}
|
|
5493
|
+
for (const call of this.waiting) {
|
|
5494
|
+
if (this.running >= this.places) {
|
|
5495
|
+
return;
|
|
5496
|
+
}
|
|
5497
|
+
this.waiting.delete(call);
|
|
5498
|
+
call.begin();
|
|
5499
|
+
}
|
|
5500
|
+
}
|
|
5501
|
+
isStuck() {
|
|
5502
|
+
return this.abandoned >= this.places;
|
|
5503
|
+
}
|
|
5504
|
+
refuseWaiting() {
|
|
5505
|
+
const refused = [...this.waiting];
|
|
5506
|
+
this.waiting.clear();
|
|
5507
|
+
refused.forEach((call) => call.refuse(new FileCallsStuckError()));
|
|
5508
|
+
}
|
|
5509
|
+
};
|
|
5510
|
+
function gatedReader(reader, gate, timeoutMillis) {
|
|
5511
|
+
return {
|
|
5512
|
+
readdir: (folder) => gate.run(() => reader.readdir(folder), timeoutMillis),
|
|
5513
|
+
lstat: (target) => gate.run(() => reader.lstat(target), timeoutMillis),
|
|
5514
|
+
stat: (target) => gate.run(() => reader.stat(target), timeoutMillis),
|
|
5515
|
+
readlink: (target) => gate.run(() => reader.readlink(target), timeoutMillis),
|
|
5516
|
+
access: (target, mode) => gate.run(() => reader.access(target, mode), timeoutMillis),
|
|
5517
|
+
homedir: () => reader.homedir()
|
|
5518
|
+
};
|
|
5519
|
+
}
|
|
5520
|
+
function gatedRemover(remover, gate, timeoutMillis) {
|
|
5521
|
+
return {
|
|
5522
|
+
lstat: (target) => gate.run(() => remover.lstat(target), timeoutMillis),
|
|
5523
|
+
stat: (target) => gate.run(() => remover.stat(target), timeoutMillis),
|
|
5524
|
+
readdir: (folder) => gate.run(() => remover.readdir(folder), timeoutMillis),
|
|
5525
|
+
unlink: (target) => gate.run(() => remover.unlink(target), timeoutMillis),
|
|
5526
|
+
rmdir: (target) => gate.run(() => remover.rmdir(target), timeoutMillis),
|
|
5527
|
+
chmod: (target, mode) => gate.run(() => remover.chmod(target, mode), timeoutMillis),
|
|
5528
|
+
realpath: (target) => gate.run(() => remover.realpath(target), timeoutMillis)
|
|
5529
|
+
};
|
|
5530
|
+
}
|
|
5531
|
+
function gatedMaker(maker, gate, timeoutMillis) {
|
|
5532
|
+
return {
|
|
5533
|
+
mkdir: (target) => gate.run(() => maker.mkdir(target), timeoutMillis)
|
|
5534
|
+
};
|
|
5535
|
+
}
|
|
5536
|
+
function gatedCopier(copier, gate, timeoutMillis) {
|
|
5537
|
+
return {
|
|
5538
|
+
lstat: (target) => gate.run(() => copier.lstat(target), timeoutMillis),
|
|
5539
|
+
stat: (target) => gate.run(() => copier.stat(target), timeoutMillis),
|
|
5540
|
+
realpath: (target) => gate.run(() => copier.realpath(target), timeoutMillis),
|
|
5541
|
+
readdir: (folder) => gate.run(() => copier.readdir(folder), timeoutMillis),
|
|
5542
|
+
mkdir: (target) => gate.run(() => copier.mkdir(target), timeoutMillis),
|
|
5543
|
+
openToRead: (target) => gate.run(() => copier.openToRead(target), timeoutMillis),
|
|
5544
|
+
createFile: (target) => gate.run(() => copier.createFile(target), timeoutMillis),
|
|
5545
|
+
read: (handle, buffer) => gate.run(() => copier.read(handle, buffer), timeoutMillis),
|
|
5546
|
+
write: (handle, buffer, length) => gate.run(() => copier.write(handle, buffer, length), timeoutMillis),
|
|
5547
|
+
close: (handle) => gate.run(() => copier.close(handle), timeoutMillis),
|
|
5548
|
+
readlink: (target) => gate.run(() => copier.readlink(target), timeoutMillis),
|
|
5549
|
+
symlink: (linkText, target, type) => gate.run(() => copier.symlink(linkText, target, type), timeoutMillis),
|
|
5550
|
+
chmod: (target, mode) => gate.run(() => copier.chmod(target, mode), timeoutMillis),
|
|
5551
|
+
utimes: (target, accessed, modified) => gate.run(
|
|
5552
|
+
() => copier.utimes(target, accessed, modified),
|
|
5553
|
+
timeoutMillis
|
|
5554
|
+
),
|
|
5555
|
+
rename: (from, to) => gate.run(() => copier.rename(from, to), timeoutMillis),
|
|
5556
|
+
unlink: (target) => gate.run(() => copier.unlink(target), timeoutMillis),
|
|
5557
|
+
freeBytes: (folder) => gate.run(() => copier.freeBytes(folder), timeoutMillis)
|
|
5558
|
+
};
|
|
5559
|
+
}
|
|
5560
|
+
|
|
5561
|
+
// src/devices/files/fileCopy.ts
|
|
5562
|
+
import crypto from "crypto";
|
|
5563
|
+
|
|
5564
|
+
// src/devices/files/fileProtectedPaths.ts
|
|
5565
|
+
import os7 from "os";
|
|
5566
|
+
import path5 from "path";
|
|
5567
|
+
var MESSAGE_PINGGY_FOLDER = "Pinggy keeps this folder so the device stays connected.";
|
|
5568
|
+
var MESSAGE_PINGGY_PROGRAM = "Pinggy needs this to keep the device connected.";
|
|
5569
|
+
var MESSAGE_SYSTEM_FOLDER = "This is a system folder.";
|
|
5570
|
+
var MESSAGE_ACCOUNTS_FOLDER = "This folder holds the accounts on this device.";
|
|
5571
|
+
var MESSAGE_ACCOUNT_FOLDER = "This is an account's home folder.";
|
|
5572
|
+
var LINUX_SYSTEM_FOLDERS = ["/bin", "/boot", "/etc", "/lib", "/lib64", "/sbin", "/usr", "/var"];
|
|
5573
|
+
var MACOS_SYSTEM_FOLDERS = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/private"];
|
|
5574
|
+
var WINDOWS_SYSTEM_FOLDER_VARIABLES = [
|
|
5575
|
+
["SystemRoot", "C:\\Windows"],
|
|
5576
|
+
["ProgramFiles", "C:\\Program Files"],
|
|
5577
|
+
["ProgramFiles(x86)", "C:\\Program Files (x86)"],
|
|
5578
|
+
["ProgramData", "C:\\ProgramData"]
|
|
5579
|
+
];
|
|
5580
|
+
var POSIX_ACCOUNTS_FOLDER = "/home";
|
|
5581
|
+
var MACOS_ACCOUNTS_FOLDER = "/Users";
|
|
5582
|
+
var WINDOWS_ACCOUNTS_FOLDER = "C:\\Users";
|
|
5583
|
+
var WINDOWS_PUBLIC_FOLDER_VARIABLE = "PUBLIC";
|
|
5584
|
+
function systemFoldersFor(platform3, environment) {
|
|
5585
|
+
if (platform3 === "win32") {
|
|
5586
|
+
return WINDOWS_SYSTEM_FOLDER_VARIABLES.map(([variable, fallback]) => environment[variable] || fallback);
|
|
5587
|
+
}
|
|
5588
|
+
return platform3 === "darwin" ? MACOS_SYSTEM_FOLDERS : LINUX_SYSTEM_FOLDERS;
|
|
5589
|
+
}
|
|
5590
|
+
function accountsFolderFor(platform3, environment) {
|
|
5591
|
+
if (platform3 === "win32") {
|
|
5592
|
+
const publicFolder = environment[WINDOWS_PUBLIC_FOLDER_VARIABLE];
|
|
5593
|
+
return publicFolder ? path5.win32.dirname(publicFolder) : WINDOWS_ACCOUNTS_FOLDER;
|
|
5594
|
+
}
|
|
5595
|
+
return platform3 === "darwin" ? MACOS_ACCOUNTS_FOLDER : POSIX_ACCOUNTS_FOLDER;
|
|
5596
|
+
}
|
|
5597
|
+
function agentFilesFor(platform3, home, environment, runningProgram, script) {
|
|
5598
|
+
const files = [installerBinaryPath(platform3, home, environment), runningProgram];
|
|
5599
|
+
if (script) {
|
|
5600
|
+
files.push(script);
|
|
5601
|
+
}
|
|
5602
|
+
const autostartFile = autostartFilePath(platform3, home);
|
|
5603
|
+
if (autostartFile) {
|
|
5604
|
+
files.push(autostartFile);
|
|
5605
|
+
}
|
|
5606
|
+
return [...new Set(files)];
|
|
5607
|
+
}
|
|
5608
|
+
function machineProtectedSources() {
|
|
5609
|
+
const home = os7.homedir();
|
|
5610
|
+
const script = isPackagedBinary() ? void 0 : process.argv[1];
|
|
5611
|
+
return {
|
|
5612
|
+
home,
|
|
5613
|
+
configFolder: getPinggyConfigDir(),
|
|
5614
|
+
systemFolders: systemFoldersFor(process.platform, process.env),
|
|
5615
|
+
accountsFolder: accountsFolderFor(process.platform, process.env),
|
|
5616
|
+
agentFiles: agentFilesFor(process.platform, home, process.env, process.execPath, script)
|
|
5617
|
+
};
|
|
5618
|
+
}
|
|
5619
|
+
function identityOf(stats) {
|
|
5620
|
+
return `${stats.dev}:${stats.ino}`;
|
|
5621
|
+
}
|
|
5622
|
+
function selfAndAncestors(target, paths) {
|
|
5623
|
+
const chain = [];
|
|
5624
|
+
let current = paths.resolve(target);
|
|
5625
|
+
for (; ; ) {
|
|
5626
|
+
chain.push(current);
|
|
5627
|
+
const parent = paths.dirname(current);
|
|
5628
|
+
if (parent === current) {
|
|
5629
|
+
return chain;
|
|
5630
|
+
}
|
|
5631
|
+
current = parent;
|
|
5632
|
+
}
|
|
5633
|
+
}
|
|
5634
|
+
function identityOrNull(read, callTimeoutMillis) {
|
|
5635
|
+
return callWithTimeout(read, callTimeoutMillis).then(identityOf, (err) => {
|
|
5636
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5637
|
+
throw err;
|
|
5638
|
+
}
|
|
5639
|
+
return null;
|
|
5640
|
+
});
|
|
5641
|
+
}
|
|
5642
|
+
async function identitiesOf(target, remover, callTimeoutMillis) {
|
|
5643
|
+
const identities = await Promise.all([remover.lstat(target), remover.stat(target)].map((read) => identityOrNull(read, callTimeoutMillis)));
|
|
5644
|
+
return identities.filter((identity) => identity !== null);
|
|
5645
|
+
}
|
|
5646
|
+
async function realPathOrNull(target, remover, callTimeoutMillis) {
|
|
5647
|
+
try {
|
|
5648
|
+
return await callWithTimeout(remover.realpath(target), callTimeoutMillis);
|
|
5649
|
+
} catch (err) {
|
|
5650
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5651
|
+
throw err;
|
|
5652
|
+
}
|
|
5653
|
+
return null;
|
|
5654
|
+
}
|
|
5655
|
+
}
|
|
5656
|
+
async function agentFileChains(files, paths, remover, callTimeoutMillis) {
|
|
5657
|
+
const realPaths = await Promise.all(files.map((file) => realPathOrNull(file, remover, callTimeoutMillis)));
|
|
5658
|
+
return files.flatMap((file, index) => {
|
|
5659
|
+
const realPath = realPaths[index];
|
|
5660
|
+
return realPath === null ? [] : [...selfAndAncestors(file, paths), ...selfAndAncestors(realPath, paths)];
|
|
5661
|
+
});
|
|
5662
|
+
}
|
|
5663
|
+
async function addFolders(reasons, folders, message, remover, callTimeoutMillis) {
|
|
5664
|
+
const identities = await Promise.all(folders.map((folder) => identitiesOf(folder, remover, callTimeoutMillis)));
|
|
5665
|
+
for (const identity of identities.flat()) {
|
|
5666
|
+
reasons.set(identity, message);
|
|
5667
|
+
}
|
|
5668
|
+
}
|
|
5669
|
+
async function readProtectedSet(sources, paths, remover, callTimeoutMillis) {
|
|
5670
|
+
const reasons = /* @__PURE__ */ new Map();
|
|
5671
|
+
const agentChains = await agentFileChains(sources.agentFiles, paths, remover, callTimeoutMillis);
|
|
5672
|
+
await addFolders(reasons, agentChains, MESSAGE_PINGGY_PROGRAM, remover, callTimeoutMillis);
|
|
5673
|
+
const systemChains = sources.systemFolders.flatMap((folder) => selfAndAncestors(folder, paths));
|
|
5674
|
+
await addFolders(reasons, systemChains, MESSAGE_SYSTEM_FOLDER, remover, callTimeoutMillis);
|
|
5675
|
+
await addFolders(
|
|
5676
|
+
reasons,
|
|
5677
|
+
selfAndAncestors(sources.accountsFolder, paths),
|
|
5678
|
+
MESSAGE_ACCOUNTS_FOLDER,
|
|
5679
|
+
remover,
|
|
5680
|
+
callTimeoutMillis
|
|
5681
|
+
);
|
|
5682
|
+
const pinggyChains = [...selfAndAncestors(sources.home, paths), ...selfAndAncestors(sources.configFolder, paths)];
|
|
5683
|
+
await addFolders(reasons, pinggyChains, MESSAGE_PINGGY_FOLDER, remover, callTimeoutMillis);
|
|
5684
|
+
const [configFolder, accountsFolder] = await Promise.all([sources.configFolder, sources.accountsFolder].map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
|
|
5685
|
+
return { reasons, configFolder, accountsFolder };
|
|
5686
|
+
}
|
|
5687
|
+
async function isInsideConfigFolder(directory, protectedSet, paths, remover, callTimeoutMillis) {
|
|
5688
|
+
if (protectedSet.configFolder === null) {
|
|
5689
|
+
return false;
|
|
5690
|
+
}
|
|
5691
|
+
const chain = selfAndAncestors(directory, paths);
|
|
5692
|
+
const identities = await Promise.all(chain.map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
|
|
5693
|
+
return identities.includes(protectedSet.configFolder);
|
|
5694
|
+
}
|
|
5695
|
+
|
|
5696
|
+
// src/devices/files/fileDelete.ts
|
|
5697
|
+
var WINDOWS_WRITABLE_MODE = 438;
|
|
5698
|
+
var MESSAGE_DELETE_FAILED = "The item could not be deleted.";
|
|
5699
|
+
var MESSAGE_PROTECTED_UNREAD = "The protected folders could not be read in time.";
|
|
5700
|
+
var MESSAGE_SELECTED_MOUNT = "This folder is a mounted disk. Open it to delete what is inside.";
|
|
5701
|
+
var MESSAGE_MOUNT_INSIDE = "Another disk is mounted inside. Pinggy left it in place.";
|
|
5702
|
+
var ProtectedEntryError = class extends Error {
|
|
5703
|
+
};
|
|
5704
|
+
async function prepareDelete(request2, dependencies) {
|
|
5705
|
+
const paths = pathsFor(dependencies.platform);
|
|
5706
|
+
const pathIssue = pathProblem(request2.path, paths);
|
|
5707
|
+
if (pathIssue) {
|
|
5708
|
+
return fileError(ERROR_INVALID_PATH, pathIssue);
|
|
5709
|
+
}
|
|
5710
|
+
const item = resolvedItem(request2.path, paths);
|
|
5711
|
+
const { remover, callTimeoutMillis } = dependencies;
|
|
5712
|
+
let stats;
|
|
5713
|
+
let parentStats;
|
|
5714
|
+
try {
|
|
5715
|
+
stats = await callWithTimeout(remover.lstat(item.path), callTimeoutMillis);
|
|
5716
|
+
parentStats = await callWithTimeout(remover.stat(item.parent), callTimeoutMillis);
|
|
5717
|
+
} catch (err) {
|
|
5718
|
+
return { error: deleteFailure(err) };
|
|
5719
|
+
}
|
|
5720
|
+
let protectedSet;
|
|
5721
|
+
let insideConfigFolder;
|
|
5722
|
+
try {
|
|
5723
|
+
protectedSet = await readProtectedSet(dependencies.protectedSources, paths, remover, callTimeoutMillis);
|
|
5724
|
+
insideConfigFolder = await isInsideConfigFolder(item.parent, protectedSet, paths, remover, callTimeoutMillis);
|
|
5725
|
+
} catch (err) {
|
|
5726
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
5727
|
+
return fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD));
|
|
5728
|
+
}
|
|
5729
|
+
if (insideConfigFolder) {
|
|
5730
|
+
return fileError(ERROR_PROTECTED_PATH, MESSAGE_PINGGY_FOLDER);
|
|
5731
|
+
}
|
|
5732
|
+
if (protectedSet.accountsFolder !== null && identityOf(parentStats) === protectedSet.accountsFolder) {
|
|
5733
|
+
return fileError(ERROR_PROTECTED_PATH, MESSAGE_ACCOUNT_FOLDER);
|
|
5734
|
+
}
|
|
5735
|
+
const reason = protectedSet.reasons.get(identityOf(stats));
|
|
5736
|
+
if (reason) {
|
|
5737
|
+
return fileError(ERROR_PROTECTED_PATH, reason);
|
|
5738
|
+
}
|
|
5739
|
+
if (stats.dev !== parentStats.dev) {
|
|
5740
|
+
return fileError(ERROR_MOUNT_POINT, MESSAGE_SELECTED_MOUNT);
|
|
5741
|
+
}
|
|
5742
|
+
return { target: item.path, name: item.name, stats, protectedSet };
|
|
5743
|
+
}
|
|
5744
|
+
async function runDelete(prepared, progress, dependencies) {
|
|
5745
|
+
const context = {
|
|
5746
|
+
device: prepared.stats.dev,
|
|
5747
|
+
protectedSet: prepared.protectedSet,
|
|
5748
|
+
progress,
|
|
5749
|
+
dependencies,
|
|
5750
|
+
paths: pathsFor(dependencies.platform)
|
|
5751
|
+
};
|
|
5752
|
+
let result = {};
|
|
5753
|
+
try {
|
|
5754
|
+
if (!await removeEntry(prepared.target, prepared.stats, context)) {
|
|
5755
|
+
result = fileError(ERROR_MOUNT_POINT, MESSAGE_MOUNT_INSIDE);
|
|
5756
|
+
}
|
|
5757
|
+
} catch (err) {
|
|
5758
|
+
result = { error: deleteFailure(err) };
|
|
5759
|
+
}
|
|
5760
|
+
progress.items_done += 1;
|
|
5761
|
+
return result;
|
|
5762
|
+
}
|
|
5763
|
+
function removeTree(target, stats, protectedSet, dependencies) {
|
|
5764
|
+
const context = {
|
|
5765
|
+
device: stats.dev,
|
|
5766
|
+
protectedSet,
|
|
5767
|
+
progress: { files_done: 0 },
|
|
5768
|
+
dependencies,
|
|
5769
|
+
paths: pathsFor(dependencies.platform)
|
|
5770
|
+
};
|
|
5771
|
+
return removeEntry(target, stats, context);
|
|
5772
|
+
}
|
|
5773
|
+
async function removeEntry(target, stats, context) {
|
|
5774
|
+
if (!stats.isDirectory()) {
|
|
5775
|
+
if (await removeWith(target, (entry) => context.dependencies.remover.unlink(entry), context)) {
|
|
5776
|
+
context.progress.files_done += 1;
|
|
5777
|
+
}
|
|
5778
|
+
return true;
|
|
5779
|
+
}
|
|
5780
|
+
return removeFolder(target, context);
|
|
5781
|
+
}
|
|
5782
|
+
async function removeFolder(folder, context) {
|
|
5783
|
+
const { remover, callTimeoutMillis } = context.dependencies;
|
|
5784
|
+
const removeFolderItself = (entry) => remover.rmdir(entry);
|
|
5785
|
+
try {
|
|
5786
|
+
if (await removeWith(folder, removeFolderItself, context)) {
|
|
5787
|
+
context.progress.files_done += 1;
|
|
5788
|
+
}
|
|
5789
|
+
return true;
|
|
5790
|
+
} catch (err) {
|
|
5791
|
+
if (!isNotEmpty(err)) {
|
|
5792
|
+
throw err;
|
|
5793
|
+
}
|
|
5794
|
+
}
|
|
5795
|
+
let names;
|
|
5796
|
+
try {
|
|
5797
|
+
names = await callWithTimeout(remover.readdir(folder), callTimeoutMillis);
|
|
5798
|
+
} catch (err) {
|
|
5799
|
+
if (isGone(err)) {
|
|
5800
|
+
return true;
|
|
5801
|
+
}
|
|
5802
|
+
throw err;
|
|
5803
|
+
}
|
|
5804
|
+
let removedAll = true;
|
|
5805
|
+
for (const name of names) {
|
|
5806
|
+
if (!await removeChild(context.paths.join(folder, name), context)) {
|
|
5807
|
+
removedAll = false;
|
|
5808
|
+
}
|
|
5809
|
+
}
|
|
5810
|
+
if (!removedAll) {
|
|
5811
|
+
return false;
|
|
5812
|
+
}
|
|
5813
|
+
if (await removeWith(folder, removeFolderItself, context)) {
|
|
5814
|
+
context.progress.files_done += 1;
|
|
5815
|
+
}
|
|
5816
|
+
return true;
|
|
5817
|
+
}
|
|
5818
|
+
async function removeChild(child, context) {
|
|
5819
|
+
let stats;
|
|
5820
|
+
try {
|
|
5821
|
+
stats = await callWithTimeout(
|
|
5822
|
+
context.dependencies.remover.lstat(child),
|
|
5823
|
+
context.dependencies.callTimeoutMillis
|
|
5824
|
+
);
|
|
5825
|
+
} catch (err) {
|
|
5826
|
+
if (isGone(err)) {
|
|
5827
|
+
return true;
|
|
5828
|
+
}
|
|
5829
|
+
throw err;
|
|
5830
|
+
}
|
|
5831
|
+
const reason = context.protectedSet.reasons.get(identityOf(stats));
|
|
5832
|
+
if (reason) {
|
|
5833
|
+
throw new ProtectedEntryError(reason);
|
|
5834
|
+
}
|
|
5835
|
+
if (stats.isDirectory() && stats.dev !== context.device) {
|
|
5836
|
+
return false;
|
|
5837
|
+
}
|
|
5838
|
+
return removeEntry(child, stats, context);
|
|
5839
|
+
}
|
|
5840
|
+
async function removeWith(target, remove, context) {
|
|
5841
|
+
const { remover, callTimeoutMillis, platform: platform3 } = context.dependencies;
|
|
5842
|
+
try {
|
|
5843
|
+
await callWithTimeout(remove(target), callTimeoutMillis);
|
|
5844
|
+
return true;
|
|
5845
|
+
} catch (err) {
|
|
5846
|
+
if (isGone(err)) {
|
|
5847
|
+
return false;
|
|
5848
|
+
}
|
|
5849
|
+
if (platform3 !== "win32" || errorCodeOf(err) !== "EPERM") {
|
|
5850
|
+
throw err;
|
|
5851
|
+
}
|
|
5852
|
+
try {
|
|
5853
|
+
await callWithTimeout(remover.chmod(target, WINDOWS_WRITABLE_MODE), callTimeoutMillis);
|
|
5854
|
+
} catch {
|
|
5855
|
+
throw err;
|
|
5856
|
+
}
|
|
5857
|
+
}
|
|
5858
|
+
try {
|
|
5859
|
+
await callWithTimeout(remove(target), callTimeoutMillis);
|
|
5860
|
+
return true;
|
|
5861
|
+
} catch (err) {
|
|
5862
|
+
if (isGone(err)) {
|
|
5863
|
+
return false;
|
|
5864
|
+
}
|
|
5865
|
+
throw err;
|
|
5866
|
+
}
|
|
5867
|
+
}
|
|
5868
|
+
function isGone(err) {
|
|
5869
|
+
return errorCodeOf(err) === "ENOENT";
|
|
5870
|
+
}
|
|
5871
|
+
function isNotEmpty(err) {
|
|
5872
|
+
const code = errorCodeOf(err);
|
|
5873
|
+
return code === "ENOTEMPTY" || code === "EEXIST";
|
|
5874
|
+
}
|
|
5875
|
+
function deleteFailure(err) {
|
|
5876
|
+
if (err instanceof FileCallTimeoutError) {
|
|
5877
|
+
return { code: ERROR_FILE_TIMEOUT, message: err.message };
|
|
5878
|
+
}
|
|
5879
|
+
if (err instanceof ProtectedEntryError) {
|
|
5880
|
+
return { code: ERROR_PROTECTED_PATH, message: err.message };
|
|
5881
|
+
}
|
|
5882
|
+
const message = failureMessage(err, MESSAGE_DELETE_FAILED);
|
|
5883
|
+
switch (errorCodeOf(err)) {
|
|
5884
|
+
case "ENOENT":
|
|
5885
|
+
case "ENOTDIR":
|
|
5886
|
+
return { code: ERROR_PATH_NOT_FOUND, message };
|
|
5887
|
+
case "EACCES":
|
|
5888
|
+
case "EPERM":
|
|
5889
|
+
case "EROFS":
|
|
5890
|
+
return { code: ERROR_PERMISSION_DENIED, message };
|
|
5891
|
+
default:
|
|
5892
|
+
return { code: ERROR_FILE_OPERATION_FAILED, message };
|
|
5893
|
+
}
|
|
5894
|
+
}
|
|
5895
|
+
|
|
5896
|
+
// src/devices/files/fileCopy.ts
|
|
5897
|
+
var COPY_PIECE_BYTES = 1024 * 1024;
|
|
5898
|
+
var SMALL_PIECE_BYTES = 4096;
|
|
5899
|
+
var PERMISSION_BITS = 0o777n;
|
|
5900
|
+
var MAX_KEEP_BOTH_NUMBER = 1e3;
|
|
5901
|
+
var EXTENSION_SEPARATOR2 = ".";
|
|
5902
|
+
var HIDDEN_NAME_PREFIX2 = ".";
|
|
5903
|
+
var HIDDEN_COPY_MARK = "copy";
|
|
5904
|
+
var HIDDEN_OLD_MARK = "old";
|
|
5905
|
+
var HIDDEN_SUFFIX_BYTES = 4;
|
|
5906
|
+
var LINK_TYPE_FILE = "file";
|
|
5907
|
+
var LINK_TYPE_FOLDER = "dir";
|
|
5908
|
+
var BYTES_PER_UNIT = 1e3;
|
|
5909
|
+
var BYTE_UNITS = ["bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
5910
|
+
var BYTE_UNIT_SINGULAR = "byte";
|
|
5911
|
+
var MESSAGE_FOLDER_UNREADABLE = "The folder could not be read.";
|
|
5912
|
+
var MESSAGE_NOT_A_FOLDER = "The path is not a folder.";
|
|
5913
|
+
var MESSAGE_ROOT = "A drive or filesystem root cannot be copied or moved.";
|
|
5914
|
+
var MESSAGE_INTO_ITSELF = "A folder cannot be copied into itself.";
|
|
5915
|
+
var MESSAGE_REPLACE_ITSELF = "An item cannot replace itself.";
|
|
5916
|
+
var MESSAGE_REPLACE_HOLDER = "An item cannot replace a folder that holds it.";
|
|
5917
|
+
var MESSAGE_TARGET_TAKEN = "1 item already exists in the destination.";
|
|
5918
|
+
var MESSAGE_PROTECTED_UNREAD2 = "The protected folders could not be read in time.";
|
|
5919
|
+
var MESSAGE_SPECIAL_SELECTED = "This is a socket, pipe or device file. Pinggy cannot copy it.";
|
|
5920
|
+
var MESSAGE_REPLACE_MOUNT = "This item is a mounted disk. Pinggy does not replace it.";
|
|
5921
|
+
var MESSAGE_COPY_FAILED = "The item could not be copied.";
|
|
5922
|
+
var MESSAGE_COPY_IN_PLACE = "The copy is in place. The old one stays as";
|
|
5923
|
+
var REASON_MOUNT_INSIDE = "a disk is mounted inside it.";
|
|
5924
|
+
var TakenError = class extends Error {
|
|
5925
|
+
};
|
|
5926
|
+
var RequestRefusal = class extends Error {
|
|
5927
|
+
constructor(refusal) {
|
|
5928
|
+
super(refusal.error.message);
|
|
5929
|
+
this.refusal = refusal;
|
|
5930
|
+
}
|
|
5931
|
+
};
|
|
5932
|
+
var SKIPPED = "skipped";
|
|
5933
|
+
function randomHiddenNameSuffix() {
|
|
5934
|
+
return crypto.randomBytes(HIDDEN_SUFFIX_BYTES).toString("hex");
|
|
5935
|
+
}
|
|
5936
|
+
async function prepareCopy(request2, dependencies) {
|
|
5937
|
+
try {
|
|
5938
|
+
return await checkedCopy(request2, dependencies);
|
|
5939
|
+
} catch (err) {
|
|
5940
|
+
return refusalOf(err);
|
|
5941
|
+
}
|
|
5942
|
+
}
|
|
5943
|
+
function refusalOf(err) {
|
|
5944
|
+
if (err instanceof RequestRefusal) {
|
|
5945
|
+
return err.refusal;
|
|
5946
|
+
}
|
|
5947
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
5948
|
+
return fileError(code, failureMessage(err, MESSAGE_FOLDER_UNREADABLE));
|
|
5949
|
+
}
|
|
5950
|
+
async function checkedCopy(request2, dependencies) {
|
|
5951
|
+
const { copier, platform: platform3 } = dependencies;
|
|
5952
|
+
const paths = pathsFor(platform3);
|
|
5953
|
+
const { source, destination } = resolvedItems(request2, paths);
|
|
5954
|
+
checkTargetName(destination.name, platform3);
|
|
5955
|
+
const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_COPY_FAILED);
|
|
5956
|
+
if (isSpecial(sourceStats)) {
|
|
5957
|
+
throw new RequestRefusal(fileError(ERROR_SPECIAL_FILE, MESSAGE_SPECIAL_SELECTED));
|
|
5958
|
+
}
|
|
5959
|
+
const destinationStats = await folderStats(destination.parent, copier);
|
|
5960
|
+
await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF);
|
|
5961
|
+
const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
|
|
5962
|
+
if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
|
|
5963
|
+
const target = await lstatOrNull(destination.path, copier);
|
|
5964
|
+
if (onConflict === ON_CONFLICT_FAIL && target !== null) {
|
|
5965
|
+
throw new RequestRefusal(targetTakenRefusal());
|
|
5966
|
+
}
|
|
5967
|
+
if (onConflict === ON_CONFLICT_REPLACE && target !== null && identityOf(target) === identityOf(sourceStats)) {
|
|
5968
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
|
|
5969
|
+
}
|
|
5970
|
+
if (onConflict === ON_CONFLICT_REPLACE) {
|
|
5971
|
+
await refuseReplacingAHolder(target, source.parent, dependencies);
|
|
5972
|
+
}
|
|
5973
|
+
}
|
|
5974
|
+
const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(
|
|
5975
|
+
destination.parent,
|
|
5976
|
+
destinationStats,
|
|
5977
|
+
await readProtectedFolders(dependencies),
|
|
5978
|
+
dependencies
|
|
5979
|
+
) : null;
|
|
5980
|
+
return {
|
|
5981
|
+
source: source.path,
|
|
5982
|
+
sourceStats,
|
|
5983
|
+
sourceName: source.name,
|
|
5984
|
+
destinationDirectory: destination.parent,
|
|
5985
|
+
targetName: destination.name,
|
|
5986
|
+
onConflict,
|
|
5987
|
+
destinationDevice: destinationStats.dev,
|
|
5988
|
+
replaceGuard
|
|
5989
|
+
};
|
|
5990
|
+
}
|
|
5991
|
+
function resolvedItems(request2, paths) {
|
|
5992
|
+
for (const requested of [request2.source_path, request2.destination_path]) {
|
|
5993
|
+
const issue = pathProblem(requested, paths);
|
|
5994
|
+
if (issue) {
|
|
5995
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PATH, issue));
|
|
5996
|
+
}
|
|
5997
|
+
}
|
|
5998
|
+
const source = resolvedItem(request2.source_path, paths);
|
|
5999
|
+
const requestedDestination = resolvedItem(request2.destination_path, paths);
|
|
6000
|
+
const destination = requestedDestination.name === source.name ? requestedDestination : withTrimmedName(requestedDestination);
|
|
6001
|
+
if (isRoot(source.path, paths) || isRoot(destination.path, paths)) {
|
|
6002
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PATH, MESSAGE_ROOT));
|
|
6003
|
+
}
|
|
6004
|
+
return { source, destination };
|
|
6005
|
+
}
|
|
6006
|
+
function checkTargetName(targetName, platform3) {
|
|
6007
|
+
const nameIssue = nameProblem(targetName, platform3);
|
|
6008
|
+
if (nameIssue) {
|
|
6009
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_PAYLOAD2, nameIssue));
|
|
6010
|
+
}
|
|
6011
|
+
const windowsIssue = platform3 === "win32" ? windowsNameProblem(targetName, "A name") : null;
|
|
6012
|
+
if (windowsIssue) {
|
|
6013
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_NAME, windowsIssue));
|
|
6014
|
+
}
|
|
6015
|
+
}
|
|
6016
|
+
async function sourceItemStats(source, copier, fallbackMessage) {
|
|
6017
|
+
try {
|
|
6018
|
+
return await copier.lstat(source);
|
|
6019
|
+
} catch (err) {
|
|
6020
|
+
throw new RequestRefusal({ error: copyFailure(err, fallbackMessage) });
|
|
6021
|
+
}
|
|
6022
|
+
}
|
|
6023
|
+
async function folderStats(folder, copier) {
|
|
6024
|
+
let stats;
|
|
6025
|
+
try {
|
|
6026
|
+
stats = await copier.stat(folder);
|
|
6027
|
+
} catch (err) {
|
|
6028
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6029
|
+
throw err;
|
|
6030
|
+
}
|
|
6031
|
+
throw new RequestRefusal(folderFailure(err));
|
|
6032
|
+
}
|
|
6033
|
+
if (!stats.isDirectory()) {
|
|
6034
|
+
throw new RequestRefusal(fileError(ERROR_NOT_A_DIRECTORY, MESSAGE_NOT_A_FOLDER));
|
|
6035
|
+
}
|
|
6036
|
+
return stats;
|
|
6037
|
+
}
|
|
6038
|
+
function folderFailure(err) {
|
|
6039
|
+
const message = failureMessage(err, MESSAGE_FOLDER_UNREADABLE);
|
|
6040
|
+
switch (errorCodeOf(err)) {
|
|
6041
|
+
case "ENOENT":
|
|
6042
|
+
case "ENOTDIR":
|
|
6043
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6044
|
+
case "EACCES":
|
|
6045
|
+
case "EPERM":
|
|
6046
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6047
|
+
default:
|
|
6048
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6049
|
+
}
|
|
6050
|
+
}
|
|
6051
|
+
async function refuseIntoItself(source, destinationDirectory, dependencies, message) {
|
|
6052
|
+
if (await folderHolds(source, destinationDirectory, dependencies)) {
|
|
6053
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, message));
|
|
6054
|
+
}
|
|
6055
|
+
}
|
|
6056
|
+
async function refuseReplacingAHolder(target, sourceDirectory, dependencies) {
|
|
6057
|
+
if (await folderHolds(target, sourceDirectory, dependencies)) {
|
|
6058
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_HOLDER));
|
|
6059
|
+
}
|
|
6060
|
+
}
|
|
6061
|
+
async function folderHolds(candidate, folder, dependencies) {
|
|
6062
|
+
if (candidate === null || !candidate.isDirectory()) {
|
|
6063
|
+
return false;
|
|
6064
|
+
}
|
|
6065
|
+
const { copier } = dependencies;
|
|
6066
|
+
const paths = pathsFor(dependencies.platform);
|
|
6067
|
+
const realFolder = await copier.realpath(folder);
|
|
6068
|
+
const chain = new Set(await Promise.all(selfAndAncestors(realFolder, paths).map((each) => identityOrNull2(copier.stat(each)))));
|
|
6069
|
+
return chain.has(identityOf(candidate));
|
|
6070
|
+
}
|
|
6071
|
+
function targetTakenRefusal() {
|
|
6072
|
+
return fileError(ERROR_FILE_EXISTS, MESSAGE_TARGET_TAKEN);
|
|
6073
|
+
}
|
|
6074
|
+
async function readProtectedFolders(dependencies) {
|
|
6075
|
+
const { remover, callTimeoutMillis, protectedSources } = dependencies;
|
|
6076
|
+
try {
|
|
6077
|
+
return await readProtectedSet(protectedSources, pathsFor(dependencies.platform), remover, callTimeoutMillis);
|
|
6078
|
+
} catch (err) {
|
|
6079
|
+
throw protectedUnread(err);
|
|
6080
|
+
}
|
|
6081
|
+
}
|
|
6082
|
+
async function removalGuard(folder, stats, protectedSet, dependencies) {
|
|
6083
|
+
const { remover, callTimeoutMillis } = dependencies;
|
|
6084
|
+
try {
|
|
6085
|
+
const insideConfigFolder = await isInsideConfigFolder(
|
|
6086
|
+
folder,
|
|
6087
|
+
protectedSet,
|
|
6088
|
+
pathsFor(dependencies.platform),
|
|
6089
|
+
remover,
|
|
6090
|
+
callTimeoutMillis
|
|
6091
|
+
);
|
|
6092
|
+
const inAccountsFolder = protectedSet.accountsFolder !== null && identityOf(stats) === protectedSet.accountsFolder;
|
|
6093
|
+
return { protectedSet, insideConfigFolder, inAccountsFolder };
|
|
6094
|
+
} catch (err) {
|
|
6095
|
+
throw protectedUnread(err);
|
|
6096
|
+
}
|
|
6097
|
+
}
|
|
6098
|
+
function protectedUnread(err) {
|
|
6099
|
+
const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
|
|
6100
|
+
return new RequestRefusal(fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD2)));
|
|
6101
|
+
}
|
|
6102
|
+
async function runCopy(prepared, progress, dependencies) {
|
|
6103
|
+
const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
|
|
6104
|
+
const totals = await countSource(prepared, dependencies);
|
|
6105
|
+
counted.files_total = totals.files;
|
|
6106
|
+
counted.bytes_total = totals.bytes;
|
|
6107
|
+
const noSpace = await noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
|
|
6108
|
+
if (noSpace) {
|
|
6109
|
+
return noSpace;
|
|
6110
|
+
}
|
|
6111
|
+
const walk = {
|
|
6112
|
+
copier: dependencies.copier,
|
|
6113
|
+
paths: pathsFor(dependencies.platform),
|
|
6114
|
+
platform: dependencies.platform,
|
|
6115
|
+
progress: counted,
|
|
6116
|
+
specialFilesLeftOut: 0
|
|
6117
|
+
};
|
|
6118
|
+
const outcome = await copyItem(prepared, walk, dependencies);
|
|
6119
|
+
counted.items_done += 1;
|
|
6120
|
+
return outcomeAnswer(outcome);
|
|
6121
|
+
}
|
|
6122
|
+
function outcomeAnswer(outcome) {
|
|
6123
|
+
if (outcome === SKIPPED) {
|
|
6124
|
+
return { skipped: true };
|
|
6125
|
+
}
|
|
6126
|
+
return outcome === null ? {} : { error: outcome };
|
|
6127
|
+
}
|
|
6128
|
+
async function noSpaceRefusal(neededBytes, destinationDirectory, copier) {
|
|
6129
|
+
const freeBytes = await copier.freeBytes(destinationDirectory).catch(() => null);
|
|
6130
|
+
if (freeBytes === null || BigInt(neededBytes) <= freeBytes) {
|
|
6131
|
+
return null;
|
|
6132
|
+
}
|
|
6133
|
+
return fileError(ERROR_NO_SPACE, `The copy needs ${formatBytes(neededBytes)}. The destination disk has ${formatBytes(freeBytes)} free.`);
|
|
6134
|
+
}
|
|
6135
|
+
async function countSource(prepared, dependencies) {
|
|
6136
|
+
const { copier } = dependencies;
|
|
6137
|
+
const paths = pathsFor(dependencies.platform);
|
|
6138
|
+
const totals = newCountTotals();
|
|
6139
|
+
const target = paths.join(prepared.destinationDirectory, prepared.targetName);
|
|
6140
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, copier).catch(() => null)) {
|
|
6141
|
+
return totals;
|
|
6142
|
+
}
|
|
6143
|
+
await countEntry(prepared.source, totals, copier, paths, null);
|
|
6144
|
+
return totals;
|
|
6145
|
+
}
|
|
6146
|
+
function newCountTotals() {
|
|
6147
|
+
return { files: 0, bytes: 0, specialFiles: 0, mountedDisks: 0 };
|
|
6148
|
+
}
|
|
6149
|
+
async function countEntry(entry, totals, copier, paths, stopAtDevice) {
|
|
6150
|
+
let stats;
|
|
6151
|
+
try {
|
|
6152
|
+
stats = await copier.lstat(entry);
|
|
6153
|
+
} catch {
|
|
6154
|
+
return;
|
|
6155
|
+
}
|
|
6156
|
+
if (isSpecial(stats)) {
|
|
6157
|
+
totals.specialFiles += 1;
|
|
6158
|
+
return;
|
|
6159
|
+
}
|
|
6160
|
+
if (stats.isDirectory() && stopAtDevice !== null && stats.dev !== stopAtDevice) {
|
|
6161
|
+
totals.mountedDisks += 1;
|
|
6162
|
+
return;
|
|
6163
|
+
}
|
|
6164
|
+
totals.files += 1;
|
|
6165
|
+
if (stats.isFile()) {
|
|
6166
|
+
totals.bytes += Number(stats.size);
|
|
6167
|
+
return;
|
|
6168
|
+
}
|
|
6169
|
+
if (!stats.isDirectory()) {
|
|
6170
|
+
return;
|
|
6171
|
+
}
|
|
6172
|
+
let children;
|
|
6173
|
+
try {
|
|
6174
|
+
children = await copier.readdir(entry);
|
|
6175
|
+
} catch {
|
|
6176
|
+
return;
|
|
6177
|
+
}
|
|
6178
|
+
for (const child of children) {
|
|
6179
|
+
await countEntry(paths.join(entry, child), totals, copier, paths, stopAtDevice);
|
|
6180
|
+
}
|
|
6181
|
+
}
|
|
6182
|
+
async function copyItem(prepared, walk, dependencies) {
|
|
6183
|
+
try {
|
|
6184
|
+
if (prepared.onConflict === ON_CONFLICT_REPLACE) {
|
|
6185
|
+
const refusal = await replaceTarget(prepared, walk, dependencies);
|
|
6186
|
+
if (refusal) {
|
|
6187
|
+
return refusal;
|
|
6188
|
+
}
|
|
6189
|
+
} else if (await copyToFreeName(
|
|
6190
|
+
prepared.source,
|
|
6191
|
+
prepared.sourceStats,
|
|
6192
|
+
prepared.targetName,
|
|
6193
|
+
prepared,
|
|
6194
|
+
walk
|
|
6195
|
+
) === SKIPPED) {
|
|
6196
|
+
return SKIPPED;
|
|
6197
|
+
}
|
|
6198
|
+
} catch (err) {
|
|
6199
|
+
return copyFailure(err, MESSAGE_COPY_FAILED);
|
|
6200
|
+
}
|
|
6201
|
+
return walk.specialFilesLeftOut > 0 ? specialFilesLeftOut(walk.specialFilesLeftOut) : null;
|
|
6202
|
+
}
|
|
6203
|
+
async function copyToFreeName(source, stats, targetName, prepared, walk) {
|
|
6204
|
+
let candidate = targetName;
|
|
6205
|
+
for (let number = 1; ; number++) {
|
|
6206
|
+
try {
|
|
6207
|
+
await copyEntry(source, stats, walk.paths.join(prepared.destinationDirectory, candidate), walk, true);
|
|
6208
|
+
return null;
|
|
6209
|
+
} catch (err) {
|
|
6210
|
+
if (!(err instanceof TakenError)) {
|
|
6211
|
+
throw err;
|
|
6212
|
+
}
|
|
6213
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP) {
|
|
6214
|
+
return SKIPPED;
|
|
6215
|
+
}
|
|
6216
|
+
if (prepared.onConflict !== ON_CONFLICT_KEEP_BOTH || number > MAX_KEEP_BOTH_NUMBER) {
|
|
6217
|
+
throw err;
|
|
6218
|
+
}
|
|
6219
|
+
candidate = keepBothName(targetName, stats.isDirectory(), number);
|
|
6220
|
+
}
|
|
6221
|
+
}
|
|
6222
|
+
}
|
|
6223
|
+
async function replaceTarget(prepared, walk, dependencies) {
|
|
6224
|
+
const { copier, paths } = walk;
|
|
6225
|
+
const { source, sourceStats: stats, targetName } = prepared;
|
|
6226
|
+
const guard = prepared.replaceGuard;
|
|
6227
|
+
const target = paths.join(prepared.destinationDirectory, targetName);
|
|
6228
|
+
const existing = await lstatOrNull(target, copier);
|
|
6229
|
+
if (existing === null) {
|
|
6230
|
+
await copyEntry(source, stats, target, walk, true);
|
|
6231
|
+
return null;
|
|
6232
|
+
}
|
|
6233
|
+
const refusal = replaceRefusal(existing, stats, prepared.destinationDevice, guard);
|
|
6234
|
+
if (refusal) {
|
|
6235
|
+
return refusal;
|
|
6236
|
+
}
|
|
6237
|
+
const suffix = dependencies.hiddenNameSuffix();
|
|
6238
|
+
const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(targetName, HIDDEN_COPY_MARK, suffix));
|
|
6239
|
+
try {
|
|
6240
|
+
await copyEntry(source, stats, hiddenCopy, walk, true);
|
|
6241
|
+
} catch (err) {
|
|
6242
|
+
if (!(err instanceof TakenError)) {
|
|
6243
|
+
await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
|
|
6244
|
+
}
|
|
6245
|
+
throw err;
|
|
6246
|
+
}
|
|
6247
|
+
let oldName;
|
|
6248
|
+
try {
|
|
6249
|
+
oldName = await swapIn(
|
|
6250
|
+
hiddenCopy,
|
|
6251
|
+
prepared.destinationDirectory,
|
|
6252
|
+
targetName,
|
|
6253
|
+
existing,
|
|
6254
|
+
stats.isDirectory(),
|
|
6255
|
+
suffix,
|
|
6256
|
+
copier,
|
|
6257
|
+
paths
|
|
6258
|
+
);
|
|
6259
|
+
} catch (err) {
|
|
6260
|
+
await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
|
|
6261
|
+
throw err;
|
|
6262
|
+
}
|
|
6263
|
+
if (oldName === null) {
|
|
6264
|
+
return null;
|
|
6265
|
+
}
|
|
6266
|
+
return removeOld(
|
|
6267
|
+
paths.join(prepared.destinationDirectory, oldName),
|
|
6268
|
+
oldName,
|
|
6269
|
+
existing,
|
|
6270
|
+
guard.protectedSet,
|
|
6271
|
+
dependencies,
|
|
6272
|
+
MESSAGE_COPY_IN_PLACE
|
|
6273
|
+
);
|
|
6274
|
+
}
|
|
6275
|
+
async function swapIn(incoming, folder, targetName, existing, incomingIsFolder, suffix, copier, paths) {
|
|
6276
|
+
const target = paths.join(folder, targetName);
|
|
6277
|
+
if (!existing.isDirectory() && !incomingIsFolder) {
|
|
6278
|
+
await copier.rename(incoming, target);
|
|
6279
|
+
return null;
|
|
6280
|
+
}
|
|
6281
|
+
const oldName = hiddenName(targetName, HIDDEN_OLD_MARK, suffix);
|
|
6282
|
+
const hiddenOld = paths.join(folder, oldName);
|
|
6283
|
+
await copier.rename(target, hiddenOld);
|
|
6284
|
+
try {
|
|
6285
|
+
await copier.rename(incoming, target);
|
|
6286
|
+
} catch (err) {
|
|
6287
|
+
await copier.rename(hiddenOld, target).catch(() => void 0);
|
|
6288
|
+
throw err;
|
|
6289
|
+
}
|
|
6290
|
+
return oldName;
|
|
6291
|
+
}
|
|
6292
|
+
function replaceRefusal(existing, source, destinationDevice, guard) {
|
|
6293
|
+
if (identityOf(existing) === identityOf(source)) {
|
|
6294
|
+
return { code: ERROR_INVALID_DESTINATION, message: MESSAGE_REPLACE_ITSELF };
|
|
6295
|
+
}
|
|
6296
|
+
return protectedRefusal(existing, destinationDevice, guard, MESSAGE_REPLACE_MOUNT);
|
|
6297
|
+
}
|
|
6298
|
+
function protectedRefusal(stats, folderDevice, guard, mountMessage) {
|
|
6299
|
+
if (guard.insideConfigFolder) {
|
|
6300
|
+
return { code: ERROR_PROTECTED_PATH, message: MESSAGE_PINGGY_FOLDER };
|
|
6301
|
+
}
|
|
6302
|
+
if (guard.inAccountsFolder) {
|
|
6303
|
+
return { code: ERROR_PROTECTED_PATH, message: MESSAGE_ACCOUNT_FOLDER };
|
|
6304
|
+
}
|
|
6305
|
+
const reason = guard.protectedSet.reasons.get(identityOf(stats));
|
|
6306
|
+
if (reason) {
|
|
6307
|
+
return { code: ERROR_PROTECTED_PATH, message: reason };
|
|
6308
|
+
}
|
|
6309
|
+
if (stats.dev !== folderDevice) {
|
|
6310
|
+
return { code: ERROR_MOUNT_POINT, message: mountMessage };
|
|
6311
|
+
}
|
|
6312
|
+
return null;
|
|
6313
|
+
}
|
|
6314
|
+
async function removeOld(hiddenOld, oldName, existing, protectedSet, dependencies, inPlaceMessage) {
|
|
6315
|
+
try {
|
|
6316
|
+
if (await removeTree(hiddenOld, existing, protectedSet, deleteDependencies(dependencies))) {
|
|
6317
|
+
return null;
|
|
6318
|
+
}
|
|
6319
|
+
return { code: ERROR_MOUNT_POINT, message: `${inPlaceMessage} ${oldName}: ${REASON_MOUNT_INSIDE}` };
|
|
6320
|
+
} catch (err) {
|
|
6321
|
+
const failure2 = deleteFailure(err);
|
|
6322
|
+
const message = sanitizeErrorMessage(`${inPlaceMessage} ${oldName}: ${failure2.message}`) ?? failure2.message;
|
|
6323
|
+
return { code: failure2.code, message };
|
|
6324
|
+
}
|
|
6325
|
+
}
|
|
6326
|
+
async function removeQuietly2(entry, protectedSet, dependencies) {
|
|
6327
|
+
try {
|
|
6328
|
+
const stats = await dependencies.remover.lstat(entry);
|
|
6329
|
+
await removeTree(entry, stats, protectedSet, deleteDependencies(dependencies));
|
|
6330
|
+
} catch {
|
|
6331
|
+
}
|
|
6332
|
+
}
|
|
6333
|
+
function deleteDependencies(dependencies) {
|
|
6334
|
+
const { remover, platform: platform3, protectedSources, callTimeoutMillis } = dependencies;
|
|
6335
|
+
return { remover, platform: platform3, protectedSources, callTimeoutMillis };
|
|
6336
|
+
}
|
|
6337
|
+
async function copyEntry(source, stats, target, walk, top) {
|
|
6338
|
+
if (stats.isSymbolicLink()) {
|
|
6339
|
+
await copyLink(source, target, walk, top);
|
|
6340
|
+
} else if (stats.isDirectory()) {
|
|
6341
|
+
await copyFolder(source, stats, target, walk, top);
|
|
6342
|
+
} else if (stats.isFile()) {
|
|
6343
|
+
await copyFile(source, stats, target, walk, top);
|
|
6344
|
+
} else {
|
|
6345
|
+
walk.specialFilesLeftOut += 1;
|
|
6346
|
+
}
|
|
6347
|
+
}
|
|
6348
|
+
async function copyFile(source, stats, target, walk, top) {
|
|
6349
|
+
const { copier, progress } = walk;
|
|
6350
|
+
const reader = await copier.openToRead(source);
|
|
6351
|
+
let writer;
|
|
6352
|
+
try {
|
|
6353
|
+
writer = await created(copier.createFile(target), top);
|
|
6354
|
+
} catch (err) {
|
|
6355
|
+
await closeQuietly(reader, copier);
|
|
6356
|
+
throw err;
|
|
6357
|
+
}
|
|
6358
|
+
const buffer = Buffer.allocUnsafe(Math.min(COPY_PIECE_BYTES, Math.max(SMALL_PIECE_BYTES, Number(stats.size) + 1)));
|
|
6359
|
+
try {
|
|
6360
|
+
for (; ; ) {
|
|
6361
|
+
const bytesRead = await copier.read(reader, buffer);
|
|
6362
|
+
if (bytesRead === 0) {
|
|
6363
|
+
break;
|
|
6364
|
+
}
|
|
6365
|
+
await copier.write(writer, buffer, bytesRead);
|
|
6366
|
+
progress.bytes_done += bytesRead;
|
|
6367
|
+
}
|
|
6368
|
+
await copier.close(writer);
|
|
6369
|
+
} catch (err) {
|
|
6370
|
+
await closeQuietly(writer, copier);
|
|
6371
|
+
await copier.unlink(target).catch(() => void 0);
|
|
6372
|
+
throw err;
|
|
6373
|
+
} finally {
|
|
6374
|
+
await closeQuietly(reader, copier);
|
|
6375
|
+
}
|
|
6376
|
+
await keepModeAndTimes(target, stats, copier);
|
|
6377
|
+
progress.files_done += 1;
|
|
6378
|
+
}
|
|
6379
|
+
async function copyFolder(source, stats, target, walk, top) {
|
|
6380
|
+
const { copier, paths } = walk;
|
|
6381
|
+
await created(copier.mkdir(target), top);
|
|
6382
|
+
walk.progress.files_done += 1;
|
|
6383
|
+
for (const child of await copier.readdir(source)) {
|
|
6384
|
+
const childSource = paths.join(source, child);
|
|
6385
|
+
let childStats;
|
|
6386
|
+
try {
|
|
6387
|
+
childStats = await copier.lstat(childSource);
|
|
6388
|
+
} catch (err) {
|
|
6389
|
+
if (errorCodeOf(err) === "ENOENT") {
|
|
6390
|
+
continue;
|
|
6391
|
+
}
|
|
6392
|
+
throw err;
|
|
6393
|
+
}
|
|
6394
|
+
await copyEntry(childSource, childStats, paths.join(target, child), walk, false);
|
|
6395
|
+
}
|
|
6396
|
+
await keepModeAndTimes(target, stats, copier);
|
|
6397
|
+
}
|
|
6398
|
+
async function copyLink(source, target, walk, top) {
|
|
6399
|
+
const { copier } = walk;
|
|
6400
|
+
const linkText = await copier.readlink(source);
|
|
6401
|
+
const type = walk.platform === "win32" ? await linkTypeOf(source, copier) : LINK_TYPE_FILE;
|
|
6402
|
+
await created(copier.symlink(linkText, target, type), top);
|
|
6403
|
+
walk.progress.files_done += 1;
|
|
6404
|
+
}
|
|
6405
|
+
async function linkTypeOf(link, copier) {
|
|
6406
|
+
try {
|
|
6407
|
+
return (await copier.stat(link)).isDirectory() ? LINK_TYPE_FOLDER : LINK_TYPE_FILE;
|
|
6408
|
+
} catch (err) {
|
|
6409
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6410
|
+
throw err;
|
|
6411
|
+
}
|
|
6412
|
+
return LINK_TYPE_FILE;
|
|
6413
|
+
}
|
|
6414
|
+
}
|
|
6415
|
+
async function keepModeAndTimes(target, stats, copier) {
|
|
6416
|
+
await copier.utimes(target, stats.atime, stats.mtime).catch(() => void 0);
|
|
6417
|
+
await copier.chmod(target, Number(stats.mode & PERMISSION_BITS)).catch(() => void 0);
|
|
6418
|
+
}
|
|
6419
|
+
async function created(making, top) {
|
|
6420
|
+
try {
|
|
6421
|
+
return await making;
|
|
6422
|
+
} catch (err) {
|
|
6423
|
+
if (top && errorCodeOf(err) === "EEXIST") {
|
|
6424
|
+
throw new TakenError(MESSAGE_NAME_TAKEN);
|
|
6425
|
+
}
|
|
6426
|
+
throw err;
|
|
6427
|
+
}
|
|
6428
|
+
}
|
|
6429
|
+
async function closeQuietly(handle, copier) {
|
|
6430
|
+
await copier.close(handle).catch(() => void 0);
|
|
6431
|
+
}
|
|
6432
|
+
function keepBothName(name, isFolder, number) {
|
|
6433
|
+
const suffix = ` (${number})`;
|
|
6434
|
+
const dot = isFolder ? -1 : name.lastIndexOf(EXTENSION_SEPARATOR2);
|
|
6435
|
+
let stem = dot > 0 ? name.slice(0, dot) : name;
|
|
6436
|
+
let extension = dot > 0 ? name.slice(dot) : "";
|
|
6437
|
+
if (Buffer.byteLength(suffix + extension, "utf8") >= MAX_NAME_BYTES) {
|
|
6438
|
+
stem = name;
|
|
6439
|
+
extension = "";
|
|
6440
|
+
}
|
|
6441
|
+
const room = MAX_NAME_BYTES - Buffer.byteLength(suffix + extension, "utf8");
|
|
6442
|
+
return `${cutToBytes(stem, room)}${suffix}${extension}`;
|
|
6443
|
+
}
|
|
6444
|
+
function hiddenName(targetName, mark, suffix) {
|
|
6445
|
+
const tail = `.pinggy-${mark}-${suffix}`;
|
|
6446
|
+
const room = MAX_NAME_BYTES - Buffer.byteLength(HIDDEN_NAME_PREFIX2 + tail, "utf8");
|
|
6447
|
+
return `${HIDDEN_NAME_PREFIX2}${cutToBytes(targetName, room)}${tail}`;
|
|
6448
|
+
}
|
|
6449
|
+
function cutToBytes(text, maxBytes) {
|
|
6450
|
+
let bytes = 0;
|
|
6451
|
+
let kept = "";
|
|
6452
|
+
for (const character of text) {
|
|
6453
|
+
const characterBytes = Buffer.byteLength(character, "utf8");
|
|
6454
|
+
if (bytes + characterBytes > maxBytes) {
|
|
6455
|
+
break;
|
|
6456
|
+
}
|
|
6457
|
+
kept += character;
|
|
6458
|
+
bytes += characterBytes;
|
|
6459
|
+
}
|
|
6460
|
+
return kept;
|
|
6461
|
+
}
|
|
6462
|
+
function formatBytes(bytes) {
|
|
6463
|
+
let value = Number(bytes);
|
|
6464
|
+
let unit = 0;
|
|
6465
|
+
while (value >= BYTES_PER_UNIT && unit < BYTE_UNITS.length - 1) {
|
|
6466
|
+
value /= BYTES_PER_UNIT;
|
|
6467
|
+
unit += 1;
|
|
6468
|
+
}
|
|
6469
|
+
if (unit > 0) {
|
|
6470
|
+
return `${value.toFixed(1)} ${BYTE_UNITS[unit]}`;
|
|
6471
|
+
}
|
|
6472
|
+
return value === 1 ? `1 ${BYTE_UNIT_SINGULAR}` : `${value} ${BYTE_UNITS[0]}`;
|
|
6473
|
+
}
|
|
6474
|
+
function isSpecial(stats) {
|
|
6475
|
+
return !stats.isFile() && !stats.isDirectory() && !stats.isSymbolicLink();
|
|
6476
|
+
}
|
|
6477
|
+
function specialFilesLeftOut(count) {
|
|
6478
|
+
const message = count === 1 ? "1 socket, pipe or device file inside was left out." : `${count} sockets, pipes or device files inside were left out.`;
|
|
6479
|
+
return { code: ERROR_SPECIAL_FILE, message };
|
|
6480
|
+
}
|
|
6481
|
+
async function lstatOrNull(target, copier) {
|
|
6482
|
+
try {
|
|
6483
|
+
return await copier.lstat(target);
|
|
6484
|
+
} catch (err) {
|
|
6485
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6486
|
+
throw err;
|
|
6487
|
+
}
|
|
6488
|
+
return null;
|
|
6489
|
+
}
|
|
6490
|
+
}
|
|
6491
|
+
async function identityOrNull2(read) {
|
|
6492
|
+
try {
|
|
6493
|
+
return identityOf(await read);
|
|
6494
|
+
} catch (err) {
|
|
6495
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6496
|
+
throw err;
|
|
6497
|
+
}
|
|
6498
|
+
return null;
|
|
6499
|
+
}
|
|
6500
|
+
}
|
|
6501
|
+
function copyFailure(err, fallbackMessage) {
|
|
6502
|
+
if (err instanceof TakenError) {
|
|
6503
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
6504
|
+
}
|
|
6505
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6506
|
+
return { code: ERROR_FILE_TIMEOUT, message: err.message };
|
|
6507
|
+
}
|
|
6508
|
+
const message = failureMessage(err, fallbackMessage);
|
|
6509
|
+
switch (errorCodeOf(err)) {
|
|
6510
|
+
case "ENOENT":
|
|
6511
|
+
case "ENOTDIR":
|
|
6512
|
+
return { code: ERROR_PATH_NOT_FOUND, message };
|
|
6513
|
+
case "EEXIST":
|
|
6514
|
+
return { code: ERROR_FILE_EXISTS, message };
|
|
6515
|
+
case "EACCES":
|
|
6516
|
+
case "EPERM":
|
|
6517
|
+
case "EROFS":
|
|
6518
|
+
return { code: ERROR_PERMISSION_DENIED, message };
|
|
6519
|
+
case "ENOSPC":
|
|
6520
|
+
case "EDQUOT":
|
|
6521
|
+
return { code: ERROR_NO_SPACE, message };
|
|
6522
|
+
default:
|
|
6523
|
+
return { code: ERROR_FILE_OPERATION_FAILED, message };
|
|
6524
|
+
}
|
|
6525
|
+
}
|
|
6526
|
+
|
|
6527
|
+
// src/devices/files/fileList.ts
|
|
6528
|
+
var ROOT_PROBE_TIMEOUT_MILLIS = 2e3;
|
|
6529
|
+
var WINDOWS_DRIVE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
6530
|
+
var POSIX_ROOT = "/";
|
|
6531
|
+
var WIDEST_NEXT_OFFSET = Number.MAX_SAFE_INTEGER;
|
|
6532
|
+
var NAME_COLLATOR = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
|
|
6533
|
+
var MESSAGE_LIST_FAILED = "The folder could not be read.";
|
|
6534
|
+
function folderReadFailure(err) {
|
|
6535
|
+
const message = failureMessage(err, MESSAGE_LIST_FAILED);
|
|
6536
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6537
|
+
return fileError(ERROR_FILE_TIMEOUT, message);
|
|
6538
|
+
}
|
|
6539
|
+
switch (errorCodeOf(err)) {
|
|
6540
|
+
case "ENOENT":
|
|
6541
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6542
|
+
case "ENOTDIR":
|
|
6543
|
+
return fileError(ERROR_NOT_A_DIRECTORY, message);
|
|
6544
|
+
case "EACCES":
|
|
6545
|
+
case "EPERM":
|
|
6546
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6547
|
+
default:
|
|
6548
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6549
|
+
}
|
|
6550
|
+
}
|
|
6551
|
+
function compareNames(left, right) {
|
|
6552
|
+
const byCollator = NAME_COLLATOR.compare(left, right);
|
|
6553
|
+
if (byCollator !== 0) return byCollator;
|
|
6554
|
+
if (left === right) return 0;
|
|
6555
|
+
return left < right ? -1 : 1;
|
|
6556
|
+
}
|
|
6557
|
+
async function readSortKeys(folder, dirents, dependencies, paths) {
|
|
6558
|
+
const keys = /* @__PURE__ */ new Map();
|
|
6559
|
+
await Promise.all(dirents.map(async (dirent) => {
|
|
6560
|
+
try {
|
|
6561
|
+
const stats = await dependencies.fs.lstat(paths.join(folder, dirent.name));
|
|
6562
|
+
keys.set(dirent.name, {
|
|
6563
|
+
sizeBytes: stats.isFile() ? stats.size : 0,
|
|
6564
|
+
modifiedMillis: stats.mtimeMs,
|
|
6565
|
+
createdMillis: stats.birthtimeMs
|
|
6566
|
+
});
|
|
6567
|
+
} catch {
|
|
6568
|
+
keys.set(dirent.name, { sizeBytes: 0, modifiedMillis: 0, createdMillis: 0 });
|
|
6569
|
+
}
|
|
6570
|
+
}));
|
|
6571
|
+
return keys;
|
|
6572
|
+
}
|
|
6573
|
+
function sortDirents(dirents, sortBy, descending, keys) {
|
|
6574
|
+
const direction = descending ? -1 : 1;
|
|
6575
|
+
return [...dirents].sort((left, right) => {
|
|
6576
|
+
const leftIsFolder = left.isDirectory();
|
|
6577
|
+
if (leftIsFolder !== right.isDirectory()) {
|
|
6578
|
+
return leftIsFolder ? -1 : 1;
|
|
6579
|
+
}
|
|
6580
|
+
let order = 0;
|
|
6581
|
+
if (keys && sortBy === SORT_BY_SIZE && !leftIsFolder) {
|
|
6582
|
+
order = keys.get(left.name).sizeBytes - keys.get(right.name).sizeBytes;
|
|
6583
|
+
} else if (keys && sortBy === SORT_BY_MODIFIED) {
|
|
6584
|
+
order = keys.get(left.name).modifiedMillis - keys.get(right.name).modifiedMillis;
|
|
6585
|
+
} else if (keys && sortBy === SORT_BY_CREATED) {
|
|
6586
|
+
order = keys.get(left.name).createdMillis - keys.get(right.name).createdMillis;
|
|
6587
|
+
}
|
|
6588
|
+
if (order === 0) {
|
|
6589
|
+
order = compareNames(left.name, right.name);
|
|
6590
|
+
}
|
|
6591
|
+
return order * direction;
|
|
6592
|
+
});
|
|
6593
|
+
}
|
|
6594
|
+
async function describeEntry(folder, dirent, dependencies, paths) {
|
|
6595
|
+
const fullPath = paths.join(folder, dirent.name);
|
|
6596
|
+
let stats;
|
|
6597
|
+
try {
|
|
6598
|
+
stats = await dependencies.fs.lstat(fullPath);
|
|
6599
|
+
} catch {
|
|
6600
|
+
return { name: dirent.name, type: "unknown" };
|
|
6601
|
+
}
|
|
6602
|
+
const type = entryTypeOf(stats);
|
|
6603
|
+
const entry = { name: dirent.name, type, modified_at: epochSeconds(stats.mtimeMs) };
|
|
6604
|
+
if (stats.birthtimeMs > 0) {
|
|
6605
|
+
entry.created_at = epochSeconds(stats.birthtimeMs);
|
|
6606
|
+
}
|
|
6607
|
+
if (type === "file") {
|
|
6608
|
+
entry.size_bytes = stats.size;
|
|
6609
|
+
}
|
|
6610
|
+
if (dirent.name.startsWith(HIDDEN_NAME_PREFIX)) {
|
|
6611
|
+
entry.hidden = true;
|
|
6612
|
+
}
|
|
6613
|
+
if (type === "symlink") {
|
|
6614
|
+
const { linkTarget, targetType } = await readLinkTarget(fullPath, dependencies.fs);
|
|
6615
|
+
if (linkTarget !== void 0) {
|
|
6616
|
+
entry.link_target = linkTarget;
|
|
6617
|
+
}
|
|
6618
|
+
if (targetType !== void 0) {
|
|
6619
|
+
entry.target_type = targetType;
|
|
6620
|
+
}
|
|
6621
|
+
}
|
|
6622
|
+
return entry;
|
|
6623
|
+
}
|
|
6624
|
+
async function listRoots(dependencies) {
|
|
6625
|
+
if (dependencies.platform !== "win32") {
|
|
6626
|
+
return [POSIX_ROOT];
|
|
6627
|
+
}
|
|
6628
|
+
const drives = [...WINDOWS_DRIVE_LETTERS].map((letter) => `${letter}:\\`);
|
|
6629
|
+
const answers = await Promise.all(drives.map((drive) => withTimeout(
|
|
6630
|
+
dependencies.fs.access(drive).then(() => true),
|
|
6631
|
+
ROOT_PROBE_TIMEOUT_MILLIS,
|
|
6632
|
+
false
|
|
6633
|
+
)));
|
|
6634
|
+
return drives.filter((_drive, index) => answers[index]);
|
|
6635
|
+
}
|
|
6636
|
+
async function listFolder(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
|
|
6637
|
+
try {
|
|
6638
|
+
return await listFolderOrThrow(request2, maxPayloadBytes, dependencies);
|
|
6639
|
+
} catch (err) {
|
|
6640
|
+
return folderReadFailure(err);
|
|
6641
|
+
}
|
|
6642
|
+
}
|
|
6643
|
+
async function listFolderOrThrow(request2, maxPayloadBytes, dependencies) {
|
|
6644
|
+
const paths = pathsFor(dependencies.platform);
|
|
6645
|
+
const firstOpen = request2.path === void 0;
|
|
6646
|
+
let folder;
|
|
6647
|
+
if (request2.path === void 0) {
|
|
6648
|
+
folder = paths.resolve(dependencies.fs.homedir());
|
|
6649
|
+
} else {
|
|
6650
|
+
const problem = pathProblem(request2.path, paths);
|
|
6651
|
+
if (problem) {
|
|
6652
|
+
return fileError(ERROR_INVALID_PATH, problem);
|
|
6653
|
+
}
|
|
6654
|
+
folder = paths.resolve(request2.path);
|
|
6655
|
+
}
|
|
6656
|
+
let dirents;
|
|
6657
|
+
try {
|
|
6658
|
+
dirents = await dependencies.fs.readdir(folder);
|
|
6659
|
+
} catch (err) {
|
|
6660
|
+
return folderReadFailure(err);
|
|
6661
|
+
}
|
|
6662
|
+
const visible = request2.include_hidden ? dirents : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX));
|
|
6663
|
+
const sortBy = request2.sort_by ?? SORT_BY_NAME;
|
|
6664
|
+
const keys = sortBy === SORT_BY_NAME ? null : await readSortKeys(folder, visible, dependencies, paths);
|
|
6665
|
+
const sorted = sortDirents(visible, sortBy, request2.sort_order === SORT_ORDER_DESC, keys);
|
|
6666
|
+
const offset = request2.offset ?? 0;
|
|
6667
|
+
const limit = request2.limit ?? DEFAULT_LIST_LIMIT;
|
|
6668
|
+
const page = sorted.slice(offset, offset + limit);
|
|
6669
|
+
const described = await Promise.all(page.map((dirent) => describeEntry(folder, dirent, dependencies, paths)));
|
|
6670
|
+
const parent = paths.dirname(folder);
|
|
6671
|
+
const answer = {
|
|
6672
|
+
path: folder,
|
|
6673
|
+
...parent !== folder ? { parent } : {},
|
|
6674
|
+
separator: paths.sep,
|
|
6675
|
+
total: visible.length,
|
|
6676
|
+
offset,
|
|
6677
|
+
entries: []
|
|
6678
|
+
};
|
|
6679
|
+
if (firstOpen) {
|
|
6680
|
+
answer.home = folder;
|
|
6681
|
+
answer.roots = await listRoots(dependencies);
|
|
6682
|
+
}
|
|
6683
|
+
let payloadBytes = utf8Bytes({ ...answer, next_offset: WIDEST_NEXT_OFFSET });
|
|
6684
|
+
for (const entry of described) {
|
|
6685
|
+
const entryBytes = utf8Bytes(entry) + (answer.entries.length > 0 ? 1 : 0);
|
|
6686
|
+
if (payloadBytes + entryBytes > maxPayloadBytes) {
|
|
6687
|
+
break;
|
|
6688
|
+
}
|
|
6689
|
+
answer.entries.push(entry);
|
|
6690
|
+
payloadBytes += entryBytes;
|
|
6691
|
+
}
|
|
6692
|
+
if (described.length > 0 && answer.entries.length === 0) {
|
|
6693
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, "The next entry does not fit in 1 frame.");
|
|
6694
|
+
}
|
|
6695
|
+
const nextOffset = offset + answer.entries.length;
|
|
6696
|
+
if (nextOffset < visible.length) {
|
|
6697
|
+
answer.next_offset = nextOffset;
|
|
6698
|
+
}
|
|
6699
|
+
return answer;
|
|
6700
|
+
}
|
|
6701
|
+
|
|
6702
|
+
// src/devices/files/fileMkdir.ts
|
|
6703
|
+
var MESSAGE_MKDIR_FAILED = "The folder could not be made.";
|
|
6704
|
+
async function makeFolder(request2, dependencies) {
|
|
6705
|
+
const { maker, platform: platform3, callTimeoutMillis } = dependencies;
|
|
6706
|
+
const paths = pathsFor(platform3);
|
|
6707
|
+
const pathIssue = pathProblem(request2.path, paths);
|
|
6708
|
+
if (pathIssue) {
|
|
6709
|
+
return fileError(ERROR_INVALID_PATH, pathIssue);
|
|
6710
|
+
}
|
|
6711
|
+
const item = withTrimmedName(resolvedItem(request2.path, paths));
|
|
6712
|
+
if (!isRoot(item.path, paths)) {
|
|
6713
|
+
const nameIssue = nameProblem(item.name, platform3);
|
|
6714
|
+
if (nameIssue) {
|
|
6715
|
+
return fileError(ERROR_INVALID_PAYLOAD2, nameIssue);
|
|
6716
|
+
}
|
|
6717
|
+
const windowsIssue = platform3 === "win32" ? windowsNameProblem(item.name) : null;
|
|
6718
|
+
if (windowsIssue) {
|
|
6719
|
+
return fileError(ERROR_INVALID_NAME, windowsIssue);
|
|
6720
|
+
}
|
|
6721
|
+
}
|
|
6722
|
+
try {
|
|
6723
|
+
await callWithTimeout(maker.mkdir(item.path), callTimeoutMillis);
|
|
6724
|
+
} catch (err) {
|
|
6725
|
+
return mkdirFailure(err);
|
|
6726
|
+
}
|
|
6727
|
+
return { path: item.path };
|
|
6728
|
+
}
|
|
6729
|
+
function mkdirFailure(err) {
|
|
6730
|
+
if (err instanceof FileCallTimeoutError) {
|
|
6731
|
+
return fileError(ERROR_FILE_TIMEOUT, err.message);
|
|
6732
|
+
}
|
|
6733
|
+
const message = failureMessage(err, MESSAGE_MKDIR_FAILED);
|
|
6734
|
+
switch (errorCodeOf(err)) {
|
|
6735
|
+
case "EEXIST":
|
|
6736
|
+
return fileError(ERROR_FILE_EXISTS, MESSAGE_NAME_TAKEN);
|
|
6737
|
+
case "ENOENT":
|
|
6738
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
6739
|
+
case "ENOTDIR":
|
|
6740
|
+
return fileError(ERROR_NOT_A_DIRECTORY, message);
|
|
6741
|
+
case "EACCES":
|
|
6742
|
+
case "EPERM":
|
|
6743
|
+
case "EROFS":
|
|
6744
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
6745
|
+
default:
|
|
6746
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
6747
|
+
}
|
|
6748
|
+
}
|
|
6749
|
+
|
|
6750
|
+
// src/devices/files/fileMove.ts
|
|
6751
|
+
var HIDDEN_MOVE_MARK = "move";
|
|
6752
|
+
var MESSAGE_INTO_ITSELF2 = "A folder cannot be moved into itself.";
|
|
6753
|
+
var MESSAGE_ALREADY_HERE = "The item is already in this folder.";
|
|
6754
|
+
var MESSAGE_SELECTED_MOUNT2 = "This folder is a mounted disk. Open it to move what is inside.";
|
|
6755
|
+
var MESSAGE_MOUNT_INSIDE2 = "Another disk is mounted inside. Pinggy does not move it to another disk.";
|
|
6756
|
+
var MESSAGE_SPECIAL_SELECTED2 = "This is a socket, pipe or device file. Pinggy cannot move it to another disk.";
|
|
6757
|
+
var MESSAGE_MOVED_IN_PLACE = "The item is in place. The old one stays as";
|
|
6758
|
+
var MESSAGE_ORIGINAL_STAYS = "The item is in its new place. The original could not be fully removed:";
|
|
6759
|
+
var MESSAGE_MOVE_FAILED = "The item could not be moved.";
|
|
6760
|
+
var PLACED = { placed: true, oldStays: null };
|
|
6761
|
+
async function prepareMove(request2, dependencies) {
|
|
6762
|
+
try {
|
|
6763
|
+
return await checkedMove(request2, dependencies);
|
|
6764
|
+
} catch (err) {
|
|
6765
|
+
return refusalOf(err);
|
|
6766
|
+
}
|
|
6767
|
+
}
|
|
6768
|
+
async function checkedMove(request2, dependencies) {
|
|
6769
|
+
const { copier, platform: platform3 } = dependencies;
|
|
6770
|
+
const paths = pathsFor(platform3);
|
|
6771
|
+
const { source, destination } = resolvedItems(request2, paths);
|
|
6772
|
+
checkTargetName(destination.name, platform3);
|
|
6773
|
+
const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_MOVE_FAILED);
|
|
6774
|
+
const sourceFolderStats = await folderStats(source.parent, copier);
|
|
6775
|
+
const destinationStats = await folderStats(destination.parent, copier);
|
|
6776
|
+
const sameFolder = identityOf(sourceFolderStats) === identityOf(destinationStats);
|
|
6777
|
+
await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF2);
|
|
6778
|
+
if (sameFolder && destination.name === source.name) {
|
|
6779
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_ALREADY_HERE));
|
|
6780
|
+
}
|
|
6781
|
+
const protectedSet = await readProtectedFolders(dependencies);
|
|
6782
|
+
const sourceGuard = await removalGuard(source.parent, sourceFolderStats, protectedSet, dependencies);
|
|
6783
|
+
const sourceRefusal = protectedRefusal(sourceStats, sourceFolderStats.dev, sourceGuard, MESSAGE_SELECTED_MOUNT2);
|
|
6784
|
+
if (sourceRefusal) {
|
|
6785
|
+
throw new RequestRefusal({ error: sourceRefusal });
|
|
6786
|
+
}
|
|
6787
|
+
const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
|
|
6788
|
+
if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
|
|
6789
|
+
await checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies);
|
|
6790
|
+
}
|
|
6791
|
+
const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(destination.parent, destinationStats, protectedSet, dependencies) : null;
|
|
6792
|
+
return {
|
|
6793
|
+
source: source.path,
|
|
6794
|
+
sourceStats,
|
|
6795
|
+
sourceName: source.name,
|
|
6796
|
+
destinationDirectory: destination.parent,
|
|
6797
|
+
targetName: destination.name,
|
|
6798
|
+
onConflict,
|
|
6799
|
+
destinationDevice: destinationStats.dev,
|
|
6800
|
+
sameFolder,
|
|
6801
|
+
acrossDisks: sourceFolderStats.dev !== destinationStats.dev,
|
|
6802
|
+
sourceGuard,
|
|
6803
|
+
replaceGuard
|
|
6804
|
+
};
|
|
6805
|
+
}
|
|
6806
|
+
async function checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies) {
|
|
6807
|
+
const target = await lstatOrNull(destination.path, dependencies.copier);
|
|
6808
|
+
if (target === null || isCaseOnlyRename(sameFolder, source.name, destination.name, sourceStats, target)) {
|
|
6809
|
+
return;
|
|
6810
|
+
}
|
|
6811
|
+
if (onConflict === ON_CONFLICT_REPLACE) {
|
|
6812
|
+
if (identityOf(target) === identityOf(sourceStats)) {
|
|
6813
|
+
throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
|
|
6814
|
+
}
|
|
6815
|
+
await refuseReplacingAHolder(target, source.parent, dependencies);
|
|
6816
|
+
return;
|
|
6817
|
+
}
|
|
6818
|
+
throw new RequestRefusal(targetTakenRefusal());
|
|
6819
|
+
}
|
|
6820
|
+
function isCaseOnlyRename(sameFolder, name, targetName, source, target) {
|
|
6821
|
+
return sameFolder && source !== null && name !== targetName && foldedName(name) === foldedName(targetName) && identityOf(source) === identityOf(target);
|
|
6822
|
+
}
|
|
6823
|
+
function foldedName(name) {
|
|
6824
|
+
return name.normalize("NFC").toLowerCase();
|
|
6825
|
+
}
|
|
6826
|
+
function moveProgress(prepared) {
|
|
6827
|
+
const progress = {
|
|
6828
|
+
items_done: 0,
|
|
6829
|
+
items_total: 1,
|
|
6830
|
+
files_done: 0,
|
|
6831
|
+
bytes_done: 0,
|
|
6832
|
+
current_name: prepared.sourceName
|
|
6833
|
+
};
|
|
6834
|
+
if (!prepared.acrossDisks) {
|
|
6835
|
+
progress.files_total = 1;
|
|
6836
|
+
progress.bytes_total = 0;
|
|
6837
|
+
}
|
|
6838
|
+
return progress;
|
|
6839
|
+
}
|
|
6840
|
+
async function runMove(prepared, progress, dependencies) {
|
|
6841
|
+
const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
|
|
6842
|
+
const item = {
|
|
6843
|
+
name: prepared.sourceName,
|
|
6844
|
+
targetName: prepared.targetName,
|
|
6845
|
+
source: prepared.source,
|
|
6846
|
+
stats: prepared.sourceStats
|
|
6847
|
+
};
|
|
6848
|
+
if (prepared.acrossDisks) {
|
|
6849
|
+
const refusal = await countAcross(item, prepared, counted, dependencies);
|
|
6850
|
+
if (refusal) {
|
|
6851
|
+
return refusal;
|
|
6852
|
+
}
|
|
6853
|
+
}
|
|
6854
|
+
const outcome = await moveItem(item, prepared, counted, dependencies);
|
|
6855
|
+
counted.items_done += 1;
|
|
6856
|
+
return outcomeAnswer(outcome);
|
|
6857
|
+
}
|
|
6858
|
+
async function countAcross(item, prepared, progress, dependencies) {
|
|
6859
|
+
const paths = pathsFor(dependencies.platform);
|
|
6860
|
+
const target = paths.join(prepared.destinationDirectory, item.targetName);
|
|
6861
|
+
if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, dependencies.copier).catch(() => null)) {
|
|
6862
|
+
progress.files_total = 0;
|
|
6863
|
+
progress.bytes_total = 0;
|
|
6864
|
+
return null;
|
|
6865
|
+
}
|
|
6866
|
+
const totals = await countItem(item, dependencies);
|
|
6867
|
+
const refusal = countRefusal(totals, item.stats);
|
|
6868
|
+
if (refusal) {
|
|
6869
|
+
return { error: refusal };
|
|
6870
|
+
}
|
|
6871
|
+
progress.files_total = totals.files;
|
|
6872
|
+
progress.bytes_total = totals.bytes;
|
|
6873
|
+
return noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
|
|
6874
|
+
}
|
|
6875
|
+
async function countItem(item, dependencies) {
|
|
6876
|
+
const totals = newCountTotals();
|
|
6877
|
+
await countEntry(item.source, totals, dependencies.copier, pathsFor(dependencies.platform), item.stats.dev);
|
|
6878
|
+
return totals;
|
|
6879
|
+
}
|
|
6880
|
+
function countRefusal(totals, stats) {
|
|
6881
|
+
if (totals.mountedDisks > 0) {
|
|
6882
|
+
return { code: ERROR_MOUNT_POINT, message: MESSAGE_MOUNT_INSIDE2 };
|
|
6883
|
+
}
|
|
6884
|
+
if (isSpecial(stats)) {
|
|
6885
|
+
return { code: ERROR_SPECIAL_FILE, message: MESSAGE_SPECIAL_SELECTED2 };
|
|
6886
|
+
}
|
|
6887
|
+
return totals.specialFiles > 0 ? specialInside(totals.specialFiles) : null;
|
|
6888
|
+
}
|
|
6889
|
+
function specialInside(count) {
|
|
6890
|
+
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.`;
|
|
6891
|
+
return { code: ERROR_SPECIAL_FILE, message };
|
|
6892
|
+
}
|
|
6893
|
+
async function moveItem(item, prepared, progress, dependencies) {
|
|
6894
|
+
if (prepared.acrossDisks) {
|
|
6895
|
+
return moveAcross(item, prepared, progress, dependencies);
|
|
6896
|
+
}
|
|
6897
|
+
try {
|
|
6898
|
+
const placement = await placeAt(item.source, item, prepared, dependencies, dependencies.hiddenNameSuffix());
|
|
6899
|
+
if (!placement.placed) {
|
|
6900
|
+
return placement.outcome;
|
|
6901
|
+
}
|
|
6902
|
+
progress.files_done += 1;
|
|
6903
|
+
return placement.oldStays;
|
|
6904
|
+
} catch (err) {
|
|
6905
|
+
if (errorCodeOf(err) !== "EXDEV") {
|
|
6906
|
+
return moveFailure(err);
|
|
6907
|
+
}
|
|
6908
|
+
}
|
|
6909
|
+
const totals = await countItem(item, dependencies);
|
|
6910
|
+
const refusal = countRefusal(totals, item.stats);
|
|
6911
|
+
if (refusal) {
|
|
6912
|
+
return refusal;
|
|
6913
|
+
}
|
|
6914
|
+
progress.files_total = (progress.files_total ?? 0) + totals.files - 1;
|
|
6915
|
+
progress.bytes_total = (progress.bytes_total ?? 0) + totals.bytes;
|
|
6916
|
+
return moveAcross(item, prepared, progress, dependencies);
|
|
6917
|
+
}
|
|
6918
|
+
async function moveAcross(item, prepared, progress, dependencies) {
|
|
6919
|
+
const { copier, platform: platform3 } = dependencies;
|
|
6920
|
+
const paths = pathsFor(platform3);
|
|
6921
|
+
const { protectedSet } = prepared.sourceGuard;
|
|
6922
|
+
try {
|
|
6923
|
+
const settledFirst = await targetBeforeCopy(item, prepared, dependencies);
|
|
6924
|
+
if (settledFirst) {
|
|
6925
|
+
return settledFirst;
|
|
6926
|
+
}
|
|
6927
|
+
} catch (err) {
|
|
6928
|
+
return moveFailure(err);
|
|
6929
|
+
}
|
|
6930
|
+
const suffix = dependencies.hiddenNameSuffix();
|
|
6931
|
+
const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(item.targetName, HIDDEN_MOVE_MARK, suffix));
|
|
6932
|
+
const walk = { copier, paths, platform: platform3, progress, specialFilesLeftOut: 0 };
|
|
6933
|
+
let placement;
|
|
6934
|
+
try {
|
|
6935
|
+
await copyEntry(item.source, item.stats, hiddenCopy, walk, true);
|
|
6936
|
+
if (walk.specialFilesLeftOut > 0) {
|
|
6937
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6938
|
+
return specialInside(walk.specialFilesLeftOut);
|
|
6939
|
+
}
|
|
6940
|
+
placement = await placeAt(hiddenCopy, item, prepared, dependencies, suffix);
|
|
6941
|
+
} catch (err) {
|
|
6942
|
+
if (!(err instanceof TakenError)) {
|
|
6943
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6944
|
+
}
|
|
6945
|
+
return moveFailure(err);
|
|
6946
|
+
}
|
|
6947
|
+
if (!placement.placed) {
|
|
6948
|
+
await removeQuietly2(hiddenCopy, protectedSet, dependencies);
|
|
6949
|
+
return placement.outcome;
|
|
6950
|
+
}
|
|
6951
|
+
return await removeOriginal(item, protectedSet, dependencies) ?? placement.oldStays;
|
|
6952
|
+
}
|
|
6953
|
+
async function targetBeforeCopy(item, prepared, dependencies) {
|
|
6954
|
+
if (prepared.onConflict === ON_CONFLICT_KEEP_BOTH) {
|
|
6955
|
+
return null;
|
|
6956
|
+
}
|
|
6957
|
+
const paths = pathsFor(dependencies.platform);
|
|
6958
|
+
const existing = await lstatOrNull(
|
|
6959
|
+
paths.join(prepared.destinationDirectory, item.targetName),
|
|
6960
|
+
dependencies.copier
|
|
6961
|
+
);
|
|
6962
|
+
if (existing === null) {
|
|
6963
|
+
return null;
|
|
6964
|
+
}
|
|
6965
|
+
switch (prepared.onConflict) {
|
|
6966
|
+
case ON_CONFLICT_SKIP:
|
|
6967
|
+
return SKIPPED;
|
|
6968
|
+
case ON_CONFLICT_REPLACE:
|
|
6969
|
+
return replaceRefusal(existing, item.stats, prepared.destinationDevice, prepared.replaceGuard);
|
|
6970
|
+
default:
|
|
6971
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
6972
|
+
}
|
|
6973
|
+
}
|
|
6974
|
+
async function placeAt(incoming, item, prepared, dependencies, suffix) {
|
|
6975
|
+
const { copier } = dependencies;
|
|
6976
|
+
const paths = pathsFor(dependencies.platform);
|
|
6977
|
+
const target = paths.join(prepared.destinationDirectory, item.targetName);
|
|
6978
|
+
const existing = await lstatOrNull(target, copier);
|
|
6979
|
+
if (existing === null || isCaseOnlyRename(prepared.sameFolder, item.name, item.targetName, item.stats, existing)) {
|
|
6980
|
+
await copier.rename(incoming, target);
|
|
6981
|
+
return PLACED;
|
|
6982
|
+
}
|
|
6983
|
+
switch (prepared.onConflict) {
|
|
6984
|
+
case ON_CONFLICT_SKIP:
|
|
6985
|
+
return { placed: false, outcome: SKIPPED };
|
|
6986
|
+
case ON_CONFLICT_KEEP_BOTH:
|
|
6987
|
+
return placeUnderFreeName(incoming, item, prepared, dependencies);
|
|
6988
|
+
case ON_CONFLICT_REPLACE:
|
|
6989
|
+
return replaceAt(incoming, existing, item, prepared, dependencies, suffix);
|
|
6990
|
+
default:
|
|
6991
|
+
return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
|
|
6992
|
+
}
|
|
6993
|
+
}
|
|
6994
|
+
async function placeUnderFreeName(incoming, item, prepared, dependencies) {
|
|
6995
|
+
const paths = pathsFor(dependencies.platform);
|
|
6996
|
+
for (let number = 1; number <= MAX_KEEP_BOTH_NUMBER; number++) {
|
|
6997
|
+
const candidate = paths.join(
|
|
6998
|
+
prepared.destinationDirectory,
|
|
6999
|
+
keepBothName(item.targetName, item.stats.isDirectory(), number)
|
|
7000
|
+
);
|
|
7001
|
+
if (await lstatOrNull(candidate, dependencies.copier) === null) {
|
|
7002
|
+
await dependencies.copier.rename(incoming, candidate);
|
|
7003
|
+
return PLACED;
|
|
7004
|
+
}
|
|
7005
|
+
}
|
|
7006
|
+
return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
|
|
7007
|
+
}
|
|
7008
|
+
async function replaceAt(incoming, existing, item, prepared, dependencies, suffix) {
|
|
7009
|
+
const guard = prepared.replaceGuard;
|
|
7010
|
+
const refusal = replaceRefusal(existing, item.stats, prepared.destinationDevice, guard);
|
|
7011
|
+
if (refusal) {
|
|
7012
|
+
return { placed: false, outcome: refusal };
|
|
7013
|
+
}
|
|
7014
|
+
const paths = pathsFor(dependencies.platform);
|
|
7015
|
+
const oldName = await swapIn(
|
|
7016
|
+
incoming,
|
|
7017
|
+
prepared.destinationDirectory,
|
|
7018
|
+
item.targetName,
|
|
7019
|
+
existing,
|
|
7020
|
+
item.stats.isDirectory(),
|
|
7021
|
+
suffix,
|
|
7022
|
+
dependencies.copier,
|
|
7023
|
+
paths
|
|
7024
|
+
);
|
|
7025
|
+
if (oldName === null) {
|
|
7026
|
+
return PLACED;
|
|
7027
|
+
}
|
|
7028
|
+
const oldStays = await removeOld(
|
|
7029
|
+
paths.join(prepared.destinationDirectory, oldName),
|
|
7030
|
+
oldName,
|
|
7031
|
+
existing,
|
|
7032
|
+
guard.protectedSet,
|
|
7033
|
+
dependencies,
|
|
7034
|
+
MESSAGE_MOVED_IN_PLACE
|
|
7035
|
+
);
|
|
7036
|
+
return { placed: true, oldStays };
|
|
7037
|
+
}
|
|
7038
|
+
async function removeOriginal(item, protectedSet, dependencies) {
|
|
7039
|
+
try {
|
|
7040
|
+
if (await removeTree(item.source, item.stats, protectedSet, deleteDependencies(dependencies))) {
|
|
7041
|
+
return null;
|
|
7042
|
+
}
|
|
7043
|
+
return { code: ERROR_MOUNT_POINT, message: `${MESSAGE_ORIGINAL_STAYS} ${REASON_MOUNT_INSIDE}` };
|
|
7044
|
+
} catch (err) {
|
|
7045
|
+
const failure2 = deleteFailure(err);
|
|
7046
|
+
const message = sanitizeErrorMessage(`${MESSAGE_ORIGINAL_STAYS} ${failure2.message}`) ?? failure2.message;
|
|
7047
|
+
return { code: failure2.code, message };
|
|
7048
|
+
}
|
|
7049
|
+
}
|
|
7050
|
+
function moveFailure(err) {
|
|
7051
|
+
switch (errorCodeOf(err)) {
|
|
7052
|
+
case "EBUSY":
|
|
7053
|
+
return { code: ERROR_PERMISSION_DENIED, message: failureMessage(err, MESSAGE_MOVE_FAILED) };
|
|
7054
|
+
case "ENOTEMPTY":
|
|
7055
|
+
case "EISDIR":
|
|
7056
|
+
return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
|
|
7057
|
+
default:
|
|
7058
|
+
return copyFailure(err, MESSAGE_MOVE_FAILED);
|
|
7059
|
+
}
|
|
7060
|
+
}
|
|
7061
|
+
|
|
7062
|
+
// src/devices/files/fileStat.ts
|
|
7063
|
+
import fs7 from "fs";
|
|
7064
|
+
var PERMISSION_BITS_MASK = 4095;
|
|
7065
|
+
var OCTAL_RADIX = 8;
|
|
7066
|
+
var MODE_DIGITS = 4;
|
|
7067
|
+
var MESSAGE_STAT_FAILED = "The path could not be read.";
|
|
7068
|
+
var MESSAGE_TOO_LARGE = "The details are too large to send.";
|
|
7069
|
+
function lstatFailure(err) {
|
|
7070
|
+
const message = failureMessage(err, MESSAGE_STAT_FAILED);
|
|
7071
|
+
if (err instanceof FileCallTimeoutError) {
|
|
7072
|
+
return fileError(ERROR_FILE_TIMEOUT, message);
|
|
7073
|
+
}
|
|
7074
|
+
switch (errorCodeOf(err)) {
|
|
7075
|
+
case "ENOENT":
|
|
7076
|
+
case "ENOTDIR":
|
|
7077
|
+
return fileError(ERROR_PATH_NOT_FOUND, message);
|
|
7078
|
+
case "EACCES":
|
|
7079
|
+
case "EPERM":
|
|
7080
|
+
return fileError(ERROR_PERMISSION_DENIED, message);
|
|
7081
|
+
default:
|
|
7082
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, message);
|
|
7083
|
+
}
|
|
7084
|
+
}
|
|
7085
|
+
function modeDigits(mode) {
|
|
7086
|
+
return (mode & PERMISSION_BITS_MASK).toString(OCTAL_RADIX).padStart(MODE_DIGITS, "0");
|
|
7087
|
+
}
|
|
7088
|
+
async function hasAccess(target, mode, dependencies) {
|
|
7089
|
+
try {
|
|
7090
|
+
await dependencies.fs.access(target, mode);
|
|
7091
|
+
return true;
|
|
7092
|
+
} catch {
|
|
7093
|
+
return false;
|
|
7094
|
+
}
|
|
7095
|
+
}
|
|
7096
|
+
async function countEntries(folder, includeHidden, dependencies) {
|
|
7097
|
+
try {
|
|
7098
|
+
const dirents = await dependencies.fs.readdir(folder);
|
|
7099
|
+
return includeHidden ? dirents.length : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX)).length;
|
|
7100
|
+
} catch {
|
|
7101
|
+
return void 0;
|
|
7102
|
+
}
|
|
7103
|
+
}
|
|
7104
|
+
async function statPath(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
|
|
7105
|
+
try {
|
|
7106
|
+
return await statPathOrThrow(request2, maxPayloadBytes, dependencies);
|
|
7107
|
+
} catch (err) {
|
|
7108
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, failureMessage(err, MESSAGE_STAT_FAILED));
|
|
7109
|
+
}
|
|
7110
|
+
}
|
|
7111
|
+
async function statPathOrThrow(request2, maxPayloadBytes, dependencies) {
|
|
7112
|
+
const paths = pathsFor(dependencies.platform);
|
|
7113
|
+
const problem = pathProblem(request2.path, paths);
|
|
7114
|
+
if (problem) {
|
|
7115
|
+
return fileError(ERROR_INVALID_PATH, problem);
|
|
7116
|
+
}
|
|
7117
|
+
const target = paths.resolve(request2.path);
|
|
7118
|
+
let stats;
|
|
7119
|
+
try {
|
|
7120
|
+
stats = await dependencies.fs.lstat(target);
|
|
7121
|
+
} catch (err) {
|
|
7122
|
+
return lstatFailure(err);
|
|
7123
|
+
}
|
|
7124
|
+
const type = entryTypeOf(stats);
|
|
7125
|
+
const name = paths.basename(target) || target;
|
|
7126
|
+
const onWindows = dependencies.platform === "win32";
|
|
7127
|
+
const answer = {
|
|
7128
|
+
path: target,
|
|
7129
|
+
name,
|
|
7130
|
+
type,
|
|
7131
|
+
...type === "file" ? { size_bytes: stats.size } : {},
|
|
7132
|
+
modified_at: epochSeconds(stats.mtimeMs),
|
|
7133
|
+
accessed_at: epochSeconds(stats.atimeMs),
|
|
7134
|
+
// 0 is a filesystem with no birth time. Some report the change time instead, which cannot be told apart.
|
|
7135
|
+
...stats.birthtimeMs > 0 ? { created_at: epochSeconds(stats.birthtimeMs) } : {},
|
|
7136
|
+
...name.startsWith(HIDDEN_NAME_PREFIX) ? { hidden: true } : {}
|
|
7137
|
+
};
|
|
7138
|
+
if (!onWindows) {
|
|
7139
|
+
answer.mode = modeDigits(stats.mode);
|
|
7140
|
+
answer.uid = stats.uid;
|
|
7141
|
+
answer.gid = stats.gid;
|
|
7142
|
+
}
|
|
7143
|
+
if (!onWindows && type !== "symlink") {
|
|
7144
|
+
const [readable, writable, executable] = await Promise.all([
|
|
7145
|
+
hasAccess(target, fs7.constants.R_OK, dependencies),
|
|
7146
|
+
hasAccess(target, fs7.constants.W_OK, dependencies),
|
|
7147
|
+
hasAccess(target, fs7.constants.X_OK, dependencies)
|
|
7148
|
+
]);
|
|
7149
|
+
Object.assign(answer, { readable, writable, executable });
|
|
7150
|
+
}
|
|
7151
|
+
if (type === "directory") {
|
|
7152
|
+
const entryCount = await countEntries(target, request2.include_hidden === true, dependencies);
|
|
7153
|
+
if (entryCount !== void 0) {
|
|
7154
|
+
answer.entry_count = entryCount;
|
|
7155
|
+
}
|
|
7156
|
+
}
|
|
7157
|
+
if (type === "symlink") {
|
|
7158
|
+
const { linkTarget, targetType, targetStats } = await readLinkTarget(target, dependencies.fs);
|
|
7159
|
+
if (linkTarget !== void 0) {
|
|
7160
|
+
answer.link_target = linkTarget;
|
|
7161
|
+
}
|
|
7162
|
+
if (targetType !== void 0) {
|
|
7163
|
+
answer.target_type = targetType;
|
|
7164
|
+
}
|
|
7165
|
+
if (targetStats?.isFile()) {
|
|
7166
|
+
answer.target_size_bytes = targetStats.size;
|
|
7167
|
+
}
|
|
7168
|
+
}
|
|
7169
|
+
if (utf8Bytes(answer) > maxPayloadBytes) {
|
|
7170
|
+
delete answer.link_target;
|
|
7171
|
+
}
|
|
7172
|
+
if (utf8Bytes(answer) > maxPayloadBytes) {
|
|
7173
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, MESSAGE_TOO_LARGE);
|
|
7174
|
+
}
|
|
7175
|
+
return answer;
|
|
7176
|
+
}
|
|
7177
|
+
|
|
7178
|
+
// src/devices/files/fileHandler.ts
|
|
7179
|
+
var DEFAULT_READ_TIMEOUT_MILLIS = 2e4;
|
|
7180
|
+
var DEFAULT_DELETE_CALL_TIMEOUT_MILLIS = 2e4;
|
|
7181
|
+
var DEFAULT_MKDIR_TIMEOUT_MILLIS = 2e4;
|
|
7182
|
+
var DEFAULT_COPY_CALL_TIMEOUT_MILLIS = 2e4;
|
|
7183
|
+
var DEFAULT_FILE_CALL_PLACES = 2;
|
|
7184
|
+
var MILLIS_PER_SECOND2 = 1e3;
|
|
7185
|
+
var PROGRESS_TICK_MILLIS = 1e3;
|
|
7186
|
+
var PROGRESS_KEEPALIVE_TICKS = 5;
|
|
7187
|
+
var QUEUED_KEEPALIVE_MILLIS = PROGRESS_TICK_MILLIS * PROGRESS_KEEPALIVE_TICKS;
|
|
7188
|
+
var NULL_PAYLOAD_BYTES = Buffer.byteLength("null", "utf8");
|
|
7189
|
+
var OUTCOME_ANSWERED = "answered";
|
|
7190
|
+
var FILE_ACCESS_OFF_MESSAGE = "File access is off on this device. To allow it, run on the device: pinggy device connect --files on";
|
|
7191
|
+
var HANDLED_OPS = /* @__PURE__ */ new Set([OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE]);
|
|
7192
|
+
var FileHandler = class {
|
|
7193
|
+
constructor(dependencies) {
|
|
7194
|
+
this.dependencies = dependencies;
|
|
7195
|
+
this.enabled = false;
|
|
7196
|
+
this.maxFrameBytes = 0;
|
|
7197
|
+
this.maxConcurrentOperations = 0;
|
|
7198
|
+
this.maxQueuedOperations = 0;
|
|
7199
|
+
this.runningOperations = 0;
|
|
7200
|
+
/** Oldest first. The first is the next to start. */
|
|
7201
|
+
this.waitingOperations = [];
|
|
7202
|
+
this.queuedKeepalive = null;
|
|
7203
|
+
const gate = new FileCallGate(dependencies.fileCallPlaces ?? DEFAULT_FILE_CALL_PLACES);
|
|
7204
|
+
const fileSystem = dependencies.fileSystem ?? machineFileSystemDependencies;
|
|
7205
|
+
this.gatedFileSystem = {
|
|
7206
|
+
platform: fileSystem.platform,
|
|
7207
|
+
fs: gatedReader(fileSystem.fs, gate, this.readTimeoutMillis())
|
|
7208
|
+
};
|
|
7209
|
+
this.gatedRemover = gatedRemover(
|
|
7210
|
+
dependencies.remover ?? machineFileSystemRemover,
|
|
7211
|
+
gate,
|
|
7212
|
+
this.deleteCallTimeoutMillis()
|
|
7213
|
+
);
|
|
7214
|
+
this.gatedMaker = gatedMaker(dependencies.maker ?? machineFileSystemMaker, gate, this.mkdirTimeoutMillis());
|
|
7215
|
+
this.gatedCopier = gatedCopier(
|
|
7216
|
+
dependencies.copier ?? machineFileSystemCopier,
|
|
7217
|
+
gate,
|
|
7218
|
+
this.copyCallTimeoutMillis()
|
|
7219
|
+
);
|
|
7220
|
+
}
|
|
7221
|
+
/**
|
|
7222
|
+
* From each `welcome`. `max_frame_bytes` is the dashboard's cap on 1 frame from this agent. Without
|
|
7223
|
+
* `file_max_concurrent_operations`, no delete, copy or move runs, and without `file_max_queued_operations`, none
|
|
7224
|
+
* waits. Requests already waiting keep their place: more slots start them, and no slot at all refuses them with
|
|
7225
|
+
* `file_busy`, since none would ever start.
|
|
7226
|
+
*/
|
|
7227
|
+
configure(fileManagerEnabled, maxFrameBytes, maxConcurrentOperations, maxQueuedOperations) {
|
|
7228
|
+
this.enabled = fileManagerEnabled === true;
|
|
7229
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
7230
|
+
this.maxConcurrentOperations = maxConcurrentOperations ?? 0;
|
|
7231
|
+
this.maxQueuedOperations = maxQueuedOperations ?? 0;
|
|
7232
|
+
this.admitWaiting();
|
|
7233
|
+
}
|
|
7234
|
+
async handle(envelope) {
|
|
7235
|
+
if (envelope.kind !== "req") {
|
|
7236
|
+
return;
|
|
7237
|
+
}
|
|
7238
|
+
if (!HANDLED_OPS.has(envelope.op)) {
|
|
7239
|
+
this.answer(envelope, fileError(ERROR_UNSUPPORTED_OP2, `Unsupported operation: file/${envelope.op}`));
|
|
7240
|
+
return;
|
|
7241
|
+
}
|
|
7242
|
+
if (!this.enabled) {
|
|
7243
|
+
this.answer(envelope, fileError(ERROR_FILE_MANAGER_DISABLED, "The file manager is disabled."));
|
|
7244
|
+
return;
|
|
7245
|
+
}
|
|
7246
|
+
if (this.dependencies.fileAccessAllowed?.() === false) {
|
|
7247
|
+
this.answer(envelope, fileError(ERROR_FILE_ACCESS_OFF, FILE_ACCESS_OFF_MESSAGE));
|
|
7248
|
+
return;
|
|
7249
|
+
}
|
|
7250
|
+
this.answer(envelope, await this.run(envelope));
|
|
7251
|
+
}
|
|
7252
|
+
run(envelope) {
|
|
7253
|
+
switch (envelope.op) {
|
|
7254
|
+
case OP_LIST:
|
|
7255
|
+
return this.list(envelope);
|
|
7256
|
+
case OP_STAT:
|
|
7257
|
+
return this.stat(envelope);
|
|
7258
|
+
case OP_MKDIR:
|
|
7259
|
+
return this.mkdir(envelope);
|
|
7260
|
+
case OP_COPY:
|
|
7261
|
+
return this.copy(envelope);
|
|
7262
|
+
case OP_MOVE:
|
|
7263
|
+
return this.move(envelope);
|
|
7264
|
+
default:
|
|
7265
|
+
return this.delete(envelope);
|
|
7266
|
+
}
|
|
7267
|
+
}
|
|
7268
|
+
list(envelope) {
|
|
7269
|
+
const parsed = FileListRequestSchema.safeParse(envelope.payload);
|
|
7270
|
+
if (!parsed.success) {
|
|
7271
|
+
return Promise.resolve(invalidPayload());
|
|
7272
|
+
}
|
|
7273
|
+
const listing = afterThisTurn(() => listFolder(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
|
|
7274
|
+
return withTimeout(listing, this.readTimeoutMillis(), this.timedOut("The folder"));
|
|
7275
|
+
}
|
|
7276
|
+
stat(envelope) {
|
|
7277
|
+
const parsed = FileStatRequestSchema.safeParse(envelope.payload);
|
|
7278
|
+
if (!parsed.success) {
|
|
7279
|
+
return Promise.resolve(invalidPayload());
|
|
7280
|
+
}
|
|
7281
|
+
const details = afterThisTurn(() => statPath(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
|
|
7282
|
+
return withTimeout(details, this.readTimeoutMillis(), this.timedOut("The path"));
|
|
7283
|
+
}
|
|
7284
|
+
mkdir(envelope) {
|
|
7285
|
+
const parsed = FileMkdirRequestSchema.safeParse(envelope.payload);
|
|
7286
|
+
if (!parsed.success) {
|
|
7287
|
+
return Promise.resolve(invalidPayload());
|
|
7288
|
+
}
|
|
7289
|
+
return makeFolder(parsed.data, {
|
|
7290
|
+
maker: this.gatedMaker,
|
|
7291
|
+
platform: this.fileSystem().platform,
|
|
7292
|
+
callTimeoutMillis: this.mkdirTimeoutMillis()
|
|
7293
|
+
});
|
|
7294
|
+
}
|
|
7295
|
+
delete(envelope) {
|
|
7296
|
+
const parsed = FileDeleteRequestSchema.safeParse(envelope.payload);
|
|
7297
|
+
if (!parsed.success) {
|
|
7298
|
+
return Promise.resolve(invalidPayload());
|
|
7299
|
+
}
|
|
7300
|
+
return this.inSlot(envelope, "delete", () => this.deleteInSlot(envelope, parsed.data));
|
|
7301
|
+
}
|
|
7302
|
+
copy(envelope) {
|
|
7303
|
+
const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
|
|
7304
|
+
if (!parsed.success) {
|
|
7305
|
+
return Promise.resolve(invalidPayload());
|
|
7306
|
+
}
|
|
7307
|
+
return this.inSlot(envelope, "copy", () => this.copyInSlot(envelope, parsed.data));
|
|
7308
|
+
}
|
|
7309
|
+
move(envelope) {
|
|
7310
|
+
const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
|
|
7311
|
+
if (!parsed.success) {
|
|
7312
|
+
return Promise.resolve(invalidPayload());
|
|
7313
|
+
}
|
|
7314
|
+
return this.inSlot(envelope, "move", () => this.moveInSlot(envelope, parsed.data));
|
|
7315
|
+
}
|
|
7316
|
+
/** Holds 1 slot from {@link takeSlot} to the answer. */
|
|
7317
|
+
async inSlot(envelope, operation, work) {
|
|
7318
|
+
const refusal = await this.takeSlot(envelope);
|
|
7319
|
+
if (refusal) {
|
|
7320
|
+
return refusal;
|
|
7321
|
+
}
|
|
7322
|
+
try {
|
|
7323
|
+
return await work();
|
|
7324
|
+
} catch (err) {
|
|
7325
|
+
logger.warn(`Device agent file ${operation} stopped`, { id: envelope.id, code: errorCodeOf(err) });
|
|
7326
|
+
return fileError(ERROR_FILE_OPERATION_FAILED, `The ${operation} stopped unexpectedly.`);
|
|
7327
|
+
} finally {
|
|
7328
|
+
this.runningOperations -= 1;
|
|
7329
|
+
this.admitWaiting();
|
|
7330
|
+
}
|
|
7331
|
+
}
|
|
7332
|
+
/**
|
|
7333
|
+
* Null once this request holds a slot: at once when 1 is free and nobody waits, else when its turn in line
|
|
7334
|
+
* comes. `file_busy` at once when the line is full, or no slot is allowed.
|
|
7335
|
+
*/
|
|
7336
|
+
takeSlot(envelope) {
|
|
7337
|
+
if (this.runningOperations < this.maxConcurrentOperations && this.waitingOperations.length === 0) {
|
|
7338
|
+
this.runningOperations += 1;
|
|
7339
|
+
return Promise.resolve(null);
|
|
7340
|
+
}
|
|
7341
|
+
if (this.maxConcurrentOperations <= 0 || this.waitingOperations.length >= this.maxQueuedOperations) {
|
|
7342
|
+
return Promise.resolve(busy(this.maxConcurrentOperations, this.waitingOperations.length));
|
|
7343
|
+
}
|
|
7344
|
+
return new Promise((admit) => {
|
|
7345
|
+
this.waitingOperations.push({ envelope, admit });
|
|
7346
|
+
this.sendQueuedPosition(envelope, this.waitingOperations.length);
|
|
7347
|
+
this.startQueuedKeepalive();
|
|
7348
|
+
});
|
|
7349
|
+
}
|
|
7350
|
+
/**
|
|
7351
|
+
* Hands each free slot to the oldest request waiting, and counts it as running at once, so a request that
|
|
7352
|
+
* arrives before the waiting one resumes cannot take its slot. Those still waiting hear their new place.
|
|
7353
|
+
*/
|
|
7354
|
+
admitWaiting() {
|
|
7355
|
+
if (this.waitingOperations.length === 0) {
|
|
7356
|
+
return;
|
|
7357
|
+
}
|
|
7358
|
+
if (this.maxConcurrentOperations <= 0) {
|
|
7359
|
+
const refusal = busy(this.maxConcurrentOperations, 0);
|
|
7360
|
+
this.waitingOperations.splice(0).forEach((waiting) => waiting.admit(refusal));
|
|
7361
|
+
this.stopQueuedKeepalive();
|
|
7362
|
+
return;
|
|
7363
|
+
}
|
|
7364
|
+
let admitted = 0;
|
|
7365
|
+
while (this.waitingOperations.length > 0 && this.runningOperations < this.maxConcurrentOperations) {
|
|
7366
|
+
this.runningOperations += 1;
|
|
7367
|
+
this.waitingOperations.shift().admit(null);
|
|
7368
|
+
admitted += 1;
|
|
7369
|
+
}
|
|
7370
|
+
if (this.waitingOperations.length === 0) {
|
|
7371
|
+
this.stopQueuedKeepalive();
|
|
7372
|
+
} else if (admitted > 0) {
|
|
7373
|
+
this.sendQueuedPositions();
|
|
7374
|
+
}
|
|
7375
|
+
}
|
|
7376
|
+
sendQueuedPosition(envelope, position) {
|
|
7377
|
+
const payload = { queued_position: position };
|
|
7378
|
+
this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, payload, envelope.id));
|
|
7379
|
+
}
|
|
7380
|
+
sendQueuedPositions() {
|
|
7381
|
+
this.waitingOperations.forEach((waiting, index) => this.sendQueuedPosition(waiting.envelope, index + 1));
|
|
7382
|
+
}
|
|
7383
|
+
/** 1 timer for the whole line, running only while someone waits. */
|
|
7384
|
+
startQueuedKeepalive() {
|
|
7385
|
+
if (this.queuedKeepalive === null) {
|
|
7386
|
+
this.queuedKeepalive = setInterval(() => this.sendQueuedPositions(), QUEUED_KEEPALIVE_MILLIS);
|
|
7387
|
+
}
|
|
7388
|
+
}
|
|
7389
|
+
stopQueuedKeepalive() {
|
|
7390
|
+
if (this.queuedKeepalive !== null) {
|
|
7391
|
+
clearInterval(this.queuedKeepalive);
|
|
7392
|
+
this.queuedKeepalive = null;
|
|
7393
|
+
}
|
|
7394
|
+
}
|
|
7395
|
+
/** A refusal from the checks sends no counted `progress`: nothing was deleted, and the answer comes at once. */
|
|
7396
|
+
async deleteInSlot(envelope, request2) {
|
|
7397
|
+
const dependencies = this.deleteDependencies();
|
|
7398
|
+
const prepared = await prepareDelete(request2, dependencies);
|
|
7399
|
+
if ("error" in prepared) {
|
|
7400
|
+
return prepared;
|
|
7401
|
+
}
|
|
7402
|
+
const progress = { items_done: 0, items_total: 1, files_done: 0, current_name: prepared.name };
|
|
7403
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7404
|
+
try {
|
|
7405
|
+
return await runDelete(prepared, progress, dependencies);
|
|
7406
|
+
} finally {
|
|
7407
|
+
stopProgress();
|
|
7408
|
+
}
|
|
7409
|
+
}
|
|
7410
|
+
/**
|
|
7411
|
+
* A refusal from the checks sends no counted `progress`: nothing was copied, and the answer comes at once.
|
|
7412
|
+
* `progress` starts before the count, so a large tree keeps the browser's timer alive while it is counted, and a
|
|
7413
|
+
* `no_space` answer follows it.
|
|
7414
|
+
*/
|
|
7415
|
+
async copyInSlot(envelope, request2) {
|
|
7416
|
+
const dependencies = this.copyDependencies();
|
|
7417
|
+
const prepared = await prepareCopy(request2, dependencies);
|
|
7418
|
+
if ("error" in prepared) {
|
|
7419
|
+
return prepared;
|
|
7420
|
+
}
|
|
7421
|
+
const progress = {
|
|
7422
|
+
items_done: 0,
|
|
7423
|
+
items_total: 1,
|
|
7424
|
+
files_done: 0,
|
|
7425
|
+
bytes_done: 0,
|
|
7426
|
+
current_name: prepared.sourceName
|
|
7427
|
+
};
|
|
7428
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7429
|
+
try {
|
|
7430
|
+
return await runCopy(prepared, progress, dependencies);
|
|
7431
|
+
} finally {
|
|
7432
|
+
stopProgress();
|
|
7433
|
+
}
|
|
7434
|
+
}
|
|
7435
|
+
/**
|
|
7436
|
+
* As for a copy. On 1 disk the first `progress` already holds the totals, since there is nothing to count. To
|
|
7437
|
+
* another disk it starts before the count, as a copy's does.
|
|
7438
|
+
*/
|
|
7439
|
+
async moveInSlot(envelope, request2) {
|
|
7440
|
+
const dependencies = this.copyDependencies();
|
|
7441
|
+
const prepared = await prepareMove(request2, dependencies);
|
|
7442
|
+
if ("error" in prepared) {
|
|
7443
|
+
return prepared;
|
|
7444
|
+
}
|
|
7445
|
+
const progress = moveProgress(prepared);
|
|
7446
|
+
const stopProgress = this.startProgress(envelope, progress);
|
|
7447
|
+
try {
|
|
7448
|
+
return await runMove(prepared, progress, dependencies);
|
|
7449
|
+
} finally {
|
|
7450
|
+
stopProgress();
|
|
7451
|
+
}
|
|
7452
|
+
}
|
|
7453
|
+
/** Sends 1 `progress` now, then from a timer. Returns the stop, which the answer waits for. */
|
|
7454
|
+
startProgress(envelope, progress) {
|
|
7455
|
+
let lastSent = this.sendProgress(envelope, progress);
|
|
7456
|
+
let ticksSinceSent = 0;
|
|
7457
|
+
const timer = setInterval(() => {
|
|
7458
|
+
ticksSinceSent += 1;
|
|
7459
|
+
if (sameProgress(progress, lastSent) && ticksSinceSent < PROGRESS_KEEPALIVE_TICKS) {
|
|
7460
|
+
return;
|
|
7461
|
+
}
|
|
7462
|
+
lastSent = this.sendProgress(envelope, progress);
|
|
7463
|
+
ticksSinceSent = 0;
|
|
7464
|
+
}, PROGRESS_TICK_MILLIS);
|
|
7465
|
+
return () => clearInterval(timer);
|
|
7466
|
+
}
|
|
7467
|
+
/** Sends a snapshot, since the op keeps counting into `progress`. Returns the snapshot sent. */
|
|
7468
|
+
sendProgress(envelope, progress) {
|
|
7469
|
+
const snapshot = { ...progress };
|
|
7470
|
+
this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, snapshot, envelope.id));
|
|
7471
|
+
return snapshot;
|
|
7472
|
+
}
|
|
7473
|
+
deleteDependencies() {
|
|
7474
|
+
return {
|
|
7475
|
+
remover: this.gatedRemover,
|
|
7476
|
+
platform: this.fileSystem().platform,
|
|
7477
|
+
protectedSources: this.dependencies.protectedSources ?? machineProtectedSources(),
|
|
7478
|
+
callTimeoutMillis: this.deleteCallTimeoutMillis()
|
|
7479
|
+
};
|
|
7480
|
+
}
|
|
7481
|
+
copyDependencies() {
|
|
7482
|
+
return {
|
|
7483
|
+
...this.deleteDependencies(),
|
|
7484
|
+
copier: this.gatedCopier,
|
|
7485
|
+
hiddenNameSuffix: this.dependencies.hiddenNameSuffix ?? randomHiddenNameSuffix
|
|
7486
|
+
};
|
|
5025
7487
|
}
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
return failure(ERROR_TUNNEL_NOT_FOUND, "No tunnel on this machine runs that config.");
|
|
7488
|
+
fileSystem() {
|
|
7489
|
+
return this.gatedFileSystem;
|
|
5029
7490
|
}
|
|
5030
|
-
|
|
5031
|
-
|
|
5032
|
-
async function handleTunnelAction(envelope, send, dependencies = machineTunnelActionDependencies) {
|
|
5033
|
-
if (envelope.kind !== "req") {
|
|
5034
|
-
return;
|
|
7491
|
+
deleteCallTimeoutMillis() {
|
|
7492
|
+
return this.dependencies.deleteCallTimeoutMillis ?? DEFAULT_DELETE_CALL_TIMEOUT_MILLIS;
|
|
5035
7493
|
}
|
|
5036
|
-
|
|
5037
|
-
|
|
5038
|
-
send(response(envelope, op, failure(ERROR_UNSUPPORTED_OP, `Unsupported operation: tunnel/${op}`)));
|
|
5039
|
-
return;
|
|
7494
|
+
copyCallTimeoutMillis() {
|
|
7495
|
+
return this.dependencies.copyCallTimeoutMillis ?? DEFAULT_COPY_CALL_TIMEOUT_MILLIS;
|
|
5040
7496
|
}
|
|
5041
|
-
|
|
5042
|
-
|
|
5043
|
-
send(response(envelope, op, failure(ERROR_INVALID_PAYLOAD, "The tunnel request could not be read.")));
|
|
5044
|
-
return;
|
|
7497
|
+
mkdirTimeoutMillis() {
|
|
7498
|
+
return this.dependencies.mkdirTimeoutMillis ?? DEFAULT_MKDIR_TIMEOUT_MILLIS;
|
|
5045
7499
|
}
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
result = await perform(op, parsed.data, dependencies);
|
|
5049
|
-
} catch (err) {
|
|
5050
|
-
result = actionFailed(err instanceof Error ? err.message : String(err));
|
|
7500
|
+
readTimeoutMillis() {
|
|
7501
|
+
return this.dependencies.readTimeoutMillis ?? DEFAULT_READ_TIMEOUT_MILLIS;
|
|
5051
7502
|
}
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
7503
|
+
/** "The folder took longer than 20 s to read." */
|
|
7504
|
+
timedOut(subject) {
|
|
7505
|
+
const seconds = Math.round(this.readTimeoutMillis() / MILLIS_PER_SECOND2);
|
|
7506
|
+
return fileError(ERROR_FILE_TIMEOUT, `${subject} took longer than ${seconds} s to read.`);
|
|
7507
|
+
}
|
|
7508
|
+
/** What is left of `max_frame_bytes` once the answer's envelope is counted. */
|
|
7509
|
+
payloadBudget(envelope) {
|
|
7510
|
+
const envelopeBytes = Buffer.byteLength(JSON.stringify(response(envelope, envelope.op, null)), "utf8");
|
|
7511
|
+
return this.maxFrameBytes - (envelopeBytes - NULL_PAYLOAD_BYTES);
|
|
7512
|
+
}
|
|
7513
|
+
answer(envelope, result) {
|
|
7514
|
+
logger.debug("Device agent file request", {
|
|
7515
|
+
op: envelope.op,
|
|
7516
|
+
id: envelope.id,
|
|
7517
|
+
outcome: "error" in result ? result.error.code : OUTCOME_ANSWERED
|
|
7518
|
+
});
|
|
7519
|
+
this.dependencies.send(response(envelope, envelope.op, result));
|
|
7520
|
+
}
|
|
7521
|
+
};
|
|
7522
|
+
function afterThisTurn(work) {
|
|
7523
|
+
return Promise.resolve().then(work);
|
|
5060
7524
|
}
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
var INITIAL_DELAY_MILLIS = 1e3;
|
|
5064
|
-
var MAX_DELAY_MILLIS = 6e4;
|
|
5065
|
-
var STABLE_CONNECTION_MILLIS = 6e4;
|
|
5066
|
-
var MAX_ATTEMPT = Math.ceil(Math.log2(MAX_DELAY_MILLIS / INITIAL_DELAY_MILLIS));
|
|
5067
|
-
function backoffCeilingMillis(attempt) {
|
|
5068
|
-
const uncapped = INITIAL_DELAY_MILLIS * 2 ** Math.max(0, attempt);
|
|
5069
|
-
return Math.min(uncapped, MAX_DELAY_MILLIS);
|
|
7525
|
+
function sameProgress(left, right) {
|
|
7526
|
+
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;
|
|
5070
7527
|
}
|
|
5071
|
-
function
|
|
5072
|
-
return
|
|
7528
|
+
function invalidPayload() {
|
|
7529
|
+
return fileError(ERROR_INVALID_PAYLOAD2, "The file request could not be read.");
|
|
5073
7530
|
}
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
this.
|
|
5077
|
-
this.connectedAtMillis = null;
|
|
5078
|
-
this.now = options.now ?? Date.now;
|
|
5079
|
-
this.random = options.random ?? Math.random;
|
|
7531
|
+
function busy(limit, waiting) {
|
|
7532
|
+
if (limit <= 0) {
|
|
7533
|
+
return fileError(ERROR_FILE_BUSY, "The dashboard allows no file operations on this device.");
|
|
5080
7534
|
}
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
7535
|
+
const noun = limit === 1 ? "file operation" : "file operations";
|
|
7536
|
+
const running = `The device is already running ${limit} ${noun}`;
|
|
7537
|
+
if (waiting <= 0) {
|
|
7538
|
+
return fileError(ERROR_FILE_BUSY, `${running}.`);
|
|
5084
7539
|
}
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
7540
|
+
const verb = waiting === 1 ? "is" : "are";
|
|
7541
|
+
return fileError(ERROR_FILE_BUSY, `${running}, and ${waiting} more ${verb} waiting.`);
|
|
7542
|
+
}
|
|
7543
|
+
|
|
7544
|
+
// src/devices/login/prompts.ts
|
|
7545
|
+
import pico4 from "picocolors";
|
|
7546
|
+
import { createInterface as createInterface2 } from "readline/promises";
|
|
7547
|
+
import { Writable } from "stream";
|
|
7548
|
+
var QUESTION_MARKER = pico4.cyan(pico4.bold("\u2192"));
|
|
7549
|
+
function createTerminalPrompter(input, output) {
|
|
7550
|
+
return {
|
|
7551
|
+
async ask(question, signal) {
|
|
7552
|
+
const readline = createInterface2({ input, output, terminal: true });
|
|
7553
|
+
try {
|
|
7554
|
+
return await readline.question(marked(question), signal ? { signal } : {});
|
|
7555
|
+
} finally {
|
|
7556
|
+
readline.close();
|
|
7557
|
+
}
|
|
7558
|
+
},
|
|
7559
|
+
async askHidden(question, signal) {
|
|
7560
|
+
output.write(marked(question));
|
|
7561
|
+
const readline = createInterface2({ input, output: discardingOutput(), terminal: true });
|
|
7562
|
+
try {
|
|
7563
|
+
const answer = await readline.question("", signal ? { signal } : {});
|
|
7564
|
+
output.write("\n");
|
|
7565
|
+
return answer;
|
|
7566
|
+
} finally {
|
|
7567
|
+
readline.close();
|
|
7568
|
+
}
|
|
7569
|
+
}
|
|
7570
|
+
};
|
|
7571
|
+
}
|
|
7572
|
+
var terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
|
|
7573
|
+
function isInteractiveTerminal() {
|
|
7574
|
+
return process.stdin.isTTY === true;
|
|
7575
|
+
}
|
|
7576
|
+
var ABORT_ERROR_NAME = "AbortError";
|
|
7577
|
+
function isCtrlCAtPrompt(err) {
|
|
7578
|
+
return err instanceof Error && err.name === ABORT_ERROR_NAME;
|
|
7579
|
+
}
|
|
7580
|
+
function marked(question) {
|
|
7581
|
+
return `${QUESTION_MARKER} ${question}`;
|
|
7582
|
+
}
|
|
7583
|
+
function discardingOutput() {
|
|
7584
|
+
return new Writable({
|
|
7585
|
+
write(_chunk, _encoding, callback) {
|
|
7586
|
+
callback();
|
|
7587
|
+
}
|
|
7588
|
+
});
|
|
7589
|
+
}
|
|
7590
|
+
|
|
7591
|
+
// src/devices/fileAccess.ts
|
|
7592
|
+
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] ";
|
|
7593
|
+
var INVALID_FILES_FLAG_MESSAGE = "--files takes on or off.";
|
|
7594
|
+
var FILES_FLAG_ON = "on";
|
|
7595
|
+
var FILES_FLAG_OFF = "off";
|
|
7596
|
+
var NO_ANSWER2 = /^n/i;
|
|
7597
|
+
var FILE_ACCESS_ON_MESSAGE = "File access is on. To turn it off, run: pinggy device connect --files off";
|
|
7598
|
+
var FILE_ACCESS_OFF_MESSAGE2 = "File access is off. To allow it, run: pinggy device connect --files on";
|
|
7599
|
+
function machineFileAccessDependencies() {
|
|
7600
|
+
return {
|
|
7601
|
+
prompter: terminalPrompter,
|
|
7602
|
+
isInteractive: isInteractiveTerminal,
|
|
7603
|
+
writeIdentity: writeDeviceIdentity,
|
|
7604
|
+
print: (message) => printer_default.print(message)
|
|
7605
|
+
};
|
|
7606
|
+
}
|
|
7607
|
+
function parseFilesFlag(value) {
|
|
7608
|
+
if (value === void 0) {
|
|
7609
|
+
return void 0;
|
|
5088
7610
|
}
|
|
5089
|
-
|
|
5090
|
-
|
|
7611
|
+
switch (value.trim().toLowerCase()) {
|
|
7612
|
+
case FILES_FLAG_ON:
|
|
7613
|
+
return true;
|
|
7614
|
+
case FILES_FLAG_OFF:
|
|
7615
|
+
return false;
|
|
7616
|
+
default:
|
|
7617
|
+
return null;
|
|
5091
7618
|
}
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
const wasStable = heldMillis >= STABLE_CONNECTION_MILLIS;
|
|
5100
|
-
if (wasStable) {
|
|
5101
|
-
this.attemptCount = 0;
|
|
7619
|
+
}
|
|
7620
|
+
async function settleFileAccess(flag, token, stored, dependencies) {
|
|
7621
|
+
const storedForToken = stored?.token === token ? stored : null;
|
|
7622
|
+
let answer = flag;
|
|
7623
|
+
if (answer === void 0) {
|
|
7624
|
+
if (typeof storedForToken?.file_manager === "boolean" || !dependencies.isInteractive()) {
|
|
7625
|
+
return void 0;
|
|
5102
7626
|
}
|
|
5103
|
-
|
|
7627
|
+
answer = !NO_ANSWER2.test((await dependencies.prompter.ask(FILE_ACCESS_QUESTION)).trim());
|
|
5104
7628
|
}
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
const delay = fullJitterMillis(this.nextCeilingMillis, this.random);
|
|
5108
|
-
this.attemptCount = Math.min(this.attemptCount + 1, MAX_ATTEMPT);
|
|
5109
|
-
return delay;
|
|
7629
|
+
if (storedForToken) {
|
|
7630
|
+
dependencies.writeIdentity({ ...storedForToken, file_manager: answer });
|
|
5110
7631
|
}
|
|
5111
|
-
|
|
7632
|
+
dependencies.print(answer ? FILE_ACCESS_ON_MESSAGE : FILE_ACCESS_OFF_MESSAGE2);
|
|
7633
|
+
return answer;
|
|
7634
|
+
}
|
|
7635
|
+
function fileAccessAllowed() {
|
|
7636
|
+
return readDeviceIdentity()?.file_manager !== false;
|
|
7637
|
+
}
|
|
7638
|
+
function describeFileAccess(identity) {
|
|
7639
|
+
if (identity.file_manager === true) {
|
|
7640
|
+
return "on";
|
|
7641
|
+
}
|
|
7642
|
+
if (identity.file_manager === false) {
|
|
7643
|
+
return "off";
|
|
7644
|
+
}
|
|
7645
|
+
return "on, not asked yet";
|
|
7646
|
+
}
|
|
5112
7647
|
|
|
5113
7648
|
// src/devices/terminal/terminal_schema.ts
|
|
5114
|
-
import { z as
|
|
7649
|
+
import { z as z5 } from "zod";
|
|
5115
7650
|
var CHANNEL_TERMINAL = "terminal";
|
|
5116
7651
|
var OP_OPEN = "open";
|
|
5117
7652
|
var OP_OPENED = "opened";
|
|
@@ -5130,43 +7665,43 @@ var MIN_GRID = 1;
|
|
|
5130
7665
|
var MAX_GRID = 1e3;
|
|
5131
7666
|
var CLOSE_REASON_USER_CLOSED = "user_closed";
|
|
5132
7667
|
var CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
|
|
5133
|
-
var
|
|
7668
|
+
var ERROR_INVALID_PAYLOAD3 = "invalid_payload";
|
|
5134
7669
|
var ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
|
|
5135
7670
|
var ERROR_TERMINAL_DISABLED = "terminal_disabled";
|
|
5136
7671
|
var ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
|
|
5137
7672
|
var ERROR_SPAWN_FAILED = "spawn_failed";
|
|
5138
|
-
var TerminalOpenSchema =
|
|
5139
|
-
terminal_id:
|
|
5140
|
-
cols:
|
|
5141
|
-
rows:
|
|
5142
|
-
shell:
|
|
5143
|
-
cwd:
|
|
7673
|
+
var TerminalOpenSchema = z5.object({
|
|
7674
|
+
terminal_id: z5.string().min(1),
|
|
7675
|
+
cols: z5.number().int().optional(),
|
|
7676
|
+
rows: z5.number().int().optional(),
|
|
7677
|
+
shell: z5.string().nullable().optional(),
|
|
7678
|
+
cwd: z5.string().nullable().optional()
|
|
5144
7679
|
});
|
|
5145
|
-
var TerminalCloseSchema =
|
|
5146
|
-
terminal_id:
|
|
5147
|
-
reason:
|
|
7680
|
+
var TerminalCloseSchema = z5.object({
|
|
7681
|
+
terminal_id: z5.string().min(1),
|
|
7682
|
+
reason: z5.string().optional()
|
|
5148
7683
|
});
|
|
5149
|
-
var TerminalResizeSchema =
|
|
5150
|
-
terminal_id:
|
|
5151
|
-
cols:
|
|
5152
|
-
rows:
|
|
7684
|
+
var TerminalResizeSchema = z5.object({
|
|
7685
|
+
terminal_id: z5.string().min(1),
|
|
7686
|
+
cols: z5.number().int(),
|
|
7687
|
+
rows: z5.number().int()
|
|
5153
7688
|
});
|
|
5154
|
-
var TerminalInputSchema =
|
|
5155
|
-
terminal_id:
|
|
5156
|
-
data:
|
|
7689
|
+
var TerminalInputSchema = z5.object({
|
|
7690
|
+
terminal_id: z5.string().min(1),
|
|
7691
|
+
data: z5.string()
|
|
5157
7692
|
});
|
|
5158
|
-
var TerminalSignalSchema =
|
|
5159
|
-
terminal_id:
|
|
5160
|
-
signal:
|
|
7693
|
+
var TerminalSignalSchema = z5.object({
|
|
7694
|
+
terminal_id: z5.string().min(1),
|
|
7695
|
+
signal: z5.enum(TERMINAL_SIGNALS)
|
|
5161
7696
|
});
|
|
5162
|
-
var TerminalAckSchema =
|
|
5163
|
-
terminal_id:
|
|
5164
|
-
ack_seq:
|
|
5165
|
-
ack_bytes:
|
|
7697
|
+
var TerminalAckSchema = z5.object({
|
|
7698
|
+
terminal_id: z5.string().min(1),
|
|
7699
|
+
ack_seq: z5.number().optional(),
|
|
7700
|
+
ack_bytes: z5.number()
|
|
5166
7701
|
});
|
|
5167
|
-
var TerminalSnapshotRequestSchema =
|
|
5168
|
-
terminal_id:
|
|
5169
|
-
snapshot_id:
|
|
7702
|
+
var TerminalSnapshotRequestSchema = z5.object({
|
|
7703
|
+
terminal_id: z5.string().min(1),
|
|
7704
|
+
snapshot_id: z5.string().min(1)
|
|
5170
7705
|
});
|
|
5171
7706
|
function clampGrid(requested, fallback) {
|
|
5172
7707
|
if (requested === void 0 || !Number.isFinite(requested)) return fallback;
|
|
@@ -5175,7 +7710,7 @@ function clampGrid(requested, fallback) {
|
|
|
5175
7710
|
|
|
5176
7711
|
// src/devices/terminal/terminalHandler.ts
|
|
5177
7712
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
5178
|
-
import
|
|
7713
|
+
import os9 from "os";
|
|
5179
7714
|
|
|
5180
7715
|
// src/devices/terminal/flowWindow.ts
|
|
5181
7716
|
var FlowWindow = class {
|
|
@@ -5300,8 +7835,8 @@ var FrameSplitter = class {
|
|
|
5300
7835
|
|
|
5301
7836
|
// src/devices/terminal/shellContext.ts
|
|
5302
7837
|
import { execFile as execFile2 } from "child_process";
|
|
5303
|
-
import
|
|
5304
|
-
import
|
|
7838
|
+
import fs8 from "fs";
|
|
7839
|
+
import os8 from "os";
|
|
5305
7840
|
var SHELL_CONTEXT_POLL_MILLIS = 5e3;
|
|
5306
7841
|
var MAX_CWD_CHARACTERS = 1024;
|
|
5307
7842
|
var MAX_COMMAND_CHARACTERS = 64;
|
|
@@ -5332,7 +7867,7 @@ function displayCwd(rawCwd, resolvedHome) {
|
|
|
5332
7867
|
}
|
|
5333
7868
|
function resolvedHomeDirectory() {
|
|
5334
7869
|
try {
|
|
5335
|
-
return
|
|
7870
|
+
return fs8.realpathSync(os8.homedir());
|
|
5336
7871
|
} catch {
|
|
5337
7872
|
return null;
|
|
5338
7873
|
}
|
|
@@ -5384,14 +7919,14 @@ async function readFromProc(shellPids) {
|
|
|
5384
7919
|
await Promise.all(shellPids.map(async (shellPid) => {
|
|
5385
7920
|
const groups = await readProcGroups(shellPid);
|
|
5386
7921
|
if (!groups) return;
|
|
5387
|
-
const cwd = await readOrNull(() =>
|
|
5388
|
-
const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() =>
|
|
7922
|
+
const cwd = await readOrNull(() => fs8.promises.readlink(`/proc/${shellPid}/cwd`));
|
|
7923
|
+
const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => fs8.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
|
|
5389
7924
|
contexts.set(shellPid, { cwd, foregroundName });
|
|
5390
7925
|
}));
|
|
5391
7926
|
return contexts;
|
|
5392
7927
|
}
|
|
5393
7928
|
async function readProcGroups(shellPid) {
|
|
5394
|
-
const stat = await readOrNull(() =>
|
|
7929
|
+
const stat = await readOrNull(() => fs8.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
|
|
5395
7930
|
if (stat === null) return null;
|
|
5396
7931
|
const afterName = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
5397
7932
|
const shellGroupId = Number.parseInt(afterName[2], 10);
|
|
@@ -5573,7 +8108,7 @@ function errorName(err) {
|
|
|
5573
8108
|
var DEFAULT_COLS = 80;
|
|
5574
8109
|
var DEFAULT_ROWS = 24;
|
|
5575
8110
|
var EXPIRY_CHECK_MILLIS = 5e3;
|
|
5576
|
-
var
|
|
8111
|
+
var MILLIS_PER_SECOND3 = 1e3;
|
|
5577
8112
|
var RESYNC_MIN_INTERVAL_MILLIS = 1e3;
|
|
5578
8113
|
var MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
|
|
5579
8114
|
var MIRROR_LOW_WATER_BYTES = 256 * 1024;
|
|
@@ -5779,7 +8314,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
5779
8314
|
open(envelope) {
|
|
5780
8315
|
const parsed = TerminalOpenSchema.safeParse(envelope.payload);
|
|
5781
8316
|
if (!parsed.success) {
|
|
5782
|
-
this.refuse(envelope, null,
|
|
8317
|
+
this.refuse(envelope, null, ERROR_INVALID_PAYLOAD3, "open payload could not be read.");
|
|
5783
8318
|
return;
|
|
5784
8319
|
}
|
|
5785
8320
|
const request2 = parsed.data;
|
|
@@ -6302,7 +8837,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
6302
8837
|
}
|
|
6303
8838
|
};
|
|
6304
8839
|
function positiveMillis(seconds) {
|
|
6305
|
-
return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds *
|
|
8840
|
+
return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND3 : void 0;
|
|
6306
8841
|
}
|
|
6307
8842
|
function splitIntoParts(bytes, partBytes) {
|
|
6308
8843
|
const parts = [];
|
|
@@ -6315,7 +8850,7 @@ function errorName2(err) {
|
|
|
6315
8850
|
return err instanceof Error ? err.name : typeof err;
|
|
6316
8851
|
}
|
|
6317
8852
|
function signalName(signal) {
|
|
6318
|
-
for (const [name, number] of Object.entries(
|
|
8853
|
+
for (const [name, number] of Object.entries(os9.constants.signals)) {
|
|
6319
8854
|
if (number === signal) return name.replace(/^SIG/, "");
|
|
6320
8855
|
}
|
|
6321
8856
|
return String(signal);
|
|
@@ -6376,8 +8911,8 @@ var TerminalRegistry = class {
|
|
|
6376
8911
|
|
|
6377
8912
|
// src/devices/terminal/ptySession.ts
|
|
6378
8913
|
import { execFile as execFile3 } from "child_process";
|
|
6379
|
-
import
|
|
6380
|
-
import
|
|
8914
|
+
import fs9 from "fs";
|
|
8915
|
+
import os10 from "os";
|
|
6381
8916
|
var loadedPty;
|
|
6382
8917
|
var TERM_NAME = "xterm-256color";
|
|
6383
8918
|
function foregroundProcessGroup(shellPid) {
|
|
@@ -6425,11 +8960,11 @@ function ensureSpawnHelperExecutable(packageRoot) {
|
|
|
6425
8960
|
function resolveCwd(requested) {
|
|
6426
8961
|
if (requested) {
|
|
6427
8962
|
try {
|
|
6428
|
-
if (
|
|
8963
|
+
if (fs9.statSync(requested).isDirectory()) return requested;
|
|
6429
8964
|
} catch {
|
|
6430
8965
|
}
|
|
6431
8966
|
}
|
|
6432
|
-
return
|
|
8967
|
+
return os10.homedir();
|
|
6433
8968
|
}
|
|
6434
8969
|
function spawnPty(request2) {
|
|
6435
8970
|
const pty = loadNodePty();
|
|
@@ -6475,14 +9010,14 @@ function spawnPty(request2) {
|
|
|
6475
9010
|
}
|
|
6476
9011
|
|
|
6477
9012
|
// src/devices/terminal/shellAllowlist.ts
|
|
6478
|
-
import
|
|
9013
|
+
import fs10 from "fs";
|
|
6479
9014
|
var FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
|
|
6480
9015
|
var WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
|
|
6481
9016
|
var ETC_SHELLS_PATH = "/etc/shells";
|
|
6482
9017
|
function readShellEnvironment() {
|
|
6483
9018
|
let etcShells = null;
|
|
6484
9019
|
try {
|
|
6485
|
-
etcShells =
|
|
9020
|
+
etcShells = fs10.readFileSync(ETC_SHELLS_PATH, "utf8");
|
|
6486
9021
|
} catch {
|
|
6487
9022
|
etcShells = null;
|
|
6488
9023
|
}
|
|
@@ -6490,9 +9025,9 @@ function readShellEnvironment() {
|
|
|
6490
9025
|
platform: process.platform,
|
|
6491
9026
|
loginShell: process.env.SHELL,
|
|
6492
9027
|
etcShells,
|
|
6493
|
-
exists: (
|
|
9028
|
+
exists: (path9) => {
|
|
6494
9029
|
try {
|
|
6495
|
-
return
|
|
9030
|
+
return fs10.statSync(path9).isFile();
|
|
6496
9031
|
} catch {
|
|
6497
9032
|
return false;
|
|
6498
9033
|
}
|
|
@@ -6525,13 +9060,13 @@ function resolveShell(requested, environment) {
|
|
|
6525
9060
|
}
|
|
6526
9061
|
|
|
6527
9062
|
// src/devices/foregroundAgent.ts
|
|
6528
|
-
import
|
|
9063
|
+
import fs11 from "fs";
|
|
6529
9064
|
var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
|
|
6530
9065
|
var STOP_WAIT_MILLIS = 1e4;
|
|
6531
9066
|
var STOP_POLL_INTERVAL_MILLIS = 200;
|
|
6532
9067
|
function readRecordFile(filePath) {
|
|
6533
9068
|
try {
|
|
6534
|
-
const record = JSON.parse(
|
|
9069
|
+
const record = JSON.parse(fs11.readFileSync(filePath, "utf-8"));
|
|
6535
9070
|
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
6536
9071
|
} catch {
|
|
6537
9072
|
return null;
|
|
@@ -6539,7 +9074,7 @@ function readRecordFile(filePath) {
|
|
|
6539
9074
|
}
|
|
6540
9075
|
function deleteRecordFile(filePath) {
|
|
6541
9076
|
try {
|
|
6542
|
-
|
|
9077
|
+
fs11.unlinkSync(filePath);
|
|
6543
9078
|
} catch (err) {
|
|
6544
9079
|
logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
|
|
6545
9080
|
}
|
|
@@ -6569,7 +9104,7 @@ function recordForegroundAgent(onRecordDeleted) {
|
|
|
6569
9104
|
};
|
|
6570
9105
|
try {
|
|
6571
9106
|
ensurePinggyConfigDir();
|
|
6572
|
-
|
|
9107
|
+
fs11.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
|
|
6573
9108
|
} catch (err) {
|
|
6574
9109
|
logger.warn(
|
|
6575
9110
|
"Could not write device-agent.json. pinggy device remove cannot stop this agent.",
|
|
@@ -6578,7 +9113,7 @@ function recordForegroundAgent(onRecordDeleted) {
|
|
|
6578
9113
|
return () => void 0;
|
|
6579
9114
|
}
|
|
6580
9115
|
const timer = setInterval(() => {
|
|
6581
|
-
if (!
|
|
9116
|
+
if (!fs11.existsSync(filePath)) {
|
|
6582
9117
|
clearInterval(timer);
|
|
6583
9118
|
onRecordDeleted();
|
|
6584
9119
|
}
|
|
@@ -6641,7 +9176,14 @@ var UNAUTHORIZED_STORED_TOKEN_MESSAGE = "The dashboard refused this machine's de
|
|
|
6641
9176
|
var UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
|
|
6642
9177
|
var HANDSHAKE_TIMEOUT_MILLIS = 3e4;
|
|
6643
9178
|
var PONG_GRACE_INTERVALS = 2;
|
|
6644
|
-
var BASE_CAPABILITIES = [
|
|
9179
|
+
var BASE_CAPABILITIES = [
|
|
9180
|
+
"tunnel",
|
|
9181
|
+
"stats",
|
|
9182
|
+
"tunnel_control",
|
|
9183
|
+
"tunnel_update",
|
|
9184
|
+
"saved_config_update",
|
|
9185
|
+
"file_manager"
|
|
9186
|
+
];
|
|
6645
9187
|
var CAPABILITY_TERMINAL = "terminal";
|
|
6646
9188
|
var CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
|
|
6647
9189
|
var CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
|
|
@@ -6672,8 +9214,8 @@ function sleep3(millis, state) {
|
|
|
6672
9214
|
function buildHello(terminalHandler) {
|
|
6673
9215
|
return {
|
|
6674
9216
|
agent_version: getVersion(),
|
|
6675
|
-
os:
|
|
6676
|
-
hostname:
|
|
9217
|
+
os: os11.platform(),
|
|
9218
|
+
hostname: os11.hostname(),
|
|
6677
9219
|
capabilities: buildCapabilities(isTerminalSupported(), isScreenMirrorSupported()),
|
|
6678
9220
|
terminals: terminalHandler.held()
|
|
6679
9221
|
};
|
|
@@ -6692,11 +9234,13 @@ function startMetricsReporting(intervalSeconds, collect, send) {
|
|
|
6692
9234
|
clearInterval(timer);
|
|
6693
9235
|
};
|
|
6694
9236
|
}
|
|
6695
|
-
function identityForRun(token, server, stored) {
|
|
6696
|
-
|
|
6697
|
-
|
|
9237
|
+
function identityForRun(token, server, stored, fileManager) {
|
|
9238
|
+
const identity = stored?.token === token ? { ...stored, server } : { device_agent_id: null, token, server, enrolled_at: null };
|
|
9239
|
+
delete identity.file_manager;
|
|
9240
|
+
if (fileManager !== void 0) {
|
|
9241
|
+
identity.file_manager = fileManager;
|
|
6698
9242
|
}
|
|
6699
|
-
return
|
|
9243
|
+
return identity;
|
|
6700
9244
|
}
|
|
6701
9245
|
function startDeviceAgent(token, manage, options = {}) {
|
|
6702
9246
|
const server = manage || DEFAULT_SERVER;
|
|
@@ -6707,7 +9251,7 @@ function startDeviceAgent(token, manage, options = {}) {
|
|
|
6707
9251
|
const context = {
|
|
6708
9252
|
wsUrl: buildDeviceAgentWsUrl(manage),
|
|
6709
9253
|
server,
|
|
6710
|
-
identity: identityForRun(token, server, stored),
|
|
9254
|
+
identity: identityForRun(token, server, stored, options.fileManager),
|
|
6711
9255
|
reconnectPolicy: options.reconnectPolicy ?? new ReconnectPolicy(),
|
|
6712
9256
|
handshakeTimeoutMillis: options.handshakeTimeoutMillis ?? HANDSHAKE_TIMEOUT_MILLIS,
|
|
6713
9257
|
terminalHandler: new TerminalHandler({
|
|
@@ -6718,6 +9262,7 @@ function startDeviceAgent(token, manage, options = {}) {
|
|
|
6718
9262
|
readShellContexts: processTableReader(),
|
|
6719
9263
|
resolvedHome: resolvedHomeDirectory()
|
|
6720
9264
|
}),
|
|
9265
|
+
fileHandler: new FileHandler({ send: (frame) => connection.send?.(frame), fileAccessAllowed }),
|
|
6721
9266
|
connection,
|
|
6722
9267
|
reporter,
|
|
6723
9268
|
writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
|
|
@@ -6783,7 +9328,7 @@ function fail(context, error) {
|
|
|
6783
9328
|
return "terminal";
|
|
6784
9329
|
}
|
|
6785
9330
|
function connectOnce(context) {
|
|
6786
|
-
const { identity, reconnectPolicy, terminalHandler, connection, reporter, state, options } = context;
|
|
9331
|
+
const { identity, reconnectPolicy, terminalHandler, fileHandler, connection, reporter, state, options } = context;
|
|
6787
9332
|
return new Promise((resolve) => {
|
|
6788
9333
|
const ws = new WebSocket3(context.wsUrl, { headers: { [TOKEN_HEADER]: identity.token } });
|
|
6789
9334
|
let heartbeat = null;
|
|
@@ -6868,7 +9413,7 @@ function connectOnce(context) {
|
|
|
6868
9413
|
const startHeartbeat = (intervalSeconds) => {
|
|
6869
9414
|
heartbeat = setInterval(
|
|
6870
9415
|
() => sendFrame(
|
|
6871
|
-
event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(
|
|
9416
|
+
event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(os11.uptime()) })
|
|
6872
9417
|
),
|
|
6873
9418
|
intervalSeconds * 1e3
|
|
6874
9419
|
);
|
|
@@ -6890,6 +9435,12 @@ function connectOnce(context) {
|
|
|
6890
9435
|
welcome.terminal_resync
|
|
6891
9436
|
);
|
|
6892
9437
|
terminalHandler.resumeAll();
|
|
9438
|
+
fileHandler.configure(
|
|
9439
|
+
welcome.file_manager_enabled,
|
|
9440
|
+
welcome.max_frame_bytes,
|
|
9441
|
+
welcome.file_max_concurrent_operations,
|
|
9442
|
+
welcome.file_max_queued_operations
|
|
9443
|
+
);
|
|
6893
9444
|
startHeartbeat(welcome.heartbeat_interval_seconds);
|
|
6894
9445
|
startPongWatchdog(welcome.heartbeat_interval_seconds);
|
|
6895
9446
|
sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
|
|
@@ -6913,6 +9464,10 @@ function connectOnce(context) {
|
|
|
6913
9464
|
terminalHandler.handle(envelope);
|
|
6914
9465
|
return;
|
|
6915
9466
|
}
|
|
9467
|
+
if (envelope.ch === CHANNEL_FILE) {
|
|
9468
|
+
void fileHandler.handle(envelope);
|
|
9469
|
+
return;
|
|
9470
|
+
}
|
|
6916
9471
|
if (envelope.ch === CHANNEL_TUNNEL) {
|
|
6917
9472
|
void handleTunnelAction(envelope, (frame) => connection.send?.(frame), options.tunnelActions).then(() => stopTunnels?.pollNow());
|
|
6918
9473
|
return;
|
|
@@ -7016,33 +9571,33 @@ function describeDisconnect(reason) {
|
|
|
7016
9571
|
}
|
|
7017
9572
|
|
|
7018
9573
|
// src/devices/login/deviceLogin.ts
|
|
7019
|
-
import
|
|
9574
|
+
import os12 from "os";
|
|
7020
9575
|
import pico5 from "picocolors";
|
|
7021
9576
|
|
|
7022
9577
|
// 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:
|
|
9578
|
+
import { z as z6 } from "zod";
|
|
9579
|
+
var LoginStartedSchema = z6.object({
|
|
9580
|
+
device_code: z6.string().min(1),
|
|
9581
|
+
match_code: z6.string().min(1).optional(),
|
|
9582
|
+
expires_in_seconds: z6.number().int().positive(),
|
|
9583
|
+
poll_interval_seconds: z6.number().int().positive()
|
|
7029
9584
|
});
|
|
7030
9585
|
var LoginStatus = {
|
|
7031
9586
|
Pending: "pending",
|
|
7032
9587
|
MfaRequired: "mfa_required",
|
|
7033
9588
|
Approved: "approved"
|
|
7034
9589
|
};
|
|
7035
|
-
var LoginAnswerSchema =
|
|
7036
|
-
status:
|
|
7037
|
-
token:
|
|
7038
|
-
device_agent_id:
|
|
7039
|
-
device_name:
|
|
7040
|
-
open_url:
|
|
7041
|
-
device_url:
|
|
9590
|
+
var LoginAnswerSchema = z6.object({
|
|
9591
|
+
status: z6.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
|
|
9592
|
+
token: z6.string().min(1).optional(),
|
|
9593
|
+
device_agent_id: z6.string().min(1).optional(),
|
|
9594
|
+
device_name: z6.string().optional(),
|
|
9595
|
+
open_url: z6.string().optional(),
|
|
9596
|
+
device_url: z6.string().optional()
|
|
7042
9597
|
});
|
|
7043
|
-
var LoginErrorSchema =
|
|
7044
|
-
error_type:
|
|
7045
|
-
errors:
|
|
9598
|
+
var LoginErrorSchema = z6.object({
|
|
9599
|
+
error_type: z6.string(),
|
|
9600
|
+
errors: z6.array(z6.string()).default([])
|
|
7046
9601
|
});
|
|
7047
9602
|
var LoginErrorType = {
|
|
7048
9603
|
/** A wrong code or authenticator code, with attempts left. Asked again. */
|
|
@@ -7077,8 +9632,8 @@ var DeviceLoginApiError = class extends Error {
|
|
|
7077
9632
|
var UNREADABLE_ANSWER = "invalid_answer";
|
|
7078
9633
|
function createDeviceLoginApi(manage, fetchImpl = fetch) {
|
|
7079
9634
|
const baseUrl = buildDashboardHttpUrl(manage);
|
|
7080
|
-
async function post(
|
|
7081
|
-
const response2 = await fetchImpl(`${baseUrl}/${
|
|
9635
|
+
async function post(path9, body, schema) {
|
|
9636
|
+
const response2 = await fetchImpl(`${baseUrl}/${path9}`, {
|
|
7082
9637
|
method: "POST",
|
|
7083
9638
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
7084
9639
|
body: JSON.stringify(body)
|
|
@@ -7124,49 +9679,6 @@ async function readJson(response2) {
|
|
|
7124
9679
|
}
|
|
7125
9680
|
}
|
|
7126
9681
|
|
|
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
9682
|
// src/devices/login/deviceLogin.ts
|
|
7171
9683
|
var EXIT_OK = 0;
|
|
7172
9684
|
var EXIT_FAILED = 1;
|
|
@@ -7174,10 +9686,9 @@ var DEFAULT_SERVER2 = "dashboard.pinggy.io";
|
|
|
7174
9686
|
var YES_ANSWER = /^y(es)?$/i;
|
|
7175
9687
|
var RESULT_MARKER = pico5.green(pico5.bold("\u2192"));
|
|
7176
9688
|
var SECONDS_PER_MINUTE = 60;
|
|
7177
|
-
var
|
|
9689
|
+
var MILLIS_PER_SECOND4 = 1e3;
|
|
7178
9690
|
var FIRST_SERVER_ERROR_STATUS = 500;
|
|
7179
9691
|
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
9692
|
function machineDeviceLoginDependencies() {
|
|
7182
9693
|
return {
|
|
7183
9694
|
createApi: (manage) => createDeviceLoginApi(manage),
|
|
@@ -7188,9 +9699,9 @@ function machineDeviceLoginDependencies() {
|
|
|
7188
9699
|
runAgent: (token, manage) => runDeviceAgent(token, manage),
|
|
7189
9700
|
renderQr: async (url) => (await createQrCodes([url]))[0],
|
|
7190
9701
|
machine: () => ({
|
|
7191
|
-
hostname:
|
|
7192
|
-
os:
|
|
7193
|
-
arch:
|
|
9702
|
+
hostname: os12.hostname(),
|
|
9703
|
+
os: os12.platform(),
|
|
9704
|
+
arch: os12.arch(),
|
|
7194
9705
|
agent_version: getVersion()
|
|
7195
9706
|
}),
|
|
7196
9707
|
print: (message) => printer_default.print(message),
|
|
@@ -7209,9 +9720,6 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
|
|
|
7209
9720
|
return EXIT_FAILED;
|
|
7210
9721
|
}
|
|
7211
9722
|
}
|
|
7212
|
-
function isCtrlCAtPrompt(err) {
|
|
7213
|
-
return err instanceof Error && err.name === ABORT_ERROR_NAME;
|
|
7214
|
-
}
|
|
7215
9723
|
async function signInAndRunAgent(options, dependencies) {
|
|
7216
9724
|
if (!dependencies.isInteractive()) {
|
|
7217
9725
|
dependencies.printError(NO_TERMINAL_MESSAGE);
|
|
@@ -7224,6 +9732,7 @@ async function signInAndRunAgent(options, dependencies) {
|
|
|
7224
9732
|
`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
9733
|
);
|
|
7226
9734
|
if (!YES_ANSWER.test(answer.trim())) {
|
|
9735
|
+
await settleFileAccess(options.fileManager, stored.token, stored, dependencies);
|
|
7227
9736
|
return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
|
|
7228
9737
|
}
|
|
7229
9738
|
}
|
|
@@ -7256,13 +9765,25 @@ async function signInAndRunAgent(options, dependencies) {
|
|
|
7256
9765
|
dependencies.printError("The dashboard approved the sign-in without a device token. Update pinggy and try again.");
|
|
7257
9766
|
return EXIT_FAILED;
|
|
7258
9767
|
}
|
|
7259
|
-
|
|
9768
|
+
const identity = {
|
|
7260
9769
|
device_agent_id: approved.device_agent_id,
|
|
7261
9770
|
token: approved.token,
|
|
7262
9771
|
server: manage || DEFAULT_SERVER2,
|
|
7263
9772
|
enrolled_at: null
|
|
7264
|
-
}
|
|
9773
|
+
};
|
|
7265
9774
|
dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
|
|
9775
|
+
let fileManager;
|
|
9776
|
+
try {
|
|
9777
|
+
fileManager = await settleFileAccess(options.fileManager, identity.token, null, dependencies);
|
|
9778
|
+
} catch (err) {
|
|
9779
|
+
if (!isCtrlCAtPrompt(err)) {
|
|
9780
|
+
throw err;
|
|
9781
|
+
}
|
|
9782
|
+
dependencies.writeIdentity(identity);
|
|
9783
|
+
dependencies.print(pico5.yellow("Cancelled. This machine is signed in, and its agent did not start. To start it, run: pinggy device connect"));
|
|
9784
|
+
return EXIT_FAILED;
|
|
9785
|
+
}
|
|
9786
|
+
dependencies.writeIdentity({ ...identity, file_manager: fileManager });
|
|
7266
9787
|
await printDeviceLink(approved, linkMinutes, dependencies);
|
|
7267
9788
|
return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
|
|
7268
9789
|
}
|
|
@@ -7283,7 +9804,7 @@ async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencie
|
|
|
7283
9804
|
const polled = pollUntilApproved(
|
|
7284
9805
|
api,
|
|
7285
9806
|
deviceCode,
|
|
7286
|
-
pollIntervalSeconds *
|
|
9807
|
+
pollIntervalSeconds * MILLIS_PER_SECOND4,
|
|
7287
9808
|
controller.signal,
|
|
7288
9809
|
dependencies
|
|
7289
9810
|
);
|
|
@@ -7447,9 +9968,10 @@ function machineBackgroundAgentDependencies() {
|
|
|
7447
9968
|
forgetSavedAgent: forgetDeviceAgent,
|
|
7448
9969
|
ensureDaemon: ensureDaemonRunning,
|
|
7449
9970
|
client: (port) => new IPCClient(port, "cli"),
|
|
7450
|
-
verify: (token, manage) => startDeviceAgent(token, manage, {
|
|
9971
|
+
verify: (token, manage, fileManager) => startDeviceAgent(token, manage, {
|
|
7451
9972
|
verifyOnly: true,
|
|
7452
|
-
reporter: verifyingReporter
|
|
9973
|
+
reporter: verifyingReporter,
|
|
9974
|
+
fileManager
|
|
7453
9975
|
}).done,
|
|
7454
9976
|
sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
|
|
7455
9977
|
now: () => Date.now(),
|
|
@@ -7487,7 +10009,7 @@ async function readBackgroundAgent(dependencies) {
|
|
|
7487
10009
|
}
|
|
7488
10010
|
async function startAgentInBackground(target, dependencies, options = {}) {
|
|
7489
10011
|
if (differsFromStored(target, dependencies.readIdentity())) {
|
|
7490
|
-
const verified = await dependencies.verify(target.token, target.manage);
|
|
10012
|
+
const verified = await dependencies.verify(target.token, target.manage, options.fileManager);
|
|
7491
10013
|
if (verified.error || !verified.welcomed) {
|
|
7492
10014
|
dependencies.printError(verified.error?.message ?? "The device did not connect. Nothing changed.");
|
|
7493
10015
|
return EXIT_FAILED;
|
|
@@ -7936,11 +10458,11 @@ async function handleAttach(args) {
|
|
|
7936
10458
|
}
|
|
7937
10459
|
|
|
7938
10460
|
// src/cli/subcommand/handlers/logsCommand.ts
|
|
7939
|
-
import
|
|
10461
|
+
import fs13 from "fs";
|
|
7940
10462
|
|
|
7941
10463
|
// src/daemon/logPaths.ts
|
|
7942
|
-
import
|
|
7943
|
-
import
|
|
10464
|
+
import fs12 from "fs";
|
|
10465
|
+
import path6 from "path";
|
|
7944
10466
|
var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
|
|
7945
10467
|
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
10468
|
function parseTunnelLogFilename(filename) {
|
|
@@ -7960,8 +10482,8 @@ function parseTunnelLogFilename(filename) {
|
|
|
7960
10482
|
}
|
|
7961
10483
|
function listTunnelLogFiles() {
|
|
7962
10484
|
const logDir = getTunnelLogDir();
|
|
7963
|
-
if (!
|
|
7964
|
-
return
|
|
10485
|
+
if (!fs12.existsSync(logDir)) return [];
|
|
10486
|
+
return fs12.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
|
|
7965
10487
|
}
|
|
7966
10488
|
function newestLogFile(q) {
|
|
7967
10489
|
const logDir = getTunnelLogDir();
|
|
@@ -7972,8 +10494,8 @@ function newestLogFile(q) {
|
|
|
7972
10494
|
const nameMatch = parsed.name !== void 0 && parsed.name === q;
|
|
7973
10495
|
const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
|
|
7974
10496
|
if (nameMatch || idMatch) {
|
|
7975
|
-
const filePath =
|
|
7976
|
-
matches.push({ ...parsed, path: filePath, mtime:
|
|
10497
|
+
const filePath = path6.join(logDir, file);
|
|
10498
|
+
matches.push({ ...parsed, path: filePath, mtime: fs12.statSync(filePath).mtimeMs });
|
|
7977
10499
|
}
|
|
7978
10500
|
}
|
|
7979
10501
|
if (matches.length === 0) return null;
|
|
@@ -8056,7 +10578,7 @@ async function handleLogs(args, follow) {
|
|
|
8056
10578
|
return;
|
|
8057
10579
|
}
|
|
8058
10580
|
client.close();
|
|
8059
|
-
if (!filePath || !
|
|
10581
|
+
if (!filePath || !fs13.existsSync(filePath)) {
|
|
8060
10582
|
printer_default.error(`Log file not found: ${filePath}`);
|
|
8061
10583
|
process.exit(1);
|
|
8062
10584
|
}
|
|
@@ -8067,18 +10589,18 @@ async function handleLogs(args, follow) {
|
|
|
8067
10589
|
}
|
|
8068
10590
|
}
|
|
8069
10591
|
function printTail(filePath, lines) {
|
|
8070
|
-
const content =
|
|
10592
|
+
const content = fs13.readFileSync(filePath, "utf-8");
|
|
8071
10593
|
const allLines = content.split("\n");
|
|
8072
10594
|
const tail = allLines.slice(-lines).join("\n");
|
|
8073
10595
|
process.stdout.write(tail);
|
|
8074
10596
|
if (!tail.endsWith("\n")) process.stdout.write("\n");
|
|
8075
10597
|
}
|
|
8076
10598
|
async function followFile(filePath) {
|
|
8077
|
-
if (
|
|
8078
|
-
let fileSize =
|
|
10599
|
+
if (fs13.existsSync(filePath)) printTail(filePath, 20);
|
|
10600
|
+
let fileSize = fs13.existsSync(filePath) ? fs13.statSync(filePath).size : 0;
|
|
8079
10601
|
let watcher = null;
|
|
8080
10602
|
const openStream = () => {
|
|
8081
|
-
const stream =
|
|
10603
|
+
const stream = fs13.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
|
|
8082
10604
|
stream.on("data", (chunk) => {
|
|
8083
10605
|
process.stdout.write(chunk);
|
|
8084
10606
|
fileSize += Buffer.byteLength(chunk, "utf-8");
|
|
@@ -8086,9 +10608,9 @@ async function followFile(filePath) {
|
|
|
8086
10608
|
stream.on("error", () => {
|
|
8087
10609
|
});
|
|
8088
10610
|
};
|
|
8089
|
-
watcher =
|
|
10611
|
+
watcher = fs13.watch(filePath, { persistent: true }, (event2) => {
|
|
8090
10612
|
if (event2 === "change") {
|
|
8091
|
-
const stat =
|
|
10613
|
+
const stat = fs13.existsSync(filePath) ? fs13.statSync(filePath) : null;
|
|
8092
10614
|
if (!stat || stat.size < fileSize) {
|
|
8093
10615
|
fileSize = 0;
|
|
8094
10616
|
}
|
|
@@ -8356,7 +10878,7 @@ function resolveConnectTarget(flagToken, environmentToken, manage, stored) {
|
|
|
8356
10878
|
}
|
|
8357
10879
|
return null;
|
|
8358
10880
|
}
|
|
8359
|
-
async function handleDevice(args, background = machineBackgroundAgentDependencies()) {
|
|
10881
|
+
async function handleDevice(args, background = machineBackgroundAgentDependencies(), fileAccess = machineFileAccessDependencies()) {
|
|
8360
10882
|
const environmentToken = takeEnvironmentToken();
|
|
8361
10883
|
if (args.length === 0) {
|
|
8362
10884
|
printDeviceHelp();
|
|
@@ -8371,19 +10893,28 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
|
|
|
8371
10893
|
process.exit(1);
|
|
8372
10894
|
}
|
|
8373
10895
|
const inBackground = !values.foreground;
|
|
10896
|
+
const fileManager = parseFilesFlag(values.files);
|
|
10897
|
+
if (fileManager === null) {
|
|
10898
|
+
printer_default.error(INVALID_FILES_FLAG_MESSAGE);
|
|
10899
|
+
process.exit(1);
|
|
10900
|
+
}
|
|
8374
10901
|
switch (verb) {
|
|
8375
10902
|
case DeviceVerb.Login:
|
|
8376
|
-
exitUnlessOk(await handleDeviceLogin(
|
|
10903
|
+
exitUnlessOk(await handleDeviceLogin(
|
|
10904
|
+
{ manage: values.manage, name: values.name, fileManager },
|
|
10905
|
+
inBackground,
|
|
10906
|
+
background
|
|
10907
|
+
));
|
|
8377
10908
|
return;
|
|
8378
10909
|
case DeviceVerb.Connect:
|
|
8379
10910
|
case DeviceVerb.Start:
|
|
8380
|
-
exitUnlessOk(await handleDeviceConnect(
|
|
8381
|
-
values.token,
|
|
10911
|
+
exitUnlessOk(await handleDeviceConnect({
|
|
10912
|
+
flagToken: values.token,
|
|
8382
10913
|
environmentToken,
|
|
8383
|
-
values.manage,
|
|
10914
|
+
manage: values.manage,
|
|
8384
10915
|
inBackground,
|
|
8385
|
-
|
|
8386
|
-
));
|
|
10916
|
+
fileManager
|
|
10917
|
+
}, background, fileAccess));
|
|
8387
10918
|
return;
|
|
8388
10919
|
case DeviceVerb.Stop:
|
|
8389
10920
|
exitUnlessOk(await stopAgentInBackground(background));
|
|
@@ -8436,29 +10967,38 @@ function mayRunInBackground(background) {
|
|
|
8436
10967
|
}
|
|
8437
10968
|
return true;
|
|
8438
10969
|
}
|
|
8439
|
-
async function handleDeviceLogin(
|
|
10970
|
+
async function handleDeviceLogin(options, inBackground, background) {
|
|
8440
10971
|
if (!inBackground) {
|
|
8441
10972
|
if (!await mayRunInForeground(background)) return EXIT_FAILED;
|
|
8442
|
-
return runDeviceLogin(
|
|
10973
|
+
return runDeviceLogin(options);
|
|
8443
10974
|
}
|
|
8444
10975
|
if (!mayRunInBackground(background)) return EXIT_FAILED;
|
|
8445
|
-
return runDeviceLogin(
|
|
10976
|
+
return runDeviceLogin(options, {
|
|
8446
10977
|
...machineDeviceLoginDependencies(),
|
|
8447
10978
|
runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
|
|
8448
10979
|
});
|
|
8449
10980
|
}
|
|
8450
|
-
async function handleDeviceConnect(
|
|
8451
|
-
const
|
|
10981
|
+
async function handleDeviceConnect(request2, background, fileAccess) {
|
|
10982
|
+
const stored = background.readIdentity();
|
|
10983
|
+
const target = resolveConnectTarget(request2.flagToken, request2.environmentToken, request2.manage, stored);
|
|
8452
10984
|
if (!target) {
|
|
8453
10985
|
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
10986
|
return EXIT_FAILED;
|
|
8455
10987
|
}
|
|
8456
|
-
|
|
8457
|
-
|
|
8458
|
-
|
|
10988
|
+
const mayRun = request2.inBackground ? mayRunInBackground(background) : await mayRunInForeground(background);
|
|
10989
|
+
if (!mayRun) return EXIT_FAILED;
|
|
10990
|
+
let fileManager;
|
|
10991
|
+
try {
|
|
10992
|
+
fileManager = await settleFileAccess(request2.fileManager, target.token, stored, fileAccess);
|
|
10993
|
+
} catch (err) {
|
|
10994
|
+
if (!isCtrlCAtPrompt(err)) throw err;
|
|
10995
|
+
fileAccess.print(pico11.yellow("Cancelled. Nothing changed."));
|
|
10996
|
+
return EXIT_FAILED;
|
|
10997
|
+
}
|
|
10998
|
+
if (request2.inBackground) {
|
|
10999
|
+
return startAgentInBackground(target, background, { fileManager });
|
|
8459
11000
|
}
|
|
8460
|
-
|
|
8461
|
-
await runDeviceAgent(target.token, target.manage);
|
|
11001
|
+
await runDeviceAgent(target.token, target.manage, { fileManager });
|
|
8462
11002
|
return EXIT_OK;
|
|
8463
11003
|
}
|
|
8464
11004
|
async function handleDeviceStatus(background) {
|
|
@@ -8476,6 +11016,7 @@ async function handleDeviceStatus(background) {
|
|
|
8476
11016
|
printer_default.print(` Token ${maskToken(identity.token)}`);
|
|
8477
11017
|
printer_default.print(` Enrolled ${identity.enrolled_at ?? pico11.gray("never")}`);
|
|
8478
11018
|
printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : pico11.gray("off")}`);
|
|
11019
|
+
printer_default.print(` Files ${describeFileAccess(identity)}`);
|
|
8479
11020
|
if (foreground) {
|
|
8480
11021
|
printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
|
|
8481
11022
|
}
|
|
@@ -8920,12 +11461,12 @@ async function initRemoteManagementBackground(values) {
|
|
|
8920
11461
|
}
|
|
8921
11462
|
|
|
8922
11463
|
// src/daemon/lifecycle/daemonChild.ts
|
|
8923
|
-
import
|
|
11464
|
+
import fs17 from "fs";
|
|
8924
11465
|
|
|
8925
11466
|
// src/daemon/ipc/ipcServer.ts
|
|
8926
11467
|
import http from "http";
|
|
8927
|
-
import
|
|
8928
|
-
import
|
|
11468
|
+
import fs15 from "fs";
|
|
11469
|
+
import path8 from "path";
|
|
8929
11470
|
import { WebSocketServer, WebSocket as WebSocket4 } from "ws";
|
|
8930
11471
|
|
|
8931
11472
|
// src/daemon/ws/wsProtocol.ts
|
|
@@ -8952,17 +11493,17 @@ function parseClientMessage(raw) {
|
|
|
8952
11493
|
}
|
|
8953
11494
|
|
|
8954
11495
|
// src/daemon/lifecycle/stateStore.ts
|
|
8955
|
-
import
|
|
8956
|
-
import
|
|
11496
|
+
import fs14 from "fs";
|
|
11497
|
+
import path7 from "path";
|
|
8957
11498
|
var STATE_FILENAME = "daemon-state.json";
|
|
8958
11499
|
function getStatePath() {
|
|
8959
|
-
return
|
|
11500
|
+
return path7.join(getPinggyConfigDir(), STATE_FILENAME);
|
|
8960
11501
|
}
|
|
8961
11502
|
function loadDaemonState() {
|
|
8962
11503
|
const statePath = getStatePath();
|
|
8963
11504
|
try {
|
|
8964
|
-
if (!
|
|
8965
|
-
const raw =
|
|
11505
|
+
if (!fs14.existsSync(statePath)) return null;
|
|
11506
|
+
const raw = fs14.readFileSync(statePath, "utf-8");
|
|
8966
11507
|
const state = JSON.parse(raw);
|
|
8967
11508
|
if (!Array.isArray(state.tunnels)) return null;
|
|
8968
11509
|
return state;
|
|
@@ -8976,8 +11517,8 @@ function persistDaemonState(state) {
|
|
|
8976
11517
|
const tmpPath = statePath + ".tmp";
|
|
8977
11518
|
try {
|
|
8978
11519
|
state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
|
|
8979
|
-
|
|
8980
|
-
|
|
11520
|
+
fs14.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
|
|
11521
|
+
fs14.renameSync(tmpPath, statePath);
|
|
8981
11522
|
} catch (err) {
|
|
8982
11523
|
logger.error("Failed to persist daemon state", { error: errorMessage(err) });
|
|
8983
11524
|
}
|
|
@@ -8985,8 +11526,8 @@ function persistDaemonState(state) {
|
|
|
8985
11526
|
function clearDaemonState() {
|
|
8986
11527
|
const statePath = getStatePath();
|
|
8987
11528
|
try {
|
|
8988
|
-
if (
|
|
8989
|
-
|
|
11529
|
+
if (fs14.existsSync(statePath)) {
|
|
11530
|
+
fs14.unlinkSync(statePath);
|
|
8990
11531
|
}
|
|
8991
11532
|
} catch {
|
|
8992
11533
|
}
|
|
@@ -9162,8 +11703,8 @@ var IPCServer = class {
|
|
|
9162
11703
|
if (n) activeNames.add(n);
|
|
9163
11704
|
}
|
|
9164
11705
|
for (const file of files) {
|
|
9165
|
-
const filePath =
|
|
9166
|
-
const stat =
|
|
11706
|
+
const filePath = path8.join(logDir, file);
|
|
11707
|
+
const stat = fs15.statSync(filePath);
|
|
9167
11708
|
const parsed = parseTunnelLogFilename(file);
|
|
9168
11709
|
if (!parsed) continue;
|
|
9169
11710
|
const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
|
|
@@ -9809,11 +12350,11 @@ function machineDeviceAgentHostDependencies(port, record) {
|
|
|
9809
12350
|
}
|
|
9810
12351
|
|
|
9811
12352
|
// src/daemon/lifecycle/daemonLock.ts
|
|
9812
|
-
import
|
|
12353
|
+
import fs16 from "fs";
|
|
9813
12354
|
var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
|
|
9814
12355
|
function readLock(lockPath) {
|
|
9815
12356
|
try {
|
|
9816
|
-
const record = JSON.parse(
|
|
12357
|
+
const record = JSON.parse(fs16.readFileSync(lockPath, "utf-8"));
|
|
9817
12358
|
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
9818
12359
|
} catch {
|
|
9819
12360
|
return null;
|
|
@@ -9821,7 +12362,7 @@ function readLock(lockPath) {
|
|
|
9821
12362
|
}
|
|
9822
12363
|
function isUnreadableLockOld(lockPath) {
|
|
9823
12364
|
try {
|
|
9824
|
-
return Date.now() -
|
|
12365
|
+
return Date.now() - fs16.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
|
|
9825
12366
|
} catch {
|
|
9826
12367
|
return true;
|
|
9827
12368
|
}
|
|
@@ -9832,7 +12373,7 @@ function isStale(lockPath, holder) {
|
|
|
9832
12373
|
}
|
|
9833
12374
|
function createLock(lockPath, record) {
|
|
9834
12375
|
try {
|
|
9835
|
-
|
|
12376
|
+
fs16.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
|
|
9836
12377
|
return true;
|
|
9837
12378
|
} catch (err) {
|
|
9838
12379
|
if (err.code === "EEXIST") return false;
|
|
@@ -9852,13 +12393,13 @@ function acquireDaemonLock() {
|
|
|
9852
12393
|
if (holder?.pid === process.pid) return true;
|
|
9853
12394
|
if (!isStale(lockPath, holder)) return false;
|
|
9854
12395
|
logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
|
|
9855
|
-
|
|
12396
|
+
fs16.rmSync(lockPath, { force: true });
|
|
9856
12397
|
return createLock(lockPath, record);
|
|
9857
12398
|
}
|
|
9858
12399
|
function releaseDaemonLock() {
|
|
9859
12400
|
const lockPath = getDaemonLockPath();
|
|
9860
12401
|
if (readLock(lockPath)?.pid === process.pid) {
|
|
9861
|
-
|
|
12402
|
+
fs16.rmSync(lockPath, { force: true });
|
|
9862
12403
|
}
|
|
9863
12404
|
}
|
|
9864
12405
|
|
|
@@ -9882,14 +12423,14 @@ function writeDaemonInfo(info) {
|
|
|
9882
12423
|
ensurePinggyConfigDir();
|
|
9883
12424
|
const infoPath = getDaemonInfoPath();
|
|
9884
12425
|
const tmpPath = infoPath + ".tmp";
|
|
9885
|
-
|
|
9886
|
-
|
|
12426
|
+
fs17.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
|
|
12427
|
+
fs17.renameSync(tmpPath, infoPath);
|
|
9887
12428
|
}
|
|
9888
12429
|
function removeDaemonInfo() {
|
|
9889
12430
|
try {
|
|
9890
12431
|
const infoPath = getDaemonInfoPath();
|
|
9891
|
-
const info = JSON.parse(
|
|
9892
|
-
if (info.pid === process.pid)
|
|
12432
|
+
const info = JSON.parse(fs17.readFileSync(infoPath, "utf-8"));
|
|
12433
|
+
if (info.pid === process.pid) fs17.unlinkSync(infoPath);
|
|
9893
12434
|
} catch {
|
|
9894
12435
|
}
|
|
9895
12436
|
}
|
|
@@ -10196,7 +12737,7 @@ async function main() {
|
|
|
10196
12737
|
const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
|
|
10197
12738
|
configureLogger(values);
|
|
10198
12739
|
if (values["_daemon-child"]) {
|
|
10199
|
-
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-
|
|
12740
|
+
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-GGG34AOT.js");
|
|
10200
12741
|
await runDaemonChild2();
|
|
10201
12742
|
return;
|
|
10202
12743
|
}
|
|
@@ -10205,7 +12746,7 @@ async function main() {
|
|
|
10205
12746
|
return;
|
|
10206
12747
|
}
|
|
10207
12748
|
if (values["_update-child"]) {
|
|
10208
|
-
const { runUpdateChild } = await import("./updateChild-
|
|
12749
|
+
const { runUpdateChild } = await import("./updateChild-RNCLN24C.js");
|
|
10209
12750
|
await runUpdateChild();
|
|
10210
12751
|
process.exit(0);
|
|
10211
12752
|
}
|