Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ npx strokedb
| `--name <name>` | Name for the connection (default: the folder name) |
| `--port <port>` | Port for the local bridge (default: any free port) |
| `--no-open` | Print the studio link instead of opening a browser |
| `--share` | (Labs) Also print a link that opens this studio on any device. Read-only. Needs Node 22+ |
| `--write` | With `--share`: let the link edit rows and run any SQL |

## How the web studio is kept private

Expand All @@ -42,3 +44,14 @@ Your queries go from your browser to your machine. They never pass through strok
Safari blocks secure pages from calling `127.0.0.1`; use Chrome, Edge, Firefox or the desktop app.

SQLite in the web studio needs Node 22.5 or newer.

## Sharing (Labs)

`npx strokedb --share` prints a second link that opens the studio on any device, for anyone you send it to, while the command runs.

- It goes through a relay at stroke.click: this command holds a connection open to it, and the studio page sends its calls there. Nothing has to be reachable from the internet.
- End-to-end encrypted. Every call is AES-256-GCM with a key that exists only in the link's `#fragment`; the relay passes ciphertext along and can't read it.
- Read-only unless you add `--write`: browsing, and SQL that only reads (SELECT, WITH, EXPLAIN, SHOW). The shared side has its own read-only connection (Postgres `BEGIN READ ONLY`, MySQL `START TRANSACTION READ ONLY`, SQLite opened read-only), so a statement can't talk its way into a write.
- Stop it with Ctrl+C; the link stops working until you share again (a new run makes a new link).

The desktop app can share an open connection the same way: turn on Settings → Labs → Share as a web studio, then pick **Share as web studio** in the command palette.
18 changes: 15 additions & 3 deletions cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "strokedb",
"version": "0.2.0",
"version": "0.3.0",
"description": "Open your project's database in Stroke: the desktop app if it's installed, otherwise the web studio at stroke.click/studio",
"license": "SEE LICENSE IN LICENSE",
"homepage": "https://stroke.click/studio",
Expand All @@ -9,12 +9,24 @@
"url": "https://github.com/stroke-app/stroke",
"directory": "cli"
},
"keywords": ["database", "studio", "postgres", "mysql", "sqlite", "gui", "stroke"],
"keywords": [
"database",
"studio",
"postgres",
"mysql",
"sqlite",
"gui",
"stroke"
],
"type": "module",
"bin": {
"strokedb": "bin/strokedb.js"
},
"files": ["bin", "src", "README.md"],
"files": [
"bin",
"src",
"README.md"
],
"engines": {
"node": ">=20.19"
},
Expand Down
96 changes: 69 additions & 27 deletions cli/src/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import crypto from 'node:crypto'

export const STUDIO_ORIGIN = 'https://stroke.click'
/** Bumped with the package; the page reads `features` to know what it may offer. */
export const BRIDGE_VERSION = '0.2.0'
export const BRIDGE_VERSION = '0.3.0'
export const FEATURES = ['structure', 'where', 'edit', 'rowCounts']
const MAX_BODY = 1 << 20

