Compare commits

..

No commits in common. "39a9ac0dadfbfad78bd2790296929bcfb54f8c59" and "a37a0932e0197af7a1dc856f6631c3c80a845779" have entirely different histories.

21 changed files with 1128 additions and 1438 deletions

View File

@ -10,18 +10,18 @@ jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
# Node # Node
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v2
- uses: actions/setup-node@v4 - uses: actions/setup-node@v3
with: with:
cache: 'pnpm' cache: 'pnpm'
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
# Docker # Docker
- uses: docker/setup-qemu-action@v3 - uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v3 - uses: docker/setup-buildx-action@v2
with: with:
install: true install: true

2
.nvmrc
View File

@ -1 +1 @@
v18.19.1 v20.9.0

View File

@ -1,17 +1,14 @@
# FRONTEND # FRONTEND
FROM node:18-alpine as client FROM node:18-alpine as client
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /tmp WORKDIR /tmp
RUN npm install -g pnpm@8
COPY . . COPY . .
RUN pnpm install --frozen-lockfile RUN pnpm install --frozen-lockfile
RUN pnpm run build RUN pnpm run build
# BACKEND # BACKEND
FROM rust:1.76-alpine as backend FROM rust:1.73-alpine as backend
WORKDIR /tmp WORKDIR /tmp
RUN apk add libc-dev openssl-dev alpine-sdk RUN apk add libc-dev openssl-dev alpine-sdk
COPY ./packages/backend ./ COPY ./packages/backend ./

View File

@ -14,12 +14,11 @@ services:
env_file: .dev.env env_file: .dev.env
depends_on: depends_on:
- redis - redis
restart: unless-stopped
ports: ports:
- 1234:8000 - 1234:8000
healthcheck: healthcheck:
test: ['CMD', 'curl', '--fail', 'http://127.0.0.1:8000/api/live/'] test: ["CMD", "curl", "--fail", "http://127.0.0.1:8000/api/live/"]
interval: 1m interval: 1m
timeout: 3s timeout: 3s
retries: 2 retries: 2

View File

