Compare commits

..

3 Commits

Author SHA1 Message Date
dependabot[bot]
24c66bd08a Merge d4a68b058b into b089323990 2023-08-04 10:49:36 +02:00
d4a68b058b Merge branch 'main' into dependabot/npm_and_yarn/vite-4.3.9 2023-08-04 10:49:33 +02:00
dependabot[bot]
27c1ad460c Bump vite from 4.3.5 to 4.3.9
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.3.5 to 4.3.9.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.3.9/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-03 05:55:31 +00:00
41 changed files with 2020 additions and 2313 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 @@
v20.11.1 v18.16

View File

@@ -5,13 +5,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.4.0] - 2023-11-01
### Changed
- Removed HTML sanitation, display the original message as string
- Links are now displayed under the note in a separate section
## [2.3.1] - 2023-06-23 ## [2.3.1] - 2023-06-23
### Added ### Added

View File

@@ -1,25 +1,25 @@
# FRONTEND # FRONTEND
FROM node:20-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.69-alpine as backend
WORKDIR /tmp WORKDIR /tmp
RUN apk add --no-cache libc-dev openssl-dev alpine-sdk RUN apk add libc-dev openssl-dev alpine-sdk
COPY ./packages/backend/Cargo.* ./
ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
RUN cargo fetch
COPY ./packages/backend ./ COPY ./packages/backend ./
RUN cargo build --release RUN cargo build --release
# RUNNER # RUNNER
FROM alpine:3.19 FROM alpine
WORKDIR /app WORKDIR /app
RUN apk add --no-cache curl RUN apk add --no-cache curl
COPY --from=backend /tmp/target/release/cryptgeon . COPY --from=backend /tmp/target/release/cryptgeon .

View File

@@ -62,21 +62,19 @@ of the notes even if it tried to.
## Environment Variables ## Environment Variables
| Variable | Default | Description | | Variable | Default | Description |
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REDIS` | `redis://redis/` | Redis URL to connect to. [According to format](https://docs.rs/redis/latest/redis/#connection-parameters) | | `REDIS` | `redis://redis/` | Redis URL to connect to. [According to format](https://docs.rs/redis/latest/redis/#connection-parameters) |
| `SIZE_LIMIT` | `1 KiB` | Max size for body. Accepted values according to [byte-unit](https://docs.rs/byte-unit/). <br> `512 MiB` is the maximum allowed. <br> The frontend will show that number including the ~35% encoding overhead. | | `SIZE_LIMIT` | `1 KiB` | Max size for body. Accepted values according to [byte-unit](https://docs.rs/byte-unit/). <br> `512 MiB` is the maximum allowed. <br> The frontend will show that number including the ~35% encoding overhead. |
| `MAX_VIEWS` | `100` | Maximal number of views. | | `MAX_VIEWS` | `100` | Maximal number of views. |
| `MAX_EXPIRATION` | `360` | Maximal expiration in minutes. | | `MAX_EXPIRATION` | `360` | Maximal expiration in minutes. |
| `ALLOW_ADVANCED` | `true` | Allow custom configuration. If set to `false` all notes will be one view only. | | `ALLOW_ADVANCED` | `true` | Allow custom configuration. If set to `false` all notes will be one view only. |
| `ALLOW_FILES` | `true` | Allow uploading files. If set to `false`, users will only be allowed to create text notes. | | `ID_LENGTH` | `32` | Set the size of the note `id` in bytes. By default this is `32` bytes. This is useful for reducing link size. _This setting does not affect encryption strength_. |
| `THEME_NEW_NOTE_NOTICE` | `true` | Show the message about how notes are stored in the memory and may be evicted after creating a new note. Defaults to `true`. | | `VERBOSITY` | `warn` | Verbosity level for the backend. [Possible values](https://docs.rs/env_logger/latest/env_logger/#enabling-logging) are: `error`, `warn`, `info`, `debug`, `trace` |
| `ID_LENGTH` | `32` | Set the size of the note `id` in bytes. By default this is `32` bytes. This is useful for reducing link size. _This setting does not affect encryption strength_. | | `THEME_IMAGE` | `""` | Custom image for replacing the logo. Must be publicly reachable |
| `VERBOSITY` | `warn` | Verbosity level for the backend. [Possible values](https://docs.rs/env_logger/latest/env_logger/#enabling-logging) are: `error`, `warn`, `info`, `debug`, `trace` | | `THEME_TEXT` | `""` | Custom text for replacing the description below the logo |
| `THEME_IMAGE` | `""` | Custom image for replacing the logo. Must be publicly reachable | | `THEME_PAGE_TITLE` | `""` | Custom text the page title |
| `THEME_TEXT` | `""` | Custom text for replacing the description below the logo | | `THEME_FAVICON` | `""` | Custom url for the favicon. Must be publicly reachable |
| `THEME_PAGE_TITLE` | `""` | Custom text the page title |
| `THEME_FAVICON` | `""` | Custom url for the favicon. Must be publicly reachable |
## Deployment ## Deployment

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.6.3",
"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.33.0",
"@types/node": "^20.11.28", "@types/node": "^20.1.3",
"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,8 @@
[package] [package]
name = "cryptgeon" name = "cryptgeon"
version = "2.6.1" version = "2.3.1"
authors = ["cupcakearmy <hi@nicco.io>"] authors = ["cupcakearmy <hi@nicco.io>"]
edition = "2021" edition = "2021"
rust-version = "1.76"
[[bin]] [[bin]]
name = "cryptgeon" name = "cryptgeon"

View File

@@ -14,34 +14,26 @@ lazy_static! {
// CONFIG // CONFIG
lazy_static! { lazy_static! {
pub static ref LIMIT: usize = pub static ref LIMIT: usize =
Byte::from_str(std::env::var("SIZE_LIMIT").unwrap_or("1 KiB".to_string())) Byte::from_str(std::env::var("SIZE_LIMIT").unwrap_or("1 KiB".to_string()))
.unwrap() .unwrap()
.get_bytes() as usize; .get_bytes() as usize;
pub static ref MAX_VIEWS: u32 = std::env::var("MAX_VIEWS") pub static ref MAX_VIEWS: u32 = std::env::var("MAX_VIEWS")
.unwrap_or("100".to_string()) .unwrap_or("100".to_string())
.parse() .parse()
.unwrap(); .unwrap();
pub static ref MAX_EXPIRATION: u32 = std::env::var("MAX_EXPIRATION") pub static ref MAX_EXPIRATION: u32 = std::env::var("MAX_EXPIRATION")
.unwrap_or("360".to_string()) // 6 hours in minutes .unwrap_or("360".to_string()) // 6 hours in minutes
.parse() .parse()
.unwrap(); .unwrap();
pub static ref ALLOW_ADVANCED: bool = std::env::var("ALLOW_ADVANCED") pub static ref ALLOW_ADVANCED: bool = std::env::var("ALLOW_ADVANCED")
.unwrap_or("true".to_string()) .unwrap_or("true".to_string())
.parse() .parse()
.unwrap(); .unwrap();
pub static ref ID_LENGTH: u32 = std::env::var("ID_LENGTH") pub static ref ID_LENGTH: u32 = std::env::var("ID_LENGTH")
.unwrap_or("32".to_string()) .unwrap_or("32".to_string())
.parse() .parse()
.unwrap(); .unwrap();
pub static ref ALLOW_FILES: bool = std::env::var("ALLOW_FILES")
.unwrap_or("true".to_string())
.parse()
.unwrap();
pub static ref THEME_NEW_NOTE_NOTICE: bool = std::env::var("THEME_NEW_NOTE_NOTICE")
.unwrap_or("true".to_string())
.parse()
.unwrap();
} }
// THEME // THEME

View File

@@ -9,8 +9,6 @@ pub struct Status {
pub max_views: u32, pub max_views: u32,
pub max_expiration: u32, pub max_expiration: u32,
pub allow_advanced: bool, pub allow_advanced: bool,
pub allow_files: bool,
pub theme_new_note_notice: bool,
// Theme // Theme
pub theme_image: String, pub theme_image: String,
pub theme_text: String, pub theme_text: String,

View File

@@ -11,12 +11,10 @@ async fn get_status() -> impl Responder {
max_views: *config::MAX_VIEWS, max_views: *config::MAX_VIEWS,
max_expiration: *config::MAX_EXPIRATION, max_expiration: *config::MAX_EXPIRATION,
allow_advanced: *config::ALLOW_ADVANCED, allow_advanced: *config::ALLOW_ADVANCED,
allow_files: *config::ALLOW_FILES,
theme_new_note_notice: *config::THEME_NEW_NOTE_NOTICE,
theme_image: config::THEME_IMAGE.to_string(), theme_image: config::THEME_IMAGE.to_string(),
theme_text: config::THEME_TEXT.to_string(), theme_text: config::THEME_TEXT.to_string(),
theme_page_title: config::THEME_PAGE_TITLE.to_string(), theme_page_title: config::THEME_PAGE_TITLE.to_string(),
theme_favicon: config::THEME_FAVICON.to_string(), theme_favicon: config::THEME_FAVICON.to_string()
}); });
} }

