@xditya/pastr 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/package.json +30 -0
- package/pastr.mjs +524 -0
package/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# pastr
|
|
2
|
+
|
|
3
|
+
Paste from the terminal to any [pastr](https://github.com/xditya/pastr) instance, such as [pastr.xditya.me](https://pastr.xditya.me).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install -g @xditya/pastr # or: npx @xditya/pastr …
|
|
7
|
+
pastr config host https://your-pastr.example
|
|
8
|
+
|
|
9
|
+
ls -la | pastr # stdin → link
|
|
10
|
+
pastr main.go --expires 1d # file (language from the extension)
|
|
11
|
+
pastr clip -E -c # clipboard, encrypted in the terminal, link copied back
|
|
12
|
+
pastr shot.png # images (png/jpeg/gif/webp, up to 700 KB); clip also takes a copied image
|
|
13
|
+
pastr text "hello there" -b # literal text, burn after read
|
|
14
|
+
pastr get https://host/AbCd1234#key
|
|
15
|
+
pastr ls # what you pasted from this machine
|
|
16
|
+
pastr rm AbCd1234 # delete (uses the locally stored edit token)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- Zero dependencies, Node 20+, macOS/Linux/Windows/WSL.
|
|
20
|
+
- `-E` encrypts with AES-256-GCM before upload; the key is only in the URL fragment. `-p`/`-P` uses a password instead.
|
|
21
|
+
- Edit tokens and link keys are kept in `~/.config/pastr/history.json` (`%APPDATA%\pastr` on Windows), mode 0600.
|
|
22
|
+
- Set the host once with `pastr config host …` or `PASTR_HOST`.
|
|
23
|
+
|
|
24
|
+
Prefer no Node at all? Every pastr instance serves a tiny POSIX shell version: `curl -fsSL https://your-pastr.example/install.sh | sh`.
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@xditya/pastr",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Paste from the terminal to a pastr instance: pipe, files, clipboard, with optional end-to-end encryption.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"pastr": "./pastr.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"pastr.mjs",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"pastebin",
|
|
18
|
+
"paste",
|
|
19
|
+
"cli",
|
|
20
|
+
"clipboard",
|
|
21
|
+
"encryption"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/xditya/pastr",
|
|
27
|
+
"directory": "cli"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://github.com/xditya/pastr#readme"
|
|
30
|
+
}
|
package/pastr.mjs
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* pastr — paste from the terminal.
|
|
4
|
+
*
|
|
5
|
+
* Zero dependencies (Node ≥ 20). Talks to any pastr instance over its HTTP API and
|
|
6
|
+
* implements the same AES-256-GCM envelope as the website, so `pastr -E` pastes are
|
|
7
|
+
* end-to-end encrypted without ever opening a browser.
|
|
8
|
+
*/
|
|
9
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir, platform } from "node:os";
|
|
12
|
+
import { basename, join } from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { parseArgs } from "node:util";
|
|
15
|
+
import { createInterface } from "node:readline";
|
|
16
|
+
|
|
17
|
+
export const VERSION = "0.2.0";
|
|
18
|
+
const NAME = "pastr";
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// Config & history
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
export function configDir() {
|
|
25
|
+
if (process.env.PASTR_CONFIG_DIR) return process.env.PASTR_CONFIG_DIR;
|
|
26
|
+
if (platform() === "win32") return join(process.env.APPDATA || join(homedir(), "AppData", "Roaming"), NAME);
|
|
27
|
+
return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), NAME);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readJson(file, fallback) {
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
33
|
+
} catch {
|
|
34
|
+
return fallback;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function writeJson(file, data) {
|
|
39
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
40
|
+
writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function getConfig() {
|
|
44
|
+
return readJson(join(configDir(), "config.json"), {});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function setConfig(patch) {
|
|
48
|
+
writeJson(join(configDir(), "config.json"), { ...getConfig(), ...patch });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function getHistory() {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
return readJson(join(configDir(), "history.json"), []).filter((p) => p.expires === null || p.expires === undefined || p.expires > now);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function remember(entry) {
|
|
57
|
+
const list = getHistory().filter((p) => p.id !== entry.id);
|
|
58
|
+
list.unshift(entry);
|
|
59
|
+
writeJson(join(configDir(), "history.json"), list.slice(0, 500));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function forget(id) {
|
|
63
|
+
writeJson(
|
|
64
|
+
join(configDir(), "history.json"),
|
|
65
|
+
getHistory().filter((p) => p.id !== id),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function resolveHost(flag) {
|
|
70
|
+
const host = flag || process.env.PASTR_HOST || getConfig().host;
|
|
71
|
+
if (!host) {
|
|
72
|
+
throw new UsageError(`no host configured. Run \`${NAME} config host https://your-pastr.example\` or set PASTR_HOST.`);
|
|
73
|
+
}
|
|
74
|
+
return host.replace(/\/+$/, "");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Crypto — identical envelope to the website (src/lib/crypto.ts)
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
const subtle = globalThis.crypto.subtle;
|
|
82
|
+
const enc = new TextEncoder();
|
|
83
|
+
const dec = new TextDecoder();
|
|
84
|
+
export const PBKDF2_ITERATIONS = 600_000;
|
|
85
|
+
|
|
86
|
+
export const b64u = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
87
|
+
export const unb64u = (s) => new Uint8Array(Buffer.from(s, "base64url"));
|
|
88
|
+
|
|
89
|
+
async function deriveKey(password, salt, iterations = PBKDF2_ITERATIONS) {
|
|
90
|
+
const material = await subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveKey"]);
|
|
91
|
+
return subtle.deriveKey({ name: "PBKDF2", salt, iterations, hash: "SHA-256" }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function encryptEnvelope(envelope, opts) {
|
|
95
|
+
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
96
|
+
const plaintext = enc.encode(JSON.stringify(envelope));
|
|
97
|
+
if (opts.password === undefined) {
|
|
98
|
+
const key = await subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]);
|
|
99
|
+
const ct = await subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext);
|
|
100
|
+
const raw = await subtle.exportKey("raw", key);
|
|
101
|
+
return { ciphertext: b64u(ct), meta: { alg: "AES-GCM", kdf: "fragment", iv: b64u(iv) }, fragment: b64u(raw) };
|
|
102
|
+
}
|
|
103
|
+
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
104
|
+
const key = await deriveKey(opts.password, salt);
|
|
105
|
+
const ct = await subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext);
|
|
106
|
+
return { ciphertext: b64u(ct), meta: { alg: "AES-GCM", kdf: "password", iv: b64u(iv), salt: b64u(salt), iterations: PBKDF2_ITERATIONS } };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function decryptEnvelope(ciphertext, meta, secret) {
|
|
110
|
+
const key =
|
|
111
|
+
secret.fragment !== undefined
|
|
112
|
+
? await subtle.importKey("raw", unb64u(secret.fragment), { name: "AES-GCM" }, false, ["decrypt"])
|
|
113
|
+
: await deriveKey(secret.password, unb64u(meta.salt), meta.iterations ?? PBKDF2_ITERATIONS);
|
|
114
|
+
let pt;
|
|
115
|
+
try {
|
|
116
|
+
pt = await subtle.decrypt({ name: "AES-GCM", iv: unb64u(meta.iv) }, key, unb64u(ciphertext));
|
|
117
|
+
} catch {
|
|
118
|
+
throw new CliError("wrong key or corrupted data");
|
|
119
|
+
}
|
|
120
|
+
return JSON.parse(dec.decode(pt));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Platform helpers: clipboard, browser, prompts
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
const isWsl = () => platform() === "linux" && /microsoft/i.test(safeRead("/proc/version"));
|
|
128
|
+
function safeRead(file) {
|
|
129
|
+
try {
|
|
130
|
+
return readFileSync(file, "utf8");
|
|
131
|
+
} catch {
|
|
132
|
+
return "";
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function tryExec(cmds, encoding = "utf8") {
|
|
137
|
+
for (const [cmd, args] of cmds) {
|
|
138
|
+
try {
|
|
139
|
+
return execFileSync(cmd, args, { encoding, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
|
|
140
|
+
} catch {
|
|
141
|
+
/* try the next one */
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function readClipboard() {
|
|
148
|
+
const os = platform();
|
|
149
|
+
const cmds =
|
|
150
|
+
os === "darwin"
|
|
151
|
+
? [["pbpaste", []]]
|
|
152
|
+
: os === "win32"
|
|
153
|
+
? [["powershell", ["-NoProfile", "-Command", "Get-Clipboard -Raw"]]]
|
|
154
|
+
: [
|
|
155
|
+
...(process.env.WAYLAND_DISPLAY ? [["wl-paste", ["--no-newline"]]] : []),
|
|
156
|
+
["xclip", ["-selection", "clipboard", "-o"]],
|
|
157
|
+
["xsel", ["--clipboard", "--output"]],
|
|
158
|
+
...(isWsl() ? [["powershell.exe", ["-NoProfile", "-Command", "Get-Clipboard -Raw"]]] : []),
|
|
159
|
+
];
|
|
160
|
+
const out = tryExec(cmds);
|
|
161
|
+
if (out === null) throw new CliError("could not read the clipboard (install wl-clipboard, xclip or xsel on Linux)");
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** PNG bytes of an image on the clipboard (a screenshot, say), or null when the clipboard holds no image. */
|
|
166
|
+
export function readClipboardImage() {
|
|
167
|
+
const os = platform();
|
|
168
|
+
const ps = "$i = Get-Clipboard -Format Image; if ($i) { $m = New-Object IO.MemoryStream; $i.Save($m, [Drawing.Imaging.ImageFormat]::Png); [Convert]::ToBase64String($m.ToArray()) }";
|
|
169
|
+
if (os === "darwin") {
|
|
170
|
+
// osascript prints the PNG as «data PNGf89504E47...»
|
|
171
|
+
const hex = tryExec([["osascript", ["-e", "the clipboard as «class PNGf»"]]])?.match(/PNGf([0-9A-Fa-f]+)/)?.[1];
|
|
172
|
+
return hex ? Buffer.from(hex, "hex") : null;
|
|
173
|
+
}
|
|
174
|
+
if (os === "win32" || isWsl()) {
|
|
175
|
+
const b64 = tryExec([[os === "win32" ? "powershell" : "powershell.exe", ["-NoProfile", "-Command", ps]]])?.trim();
|
|
176
|
+
return b64 ? Buffer.from(b64, "base64") : null;
|
|
177
|
+
}
|
|
178
|
+
const buf = tryExec(
|
|
179
|
+
[...(process.env.WAYLAND_DISPLAY ? [["wl-paste", ["-t", "image/png"]]] : []), ["xclip", ["-selection", "clipboard", "-t", "image/png", "-o"]]],
|
|
180
|
+
"buffer",
|
|
181
|
+
);
|
|
182
|
+
return buf?.length ? buf : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function writeClipboard(text) {
|
|
186
|
+
const os = platform();
|
|
187
|
+
const cmds =
|
|
188
|
+
os === "darwin"
|
|
189
|
+
? [["pbcopy", []]]
|
|
190
|
+
: os === "win32"
|
|
191
|
+
? [["clip", []]]
|
|
192
|
+
: [
|
|
193
|
+
...(process.env.WAYLAND_DISPLAY ? [["wl-copy", []]] : []),
|
|
194
|
+
["xclip", ["-selection", "clipboard"]],
|
|
195
|
+
["xsel", ["--clipboard", "--input"]],
|
|
196
|
+
...(isWsl() ? [["clip.exe", []]] : []),
|
|
197
|
+
];
|
|
198
|
+
for (const [cmd, args] of cmds) {
|
|
199
|
+
const r = spawnSync(cmd, args, { input: text, stdio: ["pipe", "ignore", "ignore"] });
|
|
200
|
+
if (r.status === 0) return true;
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function openInBrowser(url) {
|
|
206
|
+
const os = platform();
|
|
207
|
+
const [cmd, args] = os === "darwin" ? ["open", [url]] : os === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
208
|
+
const r = spawnSync(cmd, args, { stdio: "ignore" });
|
|
209
|
+
return r.status === 0;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function promptHidden(question) {
|
|
213
|
+
return new Promise((resolve) => {
|
|
214
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
215
|
+
const write = rl._writeToOutput;
|
|
216
|
+
rl._writeToOutput = function (s) {
|
|
217
|
+
if (s.includes(question)) write.call(rl, s);
|
|
218
|
+
else write.call(rl, "");
|
|
219
|
+
};
|
|
220
|
+
rl.question(question, (answer) => {
|
|
221
|
+
rl.close();
|
|
222
|
+
process.stderr.write("\n");
|
|
223
|
+
resolve(answer);
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function readStdin() {
|
|
229
|
+
if (process.stdin.isTTY) process.stderr.write("Type or paste, then press Ctrl-D:\n");
|
|
230
|
+
const chunks = [];
|
|
231
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
232
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
// Language from file name (mirrors the server's registry for the common cases)
|
|
237
|
+
// ---------------------------------------------------------------------------
|
|
238
|
+
|
|
239
|
+
const EXT = {
|
|
240
|
+
txt: "text", md: "markdown", markdown: "markdown", js: "javascript", mjs: "javascript", cjs: "javascript", ts: "typescript", mts: "typescript",
|
|
241
|
+
jsx: "jsx", tsx: "tsx", json: "json", jsonc: "jsonc", yml: "yaml", yaml: "yaml", toml: "toml", html: "html", htm: "html", css: "css", scss: "scss",
|
|
242
|
+
vue: "vue", svelte: "svelte", py: "python", go: "go", rs: "rust", java: "java", kt: "kotlin", swift: "swift", c: "c", h: "c", cpp: "cpp", cc: "cpp",
|
|
243
|
+
hpp: "cpp", cs: "csharp", php: "php", rb: "ruby", dart: "dart", scala: "scala", hs: "haskell", ex: "elixir", exs: "elixir", erl: "erlang",
|
|
244
|
+
clj: "clojure", lua: "lua", pl: "perl", r: "r", jl: "julia", zig: "zig", nim: "nim", ml: "ocaml", sh: "shellscript", bash: "shellscript",
|
|
245
|
+
zsh: "shellscript", ps1: "powershell", bat: "bat", fish: "fish", nix: "nix", sql: "sql", graphql: "graphql", gql: "graphql", prisma: "prisma",
|
|
246
|
+
proto: "proto", xml: "xml", svg: "xml", diff: "diff", patch: "diff", log: "log", csv: "csv", tex: "latex", tf: "terraform", hcl: "terraform",
|
|
247
|
+
ini: "ini", conf: "ini", cfg: "ini", env: "dotenv", mmd: "mermaid", sol: "solidity", http: "http",
|
|
248
|
+
png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp",
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Image "languages": the content is the file as base64 and the server caps the decoded size. */
|
|
252
|
+
const IMAGE_LANGS = new Set(["png", "jpeg", "gif", "webp"]);
|
|
253
|
+
const MAX_IMAGE_BYTES = 700 * 1024;
|
|
254
|
+
|
|
255
|
+
function imageItem(buf, lang, title) {
|
|
256
|
+
if (buf.length > MAX_IMAGE_BYTES) throw new CliError(`${title} is ${Math.round(buf.length / 1024)} KB; images are limited to ${MAX_IMAGE_BYTES / 1024} KB`);
|
|
257
|
+
return { content: buf.toString("base64"), lang, title };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function langFromFilename(name) {
|
|
261
|
+
const lower = name.toLowerCase();
|
|
262
|
+
if (lower === "dockerfile" || lower.startsWith("dockerfile.")) return "dockerfile";
|
|
263
|
+
if (lower === "makefile") return "makefile";
|
|
264
|
+
if (lower === ".env" || lower.startsWith(".env.")) return "dotenv";
|
|
265
|
+
const i = lower.lastIndexOf(".");
|
|
266
|
+
return i === -1 ? undefined : EXT[lower.slice(i + 1)];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function parsePasteRef(ref) {
|
|
270
|
+
// Accepts an id, or a URL like https://host/AbCd1234.go#key or https://host/AbCd1234/raw
|
|
271
|
+
let id = ref;
|
|
272
|
+
let key;
|
|
273
|
+
let host;
|
|
274
|
+
try {
|
|
275
|
+
const u = new URL(ref);
|
|
276
|
+
host = u.origin;
|
|
277
|
+
const seg = u.pathname.split("/").filter(Boolean)[0] ?? "";
|
|
278
|
+
id = seg.split(".")[0];
|
|
279
|
+
if (u.hash && !/^#L\d/.test(u.hash)) key = u.hash.slice(1);
|
|
280
|
+
} catch {
|
|
281
|
+
/* plain id */
|
|
282
|
+
}
|
|
283
|
+
if (!/^[A-Za-z0-9]{4,32}$/.test(id)) throw new UsageError(`"${ref}" doesn't look like a paste id or URL`);
|
|
284
|
+
return { id, key, host };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
// API
|
|
289
|
+
// ---------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
class UsageError extends Error {}
|
|
292
|
+
class CliError extends Error {}
|
|
293
|
+
|
|
294
|
+
async function api(host, path, init = {}) {
|
|
295
|
+
let res;
|
|
296
|
+
try {
|
|
297
|
+
res = await fetch(host + path, {
|
|
298
|
+
...init,
|
|
299
|
+
headers: { Accept: "application/json", "User-Agent": `${NAME}-cli/${VERSION}`, ...(init.body ? { "Content-Type": "application/json" } : {}), ...(init.headers ?? {}) },
|
|
300
|
+
});
|
|
301
|
+
} catch (e) {
|
|
302
|
+
throw new CliError(`could not reach ${host} (${e.cause?.code ?? e.message})`);
|
|
303
|
+
}
|
|
304
|
+
if (res.status === 204) return null;
|
|
305
|
+
const text = await res.text();
|
|
306
|
+
let data = null;
|
|
307
|
+
try {
|
|
308
|
+
data = JSON.parse(text);
|
|
309
|
+
} catch {
|
|
310
|
+
/* not json */
|
|
311
|
+
}
|
|
312
|
+
if (!res.ok) {
|
|
313
|
+
const msg = data?.error?.message ?? text.trim() ?? res.statusText;
|
|
314
|
+
throw new CliError(`${res.status} ${msg}`);
|
|
315
|
+
}
|
|
316
|
+
return data;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function createPaste(host, { content, title, lang, expires, burn, encrypt, password }) {
|
|
320
|
+
let body;
|
|
321
|
+
let fragment;
|
|
322
|
+
if (encrypt || password !== undefined) {
|
|
323
|
+
const r = await encryptEnvelope({ title, lang: lang ?? "text", content }, { password });
|
|
324
|
+
fragment = r.fragment;
|
|
325
|
+
body = { content: r.ciphertext, enc: r.meta, expires, burn };
|
|
326
|
+
} else {
|
|
327
|
+
body = { content, title, lang, expires, burn };
|
|
328
|
+
}
|
|
329
|
+
const p = await api(host, "/api/v1/pastes", { method: "POST", body: JSON.stringify(body) });
|
|
330
|
+
const url = fragment ? `${p.url}#${fragment}` : p.url;
|
|
331
|
+
remember({ id: p.id, url, editToken: p.editToken, key: fragment, title, lang: p.lang, created: p.created, expires: p.expires, burn: p.burn, encrypted: !!p.enc });
|
|
332
|
+
return { ...p, url };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ---------------------------------------------------------------------------
|
|
336
|
+
// CLI
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
const HELP = `${NAME} ${VERSION} — paste from the terminal
|
|
340
|
+
|
|
341
|
+
Usage
|
|
342
|
+
${NAME} [options] [file ...] paste files (text, or png/jpeg/gif/webp up to 700 KB), or stdin
|
|
343
|
+
${NAME} clip [options] paste the clipboard (text or an image)
|
|
344
|
+
${NAME} text [options] <words ...> paste literal text
|
|
345
|
+
${NAME} get <id|url> [--json] print a paste (decrypts when the URL carries a #key)
|
|
346
|
+
${NAME} ls pastes created from this machine
|
|
347
|
+
${NAME} rm <id|url> delete a paste created from this machine
|
|
348
|
+
${NAME} config [host <url>] show or set the default host
|
|
349
|
+
|
|
350
|
+
Options
|
|
351
|
+
-t, --title <text> title (defaults to the file name)
|
|
352
|
+
-l, --lang <id> language id or alias (default: from the file name, else plain text)
|
|
353
|
+
-e, --expires <when> 10m | 1h | 1d | 7d | 30d | never (default: 7d)
|
|
354
|
+
-b, --burn destroy after the first read
|
|
355
|
+
-E, --encrypt encrypt here; the key goes in the URL after #
|
|
356
|
+
-p, --password <pw> encrypt with a password instead ("-P" prompts for it)
|
|
357
|
+
-P, --ask-password prompt for a password
|
|
358
|
+
-c, --copy copy the URL to the clipboard
|
|
359
|
+
-o, --open open the URL in a browser
|
|
360
|
+
-r, --raw print the raw URL (plain text) instead of the page URL
|
|
361
|
+
-j, --json print the full API response
|
|
362
|
+
-H, --host <url> server to use (env PASTR_HOST, or \`${NAME} config host …\`)
|
|
363
|
+
-h, --help show this help
|
|
364
|
+
-v, --version show the version
|
|
365
|
+
|
|
366
|
+
Examples
|
|
367
|
+
ls -la | ${NAME}
|
|
368
|
+
${NAME} main.go --expires 1d
|
|
369
|
+
${NAME} clip -E -c # encrypted clipboard paste, URL copied back
|
|
370
|
+
${NAME} text "hello there" -b # burn after read
|
|
371
|
+
${NAME} get https://host/AbCd1234#key > file.txt
|
|
372
|
+
${NAME} shot.png -e 1d # image paste; "get" writes the bytes back
|
|
373
|
+
`;
|
|
374
|
+
|
|
375
|
+
function fmtRel(ms) {
|
|
376
|
+
const d = ms - Date.now();
|
|
377
|
+
const abs = Math.abs(d);
|
|
378
|
+
const u = abs < 60e3 ? [1e3, "s"] : abs < 3600e3 ? [60e3, "m"] : abs < 86400e3 ? [3600e3, "h"] : [86400e3, "d"];
|
|
379
|
+
const n = Math.round(abs / u[0]);
|
|
380
|
+
return d >= 0 ? `in ${n}${u[1]}` : `${n}${u[1]} ago`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export async function main(argv) {
|
|
384
|
+
const { values: o, positionals } = parseArgs({
|
|
385
|
+
args: argv,
|
|
386
|
+
allowPositionals: true,
|
|
387
|
+
options: {
|
|
388
|
+
title: { type: "string", short: "t" },
|
|
389
|
+
lang: { type: "string", short: "l" },
|
|
390
|
+
expires: { type: "string", short: "e" },
|
|
391
|
+
burn: { type: "boolean", short: "b", default: false },
|
|
392
|
+
encrypt: { type: "boolean", short: "E", default: false },
|
|
393
|
+
password: { type: "string", short: "p" },
|
|
394
|
+
"ask-password": { type: "boolean", short: "P", default: false },
|
|
395
|
+
copy: { type: "boolean", short: "c", default: false },
|
|
396
|
+
open: { type: "boolean", short: "o", default: false },
|
|
397
|
+
raw: { type: "boolean", short: "r", default: false },
|
|
398
|
+
json: { type: "boolean", short: "j", default: false },
|
|
399
|
+
host: { type: "string", short: "H" },
|
|
400
|
+
help: { type: "boolean", short: "h", default: false },
|
|
401
|
+
version: { type: "boolean", short: "v", default: false },
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
if (o.help) return out(HELP);
|
|
406
|
+
if (o.version) return out(`${NAME} ${VERSION}\n`);
|
|
407
|
+
|
|
408
|
+
const [cmd, ...rest] = positionals;
|
|
409
|
+
|
|
410
|
+
if (cmd === "config") {
|
|
411
|
+
if (rest[0] === "host" && rest[1]) {
|
|
412
|
+
setConfig({ host: rest[1].replace(/\/+$/, "") });
|
|
413
|
+
return out(`host set to ${rest[1]}\n`);
|
|
414
|
+
}
|
|
415
|
+
const cfg = getConfig();
|
|
416
|
+
return out(`host: ${process.env.PASTR_HOST || cfg.host || "(not set)"}\nconfig: ${configDir()}\n`);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (cmd === "ls") {
|
|
420
|
+
const list = getHistory();
|
|
421
|
+
if (!list.length) return out("no pastes yet\n");
|
|
422
|
+
for (const p of list) {
|
|
423
|
+
const flags = [p.encrypted && "enc", p.burn && "burn"].filter(Boolean).join(",");
|
|
424
|
+
out(`${p.id} ${(p.title || p.lang || "").padEnd(24).slice(0, 24)} ${fmtRel(p.created).padEnd(9)} ${p.expires ? "expires " + fmtRel(p.expires) : "never expires"}${flags ? " [" + flags + "]" : ""}\n ${p.url}\n`);
|
|
425
|
+
}
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
if (cmd === "get") {
|
|
430
|
+
if (!rest[0]) throw new UsageError("usage: get <id|url>");
|
|
431
|
+
const ref = parsePasteRef(rest[0]);
|
|
432
|
+
const host = ref.host ?? resolveHost(o.host);
|
|
433
|
+
const p = await api(host, `/api/v1/pastes/${ref.id}`);
|
|
434
|
+
if (o.json) return out(JSON.stringify(p, null, 2) + "\n");
|
|
435
|
+
if (!p.enc) return emit(p.content, p.lang);
|
|
436
|
+
let secret;
|
|
437
|
+
if (p.enc.kdf === "fragment") {
|
|
438
|
+
const key = ref.key ?? getHistory().find((h) => h.id === ref.id)?.key;
|
|
439
|
+
if (!key) throw new CliError("this paste is encrypted; pass the full URL including the #key");
|
|
440
|
+
secret = { fragment: key };
|
|
441
|
+
} else {
|
|
442
|
+
secret = { password: o.password ?? (await promptHidden("Password: ")) };
|
|
443
|
+
}
|
|
444
|
+
const env = await decryptEnvelope(p.content, p.enc, secret);
|
|
445
|
+
return emit(env.content, env.lang);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
if (cmd === "rm") {
|
|
449
|
+
if (!rest[0]) throw new UsageError("usage: rm <id|url>");
|
|
450
|
+
const ref = parsePasteRef(rest[0]);
|
|
451
|
+
const host = ref.host ?? resolveHost(o.host);
|
|
452
|
+
const entry = getHistory().find((h) => h.id === ref.id);
|
|
453
|
+
const token = entry?.editToken ?? process.env.PASTR_EDIT_TOKEN;
|
|
454
|
+
if (!token) throw new CliError(`no edit token for ${ref.id} on this machine (set PASTR_EDIT_TOKEN to use one)`);
|
|
455
|
+
await api(host, `/api/v1/pastes/${ref.id}`, { method: "DELETE", headers: { Authorization: `Bearer ${token}` } });
|
|
456
|
+
forget(ref.id);
|
|
457
|
+
return out(`deleted ${ref.id}\n`);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ---- create ----
|
|
461
|
+
const host = resolveHost(o.host);
|
|
462
|
+
const password = o["ask-password"] ? await promptHidden("Password: ") : o.password;
|
|
463
|
+
const items = [];
|
|
464
|
+
if (cmd === "clip") {
|
|
465
|
+
const img = readClipboardImage();
|
|
466
|
+
items.push(img ? imageItem(img, "png", o.title ?? "clipboard.png") : { content: readClipboard(), title: o.title });
|
|
467
|
+
} else if (cmd === "text") {
|
|
468
|
+
if (!rest.length) throw new UsageError("usage: text <words ...>");
|
|
469
|
+
items.push({ content: rest.join(" "), title: o.title });
|
|
470
|
+
} else {
|
|
471
|
+
const files = cmd ? [cmd, ...rest] : [];
|
|
472
|
+
if (!files.length) items.push({ content: await readStdin(), title: o.title });
|
|
473
|
+
for (const f of files) {
|
|
474
|
+
if (!existsSync(f)) throw new UsageError(`no such file: ${f}`);
|
|
475
|
+
const buf = readFileSync(f);
|
|
476
|
+
const lang = o.lang ?? langFromFilename(basename(f));
|
|
477
|
+
if (IMAGE_LANGS.has(lang)) {
|
|
478
|
+
items.push(imageItem(buf, lang, o.title ?? basename(f)));
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (buf.includes(0)) throw new CliError(`${f} looks binary; only text and png/jpeg/gif/webp images can be pasted`);
|
|
482
|
+
items.push({ content: buf.toString("utf8"), title: o.title ?? basename(f), lang });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
for (const item of items) {
|
|
487
|
+
if (!item.content.trim()) throw new CliError("nothing to paste");
|
|
488
|
+
const p = await createPaste(host, {
|
|
489
|
+
content: item.content,
|
|
490
|
+
title: item.title,
|
|
491
|
+
lang: item.lang ?? o.lang,
|
|
492
|
+
expires: o.expires,
|
|
493
|
+
burn: o.burn,
|
|
494
|
+
encrypt: o.encrypt,
|
|
495
|
+
password,
|
|
496
|
+
});
|
|
497
|
+
const url = o.raw ? p.rawUrl : p.url;
|
|
498
|
+
if (o.json) out(JSON.stringify(p, null, 2) + "\n");
|
|
499
|
+
else out(url + "\n");
|
|
500
|
+
if (o.copy) {
|
|
501
|
+
if (writeClipboard(url)) process.stderr.write("copied to clipboard\n");
|
|
502
|
+
else process.stderr.write("could not copy to clipboard\n");
|
|
503
|
+
}
|
|
504
|
+
if (o.open) openInBrowser(url);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function out(s) {
|
|
509
|
+
process.stdout.write(s);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Text goes out as is; image pastes are decoded so `get shot > shot.png` works. */
|
|
513
|
+
function emit(content, lang) {
|
|
514
|
+
process.stdout.write(IMAGE_LANGS.has(lang) ? Buffer.from(content, "base64") : content);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const isMain = process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href;
|
|
518
|
+
if (isMain || (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1])) {
|
|
519
|
+
main(process.argv.slice(2)).catch((err) => {
|
|
520
|
+
const usage = err instanceof UsageError || err?.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" || err?.code?.startsWith?.("ERR_PARSE_ARGS");
|
|
521
|
+
process.stderr.write(`${NAME}: ${err.message}\n${usage ? `Run \`${NAME} --help\` for usage.\n` : ""}`);
|
|
522
|
+
process.exit(usage ? 2 : 1);
|
|
523
|
+
});
|
|
524
|
+
}
|