Expand All @@ -38,32 +38,7 @@ export async function startBridge({ engine, name, origins = [STUDIO_ORIGIN], por
return b.length === want.length && crypto.timingSafeEqual(b, want)
}

/** @type {Record<string, (body: any) => Promise<unknown>>} */
const routes = {
'/info': async () => ({ ...(await engine.info()), name, bridge: BRIDGE_VERSION, features: FEATURES }),
'/tables': () => engine.tables(),
'/columns': (b) => engine.columns(str(b.schema), str(b.table)),
'/structure': (b) => engine.structure(str(b.schema), str(b.table)),
'/rows': (b) => engine.rows({
schema: str(b.schema),
table: str(b.table),
limit: Number(b.limit) || 100,
offset: Number(b.offset) || 0,
sort: b.sort ?? null,
where: typeof b.where === 'string' ? b.where : '',
}),
'/update': (b) => engine.update({ schema: str(b.schema), table: str(b.table), key: obj(b.key), set: obj(b.set) }),
'/insert': (b) => engine.insert({ schema: str(b.schema), table: str(b.table), values: obj(b.values) }),
'/delete': (b) => {
if (!Array.isArray(b.keys) || !b.keys.length) throw new Error('Expected keys')
return engine.remove({ schema: str(b.schema), table: str(b.table), keys: b.keys.map(obj) })
},
'/query': async (b) => {
const t = performance.now()
const r = await engine.query(str(b.sql))
return { ...r, durationMs: Math.round(performance.now() - t) }
},
}
const routes = makeRoutes({ engine, name })

/** @type {number} */
let boundPort = 0
Expand Down Expand Up @@ -117,6 +92,73 @@ export async function startBridge({ engine, name, origins = [STUDIO_ORIGIN], por
}
}

/**
* What the studio can call, by path. The local bridge and the share relay
* both answer from this. A shared studio that isn't allowed to write gets no
* edit routes, and its SQL console takes reading statements only (the engine
* it is given runs those read-only as well).
* @param {{ engine: import('./engines.js').Engine, name: string, shared?: boolean, write?: boolean }} o
* @returns {Record<string, (body: any) => Promise<unknown>>}
*/
export function makeRoutes({ engine, name, shared = false, write = true }) {
/** @type {Record<string, (body: any) => Promise<unknown>>} */
const routes = {
'/info': async () => ({
...(await engine.info()),
name,
bridge: BRIDGE_VERSION,
features: write ? FEATURES : [...FEATURES.filter((f) => f !== 'edit'), 'readonly'],
...(shared ? { shared: true, readonly: !write } : {}),
}),
'/tables': () => engine.tables(),
'/columns': (b) => engine.columns(str(b.schema), str(b.table)),
'/structure': (b) => engine.structure(str(b.schema), str(b.table)),
'/rows': (b) => engine.rows({
schema: str(b.schema),
table: str(b.table),
limit: Number(b.limit) || 100,
offset: Number(b.offset) || 0,
sort: b.sort ?? null,
where: typeof b.where === 'string' ? b.where : '',
}),
'/update': (b) => engine.update({ schema: str(b.schema), table: str(b.table), key: obj(b.key), set: obj(b.set) }),
'/insert': (b) => engine.insert({ schema: str(b.schema), table: str(b.table), values: obj(b.values) }),
'/delete': (b) => {
if (!Array.isArray(b.keys) || !b.keys.length) throw new Error('Expected keys')
return engine.remove({ schema: str(b.schema), table: str(b.table), keys: b.keys.map(obj) })
},
'/query': async (b) => {
const t = performance.now()
const r = await engine.query(str(b.sql))
return { ...r, durationMs: Math.round(performance.now() - t) }
},
}

if (!write) {
delete routes['/update']
delete routes['/insert']
delete routes['/delete']
const query = routes['/query']
routes['/query'] = async (b) => {
if (!isReadingSql(str(b.sql))) throw new Error('This shared studio is read-only: run SELECT, WITH, EXPLAIN or SHOW.')
return query(b)
}
}
return routes
}

/**
* A statement that only reads. The engine runs it read-only anyway; this
* turns away COPY, CALL, DO, ATTACH and friends before they reach it.
* @param {string} sql
*/
export function isReadingSql(sql) {
const text = sql.replace(/^\s*(?:(?:--[^\n]*\n)|(?:\/\*[\s\S]*?\*\/)|\s)*/, '')
const word = (text.match(/^[a-z]+/i)?.[0] ?? '').toLowerCase()
if (word === 'pragma') return !text.includes('=')
return ['select', 'with', 'explain', 'show', 'values', 'table', 'describe', 'desc'].includes(word)
}

/** @param {unknown} v @returns {Record<string, unknown>} */
function obj(v) {
if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('Expected an object')
Expand Down
41 changes: 39 additions & 2 deletions cli/src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { parseArgs } from 'node:util'
import { findConnection, engineOf, redact, URL_KEYS } from './find.js'
import { installedScheme, appLink, openUrl } from './app.js'
import { openEngine } from './engines.js'
import { startBridge, studioUrl, STUDIO_ORIGIN } from './bridge.js'
import { startBridge, studioUrl, makeRoutes, STUDIO_ORIGIN } from './bridge.js'
import { newShare, shareUrl, startRelayHost } from './relay.js'

const HELP = `strokedb - open your project's database in Stroke

Expand All @@ -21,6 +22,11 @@ Options
--name <name> Name for the connection (default: this folder's name)
--port <port> Port for the local bridge (default: any free port)
--no-open Print the studio link instead of opening a browser
--share (Labs) Also print a link that opens this studio on any
device, through stroke.click's relay. Read-only: browse
and run SELECTs. End-to-end encrypted; the key is only in
the link. Needs Node 22+.
--write With --share: let the link edit rows and run any SQL
-h, --help Show this help
-v, --version Show the version

Expand All @@ -38,6 +44,8 @@ export async function main(argv) {
name: { type: 'string' },
port: { type: 'string' },
'no-open': { type: 'boolean' },
share: { type: 'boolean' },
write: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
version: { type: 'boolean', short: 'v' },
},
Expand All @@ -57,7 +65,12 @@ export async function main(argv) {
const name = values.name ?? path.basename(cwd)
console.log(`Database: ${redact(found.uri)} (from ${found.source})`)

if (!values.web) {
if (values.write && !values.share) {
console.error('--write goes with --share.')
return 1
}
// Sharing keeps this process running, so it uses the web studio here too.
if (!values.web && !values.share) {
const scheme = installedScheme()
if (scheme) {
const ok = await openUrl(appLink(scheme, found.uri, name))
Expand Down Expand Up @@ -97,11 +110,35 @@ export async function main(argv) {
const opened = !values['no-open'] ? await openUrl(link) : false
console.log(`\n${opened ? 'Opened' : 'Open'} the studio${opened ? '' : ' at'}:\n ${link}\n\nThe link is the key to this session; don't share it. Press Ctrl+C to stop.`)

/** @type {{ close(): void } | null} */
let relay = null
/** @type {import('./engines.js').Engine | null} */
let sharedDb = null
if (values.share) {
try {
// Its own connection, read-only unless --write: the engine itself
// refuses writes, not just the routes.
sharedDb = values.write ? db : await openEngine(engine, found.uri, { readOnly: true })
const share = newShare()
relay = await startRelayHost({
routes: makeRoutes({ engine: sharedDb, name, shared: true, write: !!values.write }),
...share,
base: new URL(studio).origin,
onStatus: (status, detail) => console.log(status === 'online' ? ' Sharing: online' : ` Sharing: ${detail ?? 'offline'}`),
})
console.log(`\nShare link (Labs, ${values.write ? 'can edit' : 'read-only'}):\n ${shareUrl({ studio, ...share })}\n\nAnyone with this link can ${values.write ? 'read and change' : 'read'} this database while this runs. It's\nend-to-end encrypted: the key is only in the link, stroke.click sees ciphertext.`)
} catch (e) {
console.error(`Could not start sharing: ${e instanceof Error ? e.message : e}`)
}
}

await new Promise((resolve) => {
const stop = () => resolve(undefined)
process.once('SIGINT', stop)
process.once('SIGTERM', stop)
})
relay?.close()
if (sharedDb && sharedDb !== db) await sharedDb.close().catch(() => {})
await bridge.close()
await db.close().catch(() => {})
console.log('\nStopped.')
Expand Down
Loading
Loading