tambahan
This commit is contained in:
154
bin/g3n.ts
154
bin/g3n.ts
@@ -7,15 +7,24 @@ import checkPort from "./src/port";
|
|||||||
import route from "./src/route";
|
import route from "./src/route";
|
||||||
import compose from "./src/compose";
|
import compose from "./src/compose";
|
||||||
import generateDockerfile from "./src/docker-file";
|
import generateDockerfile from "./src/docker-file";
|
||||||
|
import frp from "./src/frp";
|
||||||
|
|
||||||
interface CheckPortResult {
|
interface CheckPortResult {
|
||||||
port: number;
|
port: number;
|
||||||
open: boolean;
|
open: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const args = minimist(process.argv.slice(2));
|
// Default constants (12-Factor App)
|
||||||
|
const DEFAULTS = {
|
||||||
|
ENV_FILE: ".env",
|
||||||
|
ENV_OUT: "types/env.d.ts",
|
||||||
|
PORT_START: 3000,
|
||||||
|
PORT_END: 4000,
|
||||||
|
HOST: "127.0.0.1",
|
||||||
|
};
|
||||||
|
|
||||||
const help = `
|
// CLI Help
|
||||||
|
const HELP_TEXT = `
|
||||||
g3n [command] [options]
|
g3n [command] [options]
|
||||||
|
|
||||||
Commands:
|
Commands:
|
||||||
@@ -23,6 +32,8 @@ Commands:
|
|||||||
scan-port Scan port range (default 3000-4000)
|
scan-port Scan port range (default 3000-4000)
|
||||||
route Generate routes.ts from AppRoutes.tsx
|
route Generate routes.ts from AppRoutes.tsx
|
||||||
compose Generate compose.yml from name
|
compose Generate compose.yml from name
|
||||||
|
docker-file Generate Dockerfile
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
--env Path ke file .env (default: .env)
|
--env Path ke file .env (default: .env)
|
||||||
--out Path file output (default: types/env.d.ts)
|
--out Path file output (default: types/env.d.ts)
|
||||||
@@ -34,64 +45,105 @@ Examples:
|
|||||||
g3n env --env .env.local --out src/types/env.d.ts
|
g3n env --env .env.local --out src/types/env.d.ts
|
||||||
g3n scan-port --start 7700 --end 7800 --host 127.0.0.1
|
g3n scan-port --start 7700 --end 7800 --host 127.0.0.1
|
||||||
g3n route
|
g3n route
|
||||||
g3n compose <name>`;
|
g3n compose <name>
|
||||||
|
g3n docker-file
|
||||||
|
`;
|
||||||
|
|
||||||
(async () => {
|
// Parse CLI arguments
|
||||||
const cmd = args._[0];
|
const args = minimist(process.argv.slice(2));
|
||||||
|
|
||||||
if (cmd === "env") {
|
/**
|
||||||
generateEnvTypes({
|
* Main CLI handler
|
||||||
envFilePath: args.env,
|
*/
|
||||||
outputDir: args.out ? path.dirname(args.out) : undefined,
|
async function main(): Promise<void> {
|
||||||
outputFileName: args.out ? path.basename(args.out) : undefined,
|
const [command, name] = args._;
|
||||||
|
|
||||||
|
switch (command) {
|
||||||
|
case "env":
|
||||||
|
handleEnv();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "scan-port":
|
||||||
|
await handleScanPort();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "route":
|
||||||
|
route();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "compose":
|
||||||
|
handleCompose(name);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "docker-file":
|
||||||
|
generateDockerfile();
|
||||||
|
break;
|
||||||
|
case "frp":
|
||||||
|
frp().catch((err) => {
|
||||||
|
console.error("❌ Error:", err);
|
||||||
|
process.exit(1);
|
||||||
});
|
});
|
||||||
return;
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.error(HELP_TEXT);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cmd === "scan-port") {
|
/**
|
||||||
const start: number = args.start ? parseInt(args.start, 10) : 3000;
|
* Handle "env" command
|
||||||
const end: number = args.end ? parseInt(args.end, 10) : 4000;
|
*/
|
||||||
const host: string = args.host || "localhost";
|
function handleEnv(): void {
|
||||||
|
const envFile = args.env || DEFAULTS.ENV_FILE;
|
||||||
|
const output = args.out || DEFAULTS.ENV_OUT;
|
||||||
|
|
||||||
console.log(`🔍 Scan port ${start}-${end} di host ${host} ...`);
|
generateEnvTypes({
|
||||||
|
envFilePath: envFile,
|
||||||
|
outputDir: path.dirname(output),
|
||||||
|
outputFileName: path.basename(output),
|
||||||
|
});
|
||||||
|
|
||||||
const ports: number[] = Array.from(
|
console.log(`✅ Env types generated at ${output}`);
|
||||||
{ length: end - start + 1 },
|
}
|
||||||
(_, i) => start + i
|
|
||||||
);
|
/**
|
||||||
|
* Handle "scan-port" command
|
||||||
|
*/
|
||||||
|
async function handleScanPort(): Promise<void> {
|
||||||
|
const start = Number(args.start) || DEFAULTS.PORT_START;
|
||||||
|
const end = Number(args.end) || DEFAULTS.PORT_END;
|
||||||
|
const host = args.host || DEFAULTS.HOST;
|
||||||
|
|
||||||
|
console.log(`🔍 Scanning ports ${start}-${end} on host ${host}...`);
|
||||||
|
|
||||||
|
const ports = Array.from({ length: end - start + 1 }, (_, i) => start + i);
|
||||||
|
|
||||||
const results: CheckPortResult[] = await Promise.all(
|
const results: CheckPortResult[] = await Promise.all(
|
||||||
ports.map((p) => checkPort(p, host))
|
ports.map((port) => checkPort(port, host))
|
||||||
);
|
);
|
||||||
|
|
||||||
results.filter((r) => r.open).forEach((r) => {
|
const openPorts = results.filter((r) => r.open);
|
||||||
console.log(`✅ Port ${r.port} sedang digunakan`);
|
openPorts.forEach((r) => console.log(`✅ Port ${r.port} is open`));
|
||||||
|
|
||||||
|
console.log("✅ Scan completed");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle "compose" command
|
||||||
|
*/
|
||||||
|
function handleCompose(name?: string): void {
|
||||||
|
if (!name) {
|
||||||
|
console.error("❌ Compose name is required");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
compose(name);
|
||||||
|
console.log(`✅ Compose file generated for ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute CLI
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error("❌ Unexpected error:", err);
|
||||||
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("✅ Selesai");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cmd === "route") {
|
|
||||||
route();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cmd === "compose") {
|
|
||||||
if (!args._[1]) {
|
|
||||||
console.error("❌ Name is required");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
compose(args._[1] as string);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cmd === "docker-file") {
|
|
||||||
generateDockerfile();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(help);
|
|
||||||
})();
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ async function compose(name: string) {
|
|||||||
const composeFile = text(name);
|
const composeFile = text(name);
|
||||||
await fs.writeFile(`./compose.yml`, composeFile);
|
await fs.writeFile(`./compose.yml`, composeFile);
|
||||||
Bun.spawnSync(["bash", "-c", generate(name)]);
|
Bun.spawnSync(["bash", "-c", generate(name)]);
|
||||||
|
console.log("✅ Compose file generated");
|
||||||
}
|
}
|
||||||
|
|
||||||
export default compose
|
export default compose
|
||||||
|
|||||||
165
bin/src/frp.ts
Normal file
165
bin/src/frp.ts
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
import { promises as fs } from "fs";
|
||||||
|
import * as os from "os";
|
||||||
|
import * as path from "path";
|
||||||
|
|
||||||
|
const CONFIG_FILE = path.join(os.homedir(), ".frpdev.conf");
|
||||||
|
|
||||||
|
interface FrpConfig {
|
||||||
|
FRP_HOST: string;
|
||||||
|
FRP_PORT: string;
|
||||||
|
FRP_USER: string;
|
||||||
|
FRP_SECRET: string;
|
||||||
|
FRP_PROTO: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProxyConf {
|
||||||
|
type?: string;
|
||||||
|
remotePort?: number;
|
||||||
|
subdomain?: string;
|
||||||
|
customDomains?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Proxy {
|
||||||
|
name?: string;
|
||||||
|
status?: string;
|
||||||
|
conf?: ProxyConf;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProxyResponse {
|
||||||
|
proxies?: Proxy[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureConfigFile(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await fs.access(CONFIG_FILE);
|
||||||
|
} catch {
|
||||||
|
const template = `
|
||||||
|
FRP_HOST=""
|
||||||
|
FRP_USER=""
|
||||||
|
FRP_SECRET=""
|
||||||
|
`;
|
||||||
|
console.error(`❌ Config not found. Template created at: ${CONFIG_FILE}`);
|
||||||
|
console.log(template);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConfig(): Promise<FrpConfig> {
|
||||||
|
await ensureConfigFile();
|
||||||
|
|
||||||
|
const raw = await fs.readFile(CONFIG_FILE, "utf8");
|
||||||
|
const lines = raw
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const conf: Record<string, string> = {};
|
||||||
|
for (const line of lines) {
|
||||||
|
const [key, ...rest] = line.split("=");
|
||||||
|
if (!key) continue;
|
||||||
|
let value = rest.join("=").trim();
|
||||||
|
|
||||||
|
if (value.startsWith('"') && value.endsWith('"')) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
conf[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
FRP_HOST: conf.FRP_HOST || "",
|
||||||
|
FRP_PORT: "443",
|
||||||
|
FRP_USER: conf.FRP_USER || "",
|
||||||
|
FRP_SECRET: conf.FRP_SECRET || "",
|
||||||
|
FRP_PROTO: "https",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchFrp(config: FrpConfig, url: string): Promise<ProxyResponse> {
|
||||||
|
const fullUrl = `${config.FRP_PROTO}://${config.FRP_HOST}:${config.FRP_PORT}${url}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch(fullUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization:
|
||||||
|
"Basic " +
|
||||||
|
Buffer.from(`${config.FRP_USER}:${config.FRP_SECRET}`).toString("base64"),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!resp.ok) return { proxies: [] };
|
||||||
|
|
||||||
|
return (await resp.json()) as ProxyResponse;
|
||||||
|
} catch {
|
||||||
|
return { proxies: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortProxies(proxies: Proxy[]): Proxy[] {
|
||||||
|
return [...proxies].sort((a, b) => {
|
||||||
|
const order = (status?: string) =>
|
||||||
|
status?.toLowerCase() === "online" || status?.toLowerCase() === "running"
|
||||||
|
? 0
|
||||||
|
: 1;
|
||||||
|
return order(a.status) - order(b.status);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTable(headers: string[], rows: string[][]): string {
|
||||||
|
const allRows = [headers, ...rows];
|
||||||
|
const colWidths = headers.map((_, i) =>
|
||||||
|
Math.max(...allRows.map((row) => (row[i] || "").length)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return allRows
|
||||||
|
.map((row) =>
|
||||||
|
row.map((cell, i) => (cell || "").padEnd(colWidths[i] ?? 0)).join(" ").trimEnd(),
|
||||||
|
)
|
||||||
|
.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function printTable(
|
||||||
|
title: string,
|
||||||
|
headers: string[],
|
||||||
|
rows: string[][],
|
||||||
|
): Promise<void> {
|
||||||
|
console.log(`========== ${title} ==========`);
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
console.log("No proxies found.\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(formatTable(headers, rows));
|
||||||
|
console.log();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function frp(): Promise<void> {
|
||||||
|
const config = await loadConfig();
|
||||||
|
|
||||||
|
const [tcpResp, httpResp] = await Promise.all([
|
||||||
|
fetchFrp(config, "/api/proxy/tcp"),
|
||||||
|
fetchFrp(config, "/api/proxy/http"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const tcpRows: string[][] = sortProxies(tcpResp.proxies || []).map((p) => [
|
||||||
|
p.name ?? "-",
|
||||||
|
p.status ?? "-",
|
||||||
|
p.conf?.remotePort?.toString() ?? "-",
|
||||||
|
]);
|
||||||
|
await printTable("TCP PROXIES", ["NAME", "STATUS", "PORT"], tcpRows);
|
||||||
|
|
||||||
|
const httpRows: string[][] = sortProxies(httpResp.proxies || []).map((p) => [
|
||||||
|
p.name ?? "-",
|
||||||
|
p.status ?? "-",
|
||||||
|
Array.isArray(p.conf?.customDomains) ? p.conf.customDomains.join(",") : "",
|
||||||
|
]);
|
||||||
|
await printTable(
|
||||||
|
"HTTP PROXIES",
|
||||||
|
["NAME", "STATUS", "CUSTOM_DOMAIN"],
|
||||||
|
httpRows,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default frp;
|
||||||
|
|
||||||
@@ -6,26 +6,62 @@ interface CheckPortResult {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Memeriksa apakah port tertentu pada host terbuka.
|
||||||
|
* @param port Nomor port yang akan diperiksa
|
||||||
|
* @param host Host target
|
||||||
|
* @returns Promise yang resolve dengan status port
|
||||||
|
*/
|
||||||
export default function checkPort(port: number, host: string): Promise<CheckPortResult> {
|
export default function checkPort(port: number, host: string): Promise<CheckPortResult> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const socket = new net.Socket();
|
const socket = new net.Socket();
|
||||||
|
|
||||||
|
// Timeout untuk koneksi
|
||||||
socket.setTimeout(200);
|
socket.setTimeout(200);
|
||||||
|
|
||||||
socket.once("connect", () => {
|
const finalize = (isOpen: boolean) => {
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
resolve({ port, open: true });
|
resolve({ port, open: isOpen });
|
||||||
});
|
};
|
||||||
|
|
||||||
socket.once("timeout", () => {
|
socket.once("connect", () => finalize(true));
|
||||||
socket.destroy();
|
socket.once("timeout", () => finalize(false));
|
||||||
resolve({ port, open: false });
|
socket.once("error", () => finalize(false));
|
||||||
});
|
|
||||||
|
|
||||||
socket.once("error", () => {
|
|
||||||
socket.destroy();
|
|
||||||
resolve({ port, open: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.connect(port, host);
|
socket.connect(port, host);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
## 🔍 Analisis
|
||||||
|
|
||||||
|
* Masalah yang ditemukan:
|
||||||
|
- Duplikasi kode pada `socket.destroy()` dan `resolve`.
|
||||||
|
- Tidak ada dokumentasi fungsi.
|
||||||
|
* Code smells terdeteksi:
|
||||||
|
- Callback anonymous yang sama diulang tiga kali.
|
||||||
|
* Peluang perbaikan:
|
||||||
|
- Ekstraksi logika finalize untuk DRY.
|
||||||
|
- Tambahkan komentar/documentation agar self-explanatory.
|
||||||
|
|
||||||
|
## ✨ Kode yang Direfaktor
|
||||||
|
|
||||||
|
Sudah diterapkan di atas.
|
||||||
|
|
||||||
|
## 📋 Perubahan yang Dilakukan
|
||||||
|
|
||||||
|
* Prinsip yang diterapkan: DRY, KISS, Clean Code
|
||||||
|
* Pattern yang digunakan: Callback extraction untuk pengurangan duplikasi
|
||||||
|
* Pertimbangan performa: Tidak ada perubahan signifikan, tetap ringan dan async.
|
||||||
|
|
||||||
|
## 🎯 Manfaat yang Dicapai
|
||||||
|
|
||||||
|
* Kemudahan pemeliharaan: Logika finalize berada di satu tempat
|
||||||
|
* Keterbacaan: Fungsi lebih jelas dengan dokumentasi dan nama `finalize`
|
||||||
|
* Kemudahan pengembangan: Bisa dengan mudah menambahkan logging atau metrik
|
||||||
|
|
||||||
|
## ⚡ Langkah Selanjutnya (Opsional)
|
||||||
|
|
||||||
|
* Tambahkan parameter timeout fleksibel
|
||||||
|
* Gunakan TypeScript enums untuk status port jika diperlukan
|
||||||
|
*/
|
||||||
|
|||||||
412
x.ts
412
x.ts
@@ -1,327 +1,167 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
import * as fs from 'fs';
|
import { promises as fs } from "fs";
|
||||||
import * as path from 'path';
|
import * as os from "os";
|
||||||
import * as os from 'os';
|
import * as path from "path";
|
||||||
import { execSync } from 'child_process';
|
|
||||||
|
|
||||||
const CONFIG_FILE = path.join(os.homedir(), '.note.conf');
|
const CONFIG_FILE = path.join(os.homedir(), ".frpdev.conf");
|
||||||
|
|
||||||
interface Config {
|
interface FrpConfig {
|
||||||
TOKEN?: string;
|
FRP_HOST: string;
|
||||||
REPO?: string;
|
FRP_PORT: string;
|
||||||
URL?: string;
|
FRP_USER: string;
|
||||||
|
FRP_SECRET: string;
|
||||||
|
FRP_PROTO: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Config management ---
|
interface ProxyConf {
|
||||||
function createDefaultConfig(): void {
|
type?: string;
|
||||||
const defaultConfig = `TOKEN=
|
remotePort?: number;
|
||||||
REPO=
|
subdomain?: string;
|
||||||
URL=https://cld-dkr-makuro-seafile.wibudev.com/api2
|
customDomains?: string[];
|
||||||
`;
|
|
||||||
fs.writeFileSync(CONFIG_FILE, defaultConfig);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function editConfig(): void {
|
interface Proxy {
|
||||||
if (!fs.existsSync(CONFIG_FILE)) {
|
name?: string;
|
||||||
createDefaultConfig();
|
status?: string;
|
||||||
|
conf?: ProxyConf;
|
||||||
}
|
}
|
||||||
|
|
||||||
const editor = process.env.EDITOR || 'vim';
|
interface ProxyResponse {
|
||||||
|
proxies?: Proxy[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureConfigFile(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' });
|
await fs.access(CONFIG_FILE);
|
||||||
} catch (error) {
|
} catch {
|
||||||
console.error('❌ Failed to open editor');
|
const template = `
|
||||||
|
FRP_HOST=""
|
||||||
|
FRP_USER=""
|
||||||
|
FRP_SECRET=""
|
||||||
|
`;
|
||||||
|
console.error(`❌ Config not found. Template created at: ${CONFIG_FILE}`);
|
||||||
|
console.log(template);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadConfig(): Config {
|
async function loadConfig(): Promise<FrpConfig> {
|
||||||
if (!fs.existsSync(CONFIG_FILE)) {
|
await ensureConfigFile();
|
||||||
console.error(`⚠️ Config file not found at ${CONFIG_FILE}`);
|
|
||||||
console.error('Run: bun note.ts config to create/edit it.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const configContent = fs.readFileSync(CONFIG_FILE, 'utf8');
|
const raw = await fs.readFile(CONFIG_FILE, "utf8");
|
||||||
const config: Config = {};
|
const lines = raw
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
for (const line of configContent.split('\n')) {
|
const conf: Record<string, string> = {};
|
||||||
const trimmed = line.trim();
|
for (const line of lines) {
|
||||||
if (trimmed && !trimmed.startsWith('#')) {
|
const [key, ...rest] = line.split("=");
|
||||||
const [key, ...valueParts] = trimmed.split('=');
|
if (!key) continue;
|
||||||
if (key && valueParts.length > 0) {
|
let value = rest.join("=").trim();
|
||||||
let value = valueParts.join('=');
|
|
||||||
// Remove surrounding quotes if present
|
if (value.startsWith('"') && value.endsWith('"')) {
|
||||||
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
||||||
(value.startsWith("'") && value.endsWith("'"))) {
|
|
||||||
value = value.slice(1, -1);
|
value = value.slice(1, -1);
|
||||||
}
|
}
|
||||||
config[key as keyof Config] = value;
|
conf[key] = value;
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!config.TOKEN || !config.REPO) {
|
return {
|
||||||
console.error(`❌ Config invalid. Please set TOKEN=... and REPO=... inside ${CONFIG_FILE}`);
|
FRP_HOST: conf.FRP_HOST || "",
|
||||||
process.exit(1);
|
FRP_PORT: "443",
|
||||||
}
|
FRP_USER: conf.FRP_USER || "",
|
||||||
|
FRP_SECRET: conf.FRP_SECRET || "",
|
||||||
if (!config.URL) {
|
FRP_PROTO: "https",
|
||||||
console.error(`❌ Config invalid. Please set URL=... inside ${CONFIG_FILE}`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
return config;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- HTTP helpers ---
|
|
||||||
async function fetchWithAuth(config: Config, url: string, options: RequestInit = {}): Promise<Response> {
|
|
||||||
const headers = {
|
|
||||||
'Authorization': `Token ${config.TOKEN}`,
|
|
||||||
...options.headers
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchFrp(config: FrpConfig, url: string): Promise<ProxyResponse> {
|
||||||
|
const fullUrl = `${config.FRP_PROTO}://${config.FRP_HOST}:${config.FRP_PORT}${url}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, { ...options, headers });
|
const resp = await fetch(fullUrl, {
|
||||||
if (!response.ok) {
|
headers: {
|
||||||
console.error(`❌ Request failed: ${response.status} ${response.statusText}`);
|
Authorization:
|
||||||
console.error(`🔍 URL: ${url}`);
|
"Basic " +
|
||||||
console.error(`🔍 Headers:`, headers);
|
Buffer.from(`${config.FRP_USER}:${config.FRP_SECRET}`).toString("base64"),
|
||||||
|
},
|
||||||
// Try to get response body for more details
|
|
||||||
try {
|
|
||||||
const errorText = await response.text();
|
|
||||||
console.error(`🔍 Response body: ${errorText}`);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('🔍 Could not read response body');
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof Error && error.message.includes('HTTP')) {
|
|
||||||
// Already handled above
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
console.error('❌ Network request failed:', error);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Commands ---
|
|
||||||
async function testConnection(config: Config): Promise<void> {
|
|
||||||
console.log('🔍 Testing connection...');
|
|
||||||
try {
|
|
||||||
// Test basic API endpoint
|
|
||||||
const response = await fetchWithAuth(config, `${config.URL}/ping/`);
|
|
||||||
const result = await response.text();
|
|
||||||
console.log(`✅ API connection successful: ${result}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.log('⚠️ API ping failed, trying repo access...');
|
|
||||||
try {
|
|
||||||
// Try accessing the repo directly
|
|
||||||
const response = await fetchWithAuth(config, `${config.URL}/${config.REPO}/`);
|
|
||||||
const result = await response.text();
|
|
||||||
console.log(`✅ Repo access successful`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Both API ping and repo access failed');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function listFiles(config: Config): Promise<void> {
|
|
||||||
const url = `${config.URL}/${config.REPO}/dir/?p=/`;
|
|
||||||
const response = await fetchWithAuth(config, url);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const files = await response.json();
|
|
||||||
for (const file of files as { name: string }[]) {
|
|
||||||
console.log(file.name);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Failed to parse response');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function catFile(config: Config, fileName: string): Promise<void> {
|
|
||||||
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`);
|
|
||||||
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
|
|
||||||
|
|
||||||
const contentResponse = await fetchWithAuth(config, downloadUrl);
|
|
||||||
const content = await contentResponse.text();
|
|
||||||
console.log(content);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function uploadFile(config: Config, localFile: string, remoteFile?: string): Promise<void> {
|
|
||||||
if (!fs.existsSync(localFile)) {
|
|
||||||
console.error(`❌ File not found: ${localFile}`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const remoteName = remoteFile || path.basename(localFile);
|
|
||||||
|
|
||||||
// Get upload URL
|
|
||||||
const uploadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/upload-link/?p=/`);
|
|
||||||
const uploadUrl = (await uploadUrlResponse.text()).replace(/"/g, '');
|
|
||||||
|
|
||||||
// Create FormData
|
|
||||||
const formData = new FormData();
|
|
||||||
const fileContent = fs.readFileSync(localFile);
|
|
||||||
const blob = new Blob([fileContent]);
|
|
||||||
formData.append('file', blob, remoteName);
|
|
||||||
formData.append('filename', remoteName);
|
|
||||||
formData.append('parent_dir', '/');
|
|
||||||
|
|
||||||
try {
|
|
||||||
await fetchWithAuth(config, uploadUrl, {
|
|
||||||
method: 'POST',
|
|
||||||
body: formData
|
|
||||||
});
|
});
|
||||||
console.log(`✅ Uploaded ${localFile} → ${remoteName}`);
|
|
||||||
} catch (error) {
|
if (!resp.ok) return { proxies: [] };
|
||||||
console.error('❌ Upload failed');
|
|
||||||
process.exit(1);
|
return (await resp.json()) as ProxyResponse;
|
||||||
|
} catch {
|
||||||
|
return { proxies: [] };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeFile(config: Config, fileName: string): Promise<void> {
|
function sortProxies(proxies: Proxy[]): Proxy[] {
|
||||||
const url = `${config.URL}/${config.REPO}/file/?p=/${fileName}`;
|
return [...proxies].sort((a, b) => {
|
||||||
await fetchWithAuth(config, url, { method: 'DELETE' });
|
const order = (status?: string) =>
|
||||||
console.log(`🗑️ Removed ${fileName}`);
|
status?.toLowerCase() === "online" || status?.toLowerCase() === "running"
|
||||||
}
|
? 0
|
||||||
|
: 1;
|
||||||
async function moveFile(config: Config, oldName: string, newName: string): Promise<void> {
|
return order(a.status) - order(b.status);
|
||||||
const url = `${config.URL}/${config.REPO}/file/?p=/${oldName}`;
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('operation', 'rename');
|
|
||||||
formData.append('newname', newName);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await fetchWithAuth(config, url, {
|
|
||||||
method: 'POST',
|
|
||||||
body: formData
|
|
||||||
});
|
});
|
||||||
console.log(`✏️ Renamed ${oldName} → ${newName}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Rename failed');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function downloadFile(config: Config, remoteFile: string, localFile?: string): Promise<void> {
|
function formatTable(headers: string[], rows: string[][]): string {
|
||||||
const localName = localFile || remoteFile;
|
const allRows = [headers, ...rows];
|
||||||
|
const colWidths = headers.map((_, i) =>
|
||||||
|
Math.max(...allRows.map((row) => (row[i] || "").length)),
|
||||||
|
);
|
||||||
|
|
||||||
// Get download URL
|
return allRows
|
||||||
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${remoteFile}`);
|
.map((row) =>
|
||||||
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
|
row.map((cell, i) => (cell || "").padEnd(colWidths[i] ?? 0)).join(" ").trimEnd(),
|
||||||
|
)
|
||||||
try {
|
.join("\n");
|
||||||
const fileResponse = await fetchWithAuth(config, downloadUrl);
|
|
||||||
const arrayBuffer = await fileResponse.arrayBuffer();
|
|
||||||
const buffer = Buffer.from(arrayBuffer);
|
|
||||||
|
|
||||||
fs.writeFileSync(localName, buffer);
|
|
||||||
console.log(`⬇️ Downloaded ${remoteFile} → ${localName}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Download failed');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function showHelp(): void {
|
async function printTable(
|
||||||
console.log(`note - simple CLI for Seafile notes
|
title: string,
|
||||||
Usage:
|
headers: string[],
|
||||||
bun note.ts ls List files
|
rows: string[][],
|
||||||
bun note.ts cat <file> Show file content
|
): Promise<void> {
|
||||||
bun note.ts cp <local> [remote] Upload file
|
console.log(`========== ${title} ==========`);
|
||||||
bun note.ts rm <remote> Remove file
|
|
||||||
bun note.ts mv <old> <new> Rename/move file
|
|
||||||
bun note.ts get <remote> [local] Download file
|
|
||||||
bun note.ts test Test API connection
|
|
||||||
bun note.ts config Edit config (~/.note.conf)
|
|
||||||
|
|
||||||
Config (~/.note.conf):
|
if (rows.length === 0) {
|
||||||
TOKEN=your_seafile_token
|
console.log("No proxies found.\n");
|
||||||
REPO=repos/<repo-id>
|
|
||||||
URL=your_seafile_url/api2`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Main ---
|
|
||||||
async function not3(): Promise<void> {
|
|
||||||
const args = process.argv.slice(2);
|
|
||||||
const cmd = args[0] || 'help';
|
|
||||||
|
|
||||||
// Handle config command
|
|
||||||
if (cmd === 'config') {
|
|
||||||
editConfig();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load config for other commands
|
console.log(formatTable(headers, rows));
|
||||||
const config = loadConfig();
|
console.log();
|
||||||
|
|
||||||
switch (cmd) {
|
|
||||||
case 'test':
|
|
||||||
await testConnection(config);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'ls':
|
|
||||||
await listFiles(config);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'cat':
|
|
||||||
if (!args[1]) {
|
|
||||||
console.error('Usage: bun note.ts cat <file>');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
await catFile(config, args[1]);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'cp':
|
|
||||||
if (!args[1]) {
|
|
||||||
console.error('Usage: bun note.ts cp <local_file> [remote_file]');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
await uploadFile(config, args[1], args[2]);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'rm':
|
|
||||||
if (!args[1]) {
|
|
||||||
console.error('Usage: bun note.ts rm <remote_file>');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
await removeFile(config, args[1]);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'mv':
|
|
||||||
if (!args[1] || !args[2]) {
|
|
||||||
console.error('Usage: bun note.ts mv <old_name> <new_name>');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
await moveFile(config, args[1], args[2]);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'get':
|
|
||||||
if (!args[1]) {
|
|
||||||
console.error('Usage: bun note.ts get <remote_file> [local_file]');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
await downloadFile(config, args[1], args[2]);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'help':
|
|
||||||
default:
|
|
||||||
showHelp();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the main function
|
async function main(): Promise<void> {
|
||||||
not3().catch((error) => {
|
const config = await loadConfig();
|
||||||
console.error('❌ Error:', error);
|
|
||||||
|
const [tcpResp, httpResp] = await Promise.all([
|
||||||
|
fetchFrp(config, "/api/proxy/tcp"),
|
||||||
|
fetchFrp(config, "/api/proxy/http"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const tcpRows: string[][] = sortProxies(tcpResp.proxies || []).map((p) => [
|
||||||
|
p.name ?? "-",
|
||||||
|
p.status ?? "-",
|
||||||
|
p.conf?.remotePort?.toString() ?? "-",
|
||||||
|
]);
|
||||||
|
await printTable("TCP PROXIES", ["NAME", "STATUS", "PORT"], tcpRows);
|
||||||
|
|
||||||
|
const httpRows: string[][] = sortProxies(httpResp.proxies || []).map((p) => [
|
||||||
|
p.name ?? "-",
|
||||||
|
p.status ?? "-",
|
||||||
|
Array.isArray(p.conf?.customDomains) ? p.conf.customDomains.join(",") : "",
|
||||||
|
]);
|
||||||
|
await printTable(
|
||||||
|
"HTTP PROXIES",
|
||||||
|
["NAME", "STATUS", "CUSTOM_DOMAIN"],
|
||||||
|
httpRows,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error("❌ Error:", err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
export default not3;
|
|
||||||
Reference in New Issue
Block a user