View File

@@ -1,44 +1,43 @@
{ {
"version": "2.3.1",
"name": "cryptgeon", "name": "cryptgeon",
"version": "2.6.1",
"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": {
".": "./dist/index.mjs" "node": ">=18"
}, },
"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": "rm -rf dist && tsc && ./scripts/build.js",
"dev": "./scripts/build.js --watch",
"prepublishOnly": "run-s build"
},
"devDependencies": { "devDependencies": {
"@commander-js/extra-typings": "^12.0.1", "@commander-js/extra-typings": "^10.0.3",
"@cryptgeon/shared": "workspace:*", "@cryptgeon/shared": "workspace:*",
"@types/inquirer": "^9.0.7", "@types/inquirer": "^9.0.3",
"@types/mime": "^3.0.4", "@types/mime": "^3.0.1",
"@types/node": "^20.11.24", "@types/node": "^20.1.3",
"commander": "^12.0.0", "commander": "^10.0.1",
"esbuild": "^0.20.1", "esbuild": "^0.17.19",
"inquirer": "^9.2.15", "inquirer": "^9.2.2",
"mime": "^4.0.1", "mime": "^3.0.0",
"occulto": "^2.0.3", "occulto": "^2.0.1",
"pretty-bytes": "^6.1.1", "pkg": "^5.8.1",
"typescript": "^5.3.3" "pretty-bytes": "^6.1.0",
}, "typescript": "^5.0.4"
"engines": {
"node": ">=18"
} }
} }

View File

@@ -3,32 +3,15 @@
import { build, context } from 'esbuild' import { build, context } from 'esbuild'
import pkg from '../package.json' assert { type: 'json' } import pkg from '../package.json' assert { type: 'json' }
const common = { const options = {
entryPoints: ['./src/index.ts'],
bundle: true, bundle: true,
minify: true, minify: true,
platform: 'node', platform: 'node',
outfile: './dist/index.cjs',
define: { VERSION: `"${pkg.version}"` }, define: { VERSION: `"${pkg.version}"` },
} }
const cliOptions = {
...common,
entryPoints: ['./src/cli.ts'],
format: 'cjs',
outfile: './dist/cli.cjs',
}
const indexOptions = {
...common,
entryPoints: ['./src/index.ts'],
outfile: './dist/index.mjs',
format: 'esm',
}
const watch = process.argv.slice(2)[0] === '--watch' const watch = process.argv.slice(2)[0] === '--watch'
if (watch) { if (watch) (await context(options)).watch()
const ctx = await context(cliOptions) else await build(options)
ctx.watch()
} else {
await build(cliOptions)
await build(indexOptions)
}

