Targets now have a kind. SFTP takes a password or a private key and remembers the server's host key on
first contact (checked on every later connection, reset when the address changes). FTP supports explicit
TLS (ftps://). Dropbox uses an app key and refresh token or a long-lived token, and gives folder links.
New A Bola preset (folder /{event}/, PS_{event}_{n:pad3}, originals at full size); {event} is
"Home x Away" as in Photo Mechanic. Admins can test a target's connection (Nextcloud now really logs in).
Also fixes updates of a target resetting its size and quality to the defaults.
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
173 lines
9.2 KiB
TypeScript
173 lines
9.2 KiB
TypeScript
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { FtpSrv } from "ftp-srv";
|
|
import ssh2 from "ssh2";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { DropboxTransport, FtpTransport, SftpTransport, TransportError, dropboxArg } from "../src/delivery/transports.js";
|
|
|
|
const { Server, utils } = ssh2;
|
|
const { STATUS_CODE } = utils.sftp;
|
|
|
|
/** A tiny in-memory SFTP server: enough for mkdir -p, stat, put and realpath. */
|
|
function sftpServer(users: Record<string, string>) {
|
|
const hostKey = utils.generateKeyPairSync("ed25519").private;
|
|
const dirs = new Set<string>(["/"]);
|
|
const files = new Map<string, Buffer>();
|
|
const server = new Server({ hostKeys: [hostKey] }, (client) => {
|
|
client.on("authentication", (ctx) => {
|
|
if (ctx.method === "password" && users[ctx.username] === ctx.password) ctx.accept();
|
|
else ctx.reject(["password"]);
|
|
});
|
|
client.on("ready", () => {
|
|
client.on("session", (accept) => {
|
|
const session = accept();
|
|
session.on("sftp", (acceptSftp) => {
|
|
const sftp = acceptSftp();
|
|
const open = new Map<number, string>();
|
|
let next = 0;
|
|
const attrs = (dir: boolean, size = 0) => ({ mode: dir ? 0o40755 : 0o100644, uid: 0, gid: 0, size, atime: 0, mtime: 0 });
|
|
const stat = (reqid: number, p: string) => {
|
|
if (dirs.has(p)) return sftp.attrs(reqid, attrs(true));
|
|
const f = files.get(p);
|
|
return f ? sftp.attrs(reqid, attrs(false, f.length)) : sftp.status(reqid, STATUS_CODE.NO_SUCH_FILE);
|
|
};
|
|
sftp.on("REALPATH", (reqid, p) => sftp.name(reqid, [{ filename: p === "." ? "/" : p, longname: p, attrs: attrs(true) }]));
|
|
sftp.on("STAT", stat);
|
|
sftp.on("LSTAT", stat);
|
|
sftp.on("MKDIR", (reqid, p) => {
|
|
const parent = path.posix.dirname(p);
|
|
if (!dirs.has(parent) || dirs.has(p)) return sftp.status(reqid, STATUS_CODE.FAILURE);
|
|
dirs.add(p);
|
|
sftp.status(reqid, STATUS_CODE.OK);
|
|
});
|
|
sftp.on("OPEN", (reqid, filename) => {
|
|
if (!dirs.has(path.posix.dirname(filename))) return sftp.status(reqid, STATUS_CODE.NO_SUCH_FILE);
|
|
const h = Buffer.alloc(4);
|
|
h.writeUInt32BE(++next);
|
|
open.set(next, filename);
|
|
files.set(filename, Buffer.alloc(0));
|
|
sftp.handle(reqid, h);
|
|
});
|
|
sftp.on("WRITE", (reqid, handle, offset, data) => {
|
|
const name = open.get(handle.readUInt32BE(0))!;
|
|
const cur = files.get(name)!;
|
|
const out = Buffer.alloc(Math.max(cur.length, offset + data.length));
|
|
cur.copy(out);
|
|
data.copy(out, offset);
|
|
files.set(name, out);
|
|
sftp.status(reqid, STATUS_CODE.OK);
|
|
});
|
|
sftp.on("FSTAT", (reqid, handle) => sftp.attrs(reqid, attrs(false, files.get(open.get(handle.readUInt32BE(0))!)?.length ?? 0)));
|
|
sftp.on("FSETSTAT", (reqid) => sftp.status(reqid, STATUS_CODE.OK));
|
|
sftp.on("SETSTAT", (reqid) => sftp.status(reqid, STATUS_CODE.OK));
|
|
sftp.on("CLOSE", (reqid, handle) => {
|
|
open.delete(handle.readUInt32BE(0));
|
|
sftp.status(reqid, STATUS_CODE.OK);
|
|
});
|
|
});
|
|
});
|
|
});
|
|
client.on("error", () => {});
|
|
});
|
|
return { server, dirs, files };
|
|
}
|
|
|
|
describe("SFTP delivery", () => {
|
|
const fake = sftpServer({ abola: "segredo" });
|
|
let port = 0;
|
|
beforeAll(async () => {
|
|
await new Promise<void>((resolve) => fake.server.listen(0, "127.0.0.1", resolve));
|
|
port = (fake.server.address() as { port: number }).port;
|
|
});
|
|
afterAll(() => new Promise<void>((resolve) => fake.server.close(() => resolve())));
|
|
|
|
it("makes the folder, uploads (replacing) and remembers the host key", async () => {
|
|
const seen: string[] = [];
|
|
const t = new SftpTransport({ kind: "SFTP", baseUrl: `sftp://127.0.0.1:${port}`, username: "abola", secret: "segredo", onFingerprint: (f) => void seen.push(f) });
|
|
const tested = await t.test();
|
|
expect(tested.fingerprint).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(seen).toEqual([tested.fingerprint]);
|
|
await t.ensureFolder("/ABC de Braga x CDE Gil Eanes/");
|
|
await t.upload("/ABC de Braga x CDE Gil Eanes/PS_1.jpg", Buffer.from("one"));
|
|
await t.upload("/ABC de Braga x CDE Gil Eanes/PS_1.jpg", Buffer.from("two"));
|
|
expect(fake.files.get("/ABC de Braga x CDE Gil Eanes/PS_1.jpg")?.toString()).toBe("two");
|
|
await t.close();
|
|
|
|
// The same key later: fine. Another key: refused, and not worth retrying.
|
|
const again = new SftpTransport({ kind: "SFTP", baseUrl: `sftp://127.0.0.1:${port}`, username: "abola", secret: "segredo", hostFingerprint: tested.fingerprint! });
|
|
await again.ensureFolder("/a/b/c/");
|
|
expect(fake.dirs.has("/a/b/c")).toBe(true);
|
|
await again.close();
|
|
const spoofed = new SftpTransport({ kind: "SFTP", baseUrl: `sftp://127.0.0.1:${port}`, username: "abola", secret: "segredo", hostFingerprint: "0".repeat(64) });
|
|
await expect(spoofed.test()).rejects.toMatchObject({ transient: false, message: expect.stringContaining("host key changed") });
|
|
});
|
|
|
|
it("does not retry a wrong password", async () => {
|
|
const t = new SftpTransport({ kind: "SFTP", baseUrl: `sftp://127.0.0.1:${port}`, username: "abola", secret: "errado" });
|
|
const err = await t.test().catch((e: unknown) => e);
|
|
expect(err).toBeInstanceOf(TransportError);
|
|
expect((err as TransportError).transient).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("FTP delivery", () => {
|
|
let dir: string;
|
|
let ftp: FtpSrv;
|
|
let port = 0;
|
|
beforeAll(async () => {
|
|
dir = await mkdtemp(path.join(tmpdir(), "pr-ftp-"));
|
|
port = 20000 + Math.floor(Math.random() * 20000);
|
|
ftp = new FtpSrv({ url: `ftp://127.0.0.1:${port}`, anonymous: false, pasv_url: "127.0.0.1", pasv_min: port + 1, pasv_max: port + 50, log: { trace() {}, debug() {}, info() {}, warn() {}, error() {}, child() { return this; } } as never });
|
|
ftp.on("login", ({ username, password }, resolve, reject) => (username === "jornal" && password === "segredo" ? resolve({ root: dir }) : reject(new Error("bad login"))));
|
|
await ftp.listen();
|
|
});
|
|
afterAll(async () => {
|
|
await ftp.close();
|
|
await rm(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
it("makes folders and uploads", async () => {
|
|
const t = new FtpTransport({ kind: "FTP", baseUrl: `ftp://127.0.0.1:${port}`, username: "jornal", secret: "segredo" });
|
|
expect(await t.test()).toEqual({ account: "/" });
|
|
await t.ensureFolder("/2026/Jogo/");
|
|
await t.upload("/2026/Jogo/PS_001.jpg", Buffer.from("jpeg"));
|
|
expect((await readFile(path.join(dir, "2026/Jogo/PS_001.jpg"))).toString()).toBe("jpeg");
|
|
await t.close();
|
|
});
|
|
});
|
|
|
|
describe("Dropbox delivery", () => {
|
|
it("refreshes its token, uploads with an ASCII header, and reuses an existing link", async () => {
|
|
const calls: { url: string; headers: Record<string, string>; body: string }[] = [];
|
|
const fetcher = (async (input: string, init: RequestInit) => {
|
|
const headers = init.headers as Record<string, string>;
|
|
const body = typeof init.body === "string" ? init.body : "";
|
|
calls.push({ url: input, headers, body });
|
|
if (input.endsWith("/oauth2/token")) return Response.json({ access_token: "short", expires_in: 14400 });
|
|
if (input.endsWith("/files/upload")) return new Response("{}", { status: 200 });
|
|
if (input.endsWith("/files/create_folder_v2")) return new Response('{"error_summary":"path/conflict/folder/"}', { status: 409 });
|
|
if (input.endsWith("/create_shared_link_with_settings")) return new Response('{"error_summary":"shared_link_already_exists/"}', { status: 409 });
|
|
if (input.endsWith("/list_shared_links")) return Response.json({ links: [{ url: "https://www.dropbox.com/scl/fo/x" }] });
|
|
return new Response("?", { status: 404 });
|
|
}) as unknown as typeof fetch;
|
|
const t = new DropboxTransport({ kind: "DROPBOX", baseUrl: "https://www.dropbox.com", username: "appkey", secret: "refresh" }, fetcher);
|
|
await t.upload("/Fotos/Sporting x Benfica/Ação.jpg", Buffer.from("x"));
|
|
await t.upload("/Fotos/2.jpg", Buffer.from("y"));
|
|
expect(calls.filter((c) => c.url.endsWith("/oauth2/token"))).toHaveLength(1);
|
|
const upload = calls.find((c) => c.url.endsWith("/files/upload"))!;
|
|
expect(upload.headers.authorization).toBe("Bearer short");
|
|
expect(upload.headers["dropbox-api-arg"]).toBe(dropboxArg({ path: "/Fotos/Sporting x Benfica/Ação.jpg", mode: "overwrite", autorename: false, mute: true }));
|
|
expect(/^[\x00-\x7f]*$/.test(upload.headers["dropbox-api-arg"]!)).toBe(true);
|
|
expect(await t.shareLink("/Fotos/Sporting x Benfica/")).toBe("https://www.dropbox.com/scl/fo/x");
|
|
});
|
|
|
|
it("treats a revoked token as final and a busy server as worth retrying", async () => {
|
|
const status = { code: 401 };
|
|
const t = new DropboxTransport({ kind: "DROPBOX", baseUrl: "https://www.dropbox.com", username: "", secret: "token" }, (async () => new Response("no", { status: status.code })) as unknown as typeof fetch);
|
|
await expect(t.upload("/a.jpg", Buffer.from("x"))).rejects.toMatchObject({ transient: false });
|
|
status.code = 503;
|
|
await expect(t.upload("/a.jpg", Buffer.from("x"))).rejects.toMatchObject({ transient: true });
|
|
});
|
|
});
|