@ -1,4 +1,5 @@
{ {
"packageManager": "pnpm@8.10.1",
"scripts": { "scripts": {
"dev:docker": "docker-compose -f docker-compose.dev.yaml up redis", "dev:docker": "docker-compose -f docker-compose.dev.yaml up redis",
"dev:packages": "pnpm --parallel run dev", "dev:packages": "pnpm --parallel run dev",
@ -12,10 +13,9 @@
"build": "pnpm run --recursive --filter=!@cryptgeon/backend build" "build": "pnpm run --recursive --filter=!@cryptgeon/backend build"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.42.1", "@playwright/test": "^1.39.0",
"@types/node": "^20.11.24", "@types/node": "^20.8.10",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"shelljs": "^0.8.5" "shelljs": "^0.8.5"
}, }
"packageManager": "pnpm@8.15.4"
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,9 @@
[package] [package]
name = "cryptgeon" name = "cryptgeon"
version = "2.5.0" version = "2.4.0"
authors = ["cupcakearmy <hi@nicco.io>"] authors = ["cupcakearmy <hi@nicco.io>"]
edition = "2021" edition = "2021"
rust-version = "1.76" rust-version = "1.73"
[[bin]] [[bin]]
name = "cryptgeon" name = "cryptgeon"

View File

@ -1,49 +1,43 @@
{ {
"version": "2.4.0",
"name": "cryptgeon", "name": "cryptgeon",
"version": "2.5.0",
"homepage": "https://github.com/cupcakearmy/cryptgeon",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/cupcakearmy/cryptgeon.git", "url": "https://github.com/cupcakearmy/cryptgeon.git",
"directory": "packages/cli" "directory": "packages/cli"
}, },
"homepage": "https://github.com/cupcakearmy/cryptgeon",
"type": "module", "type": "module",
"exports": { "engines": {
".": { "node": ">=18"
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
}, },
"types": "./dist/index.d.ts", "scripts": {
"dev": "./scripts/build.js --watch",
"build": "./scripts/build.js",
"package": "./scripts/package.js",
"bin": "run-s build package",
"prepublishOnly": "run-s build"
},
"main": "./dist/index.cjs",
"bin": { "bin": {
"cryptgeon": "./dist/cli.cjs" "cryptgeon": "./dist/index.cjs"
}, },
"files": [ "files": [
"dist" "dist"
], ],
"scripts": {
"bin": "run-s build package",
"build": "tsc && ./scripts/build.js",
"dev": "./scripts/build.js --watch",
"package": "./scripts/package.js",
"prepublishOnly": "run-s build"
},
"devDependencies": { "devDependencies": {
"@commander-js/extra-typings": "^12.0.1", "@commander-js/extra-typings": "^11.1.0",
"@cryptgeon/shared": "workspace:*", "@cryptgeon/shared": "workspace:*",
"@types/inquirer": "^9.0.7", "@types/inquirer": "^9.0.6",
"@types/mime": "^3.0.4", "@types/mime": "^3.0.3",
"@types/node": "^20.11.24", "@types/node": "^20.8.10",
"commander": "^12.0.0", "commander": "^11.1.0",
"esbuild": "^0.20.1", "esbuild": "^0.19.5",
"inquirer": "^9.2.15", "inquirer": "^9.2.11",
"mime": "^4.0.1", "mime": "^3.0.0",
"occulto": "^2.0.3", "occulto": "^2.0.1",
"pkg": "^5.8.1", "pkg": "^5.8.1",
"pretty-bytes": "^6.1.1", "pretty-bytes": "^6.1.1",
"typescript": "^5.3.3" "typescript": "^5.2.2"
},
"engines": {
"node": ">=18"
} }
} }

View File

@ -4,28 +4,14 @@ import { build, context } from 'esbuild'
import pkg from '../package.json' assert { type: 'json' } import pkg from '../package.json' assert { type: 'json' }
const options = { const options = {
entryPoints: ['./src/cli.ts'], entryPoints: ['./src/index.ts'],
bundle: true, bundle: true,
minify: true, minify: true,
platform: 'node', platform: 'node',
outfile: './dist/cli.cjs', outfile: './dist/index.cjs',
define: { VERSION: `"${pkg.version}"` }, define: { VERSION: `"${pkg.version}"` },
} }
const watch = process.argv.slice(2)[0] === '--watch' const watch = process.argv.slice(2)[0] === '--watch'
if (watch) { if (watch) (await context(options)).watch()
;(await context(options)).watch() else await build(options)
} else {
await build(options)
// Also build internals to expose
await build({
entryPoints: ['./src/index.ts'],
bundle: true,
minify: true,
platform: 'node',
format: 'esm',
outfile: './dist/index.js',
define: { VERSION: `"${pkg.version}"` },
})
}

View File

@ -13,5 +13,5 @@ const targets = [
for (const target of targets) { for (const target of targets) {
console.log(`🚀 Building ${target}`) console.log(`🚀 Building ${target}`)
await exec(['./dist/cli.cjs', '--target', target, '--output', `./bin/${target.replace('node18', 'cryptgeon')}`]) await exec(['./dist/index.cjs', '--target', target, '--output', `./bin/${target.replace('node18', 'cryptgeon')}`])
} }

View File

@ -1,106 +0,0 @@
#!/usr/bin/env node
import { Argument, Option, program } from '@commander-js/extra-typings'
import { setBase, status } from '@cryptgeon/shared'
import prettyBytes from 'pretty-bytes'
import { download } from './download.js'
import { parseFile, parseNumber } from './parsers.js'
import { getStdin } from './stdin.js'
import { upload } from './upload.js'
import { checkConstrains, exit } from './utils.js'
const defaultServer = process.env['CRYPTGEON_SERVER'] || 'https://cryptgeon.org'
const server = new Option('-s --server <url>', 'the cryptgeon server to use').default(defaultServer)
const files = new Argument('<file...>', 'Files to be sent').argParser(parseFile)
const text = new Argument('<text>', 'Text content of the note')
const password = new Option('-p --password <string>', 'manually set a password')
const all = new Option('-a --all', 'Save all files without prompt').default(false)
const url = new Argument('<url>', 'The url to open')
const views = new Option('-v --views <number>', 'Amount of views before getting destroyed').argParser(parseNumber)
const minutes = new Option('-m --minutes <number>', 'Minutes before the note expires').argParser(parseNumber)
// Node 18 guard
parseInt(process.version.slice(1).split(',')[0]) < 18 && exit('Node 18 or higher is required')
// @ts-ignore
const version: string = VERSION
program.name('cryptgeon').version(version).configureHelp({ showGlobalOptions: true })
program
.command('info')
.description('show information about the server')
.addOption(server)
.action(async (options) => {
setBase(options.server)
const response = await status()
const formatted = {
...response,
max_size: prettyBytes(response.max_size),
}
for (const key of Object.keys(formatted)) {
if (key.startsWith('theme_')) delete formatted[key as keyof typeof formatted]
}
console.table(formatted)
})
const send = program.command('send').description('send a note')
send
.command('file')
.addArgument(files)
.addOption(server)
.addOption(views)
.addOption(minutes)
.addOption(password)
.action(async (files, options) => {
setBase(options.server!)
await checkConstrains(options)
options.password ||= await getStdin()
try {
const url = await upload(files, { views: options.views, expiration: options.minutes, password: options.password })
console.log(`Note created:\n\n${url}`)
} catch {
exit('Could not create note')
}
})
send
.command('text')
.addArgument(text)
.addOption(server)
.addOption(views)
.addOption(minutes)
.addOption(password)
.action(async (text, options) => {
setBase(options.server!)
await checkConstrains(options)
options.password ||= await getStdin()
try {
const url = await upload(text, { views: options.views, expiration: options.minutes, password: options.password })
console.log(`Note created:\n\n${url}`)
} catch {
exit('Could not create note')
}
})
program
.command('open')
.description('open a link with text or files inside')
.addArgument(url)
.addOption(password)
.addOption(all)
.action(async (note, options) => {
try {
const url = new URL(note)
options.password ||= await getStdin()
try {
await download(url, options.all, options.password)
} catch (e) {
exit(e instanceof Error ? e.message : 'Unknown error occurred')
}
} catch {
exit('Invalid URL')
}
})
program.parse()

View File

@ -5,12 +5,12 @@ import { basename, resolve } from 'node:path'
import { AES, Hex } from 'occulto' import { AES, Hex } from 'occulto'
import pretty from 'pretty-bytes' import pretty from 'pretty-bytes'
import { exit } from './utils'
export async function download(url: URL, all: boolean, suggestedPassword?: string) { export async function download(url: URL, all: boolean, suggestedPassword?: string) {
setBase(url.origin) setBase(url.origin)
const id = url.pathname.split('/')[2] const id = url.pathname.split('/')[2]
const preview = await info(id).catch(() => { const preview = await info(id).catch(() => exit('Note does not exist or is expired'))
throw new Error('Note does not exist or is expired')
})
// Password // Password
let password: string let password: string
@ -35,14 +35,13 @@ export async function download(url: URL, all: boolean, suggestedPassword?: strin
const key = derivation ? (await AES.derive(password, derivation))[0] : Hex.decode(password) const key = derivation ? (await AES.derive(password, derivation))[0] : Hex.decode(password)
const note = await get(id) const note = await get(id)
const couldNotDecrypt = new Error('Could not decrypt note. Probably an invalid password') const couldNotDecrypt = () => exit('Could not decrypt note. Probably an invalid password')
switch (note.meta.type) { switch (note.meta.type) {
case 'file': case 'file':
const files = await Adapters.Files.decrypt(note.contents, key).catch(() => { const files = await Adapters.Files.decrypt(note.contents, key).catch(couldNotDecrypt)
throw couldNotDecrypt
})
if (!files) { if (!files) {
throw new Error('No files found in note') exit('No files found in note')
return
} }
let selected: typeof files let selected: typeof files
@ -64,7 +63,7 @@ export async function download(url: URL, all: boolean, suggestedPassword?: strin
selected = files.filter((file) => names.includes(file.name)) selected = files.filter((file) => names.includes(file.name))
} }
if (!selected.length) throw new Error('No files selected') if (!selected.length) exit('No files selected')
await Promise.all( await Promise.all(
selected.map(async (file) => { selected.map(async (file) => {
let filename = resolve(file.name) let filename = resolve(file.name)
@ -80,9 +79,7 @@ export async function download(url: URL, all: boolean, suggestedPassword?: strin
break break
case 'text': case 'text':
const plaintext = await Adapters.Text.decrypt(note.contents, key).catch(() => { const plaintext = await Adapters.Text.decrypt(note.contents, key).catch(couldNotDecrypt)
throw couldNotDecrypt
})
console.log(plaintext) console.log(plaintext)
break break
} }

View File

@ -1,4 +1,104 @@
export * from '@cryptgeon/shared' #!/usr/bin/env node
export * from './download.js'
export * from './upload.js' import { Argument, Option, program } from '@commander-js/extra-typings'
export * from './utils.js' import { setBase, status } from '@cryptgeon/shared'
import prettyBytes from 'pretty-bytes'
import { download } from './download.js'
import { parseFile, parseNumber } from './parsers.js'
import { getStdin } from './stdin.js'
import { upload } from './upload.js'
import { exit } from './utils.js'
const defaultServer = process.env['CRYPTGEON_SERVER'] || 'https://cryptgeon.org'
const server = new Option('-s --server <url>', 'the cryptgeon server to use').default(defaultServer)
const files = new Argument('<file...>', 'Files to be sent').argParser(parseFile)
const text = new Argument('<text>', 'Text content of the note')
const password = new Option('-p --password <string>', 'manually set a password')
const all = new Option('-a --all', 'Save all files without prompt').default(false)
const url = new Argument('<url>', 'The url to open')
const views = new Option('-v --views <number>', 'Amount of views before getting destroyed').argParser(parseNumber)
const minutes = new Option('-m --minutes <number>', 'Minutes before the note expires').argParser(parseNumber)
// Node 18 guard
parseInt(process.version.slice(1).split(',')[0]) < 18 && exit('Node 18 or higher is required')
// @ts-ignore
const version: string = VERSION
async function checkConstrains(constrains: { views?: number; minutes?: number }) {
const { views, minutes } = constrains
if (views && minutes) exit('cannot set view and minutes constrains simultaneously')
if (!views && !minutes) constrains.views = 1
const response = await status()
if (views && views > response.max_views)
exit(`Only a maximum of ${response.max_views} views allowed. ${views} given.`)
if (minutes && minutes > response.max_expiration)
exit(`Only a maximum of ${response.max_expiration} minutes allowed. ${minutes} given.`)
}
program.name('cryptgeon').version(version).configureHelp({ showGlobalOptions: true })
program
.command('info')
.description('show information about the server')
.addOption(server)
.action(async (options) => {
setBase(options.server)
const response = await status()
const formatted = {
...response,
max_size: prettyBytes(response.max_size),
}
for (const key of Object.keys(formatted)) {
if (key.startsWith('theme_')) delete formatted[key as keyof typeof formatted]
}
console.table(formatted)
})
const send = program.command('send').description('send a note')
send
.command('file')
.addArgument(files)
.addOption(server)
.addOption(views)
.addOption(minutes)
.addOption(password)
.action(async (files, options) => {
setBase(options.server!)
await checkConstrains(options)
options.password ||= await getStdin()
await upload(files, { views: options.views, expiration: options.minutes, password: options.password })
})
send
.command('text')
.addArgument(text)
.addOption(server)
.addOption(views)
.addOption(minutes)
.addOption(password)
.action(async (text, options) => {
setBase(options.server!)
await checkConstrains(options)
options.password ||= await getStdin()
await upload(text, { views: options.views, expiration: options.minutes, password: options.password })
})
program
.command('open')
.description('open a link with text or files inside')
.addArgument(url)
.addOption(password)
.addOption(all)
.action(async (note, options) => {
try {
const url = new URL(note)
options.password ||= await getStdin()
await download(url, options.all, options.password)
} catch {
exit('Invalid URL')
}
})
program.parse()

View File

@ -3,43 +3,49 @@ import { basename } from 'node:path'
import { Adapters, BASE, create, FileDTO, Note, NoteMeta } from '@cryptgeon/shared' import { Adapters, BASE, create, FileDTO, Note, NoteMeta } from '@cryptgeon/shared'
import mime from 'mime' import mime from 'mime'
import { AES, Hex } from 'occulto' import { AES, Hex, TypedArray } from 'occulto'
export type UploadOptions = Pick<Note, 'views' | 'expiration'> & { password?: string } import { exit } from './utils.js'
export async function upload(input: string | string[], options: UploadOptions): Promise<string> { type UploadOptions = Pick<Note, 'views' | 'expiration'> & { password?: string }
const { password, ...noteOptions } = options
const derived = options.password ? await AES.derive(options.password) : undefined
const key = derived ? derived[0] : await AES.generateKey()
let contents: string export async function upload(input: string | string[], options: UploadOptions) {
let type: NoteMeta['type'] try {
if (typeof input === 'string') { const { password, ...noteOptions } = options
contents = await Adapters.Text.encrypt(input, key) const derived = options.password ? await AES.derive(options.password) : undefined
type = 'text' const key = derived ? derived[0] : await AES.generateKey()
} else {
const files: FileDTO[] = await Promise.all( let contents: string
input.map(async (path) => { let type: NoteMeta['type']
const data = new Uint8Array(await readFile(path)) if (typeof input === 'string') {
const stats = await stat(path) contents = await Adapters.Text.encrypt(input, key)
const extension = path.substring(path.indexOf('.') + 1) type = 'text'
const type = mime.getType(extension) ?? 'application/octet-stream' } else {
return { const files: FileDTO[] = await Promise.all(
name: basename(path), input.map(async (path) => {
size: stats.size, const data = new Uint8Array(await readFile(path))
contents: data, const stats = await stat(path)
type, const extension = path.substring(path.indexOf('.') + 1)
} satisfies FileDTO const type = mime.getType(extension) ?? 'application/octet-stream'
}) return {
) name: basename(path),
contents = await Adapters.Files.encrypt(files, key) size: stats.size,
type = 'file' contents: data,
type,
} satisfies FileDTO
})
)
contents = await Adapters.Files.encrypt(files, key)
type = 'file'
}
// Create the actual note and upload it.
const note: Note = { ...noteOptions, contents, meta: { type, derivation: derived?.[1] } }
const result = await create(note)
let url = `${BASE}/note/${result.id}`
if (!derived) url += `#${Hex.encode(key)}`
console.log(`Note created:\n\n${url}`)
} catch {
exit('Could not create note')
} }
// Create the actual note and upload it.
const note: Note = { ...noteOptions, contents, meta: { type, derivation: derived?.[1] } }
const result = await create(note)
let url = `${BASE}/note/${result.id}`
if (!derived) url += `#${Hex.encode(key)}`
return url
} }

View File

@ -1,19 +1,6 @@
import { status } from '@cryptgeon/shared'
import { exit as exitNode } from 'node:process' import { exit as exitNode } from 'node:process'
export function exit(message: string) { export function exit(message: string) {
console.error(message) console.error(message)
exitNode(1) exitNode(1)
} }
export async function checkConstrains(constrains: { views?: number; minutes?: number }) {
const { views, minutes } = constrains
if (views && minutes) exit('cannot set view and minutes constrains simultaneously')
if (!views && !minutes) constrains.views = 1
const response = await status()
if (views && views > response.max_views)
exit(`Only a maximum of ${response.max_views} views allowed. ${views} given.`)
if (minutes && minutes > response.max_expiration)
exit(`Only a maximum of ${response.max_expiration} minutes allowed. ${minutes} given.`)
}

View File

@ -3,11 +3,8 @@
"target": "es2022", "target": "es2022",
"module": "es2022", "module": "es2022",
"moduleResolution": "node", "moduleResolution": "node",
"declaration": true, "noEmit": true,
"emitDeclarationOnly": true,
"strict": true, "strict": true,
"outDir": "./dist",
"rootDir": "./src",
"allowSyntheticDefaultImports": true "allowSyntheticDefaultImports": true
} }
} }

View File

@ -13,27 +13,26 @@
}, },
"type": "module", "type": "module",
"devDependencies": { "devDependencies": {
"@lokalise/node-api": "^12.1.0", "@lokalise/node-api": "^12.0.0",
"@sveltejs/adapter-static": "^3.0.1", "@sveltejs/adapter-static": "^2.0.3",
"@sveltejs/kit": "^2.5.2", "@sveltejs/kit": "^1.27.2",
"@sveltejs/vite-plugin-svelte": "^3.0.2", "@types/file-saver": "^2.0.6",
"@types/file-saver": "^2.0.7",
"@zerodevx/svelte-toast": "^0.9.5", "@zerodevx/svelte-toast": "^0.9.5",
"adm-zip": "^0.5.10", "adm-zip": "^0.5.10",
"dotenv": "^16.4.5", "dotenv": "^16.3.1",
"svelte": "^4.2.12", "svelte": "^4.2.2",
"svelte-check": "^3.6.6", "svelte-check": "^3.5.2",
"svelte-intl-precompile": "^0.12.3", "svelte-intl-precompile": "^0.12.3",
"tslib": "^2.6.2", "tslib": "^2.6.2",
"typescript": "^5.3.3", "typescript": "^5.2.2",
"vite": "^5.1.4" "vite": "^4.5.0"
}, },
"dependencies": { "dependencies": {
"@cryptgeon/shared": "workspace:*", "@cryptgeon/shared": "workspace:*",
"@fontsource/fira-mono": "^5.0.8", "@fontsource/fira-mono": "^5.0.8",
"copy-to-clipboard": "^3.3.3", "copy-to-clipboard": "^3.3.3",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"occulto": "^2.0.3", "occulto": "^2.0.1",
"pretty-bytes": "^6.1.1", "pretty-bytes": "^6.1.1",
"qrious": "^4.0.2" "qrious": "^4.0.2"
} }

View File

@ -1,6 +1,6 @@
import adapter from '@sveltejs/adapter-static' import adapter from '@sveltejs/adapter-static'
import precompileIntl from 'svelte-intl-precompile/sveltekit-plugin' import precompileIntl from 'svelte-intl-precompile/sveltekit-plugin'
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte' import { vitePreprocess } from '@sveltejs/kit/vite'
export default { export default {
preprocess: vitePreprocess([precompileIntl('locales')]), preprocess: vitePreprocess([precompileIntl('locales')]),

View File

@ -14,9 +14,9 @@
"build": "tsc" "build": "tsc"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5.3.3" "typescript": "^5.2.2"
}, },
"dependencies": { "dependencies": {
"occulto": "^2.0.3" "occulto": "^2.0.1"
} }
} }

1668
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -88,7 +88,7 @@ export async function checkLinkDoesNotExist(page: Page, link: string) {
} }
export async function CLI(...args: string[]) { export async function CLI(...args: string[]) {
return await exec('./packages/cli/dist/cli.cjs', args, { return await exec('./packages/cli/dist/index.cjs', args, {
env: { env: {
...process.env, ...process.env,
CRYPTGEON_SERVER: 'http://localhost:1234', CRYPTGEON_SERVER: 'http://localhost:1234',