17
packages/cli/scripts/package.js Executable file
View File

@@ -0,0 +1,17 @@
#!/usr/bin/env node
import { exec } from 'pkg'
const targets = [
'node18-macos-arm64',
'node18-macos-x64',
'node18-linux-arm64',
'node18-linux-x64',
'node18-win-arm64',
'node18-win-x64',
]
for (const target of targets) {
console.log(`🚀 Building ${target}`)
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

@@ -1,58 +1,56 @@
{ {
"common": { "common": {
"note": "Notiz", "note": "Hinweis",
"file": "Datei", "file": "Datei",
"advanced": "Erweiterte Optionen", "advanced": "erweitert",
"create": "Erstellen", "create": "erstellen",
"loading": "Lädt...", "loading": "läd",
"mode": "Modus", "mode": "Modus",
"views": "{n, plural, =0 {Ansichten} =1 {1 Ansicht} other {# Ansichten}}", "views": "{n, plural, =0 {Ansichten} =1 {1 Ansicht} other {# Ansichten}}",
"minutes": "{n, plural, =0 {Minuten} =1 {1 Minute} other {# Minuten}}", "minutes": "{n, plural, =0 {Minuten} =1 {1 Minute} other {# Minuten}}",
"max": "max", "max": "max",
"share_link": "Link teilen", "share_link": "Link teilen",
"copy_clipboard": "In die Zwischenablage kopieren", "copy_clipboard": "in die Zwischenablage kopieren",
"copied_to_clipboard": "In die Zwischenablage kopiert.", "copied_to_clipboard": "in die Zwischenablage kopiert",
"encrypting": "Wird verschlüsselt...", "encrypting": "verschlüsseln",
"decrypting": "Wird entschlüsselt...", "decrypting": "entschlüsselt",
"uploading": "Hochladen", "uploading": "hochladen",
"downloading": "Wird heruntergeladen", "downloading": "wird heruntergeladen",
"qr_code": "QR-Code", "qr_code": "qr-code",
"password": "Passwort" "password": "Passwort"
}, },
"home": { "home": {
"intro": "Erstellen Sie mit einem Klick <i>vollständig verschlüsselte</i>, sichere Notizen oder Dateien und teilen Sie diese über einen Link.", "intro": "Senden Sie ganz einfach <i>vollständig verschlüsselte</i>, sichere Notizen oder Dateien mit einem Klick. Erstellen Sie einfach eine Notiz und teilen Sie den Link.",
"explanation": "Die Notiz verfällt nach {type}.", "explanation": "die Notiz verfällt und wird nach {type} zerstört.",
"new_note": "Neue Notiz", "new_note": "neue Note",
"new_note_notice": "<b>Wichtiger Hinweis zur Verfügbarkeit:</b><br />Es kann nicht garantiert werden, dass diese Notiz gespeichert wird, da diese <b>ausschließlich im Speicher</b> gehalten werden. Ist dieser voll, werden die ältesten Notizen entfernt.<br />(Wahrscheinlich gibt es keine derartigen Probleme, seien Sie nur vorgewarnt).", "new_note_notice": "<b>Verfügbarkeit:</b><br />es ist nicht garantiert, dass die Notiz gespeichert wird, da alles im Speicher gehalten wird. Wenn dieser voll ist, werden die ältesten Notizen entfernt.<br />(Sie werden wahrscheinlich keine Probleme haben, seien Sie nur gewarnt).",
"errors": { "errors": {
"note_to_big": "Notiz konnte nicht erstellt werden, da sie zu groß ist.", "note_to_big": "Notiz konnte nicht erstellt werden. Notiz ist zu groß",
"note_error": "Notiz konnte nicht erstellt werden. Bitte versuchen Sie es erneut.", "note_error": "konnte keine Notiz erstellen. Bitte versuchen Sie es erneut.",
"max": "max: {n}", "max": "max: {n}",
"empty_content": "Notiz ist leer." "empty_content": "Notiz ist leer."
}, },
"messages": { "messages": {
"note_created": "Notiz wurde erstellt." "note_created": "notiz erstellt."
}, },
"advanced": { "advanced": {
"explanation": "Standardmäßig wird für jede Notiz ein generiertes, sicheres Passwort verwendet. Alternativ können Sie ein eigenes Kennwort festlegen, welches nicht im Link enthalten ist.", "explanation": "Standardmäßig wird für jede Notiz ein sicher generiertes Passwort verwendet. Sie können jedoch auch ein eigenes Kennwort wählen, das nicht in dem Link enthalten ist.",
"custom_password": "Benutzerdefiniertes Passwort" "custom_password": "benutzerdefiniertes Passwort"
} }
}, },
"show": { "show": {
"errors": { "errors": {
"not_found": "Notiz konnte nicht gefunden werden oder wurde bereits gelöscht.", "not_found": "wurde nicht gefunden oder wurde bereits gelöscht.",
"decryption_failed": "Notiz konnte nicht entschlüsselt werden. Vermutlich ist das Passwort falsch oder der Link defekt. Die Notiz wurde daher gelöscht.", "decryption_failed": "falsches Passwort. konnte nicht entziffert werden. wahrscheinlich ein defekter Link. Notiz wurde zerstört.",
"unsupported_type": "Nicht unterstützter Notiztyp." "unsupported_type": "nicht unterstützter Notiztyp."
}, },
"explanation": "Klicken Sie auf den Button, um die Notiz anzuzeigen und anschließend zu löschen, falls ein festgelegtes Limit erreicht wurde.", "explanation": "Klicken Sie unten, um die Notiz anzuzeigen und zu löschen, wenn der Zähler sein Limit erreicht hat",
"show_note": "Notiz anzeigen", "show_note": "Notiz anzeigen",
"warning_will_not_see_again": "ACHTUNG! Sie werden anschließend <b>keine</b> Gelegenheit mehr haben, die Notiz erneut anzusehen.", "warning_will_not_see_again": "haben Sie <b>keine</b> Gelegenheit, die Notiz noch einmal zu sehen.",
"download_all": "Alle Dateien herunterladen", "download_all": "alle herunterladen"
"links_found": "Gefundene Links in der Notiz:"
}, },
"file_upload": { "file_upload": {
"selected_files": "Ausgewählte Dateien", "selected_files": "Ausgewählte Dateien",
"no_files_selected": "Keine Dateien ausgewählt", "no_files_selected": "Keine Dateien ausgewählt"
"clear": "Zurücksetzen"
} }
} }

View File

@@ -23,9 +23,9 @@
"intro": "Easily send <i>fully encrypted</i>, secure notes or files with one click. Just create a note and share the link.", "intro": "Easily send <i>fully encrypted</i>, secure notes or files with one click. Just create a note and share the link.",
"explanation": "the note will expire and be destroyed after {type}.", "explanation": "the note will expire and be destroyed after {type}.",
"new_note": "new note", "new_note": "new note",
"new_note_notice": "<b>availability:</b><br />the note is not guaranteed to be stored as everything is kept in ram, if it fills up the oldest notes will be removed.<br />(you probably will be fine, just be warned.)", "new_note_notice": "<b>availability:</b><br />the note is not guaranteed to be stored, as everything is kept in ram. if it fills up, the oldest notes will be removed.<br />(you probably will be fine, but just be warned.)",
"errors": { "errors": {
"note_to_big": "could not create note. note is to big", "note_to_big": "could not create note. note is too big.",
"note_error": "could not create note. please try again.", "note_error": "could not create note. please try again.",
"max": "max: {n}", "max": "max: {n}",
"empty_content": "note is empty." "empty_content": "note is empty."
@@ -34,7 +34,7 @@
"note_created": "note created." "note_created": "note created."
}, },
"advanced": { "advanced": {
"explanation": "By default, a securely generated password is used for each note. You can however also choose your own password, which is not included in the link.", "explanation": "By default, a securely generated password is used for each note. You can, however, also choose your own password, which is not included in the link.",
"custom_password": "custom password" "custom_password": "custom password"
} }
}, },
@@ -44,15 +44,13 @@
"decryption_failed": "wrong password. could not decipher. probably a broken link. note was destroyed.", "decryption_failed": "wrong password. could not decipher. probably a broken link. note was destroyed.",
"unsupported_type": "unsupported note type." "unsupported_type": "unsupported note type."
}, },
"explanation": "click below to show and delete the note if the counter has reached it's limit", "explanation": "click below to show and delete the note if the counter has reached its limit.",
"show_note": "show note", "show_note": "show note",
"warning_will_not_see_again": "you will <b>not</b> get the chance to see the note again.", "warning_will_not_see_again": "you will <b>not</b> get the chance to see the note again.",
"download_all": "download all", "download_all": "download all"
"links_found": "links found inside the note:"
}, },
"file_upload": { "file_upload": {
"selected_files": "Selected Files", "selected_files": "Selected Files",
"no_files_selected": "No Files Selected", "no_files_selected": "No Files Selected"
"clear": "Reset"
} }
} }

View File

@@ -23,7 +23,7 @@
"intro": "Envía fácilmente notas o archivos <i>totalmente encriptados</i> y seguros con un solo clic. Solo tienes que crear una nota y compartir el enlace.", "intro": "Envía fácilmente notas o archivos <i>totalmente encriptados</i> y seguros con un solo clic. Solo tienes que crear una nota y compartir el enlace.",
"explanation": "la nota expirará y se destruirá después de {type}.", "explanation": "la nota expirará y se destruirá después de {type}.",
"new_note": "nueva nota", "new_note": "nueva nota",
"new_note_notice": "<b>disponibilidad:</b><br />no se garantiza que la nota se almacene, ya que todo se guarda en la memoria RAM, si se llena se eliminarán las notas más antiguas.<br />(probablemente estará bien, solo está advertido.)", "new_note_notice": "<b>disponibilidad:</b><br />no se garantiza que la nota se almacene, ya que todo se guarda en la memoria RAM, si se llena se eliminarán las notas más antiguas.<br />(probablemente estará bien, sólo está advertido.)",
"errors": { "errors": {
"note_to_big": "no se pudo crear la nota. la nota es demasiado grande", "note_to_big": "no se pudo crear la nota. la nota es demasiado grande",
"note_error": "No se ha podido crear la nota. Por favor, inténtelo de nuevo.", "note_error": "No se ha podido crear la nota. Por favor, inténtelo de nuevo.",
@@ -34,7 +34,7 @@
"note_created": "nota creada." "note_created": "nota creada."
}, },
"advanced": { "advanced": {
"explanation": "Por defecto, se utiliza una contraseña generada de forma segura para cada nota. No obstante, también puede elegir su propia contraseña, la cual no se incluye en el enlace.", "explanation": "Por defecto, se utiliza una contraseña generada de forma segura para cada nota. No obstante, también puede elegir su propia contraseña, que no se incluye en el enlace.",
"custom_password": "contraseña personalizada" "custom_password": "contraseña personalizada"
} }
}, },
@@ -47,12 +47,10 @@
"explanation": "pulse abajo para mostrar y borrar la nota si el contador ha llegado a su límite", "explanation": "pulse abajo para mostrar y borrar la nota si el contador ha llegado a su límite",
"show_note": "mostrar nota", "show_note": "mostrar nota",
"warning_will_not_see_again": "<b>no</b> tendrás la oportunidad de volver a ver la nota.", "warning_will_not_see_again": "<b>no</b> tendrás la oportunidad de volver a ver la nota.",
"download_all": "descargar todo", "download_all": "descargar todo"
"links_found": "enlaces que se encuentran dentro de la nota:"
}, },
"file_upload": { "file_upload": {
"selected_files": "Archivos seleccionados", "selected_files": "Archivos seleccionados",
"no_files_selected": "No hay archivos seleccionados", "no_files_selected": "No hay archivos seleccionados"
"clear": "Restablecer"
} }
} }

View File

@@ -12,20 +12,20 @@
"share_link": "partager le lien", "share_link": "partager le lien",
"copy_clipboard": "copier dans le presse-papiers", "copy_clipboard": "copier dans le presse-papiers",
"copied_to_clipboard": "copié dans le presse-papiers", "copied_to_clipboard": "copié dans le presse-papiers",
"encrypting": "chiffrer", "encrypting": "cryptage",
"decrypting": "déchiffrer", "decrypting": "déchiffrer",
"uploading": "téléversement", "uploading": "téléchargement",
"downloading": "téléchargement", "downloading": "téléchargement",
"qr_code": "code qr", "qr_code": "code qr",
"password": "mot de passe" "password": "mot de passe"
}, },
"home": { "home": {
"intro": "Envoyez facilement des notes ou des fichiers <i>entièrement chiffrés</i> et sécurisés en un seul clic. Il suffit de créer une note et de partager le lien.", "intro": "Envoyez facilement des notes ou des fichiers <i>entièrement cryptés</i> et sécurisés en un seul clic. Il suffit de créer une note et de partager le lien.",
"explanation": "la note expirera et sera détruite après {type}.", "explanation": "la note expirera et sera détruite après {type}.",
"new_note": "nouvelle note", "new_note": "nouvelle note",
"new_note_notice": "<b>disponibilité :</b><br />la note n'est pas garantie d'être stockée car tout est conservé dans la mémoire vive; si elle se remplit, les notes les plus anciennes seront supprimées.<br />(tout ira probablement bien, soyez juste averti.)", "new_note_notice": "<b>disponibilité :</b><br />la note n'est pas garantie d'être stockée car tout est conservé dans la mémoire vive, si elle se remplit les notes les plus anciennes seront supprimées.<br />(vous serez probablement bien, soyez juste averti.)",
"errors": { "errors": {
"note_to_big": "Impossible de créer une note. La note est trop grande.", "note_to_big": "Impossible de créer une note. La note est trop grande",
"note_error": "n'a pas pu créer de note. Veuillez réessayer.", "note_error": "n'a pas pu créer de note. Veuillez réessayer.",
"max": "max: {n}", "max": "max: {n}",
"empty_content": "La note est vide." "empty_content": "La note est vide."
@@ -47,12 +47,10 @@
"explanation": "Cliquez ci-dessous pour afficher et supprimer la note si le compteur a atteint sa limite.", "explanation": "Cliquez ci-dessous pour afficher et supprimer la note si le compteur a atteint sa limite.",
"show_note": "note de présentation", "show_note": "note de présentation",
"warning_will_not_see_again": "vous <b>n'aurez pas</b> la chance de revoir la note.", "warning_will_not_see_again": "vous <b>n'aurez pas</b> la chance de revoir la note.",
"download_all": "télécharger tout", "download_all": "télécharger tout"
"links_found": "liens trouvés à lintérieur de la note :"
}, },
"file_upload": { "file_upload": {
"selected_files": "Fichiers sélectionnés", "selected_files": "Fichiers sélectionnés",
"no_files_selected": "Aucun fichier sélectionné", "no_files_selected": "Aucun fichier sélectionné"
"clear": "Réinitialiser"
} }
} }

View File

@@ -47,12 +47,10 @@
"explanation": "clicca sotto per mostrare e cancellare la nota se il contatore ha raggiunto il suo limite", "explanation": "clicca sotto per mostrare e cancellare la nota se il contatore ha raggiunto il suo limite",
"show_note": "mostra la nota", "show_note": "mostra la nota",
"warning_will_not_see_again": "<b>non</b> avrete la possibilità di rivedere la nota.", "warning_will_not_see_again": "<b>non</b> avrete la possibilità di rivedere la nota.",
"download_all": "scarica tutti", "download_all": "scarica tutti"
"links_found": "link presenti all'interno della nota:"
}, },
"file_upload": { "file_upload": {
"selected_files": "File selezionati", "selected_files": "File selezionati",
"no_files_selected": "Nessun file selezionato", "no_files_selected": "Nessun file selezionato"
"clear": "Reset"
} }
} }

View File

@@ -47,12 +47,10 @@
"explanation": "カウンターが上限に達した場合、ノートの表示と削除を行うには、以下をクリックします。", "explanation": "カウンターが上限に達した場合、ノートの表示と削除を行うには、以下をクリックします。",
"show_note": "メモを表示", "show_note": "メモを表示",
"warning_will_not_see_again": "あなた <b>できません</b> このノートをもう一度見る", "warning_will_not_see_again": "あなた <b>できません</b> このノートをもう一度見る",
"download_all": "すべてダウンロード", "download_all": "すべてダウンロード"
"links_found": "メモ内にあるリンク:"
}, },
"file_upload": { "file_upload": {
"selected_files": "選択したファイル", "selected_files": "選択したファイル",
"no_files_selected": "ファイルが選択されていません", "no_files_selected": "ファイルが選択されていません"
"clear": "リセット"
} }
} }

View File

@@ -1,58 +0,0 @@
{
"common": {
"note": "notatka",
"file": "plik",
"advanced": "zaawansowane",
"create": "utwórz",
"loading": "ładowanie",
"mode": "tryb",
"views": "{n, plural, =0 {wyświetleń} =1 {1 wyświetlenie} other {# wyświetleń}}",
"minutes": "{n, plural, =0 {minut} =1 {1 minuta} other {# minuty}}",
"max": "maks.",
"share_link": "link udostępniania",
"copy_clipboard": "kopiuj do schowka",
"copied_to_clipboard": "skopiowano do schowka",
"encrypting": "szyfrowanie",
"decrypting": "odszyfrowywanie",
"uploading": "wysyłanie",
"downloading": "pobieranie",
"qr_code": "kod QR",
"password": "hasło"
},
"home": {
"intro": "Łatwo wysyłaj <i>w pełni zaszyfrowane</i>, bezpieczne notatki lub pliki jednym kliknięciem. Po prostu utwórz notatkę i udostępnij link.",
"explanation": "notatka wygaśnie i zostanie zniszczona po {type}.",
"new_note": "nowa notatka",
"new_note_notice": "<b>dostępność:</b><br />nie ma gwarancji, że notatka będzie przechowywana, ponieważ wszystko jest przechowywane w pamięci RAM, jeśli się zapełni, najstarsze notatki zostaną usunięte.<br />(prawdopodobnie nic się nie stanie, ale warto ostrzec.)",
"errors": {
"note_to_big": "nie można utworzyć notatki. notatka jest za duża",
"note_error": "nie można utworzyć notatki. spróbuj ponownie.",
"max": "maks .: {n}",
"empty_content": "notatka jest pusta."
},
"messages": {
"note_created": "notatka utworzona."
},
"advanced": {
"explanation": "Domyślnie dla każdej notatki używane jest bezpiecznie wygenerowane hasło. Możesz jednak wybrać własne hasło, które nie jest uwzględnione w linku.",
"custom_password": "własne hasło"
}
},
"show": {
"errors": {
"not_found": "notatka nie została znaleziona lub została już usunięta.",
"decryption_failed": "błędne hasło. nie można odszyfrować. prawdopodobnie uszkodzony link. notatka została zniszczona.",
"unsupported_type": "nieobsługiwany typ notatki."
},
"explanation": "kliknij poniżej, aby wyświetlić i usunąć notatkę, jeśli licznik osiągnie swój limit",
"show_note": "pokaż notatkę",
"warning_will_not_see_again": "<b>nie będziesz mieć</b> możliwości ponownego zobaczenia notatki.",
"download_all": "pobierz wszystko",
"links_found": "linki znalezione w notatce:"
},
"file_upload": {
"selected_files": "Wybrane pliki",
"no_files_selected": "Nie wybrano plików",
"clear": "Wyczyść"
}
}

View File

@@ -1,58 +1,56 @@
{ {
"common": { "common": {
"note": "заметка", "note": "заметка",
"file": "файл", "file": "файл",
"advanced": "расширенные", "advanced": "расширенные",
"create": "создать", "create": "создать",
"loading": "загрузка", "loading": "загрузка",
"mode": "режим", "mode": "режим",
"views": "{n, plural, =0 {просмотры} =1 {1 просмотр} other {# просмотры}}", "views": "{n, plural, =0 {просмотры} =1 {1 просмотр} other {# просмотры}}",
"minutes": "{n, plural, =0 {минут} =1 {1 минута} other {# минуты}}", "minutes": "{n, plural, =0 {минут} =1 {1 минута} other {# минуты}}",
"max": "макс", "max": "макс",
"share_link": "поделиться ссылкой", "share_link": "поделиться ссылкой",
"copy_clipboard": "скопировать в буфер обмена", "copy_clipboard": "скопировать в буфер обмена",
"copied_to_clipboard": "скопировано в буфер обмена", "copied_to_clipboard": "скопировано в буфер обмена",
"encrypting": "шифрование", "encrypting": "шифрование",
"decrypting": "расшифровка", "decrypting": "расшифровка",
"uploading": "загрузка", "uploading": "загрузка",
"downloading": "скачивание", "downloading": "скачивание",
"qr_code": "qr код", "qr_code": "qr код",
"password": "пароль" "password": "пароль"
}, },
"home": { "home": {
"intro": "Легко отправляйте <i>полностью зашифрованные</i> защищенные заметки или файлы одним щелчком мыши. Просто создайте заметку и поделитесь ссылкой.", "intro": "Легко отправляйте <i>полностью зашифрованные</i> защищенные заметки или файлы одним щелчком мыши. Просто создайте заметку и поделитесь ссылкой.",
"explanation": "заметка истечет и будет уничтожена после {type}.", "explanation": "заметка истечет и будет уничтожена после {type}.",
"new_note": "новая заметка", "new_note": "новая заметка",
"new_note_notice": "<b>доступность:</b><br />сохранение заметки не гарантируется, поскольку все хранится в оперативной памяти; если она заполнится, самые старые заметки будут удалены.<br />( вероятно, все будет в порядке, просто будьте осторожны.)", "new_note_notice": "<b>предупреждение:</b><br />не гарантируется, что заметка будет сохранена, так как все хранится в оперативной памяти, если она заполнится, самые старые заметки будут удалены..<br />(вероятно всё будет хорошо, просто будьте осторожны.)",
"errors": { "errors": {
"note_to_big": "нельзя создать новую заметку. заметка слишком большая", "note_to_big": "нельзя создать новую заметку. заметка слишком большая",
"note_error": "нельзя создать новую заметку. пожалйста попробуйте позднее.", "note_error": "нельзя создать новую заметку. пожалуйста попробуйте позднее.",
"max": "макс: {n}", "max": "макс: {n}",
"empty_content": "пустая заметка." "empty_content": "пустая заметка."
}, },
"messages": { "messages": {
"note_created": "заметка создана." "note_created": "заметка создана."
}, },
"advanced": { "advanced": {
"explanation": "По умолчанию для каждой заметки используется безопасно сгенерированный пароль. Однако вы также можете выбрать свой собственный пароль, который не включен в ссылку.", "explanation": "По умолчанию для каждой заметки используется безопасно сгенерированный пароль. Однако вы также можете выбрать свой собственный пароль, который не включен в ссылку.",
"custom_password": "пользовательский пароль" "custom_password": "пользовательский пароль"
} }
}, },
"show": { "show": {
"errors": { "errors": {
"not_found": "заметка не найдена или была удалена.", "not_found": "заметка не найдена или была удалена.",
"decryption_failed": "неправильный пароль. не смог расшифровать. возможно ссылка битая. записка уничтожена.", "decryption_failed": "неправильный пароль. не смог расшифровать. возможно ссылка битая. записка уничтожена.",
"unsupported_type": "неподдерживаемый тип заметки." "unsupported_type": "неподдерживаемый тип заметки."
}, },
"explanation": "щелкните ниже, чтобы показать и удалить примечание, если счетчик достиг предела", "explanation": "щелкните ниже, чтобы показать и удалить заметку, если счетчик достиг предела",
"show_note": "показать заметку", "show_note": "показать заметку",
"warning_will_not_see_again": "вы <b>не сможете</b> больше просмотреть заметку.", "warning_will_not_see_again": "вы <b>не сможете</b> больше просмотреть заметку.",
"download_all": "скачать всё", "download_all": "скачать всё"
"links_found": "ссылки внутри заметки:" },
}, "file_upload": {
"file_upload": { "selected_files": "Выбранные файлы",
"selected_files": "Выбранные файлы", "no_files_selected": "Файлы не выбраны"
"no_files_selected": "Файлы не выбраны", }
"clear": "Сброс" }
}
}

View File

@@ -47,12 +47,10 @@
"explanation": "点击下方按钮即可查看密信,阅后即焚。", "explanation": "点击下方按钮即可查看密信,阅后即焚。",
"show_note": "查看密信", "show_note": "查看密信",
"warning_will_not_see_again": "你将<b>无法</b>再次查看该密信,请尽快复制到粘贴板。", "warning_will_not_see_again": "你将<b>无法</b>再次查看该密信,请尽快复制到粘贴板。",
"download_all": "下载全部", "download_all": "下载全部"
"links_found": "注释中找到的链接:"
}, },
"file_upload": { "file_upload": {
"selected_files": "已选中的文件", "selected_files": "已选中的文件",
"no_files_selected": "没有文件被选中", "no_files_selected": "没有文件被选中"
"clear": "重置"
} }
} }

View File

@@ -13,28 +13,29 @@
}, },
"type": "module", "type": "module",
"devDependencies": { "devDependencies": {
"@lokalise/node-api": "^12.1.0", "@lokalise/node-api": "^9.8.0",
"@sveltejs/adapter-static": "^3.0.1", "@sveltejs/adapter-static": "^2.0.2",
"@sveltejs/kit": "^2.5.2", "@sveltejs/kit": "^1.16.3",
"@sveltejs/vite-plugin-svelte": "^3.0.2", "@types/dompurify": "^3.0.2",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.5",
"@zerodevx/svelte-toast": "^0.9.5", "@zerodevx/svelte-toast": "^0.9.3",
"adm-zip": "^0.5.10", "adm-zip": "^0.5.10",
"dotenv": "^16.4.5", "dotenv": "^16.0.3",
"svelte": "^4.2.12", "svelte": "^3.59.1",
"svelte-check": "^3.6.6", "svelte-check": "^3.3.2",
"svelte-intl-precompile": "^0.12.3", "svelte-intl-precompile": "^0.12.1",
"tslib": "^2.6.2", "tslib": "^2.5.0",
"typescript": "^5.3.3", "typescript": "^5.0.4",
"vite": "^5.1.7" "vite": "^4.3.9"
}, },
"dependencies": { "dependencies": {
"@cryptgeon/shared": "workspace:*", "@cryptgeon/shared": "workspace:*",
"@fontsource/fira-mono": "^5.0.8", "@fontsource/fira-mono": "^4.5.10",
"copy-to-clipboard": "^3.3.3", "copy-to-clipboard": "^3.3.3",
"dompurify": "^3.0.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.0",
"qrious": "^4.0.2" "qrious": "^4.0.2"
} }
} }

View File

@@ -46,7 +46,7 @@
</div> </div>
{/each} {/each}
<div class="spacer" /> <div class="spacer" />
<Button on:click={clear}>{$t('file_upload.clear')}</Button> <Button on:click={clear}>Clear</Button>
</div> </div>
{:else} {:else}
<div> <div>

View File

@@ -7,7 +7,7 @@
<script lang="ts"> <script lang="ts">
import { t } from 'svelte-intl-precompile' import { t } from 'svelte-intl-precompile'
import { status } from '$lib/stores/status'
import Button from '$lib/ui/Button.svelte' import Button from '$lib/ui/Button.svelte'
import TextInput from '$lib/ui/TextInput.svelte' import TextInput from '$lib/ui/TextInput.svelte'
import Canvas from './Canvas.svelte' import Canvas from './Canvas.svelte'
@@ -35,11 +35,9 @@
<Canvas value={url} /> <Canvas value={url} />
</div> </div>
{#if $status?.theme_new_note_notice} <p>
<p> {@html $t('home.new_note_notice')}
{@html $t('home.new_note_notice')} </p>
</p>
{/if}
<br /> <br />
<Button on:click={reset}>{$t('home.new_note')}</Button> <Button on:click={reset}>{$t('home.new_note')}</Button>

View File

@@ -3,8 +3,8 @@
</script> </script>
<script lang="ts"> <script lang="ts">
import pkg from 'file-saver' import DOMPurify from 'dompurify'
const { saveAs } = pkg import { saveAs } from 'file-saver'
import prettyBytes from 'pretty-bytes' import prettyBytes from 'pretty-bytes'
import { t } from 'svelte-intl-precompile' import { t } from 'svelte-intl-precompile'
@@ -34,29 +34,22 @@
saveAs(f) saveAs(f)
} }
$: links = typeof note.contents === 'string' ? note.contents.match(RE_URL) : [] function contentWithLinks(content: string): string {
const replaced = content.replace(
RE_URL,
(url) => `<a href="${url}" rel="noreferrer">${url}</a>`
)
return DOMPurify.sanitize(replaced, { USE_PROFILES: { html: true } })
}
</script> </script>
<p class="error-text">{@html $t('show.warning_will_not_see_again')}</p> <p class="error-text">{@html $t('show.warning_will_not_see_again')}</p>
<div data-testid="result"> <div data-testid="result">
{#if note.meta.type === 'text'} {#if note.meta.type === 'text'}
<div class="note"> <div class="note">
{note.contents} {@html contentWithLinks(note.contents)}
</div> </div>
<Button on:click={() => copy(note.contents)}>{$t('common.copy_clipboard')}</Button> <Button on:click={() => copy(note.contents)}>{$t('common.copy_clipboard')}</Button>
{#if links && links.length}
<div class="links">
{$t('show.links_found')}
<ul>
{#each links as link}
<li>
<a href={link} target="_blank" rel="noopener noreferrer">{link}</a>
</li>
{/each}
</ul>
</div>
{/if}
{:else} {:else}
{#each files as file} {#each files as file}
<div class="note file"> <div class="note file">
@@ -99,20 +92,4 @@
.note.file small { .note.file small {
padding-left: 1rem; padding-left: 1rem;
} }
.links {
margin-top: 2rem;
}
.links ul {
margin: 0;
padding: 0;
margin-top: 0.5rem;
padding-left: 1rem;
list-style: square;
}
.links ul li {
margin-bottom: 0.5rem;
word-wrap: break-word;
}
</style> </style>

View File

@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { AES, Hex } from 'occulto' import { AES, Hex, Bytes } from 'occulto'
import { t } from 'svelte-intl-precompile' import { t } from 'svelte-intl-precompile'
import { blur } from 'svelte/transition' import { blur } from 'svelte/transition'
@@ -14,7 +14,7 @@
import Switch from '$lib/ui/Switch.svelte' import Switch from '$lib/ui/Switch.svelte'
import TextArea from '$lib/ui/TextArea.svelte' import TextArea from '$lib/ui/TextArea.svelte'
import type { FileDTO, Note } from '@cryptgeon/shared' import type { FileDTO, Note } from '@cryptgeon/shared'
import { Adapters, PayloadToLargeError, create } from '@cryptgeon/shared' import { Adapters, create, PayloadToLargeError } from '@cryptgeon/shared'
let note: Note = { let note: Note = {
contents: '', contents: '',
@@ -118,14 +118,12 @@
{/if} {/if}
<div class="bottom"> <div class="bottom">
{#if $status?.allow_files} <Switch
<Switch data-testid="switch-file"
data-testid="switch-file" class="file"
class="file" label={$t('common.file')}
label={$t('common.file')} bind:value={isFile}
bind:value={isFile} />
/>
{/if}
{#if $status?.allow_advanced} {#if $status?.allow_advanced}
<Switch <Switch
data-testid="switch-advanced" data-testid="switch-advanced"
@@ -151,7 +149,7 @@
</p> </p>
{#if advanced} {#if advanced}
<div transition:blur|global={{ duration: 250 }}> <div transition:blur={{ duration: 250 }}>
<hr /> <hr />
<AdvancedParameters bind:note bind:timeExpiration bind:customPassword /> <AdvancedParameters bind:note bind:timeExpiration bind:customPassword />
</div> </div>

View File

@@ -1,13 +1,9 @@
<script lang="ts"> <script lang="ts">
import { status } from '$lib/stores/status' import { status } from '$lib/stores/status'
function reset() {
window.location.reload()
}
</script> </script>
<header> <header>
<a on:click={reset} href="/"> <a href="/">
{#if $status?.theme_image} {#if $status?.theme_image}
<img alt="logo" src={$status.theme_image} /> <img alt="logo" src={$status.theme_image} />
{:else} {:else}

View File

@@ -40,8 +40,8 @@
<br /> <br />
you are welcomed to check & audit the you are welcomed to check & audit the
<a href="https://github.com/cupcakearmy/cryptgeon" target="_blank" rel="noopener noreferrer"> <a href="https://github.com/cupcakearmy/cryptgeon" target="_blank" rel="noopener noreferrer">
source code</a source code
>. </a>.
</span> </span>
</AboutParagraph> </AboutParagraph>

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.0.4"
}, },
"dependencies": { "dependencies": {
"occulto": "^2.0.3" "occulto": "^2.0.1"
} }
} }

2640
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',