From a72c5539c0e1e64179eef5aad08818babe840b1c Mon Sep 17 00:00:00 2001 From: broisnees Date: Tue, 17 Nov 2026 10:40:13 +0000 Subject: [PATCH] Share a database as a web studio (Labs): strokedb --share and the app's Share as web studio --- cli/README.md | 13 + cli/package.json | 18 +- cli/src/bridge.js | 96 +++++-- cli/src/cli.js | 41 ++- cli/src/engines.js | 93 +++++-- cli/src/relay.js | 140 +++++++++++ cli/test/cli.test.js | 47 ++++ src-tauri/src/commands.rs | 18 ++ src-tauri/src/lib.rs | 1 + src/lib/components/CommandPalette.svelte | 3 + src/lib/components/SettingsDialog.svelte | 11 + src/lib/components/StudioShareDialog.svelte | 148 +++++++++++ src/lib/components/StudioShell.svelte | 69 ++++++ src/lib/stores/settings.js | 6 +- src/lib/studio-share.js | 262 ++++++++++++++++++++ 15 files changed, 908 insertions(+), 58 deletions(-) create mode 100644 cli/src/relay.js create mode 100644 src/lib/components/StudioShareDialog.svelte create mode 100644 src/lib/studio-share.js diff --git a/cli/README.md b/cli/README.md index 0bf81f43..08ab24eb 100644 --- a/cli/README.md +++ b/cli/README.md @@ -27,6 +27,8 @@ npx strokedb | `--name ` | Name for the connection (default: the folder name) | | `--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 @@ -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. diff --git a/cli/package.json b/cli/package.json index 08dcd832..1b38fbb8 100644 --- a/cli/package.json +++ b/cli/package.json @@ -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", @@ -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" }, diff --git a/cli/src/bridge.js b/cli/src/bridge.js index 04ae8bd4..8a572751 100644 --- a/cli/src/bridge.js +++ b/cli/src/bridge.js @@ -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 @@ -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 Promise>} */ - 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 @@ -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 Promise>} + */ +export function makeRoutes({ engine, name, shared = false, write = true }) { + /** @type {Record Promise>} */ + 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} */ function obj(v) { if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('Expected an object') diff --git a/cli/src/cli.js b/cli/src/cli.js index 3a72e2f0..c5c546f9 100644 --- a/cli/src/cli.js +++ b/cli/src/cli.js @@ -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 @@ -21,6 +22,11 @@ Options --name Name for the connection (default: this folder's name) --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 @@ -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' }, }, @@ -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)) @@ -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.') diff --git a/cli/src/engines.js b/cli/src/engines.js index 815a3fa0..e1b40cdc 100644 --- a/cli/src/engines.js +++ b/cli/src/engines.js @@ -128,12 +128,31 @@ function checkOne(n, step) { * @param {string} uri * @returns {Promise} */ -export async function openPostgres(uri) { +export async function openPostgres(uri, { readOnly = false } = {}) { const { default: pg } = await import('pg') // Dates and timestamps as text, exactly as stored: no timezone shifts. for (const oid of [1082, 1114, 1184, 1083, 1266]) pg.types.setTypeParser(oid, (v) => v) const pool = new pg.Pool({ connectionString: uri, max: 4, connectionTimeoutMillis: 15_000 }) await (await pool.connect()).release() + /** + * Every query this engine runs. Read-only (a shared studio): each statement + * runs alone, extended protocol (one statement, so no `COMMIT; DELETE`), in + * its own `BEGIN READ ONLY` that is always rolled back, so even a SET it + * makes is undone. + * @param {any} cfg @param {unknown[]} [values] + */ + const pq = async (cfg, values) => { + if (!readOnly) return pool.query(cfg, values) + const c = await pool.connect() + try { + await c.query('BEGIN READ ONLY') + const q = typeof cfg === 'string' ? { text: cfg, values } : { ...cfg, values: cfg.values ?? values } + return await c.query({ ...q, queryMode: 'extended' }) + } finally { + await c.query('ROLLBACK').catch(() => {}) + c.release() + } + } const sql = dialect({ q: dq, ph: (i) => `$${i}`, @@ -143,7 +162,7 @@ export async function openPostgres(uri) { /** @param {string} text @param {unknown[]} [values] */ const arr = async (text, values) => { - const r = await pool.query({ text, values, rowMode: 'array' }) + const r = await pq({ text, values, rowMode: 'array' }) const last = Array.isArray(r) ? r[r.length - 1] : r return { columns: (last.fields ?? []).map((/** @type {{ name: string }} */ f) => f.name), @@ -154,6 +173,7 @@ export async function openPostgres(uri) { } /** @param {Step[]} steps */ const tx = async (steps) => { + if (readOnly) throw new Error(READ_ONLY) const c = await pool.connect() let total = 0 try { @@ -175,7 +195,7 @@ export async function openPostgres(uri) { /** @param {string} schema @param {string} table */ const columns = async (schema, table) => { - const r = await pool.query( + const r = await pq( `select a.attname as name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, coalesce(a.attnum = any(i.indkey), false) as "primaryKey", pg_get_expr(d.adbin, d.adrelid) as default @@ -194,12 +214,12 @@ export async function openPostgres(uri) { return { engine: 'postgres', async info() { - const r = await pool.query('select current_database() as db, version() as v') + const r = await pq('select current_database() as db, version() as v') const u = new URL(uri.replace(/^[a-z0-9+.-]+:/i, 'http:')) return { engine: 'postgres', database: r.rows[0].db, host: u.hostname, version: String(r.rows[0].v).split(' on ')[0] } }, async tables() { - const r = await pool.query(` + const r = await pq(` select n.nspname as schema, c.relname as name, case when c.relkind in ('v', 'm') then 'view' else 'table' end as kind, case when c.relkind in ('r', 'p') then coalesce(nullif(c.reltuples, -1)::bigint, st.n_live_tup) end as rows @@ -213,14 +233,14 @@ export async function openPostgres(uri) { }, columns, async structure(schema, table) { - const idx = await pool.query( + const idx = await pq( `select i.relname as name, ix.indisunique as unique, ix.indisprimary as primary, array(select a.attname from unnest(ix.indkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = t.oid and a.attnum = k.n order by k.o)::text[] as columns from pg_index ix join pg_class t on t.oid = ix.indrelid join pg_class i on i.oid = ix.indexrelid join pg_namespace n on n.oid = t.relnamespace where n.nspname = $1 and t.relname = $2 order by ix.indisprimary desc, i.relname`, [schema, table], ) - const fks = await pool.query( + const fks = await pq( `select con.conname as name, rn.nspname as "refSchema", rt.relname as "refTable", array(select a.attname from unnest(con.conkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = con.conrelid and a.attnum = k.n order by k.o)::text[] as columns, array(select a.attname from unnest(con.confkey) with ordinality k(n, o) join pg_attribute a on a.attrelid = con.confrelid and a.attnum = k.n order by k.o)::text[] as "refColumns" @@ -235,14 +255,14 @@ export async function openPostgres(uri) { const q = sql.page(o) const page = await arr(q.sql) if (!o.where?.trim()) { - const est = await pool.query( + const est = await pq( `select c.reltuples::bigint as n from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = $1 and c.relname = $2`, [o.schema, o.table], ) const guess = Number(est.rows[0]?.n ?? -1) if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } } - const exact = await pool.query(q.count) + const exact = await pq(q.count) return { ...page, total: Number(exact.rows[0].n), estimated: false } }, update: async (o) => tx([sql.update(o.schema, o.table, o.key, o.set)]), @@ -257,10 +277,27 @@ export async function openPostgres(uri) { * @param {string} uri * @returns {Promise} */ -export async function openMysql(uri) { +export async function openMysql(uri, { readOnly = false } = {}) { const mysql = await import('mysql2/promise') const pool = mysql.createPool({ uri: uri.replace(/^(mariadb|mysql2):/i, 'mysql:'), connectionLimit: 4, dateStrings: true, supportBigNumbers: true, bigNumberStrings: true, connectTimeout: 15_000 }) await (await pool.getConnection()).release() + /** + * Every query this engine runs. Read-only (a shared studio): one statement + * per call (mysql2 keeps multipleStatements off) inside its own + * `START TRANSACTION READ ONLY`, always rolled back. + * @param {any} cfg @param {unknown[]} [values] + */ + const pq = async (cfg, values) => { + if (!readOnly) return pool.query(cfg, values) + const c = await pool.getConnection() + try { + await c.query('START TRANSACTION READ ONLY') + return await c.query(cfg, values) + } finally { + await c.query('ROLLBACK').catch(() => {}) + c.release() + } + } const sql = dialect({ q: bq, ph: () => '?', @@ -270,7 +307,7 @@ export async function openMysql(uri) { /** @param {string} text @param {unknown[]} [values] */ const arr = async (text, values) => { - const [rows, fields] = await pool.query({ sql: text, values, rowsAsArray: true }) + const [rows, fields] = await pq({ sql: text, values, rowsAsArray: true }) if (!Array.isArray(rows)) { const h = /** @type {{ affectedRows?: number }} */ (rows) return { columns: [], rows: [], rowCount: h.affectedRows ?? null, command: text.trim().split(/\s+/)[0].toUpperCase() } @@ -284,6 +321,7 @@ export async function openMysql(uri) { } /** @param {Step[]} steps */ const tx = async (steps) => { + if (readOnly) throw new Error(READ_ONLY) const c = await pool.getConnection() let total = 0 try { @@ -304,7 +342,7 @@ export async function openMysql(uri) { } /** @param {string} schema @param {string} table */ const columns = async (schema, table) => { - const [r] = /** @type {any} */ (await pool.query( + const [r] = /** @type {any} */ (await pq( `select column_name as name, column_type as type, is_nullable = 'YES' as nullable, column_key = 'PRI' as primaryKey, column_default as \`default\` from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position`, [schema, table], @@ -315,12 +353,12 @@ export async function openMysql(uri) { return { engine: 'mysql', async info() { - const [r] = /** @type {any} */ (await pool.query('select database() as db, version() as v')) + const [r] = /** @type {any} */ (await pq('select database() as db, version() as v')) const u = new URL(uri.replace(/^[a-z0-9+.-]+:/i, 'http:')) return { engine: 'mysql', database: r[0].db ?? '', host: u.hostname, version: r[0].v } }, async tables() { - const [r] = /** @type {any} */ (await pool.query( + const [r] = /** @type {any} */ (await pq( `select table_schema as \`schema\`, table_name as name, if(table_type = 'VIEW', 'view', 'table') as kind, table_rows as \`rows\` from information_schema.tables where table_schema = coalesce(database(), table_schema) @@ -331,12 +369,12 @@ export async function openMysql(uri) { }, columns, async structure(schema, table) { - const [idx] = /** @type {any} */ (await pool.query( + const [idx] = /** @type {any} */ (await pq( `select index_name as name, non_unique = 0 as \`unique\`, index_name = 'PRIMARY' as \`primary\`, group_concat(column_name order by seq_in_index separator '\\n') as cols from information_schema.statistics where table_schema = ? and table_name = ? group by index_name, non_unique order by \`primary\` desc, name`, [schema, table], )) - const [fks] = /** @type {any} */ (await pool.query( + const [fks] = /** @type {any} */ (await pq( `select constraint_name as name, referenced_table_schema as refSchema, referenced_table_name as refTable, group_concat(column_name order by ordinal_position separator '\\n') as cols, group_concat(referenced_column_name order by ordinal_position separator '\\n') as refCols @@ -355,14 +393,14 @@ export async function openMysql(uri) { const q = sql.page(o) const page = await arr(q.sql) if (!o.where?.trim()) { - const [est] = /** @type {any} */ (await pool.query( + const [est] = /** @type {any} */ (await pq( 'select table_rows as n from information_schema.tables where table_schema = ? and table_name = ?', [o.schema, o.table], )) const guess = Number(est[0]?.n ?? -1) if (guess > EXACT_COUNT_MAX) return { ...page, total: guess, estimated: true } } - const [exact] = /** @type {any} */ (await pool.query(q.count)) + const [exact] = /** @type {any} */ (await pq(q.count)) return { ...page, total: Number(exact[0].n), estimated: false } }, update: async (o) => tx([sql.update(o.schema, o.table, o.key, o.set)]), @@ -377,7 +415,7 @@ export async function openMysql(uri) { * @param {string} file * @returns {Promise} */ -export async function openSqlite(file) { +export async function openSqlite(file, { readOnly = false } = {}) { /** @type {typeof import('node:sqlite')} */ let sqlite try { @@ -385,7 +423,9 @@ export async function openSqlite(file) { } catch { throw new Error(`SQLite needs Node 22.5 or newer (this is ${process.version}). Or open the file in the Stroke app.`) } - const db = new sqlite.DatabaseSync(file) + // Read-only (a shared studio): opened read-only at the file level, which no + // statement can undo (PRAGMA query_only can be switched back off; this can't). + const db = readOnly ? new sqlite.DatabaseSync(file, { readOnly: true }) : new sqlite.DatabaseSync(file) // One schema per file; the page still sends "main". const sql = dialect({ q: dq, ph: () => '?', from: (_s, t) => dq(t), emptyInsert: (from) => `INSERT INTO ${from} DEFAULT VALUES` }) /** @param {unknown} v */ @@ -406,6 +446,7 @@ export async function openSqlite(file) { } /** @param {Step[]} steps */ const tx = async (steps) => { + if (readOnly) throw new Error(READ_ONLY) let total = 0 db.exec('BEGIN') try { @@ -477,6 +518,7 @@ export async function openSqlite(file) { // node:sqlite prepares one statement at a time; run all but the last // with exec and return the last one's rows, like the other consoles do. const parts = splitStatements(text) + if (parts.length > 1 && readOnly) throw new Error('Run one statement at a time in a shared studio.') if (parts.length > 1) db.exec(parts.slice(0, -1).join(';\n')) return arr(parts[parts.length - 1] ?? text) }, @@ -521,9 +563,12 @@ export function splitStatements(text) { /** * @param {'postgres' | 'mysql' | 'sqlite'} engine * @param {string} uri + * @param {{ readOnly?: boolean }} [opts] */ -export function openEngine(engine, uri) { - if (engine === 'postgres') return openPostgres(uri) - if (engine === 'mysql') return openMysql(uri) - return openSqlite(uri) +export function openEngine(engine, uri, opts = {}) { + if (engine === 'postgres') return openPostgres(uri, opts) + if (engine === 'mysql') return openMysql(uri, opts) + return openSqlite(uri, opts) } + +const READ_ONLY = 'This shared studio is read-only.' diff --git a/cli/src/relay.js b/cli/src/relay.js new file mode 100644 index 00000000..508240b5 --- /dev/null +++ b/cli/src/relay.js @@ -0,0 +1,140 @@ +// Share the studio beyond this machine (Labs). The local bridge only answers +// 127.0.0.1; a share holds one WebSocket open to a room on the relay at +// stroke.click, and a studio page on any device sends its calls there. +// +// Everything is end-to-end encrypted: AES-256-GCM with a key that exists only +// in the share link's #fragment, which no browser sends to a server. The relay +// sees the room id and ciphertext. The same scheme is in stroke-web +// (src/lib/relay/relay-crypto.ts) and the desktop app (src/lib/studio-share.js). + +import crypto from 'node:crypto' + +const subtle = crypto.webcrypto.subtle + +/** @param {Uint8Array | Buffer} b */ +export const toB64u = (b) => Buffer.from(b).toString('base64url') +/** @param {string} s */ +export const fromB64u = (s) => new Uint8Array(Buffer.from(s, 'base64url')) + +/** A fresh share: a room on the relay, the link's key, and the host's claim on the room. */ +export function newShare() { + return { + room: toB64u(crypto.randomBytes(16)), + key: toB64u(crypto.randomBytes(32)), + secret: toB64u(crypto.randomBytes(32)), + } +} + +/** The link someone else opens. Everything after # stays in their browser. */ +export function shareUrl({ studio, room, key }) { + return `${studio}#${new URLSearchParams({ relay: room, key })}` +} + +/** @param {string} key */ +export async function importKey(key) { + return subtle.importKey('raw', fromB64u(key), 'AES-GCM', false, ['encrypt', 'decrypt']) +} + +/** @param {CryptoKey} key @param {unknown} value */ +export async function seal(key, value) { + const iv = crypto.randomBytes(12) + const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, Buffer.from(JSON.stringify(value))) + return { iv: toB64u(iv), ct: toB64u(new Uint8Array(ct)) } +} + +/** @param {CryptoKey} key @param {{ iv: string, ct: string }} sealed */ +export async function open(key, sealed) { + const pt = await subtle.decrypt({ name: 'AES-GCM', iv: fromB64u(sealed.iv) }, key, fromB64u(sealed.ct)) + return JSON.parse(Buffer.from(pt).toString('utf8')) +} + +/** + * Answer a room's calls until closed. Reconnects with backoff if the socket + * drops (laptop sleep, Wi-Fi change); the link keeps working when it's back. + * @param {{ + * routes: Record Promise>, + * room: string, key: string, secret: string, + * base?: string, + * onStatus?: (status: 'online' | 'offline', detail?: string) => void, + * }} o + */ +export async function startRelayHost({ routes, room, key, secret, base = 'https://stroke.click', onStatus = () => {} }) { + if (typeof WebSocket !== 'function') { + throw new Error(`Sharing needs Node 22 or newer (this is ${process.version}).`) + } + const cryptoKey = await importKey(key) + const url = `${base.replace(/^http/, 'ws')}/api/relay/${room}/host?${new URLSearchParams({ secret })}` + let closed = false + let delay = 1000 + /** @type {WebSocket | null} */ + let ws = null + /** @type {ReturnType | undefined} */ + let ping + + /** @param {{ id: number, iv: string, ct: string }} msg */ + const answer = async (msg) => { + let reply + try { + const { path, body } = await open(cryptoKey, msg) + const route = typeof path === 'string' ? routes[path] : undefined + reply = route + ? { status: 200, data: await route(body ?? {}) } + : { status: 404, error: 'Not available in this shared studio.' } + } catch (e) { + reply = { status: 400, error: e instanceof Error ? e.message : String(e) } + } + try { + ws?.send(JSON.stringify({ id: msg.id, ...(await seal(cryptoKey, reply)) })) + } catch { + // the socket went; the caller times out and retries + } + } + + const connect = () => { + if (closed) return + const sock = new WebSocket(url) + ws = sock + sock.addEventListener('open', () => { + delay = 1000 + onStatus('online') + clearInterval(ping) + ping = setInterval(() => sock.readyState === 1 && sock.send('{"ping":1}'), 25_000) + }) + sock.addEventListener('message', (ev) => { + let msg + try { + msg = JSON.parse(String(ev.data)) + } catch { + return + } + if (typeof msg?.id === 'number' && typeof msg.iv === 'string' && typeof msg.ct === 'string') void answer(msg) + }) + sock.addEventListener('close', (ev) => { + clearInterval(ping) + if (ws !== sock || closed) return + if (ev.code === 1008 || ev.code === 4003) { + onStatus('offline', 'The relay refused this share.') + return + } + onStatus('offline', 'Reconnecting') + setTimeout(connect, delay) + delay = Math.min(delay * 2, 30_000) + }) + sock.addEventListener('error', () => { + // 'close' follows and reconnects + }) + } + connect() + + return { + close() { + closed = true + clearInterval(ping) + try { + ws?.close(1000, 'Stopped sharing') + } catch { + // already closed + } + }, + } +} diff --git a/cli/test/cli.test.js b/cli/test/cli.test.js index 2a406857..d1f6460a 100644 --- a/cli/test/cli.test.js +++ b/cli/test/cli.test.js @@ -182,3 +182,50 @@ test('sqlite: structure, where, and edits by primary key', async () => { await db.close() } }) + +test('share: read-only routes drop edits and keep reading SQL only', async () => { + const { makeRoutes, isReadingSql } = await import('../src/bridge.js') + const engine = { info: async () => ({ engine: 'sqlite', database: 'x', host: 'local file', version: '' }), query: async (sql) => ({ columns: ['q'], rows: [[sql]] }) } + const ro = makeRoutes({ engine: /** @type {any} */ (engine), name: 'x', shared: true, write: false }) + assert.equal(ro['/update'], undefined) + assert.equal(ro['/insert'], undefined) + assert.equal(ro['/delete'], undefined) + const info = /** @type {any} */ (await ro['/info']({})) + assert.equal(info.shared, true) + assert.equal(info.readonly, true) + assert.ok(info.features.includes('readonly') && !info.features.includes('edit')) + await assert.rejects(() => ro['/query']({ sql: 'delete from t' }), /read-only/) + assert.deepEqual((/** @type {any} */ (await ro['/query']({ sql: 'select 1' }))).rows, [['select 1']]) + for (const sql of ['select 1', 'WITH a AS (select 1) select * from a', '/* x */ show tables', 'pragma table_info(t)']) assert.ok(isReadingSql(sql), sql) + for (const sql of ['delete from t', 'copy t to stdout', "attach 'x' as y", 'pragma query_only = 0', 'update t set a=1']) assert.ok(!isReadingSql(sql), sql) + const rw = makeRoutes({ engine: /** @type {any} */ (engine), name: 'x', shared: true, write: true }) + assert.equal(typeof rw['/update'], 'function') +}) + +test('share: sealed calls round-trip with the link key and fail with another', async () => { + const { newShare, importKey, seal, open, shareUrl } = await import('../src/relay.js') + const a = newShare() + assert.match(a.room, /^[A-Za-z0-9_-]{22}$/) + assert.match(a.key, /^[A-Za-z0-9_-]{43}$/) + const key = await importKey(a.key) + const sealed = await seal(key, { path: '/tables', body: {} }) + assert.deepEqual(await open(key, sealed), { path: '/tables', body: {} }) + const other = await importKey(newShare().key) + await assert.rejects(() => open(other, sealed)) + assert.equal(shareUrl({ studio: 'https://stroke.click/studio', room: a.room, key: a.key }), `https://stroke.click/studio#relay=${a.room}&key=${a.key}`) +}) + +test('sqlite: a read-only engine refuses writes at the file level', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'strokedb-ro-')) + const file = path.join(dir, 'ro.db') + const rw = await openSqlite(file) + await rw.query('create table t(id integer primary key, a text)') + await rw.query("insert into t(a) values ('x')") + await rw.close() + const ro = await openSqlite(file, { readOnly: true }) + assert.equal((await ro.query('select count(*) as n from t')).rows[0][0], 1) + await assert.rejects(() => ro.query("insert into t(a) values ('y')")) + await assert.rejects(() => ro.query('select 1; delete from t'), /one statement/) + await assert.rejects(() => ro.update({ schema: 'main', table: 't', key: { id: 1 }, set: { a: 'z' } }), /read-only/) + await ro.close() +}) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index cb95a412..79a49470 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1603,6 +1603,24 @@ pub async fn pg_execute_sql( execute_sql(state, sql, query_id).await } +/// A shared studio's SQL (Labs: Share in a connection's menu). Read-only +/// shares go through the MCP server's own path: the access classifier first +/// (one reading statement), then the engine's read-only transaction +/// (Postgres, MySQL) or a transaction that is always rolled back (SQLite). +/// Returns the MCP tool's JSON: { columns, rows, row_count, truncated }. +#[tauri::command] +pub async fn share_execute_sql(state: Db<'_>, sql: String, read_only: bool) -> Result { + use crate::mcp::access; + let conn = require_conn(&state)?; + if read_only { + let dialect = access::Dialect::for_driver(conn.driver()); + if access::script_level_in(dialect, &sql) > access::READ || access::statement_count(dialect, &sql) > 1 { + return Err("This shared studio is read-only: run one SELECT, WITH, EXPLAIN or SHOW at a time.".into()); + } + } + crate::mcp::tools::call_tool(&conn, "execute_sql", &serde_json::json!({ "sql": sql, "max_rows": 1000 }), read_only).await +} + #[tauri::command] pub async fn pg_execute_sql_multi( state: Db<'_>, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ceb4c7df..2b954f69 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -809,6 +809,7 @@ pub fn run() { commands::instance_set_config, commands::instance_replication, commands::pg_execute_sql, + commands::share_execute_sql, commands::pg_execute_sql_multi, commands::pg_execute_sql_stream, commands::result_window, diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index e23d2ca6..fdcf5eeb 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -69,6 +69,8 @@ /** What's new in this version, any time. */ onopenwhatsnew = () => {}, onopeninsights = () => {}, + /** Labs: share the open database as a web studio (shown when the Labs switch is on). */ + onsharestudio = /** @type {(() => void) | null} */ (null), onopenadvisor = () => {}, onopenobjects = () => {}, onopenormschema = () => {}, @@ -260,6 +262,7 @@ { icon: 'shield-check', label: 'Security', action: onopensecurity, show: connected && hasSecurity, value: 'open security roles users policies rls row level' }, { icon: 'shield-check', label: 'Advisor', action: onopenadvisor, show: connected && hasAdvisor, value: 'open advisor lint audit checks security performance schema rls unused index foreign key bloat' }, { icon: 'database', label: 'Instance insights', action: onopeninsights, show: connected && hasInsights, value: 'open instance insights monitoring sessions locks replication config pg_settings' }, + { icon: 'globe', label: 'Share as web studio', action: () => onsharestudio?.(), show: connected && !!onsharestudio, value: 'share as web studio link remote relay browser device labs collaborate' }, { icon: 'layout-dashboard',label: 'Dashboard', action: onopendashboard, show: connected && !isKeyValue, value: 'open dashboard saved metrics overview widgets' }, { icon: 'bar-chart-2', label: 'Charts', action: onopencharts, show: connected && !isKeyValue, value: 'open charts visualize query results graphs plots' }, { icon: 'git-branch', label: 'Diagrams', action: onopendiagrams, show: connected && !isKeyValue, value: 'open diagrams draw erd relationship map' }, diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index 56913dca..7d50e0c9 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -798,6 +798,17 @@ }, )} {/if} + {#if show('Share as a web studio', 'Labs, share a connection with a link that opens in any browser, relay, remote')} + {@render switchRow( + 'Share as a web studio', + 'Share the open database with a link that works in any browser, on any device, while Stroke is open. End-to-end encrypted through stroke.click. Read-only unless you allow edits.', + settings.studioShare === true, + () => { + settings = updateSettings({ studioShare: settings.studioShare !== true }); + window.dispatchEvent(new CustomEvent('stroke:studio-share-changed', { detail: settings.studioShare === true })); + }, + )} + {/if} {#if show('Focus the tree on switch', 'Labs, collapse the sidebar tree to the new database tables when you switch')} {@render switchRow( 'Focus the tree on switch', diff --git a/src/lib/components/StudioShareDialog.svelte b/src/lib/components/StudioShareDialog.svelte new file mode 100644 index 00000000..2631fa9e --- /dev/null +++ b/src/lib/components/StudioShareDialog.svelte @@ -0,0 +1,148 @@ + + + + + + + + +
+ + {share ? `Sharing ${databaseName || 'this database'}` : `Share ${databaseName || 'this database'} as a web studio`} + + + + End-to-end encrypted. stroke.click only passes it along. + +
+
+ +
+ {#if unsupported} +

{unsupported}

+ {:else} + +
+ {#each [{ v: false, l: 'Read-only', d: 'Browse tables and run SELECT queries.' }, { v: true, l: 'Allow edits', d: 'Edit rows and run any SQL on this database.' }] as opt (opt.l)} + + {/each} +
+ + {#if share} +
+ + + +
+

+ + {statusText}. Anyone with the link can {share.write ? 'read and change' : 'read'} this database while Stroke is open. +

+ {:else} +

+ You get a link that opens this database in any browser, on any device. It works while Stroke is open and this database is connected. Send the whole link: the key is the part after #. +

+ {/if} + {/if} +
+ +
+ Labs + + {#if share} + + + {:else if !unsupported} + + + {:else} + + {/if} +
+
+
diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index a57aba6d..e7af4324 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -110,6 +110,7 @@ import DatabaseInfoDialog from './DatabaseInfoDialog.svelte' import { CatalogCache, catalogKey, connectionPrefix } from '$lib/catalog-cache.js' import { whenIdle } from '$lib/idle.js' + import { studioEngine as studioEngineFor } from '$lib/studio-share.js' import { refreshExternalPlugins, stopAllExternalPlugins } from '$lib/plugins/external/host.js' import { dbAdminKind, @@ -691,6 +692,60 @@ return () => cancel() }) + // ── Labs: share as a web studio ───────────────────────────────────────── + let showStudioShare = $state(false) + /** @type {{ link: string, write: boolean, stop: () => void } | null} */ + let studioShare = $state(null) + let studioShareStatus = $state(/** @type {'connecting' | 'online' | 'offline'} */ ('offline')) + /** The connection the share answers for; a switch away pauses it (isLive). */ + let studioShareConnId = '' + const studioShareUnsupported = $derived( + connection && !studioEngineOf(connection) ? 'The web studio speaks PostgreSQL, MySQL and SQLite. Share a connection to one of those.' : '', + ) + /** @param {any} c */ + function studioEngineOf(c) { + return studioEngineFor(c?.type ?? dbType) + } + /** @param {boolean} write */ + async function startStudioShare(write) { + stopStudioShare() + const c = connection + const engine = studioEngineOf(c) + if (!c || !engine) return + studioShareConnId = activeConnectionId ?? '' + const { startShare } = await import('$lib/studio-share.js') + studioShare = await startShare({ + engine, + name: c.name || c.database || 'Database', + database: c.database || c.filePath?.split(/[\\/]/).pop() || c.name || '', + host: c.host || (engine === 'sqlite' ? 'local file' : ''), + write, + isLive: () => !!connection && (activeConnectionId ?? '') === studioShareConnId, + onStatus: (st) => (studioShareStatus = st), + // A local stroke-web for testing the relay; unset in every release build. + origin: import.meta.env.VITE_STUDIO_ORIGIN || undefined, + }) + } + function stopStudioShare() { + studioShare?.stop() + studioShare = null + studioShareStatus = 'offline' + } + // Disconnecting ends the share; so does turning the Labs switch off. + $effect(() => { + if (!connection && studioShare) untrack(() => stopStudioShare()) + }) + /** The Labs switch, live: the palette entry follows it. */ + let studioShareEnabled = $state(loadSettings().studioShare === true) + $effect(() => { + const changed = (/** @type {Event} */ e) => { + studioShareEnabled = /** @type {CustomEvent} */ (e).detail === true + if (!studioShareEnabled) stopStudioShare() + } + window.addEventListener('stroke:studio-share-changed', changed) + return () => window.removeEventListener('stroke:studio-share-changed', changed) + }) + let commandOpen = $state(false) let commandPage = $state(/** @type {'root'|'docker'|'connections'|'tables'|'pages'} */ ('root')) // Reset to the root view whenever the palette closes so generic openers @@ -9915,6 +9970,19 @@ let rowSearch = $state('') lead={crashReport ? 'Stroke closed by itself last time. This report holds the error and where in Stroke it happened, nothing else; read it over before you send it.' : ''} /> +{#if showStudioShare || studioShare} + {#await import('./StudioShareDialog.svelte') then { default: StudioShareDialog }} + startStudioShare(write)} + onstop={stopStudioShare} + /> + {/await} +{/if} {#if dialogMounted.share} {#await lazyDialogs.share() then { default: ShareDialog }} @@ -10009,6 +10077,7 @@ let rowSearch = $state('') onopenterminal={() => { if (aiMode) exitAiMode(); if (!terminalDockOpen) toggleTerminalDock() }} onnewterminal={() => { commandOpen = false; if (aiMode) exitAiMode(); openNewTerminalTab() }} onopenwhatsnew={() => { commandOpen = false; void updateDialog?.showWhatsNew?.() }} + onsharestudio={studioShareEnabled ? () => { commandOpen = false; showStudioShare = true } : null} onopeninsights={() => { if (aiMode) exitAiMode(); openInsightsTab() }} onopenadvisor={() => { if (aiMode) exitAiMode(); openAdvisorTab() }} onopenobjects={() => { if (aiMode) exitAiMode(); openObjectsTab() }} diff --git a/src/lib/stores/settings.js b/src/lib/stores/settings.js index db6e7919..5691e039 100644 --- a/src/lib/stores/settings.js +++ b/src/lib/stores/settings.js @@ -108,7 +108,7 @@ const markQualifyDefaultApplied = () => { /** @typedef {'claude' | 'geist' | 'serif' | 'apple' | 'inter' | 'mono' | 'fira' | 'plex' | 'space' | 'source'} FontId */ /** @typedef {'regular' | 'light' | 'bold'} IconStyleId */ /** @typedef {'lucide' | 'hugeicons' | 'phosphor'} IconSetId */ -/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, aiInTab: boolean, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, panelMotion: boolean, quitGuard: boolean, multiConnection: boolean, treeFocusOnSwitch: boolean, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions, shareDefaults: Record | null }} AppSettings */ +/** @typedef {{ theme: ThemeId, zoom: number, font: FontId, iconStyle: IconStyleId, iconSet: IconSetId, tableStyle: TableStyleId, jsonTheme: JsonThemeId, editorTheme: import('$lib/themes/editor-themes.js').EditorThemeId, mcpAutoStart: boolean, launchAtLogin: boolean, autoUpdate: boolean, autoReconnectOnStartup: boolean, previewDmlBeforeApply: boolean, defaultDataView: string, paginationMode: string, maxQueryHistory: number, connectTimeoutMs: number, socketTimeoutMs: number, maxAllowedPacket: number, sessionTimezone: string, vimMode: boolean, cmdkAiEnabled: boolean, liveModeEnabled: boolean, sidebarStyle: SidebarStyleId, aiInTab: boolean, lazyWideColumns: boolean, nullSortOrder: string, agentChatFontSize: number, agentCodeFontSize: number, agentThinkingStyle: string, agentShowQueryCards: boolean, agentWebAccess: boolean, tableTextAlign: string, telemetry: boolean, jsonWordWrap: boolean, nativeScroll: boolean, rowSpacing: RowSpacingId, motion: MotionId, panelMotion: boolean, quitGuard: boolean, multiConnection: boolean, studioShare: boolean, treeFocusOnSwitch: boolean, zebraRows: boolean, showRowNumbers: boolean, showMenuBar: boolean, numberGrouping: boolean, imagePreview: boolean, openUrlsOnClick: boolean, highlightActiveRow: boolean, fkAutoExpandJson: boolean, gridFontSize: number, autoSaveQueries: boolean, streamResults: boolean, sqlUndo: boolean, sidebarComments: boolean, sidebarRememberGroups: boolean, sqlFormat: import('$lib/sql-format-options.js').SqlFormatOptions, sqlEditor: import('$lib/sql-editor-options.js').SqlEditorOptions, shareDefaults: Record | null }} AppSettings */ /** * UI type scale in design pixels: `[step, font-size, line-height?]`, matching @@ -578,6 +578,7 @@ export const DEFAULT_SETTINGS = { panelMotion: true, quitGuard: true, multiConnection: false, + studioShare: false, // Labs: a database switch folds the tree to the new database's tables. treeFocusOnSwitch: false, // SQL formatter preferences. Defaults live with the formatter (format-sql.js) @@ -972,6 +973,7 @@ export function loadSettings() { const panelMotion = parsed.panelMotion !== false const quitGuard = parsed.quitGuard !== false const multiConnection = parsed.multiConnection === true + const studioShare = parsed.studioShare === true const treeFocusOnSwitch = parsed.treeFocusOnSwitch === true const sqlFormat = normalizeSqlFormat(parsed.sqlFormat) const sqlEditor = normalizeSqlEditor(parsed.sqlEditor) @@ -1008,7 +1010,7 @@ export function loadSettings() { const agentShowQueryCards = parsed.agentShowQueryCards === true const agentWebAccess = parsed.agentWebAccess === true const tableTextAlign = TABLE_ALIGN_IDS.includes(parsed.tableTextAlign) ? parsed.tableTextAlign : DEFAULT_TABLE_ALIGN - _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, aiInTab, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, panelMotion, quitGuard, multiConnection, treeFocusOnSwitch, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor, shareDefaults } + _settingsCache = { theme, zoom, font, iconStyle, iconSet, tableStyle, jsonTheme, editorTheme, mcpAutoStart, launchAtLogin, autoUpdate, autoReconnectOnStartup, previewDmlBeforeApply, defaultDataView, paginationMode, maxQueryHistory, connectTimeoutMs, socketTimeoutMs, maxAllowedPacket, sessionTimezone, vimMode, cmdkAiEnabled, liveModeEnabled, sidebarStyle, aiInTab, lazyWideColumns, nullSortOrder, agentChatFontSize, agentCodeFontSize, agentThinkingStyle, agentShowQueryCards, agentWebAccess, tableTextAlign, telemetry, jsonWordWrap, nativeScroll, rowSpacing, motion, panelMotion, quitGuard, multiConnection, studioShare, treeFocusOnSwitch, zebraRows, showRowNumbers, showMenuBar, numberGrouping, imagePreview, openUrlsOnClick, highlightActiveRow, fkAutoExpandJson, gridFontSize, autoSaveQueries, streamResults, sqlUndo, sidebarComments, sidebarRememberGroups, sqlFormat, sqlEditor, shareDefaults } // A migrated value is saved at once, or the next launch reads the old one. if (settingsMigrated) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(_settingsCache)) } catch {} diff --git a/src/lib/studio-share.js b/src/lib/studio-share.js new file mode 100644 index 00000000..d5d0c767 --- /dev/null +++ b/src/lib/studio-share.js @@ -0,0 +1,262 @@ +/** + * Share a connection as a web studio (Labs). The app answers the studio's + * calls itself, on the connection it already has open, through the relay at + * stroke.click: no strokedb, no Node, nothing to install on either side. + * + * Everything is end-to-end encrypted: AES-256-GCM with a key that exists only + * in the share link's #fragment, which no browser sends to a server. The relay + * sees the room id and ciphertext. Same scheme as strokedb (cli/src/relay.js) + * and the studio page (stroke-web src/lib/relay/relay-crypto.ts). + * + * A read-only share runs every statement through `share_execute_sql`, which + * is the MCP server's path: the access classifier, then the engine's read-only + * transaction. Its links have no edit routes at all. + */ +import { invoke } from '@tauri-apps/api/core' +import { listSchemas, listTables, getTableColumnStructure, listIndexes, updateTableCell, insertTableRow, deleteTableRows } from '$lib/api.js' + +export const STUDIO_ORIGIN = 'https://stroke.click' +const VERSION = '0.2.0' +const FEATURES = ['structure', 'where', 'edit', 'rowCounts'] + +/** The engines the web studio speaks, by the app's connection types. */ +export function studioEngine(/** @type {string} */ type) { + const t = String(type || '').toLowerCase() + if (['postgres', 'postgresql', 'cockroach', 'cockroachdb', 'supabase', 'neon', 'timescale', 'yugabyte'].includes(t)) return 'postgres' + if (['mysql', 'mariadb', 'tidb', 'planetscale'].includes(t)) return 'mysql' + if (['sqlite'].includes(t)) return 'sqlite' + return null +} + +const SYSTEM_SCHEMAS = new Set(['pg_catalog', 'information_schema', 'pg_toast', 'mysql', 'performance_schema', 'sys', 'crdb_internal', 'pg_extension']) + +// ── crypto ────────────────────────────────────────────────────────────────── + +/** @param {Uint8Array} bytes */ +function toB64u(bytes) { + let s = '' + for (const b of bytes) s += String.fromCharCode(b) + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} +/** @param {string} text */ +function fromB64u(text) { + const b = atob(text.replace(/-/g, '+').replace(/_/g, '/')) + const out = new Uint8Array(b.length) + for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i) + return out +} +const rand = (/** @type {number} */ n) => crypto.getRandomValues(new Uint8Array(n)) +/** @param {CryptoKey} key @param {unknown} value */ +async function seal(key, value) { + const iv = rand(12) + const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(JSON.stringify(value)))) + return { iv: toB64u(iv), ct: toB64u(ct) } +} +/** @param {CryptoKey} key @param {{ iv: string, ct: string }} s */ +async function unseal(key, s) { + const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64u(s.iv) }, key, fromB64u(s.ct)) + return JSON.parse(new TextDecoder().decode(pt)) +} + +// ── the studio's routes, on the app's connection ──────────────────────────── + +/** + * @param {{ + * engine: 'postgres' | 'mysql' | 'sqlite', + * name: string, database: string, host: string, + * write: boolean, + * isLive: () => boolean, + * }} o + */ +function makeRoutes({ engine, name, database, host, write, isLive }) { + const q = (/** @type {string} */ id) => (engine === 'mysql' ? '`' + id.replace(/`/g, '``') + '`' : '"' + id.replace(/"/g, '""') + '"') + const from = (/** @type {string} */ schema, /** @type {string} */ table) => (engine === 'sqlite' ? q(table) : `${q(schema)}.${q(table)}`) + const str = (/** @type {unknown} */ v) => { + if (typeof v !== 'string') throw new Error('Expected a string') + return v + } + /** @param {string} sql @returns {Promise<{ columns: string[], rows: unknown[][], rowCount: number }>} */ + const run = async (sql) => { + const r = JSON.parse(/** @type {string} */ (await invoke('share_execute_sql', { sql, readOnly: !write }))) + const columns = /** @type {string[]} */ (r.columns ?? []) + const rows = (r.rows ?? []).map((/** @type {any} */ row) => (Array.isArray(row) ? row : columns.map((c) => row?.[c]))) + return { columns, rows, rowCount: Number(r.row_count ?? rows.length) } + } + const guard = () => { + if (!isLive()) throw new Error('The shared database isn\'t open in Stroke right now.') + } + + /** @type {Record Promise>} */ + const routes = { + '/info': async () => ({ + engine, + database, + host, + version: '', + name, + bridge: VERSION, + features: write ? FEATURES : [...FEATURES.filter((f) => f !== 'edit'), 'readonly'], + shared: true, + readonly: !write, + }), + '/tables': async () => { + const schemas = engine === 'sqlite' ? ['main'] : (/** @type {string[]} */ (await listSchemas())).filter((s) => !SYSTEM_SCHEMAS.has(s)) + const out = [] + for (const schema of schemas) { + const list = /** @type {any[]} */ (await listTables(schema)) + for (const t of list) { + out.push({ + schema, + name: t.name, + kind: /view/.test(String(t.kind)) ? 'view' : 'table', + rows: Number(t.rowCount) >= 0 ? Number(t.rowCount) : null, + }) + } + } + return out + }, + '/columns': async (b) => { + const cols = /** @type {any[]} */ (await getTableColumnStructure(str(b.schema), str(b.table))) + return cols.map((c) => ({ name: c.name, type: c.dataType, nullable: !!c.isNullable, primaryKey: !!c.isPrimaryKey, default: c.columnDefault ?? null })) + }, + '/structure': async (b) => { + const schema = str(b.schema) + const table = str(b.table) + const cols = /** @type {any[]} */ (await getTableColumnStructure(schema, table)) + const idx = /** @type {any[]} */ (await listIndexes(schema, table).catch(() => [])) + return { + columns: cols.map((c) => ({ name: c.name, type: c.dataType, nullable: !!c.isNullable, primaryKey: !!c.isPrimaryKey, default: c.columnDefault ?? null })), + indexes: idx + .filter((i) => !i.tableName || i.tableName === table) + .map((i) => ({ name: i.name, columns: String(i.columns || '').split(',').map((s) => s.trim()).filter(Boolean), unique: !!i.isUnique, primary: !!i.isPrimary })), + foreignKeys: cols + .filter((c) => c.foreignKey) + .map((c) => { + const parts = String(c.foreignKey).split('.') + const refColumn = parts.pop() ?? '' + const refTable = parts.pop() ?? '' + return { name: c.fkConstraintName || `fk_${c.name}`, columns: [c.name], refSchema: parts.join('.') || schema, refTable, refColumns: [refColumn] } + }), + } + }, + '/rows': async (b) => { + guard() + const schema = str(b.schema) + const table = str(b.table) + const limit = Math.min(Math.max(Number(b.limit) || 100, 1), 1000) + const offset = Math.max(Number(b.offset) || 0, 0) + const where = typeof b.where === 'string' && b.where.trim() ? ` WHERE ${b.where}` : '' + const order = b.sort && typeof b.sort.column === 'string' ? ` ORDER BY ${q(b.sort.column)} ${b.sort.dir === 'desc' ? 'DESC' : 'ASC'}` : '' + const page = await run(`SELECT * FROM ${from(schema, table)}${where}${order} LIMIT ${limit} OFFSET ${offset}`) + const count = await run(`SELECT COUNT(*) AS n FROM ${from(schema, table)}${where}`) + return { columns: page.columns, rows: page.rows, rowCount: page.rows.length, total: Number(count.rows[0]?.[0] ?? 0), estimated: false } + }, + '/query': async (b) => { + guard() + const t = performance.now() + const r = await run(str(b.sql)) + return { columns: r.columns, rows: r.rows, rowCount: r.rowCount, command: '', durationMs: Math.round(performance.now() - t) } + }, + } + if (write) { + routes['/update'] = async (b) => { + guard() + for (const [column, value] of Object.entries(b.set ?? {})) await updateTableCell(str(b.schema), str(b.table), b.key, column, value) + return { rowCount: 1 } + } + routes['/insert'] = async (b) => { + guard() + await insertTableRow(str(b.schema), str(b.table), b.values ?? {}) + return { rowCount: 1 } + } + routes['/delete'] = async (b) => { + guard() + const n = await deleteTableRows(str(b.schema), str(b.table), Array.isArray(b.keys) ? b.keys : []) + return { rowCount: Number(n) || 0 } + } + } + return routes +} + +// ── the share ─────────────────────────────────────────────────────────────── + +/** + * Start sharing. Resolves once the link exists; `onStatus` reports the relay + * connection as it comes and goes (sleep, Wi-Fi), and it reconnects by itself. + * @param {{ + * engine: 'postgres' | 'mysql' | 'sqlite', + * name: string, database: string, host: string, + * write: boolean, + * isLive: () => boolean, + * onStatus?: (s: 'connecting' | 'online' | 'offline') => void, + * origin?: string, + * }} o + */ +export async function startShare(o) { + const origin = o.origin ?? STUDIO_ORIGIN + const room = toB64u(rand(16)) + const keyText = toB64u(rand(32)) + const secret = toB64u(rand(32)) + const key = await crypto.subtle.importKey('raw', fromB64u(keyText), 'AES-GCM', false, ['encrypt', 'decrypt']) + const routes = makeRoutes(o) + const url = `${origin.replace(/^http/, 'ws')}/api/relay/${room}/host?${new URLSearchParams({ secret })}` + const onStatus = o.onStatus ?? (() => {}) + let closed = false + let delay = 1000 + /** @type {WebSocket | null} */ + let ws = null + /** @type {ReturnType | undefined} */ + let ping + + /** @param {{ id: number, iv: string, ct: string }} msg */ + const answer = async (msg) => { + let reply + try { + const { path, body } = await unseal(key, msg) + const route = typeof path === 'string' ? routes[path] : undefined + reply = route ? { status: 200, data: await route(body ?? {}) } : { status: 404, error: 'Not available in this shared studio.' } + } catch (e) { + reply = { status: 400, error: e instanceof Error ? e.message : String(e) } + } + try { + ws?.send(JSON.stringify({ id: msg.id, ...(await seal(key, reply)) })) + } catch { /* the socket went; the page retries */ } + } + + const connect = () => { + if (closed) return + onStatus('connecting') + const sock = new WebSocket(url) + ws = sock + sock.onopen = () => { + delay = 1000 + onStatus('online') + clearInterval(ping) + ping = setInterval(() => sock.readyState === 1 && sock.send('{"ping":1}'), 25_000) + } + sock.onmessage = (ev) => { + let msg + try { msg = JSON.parse(String(ev.data)) } catch { return } + if (typeof msg?.id === 'number' && typeof msg.iv === 'string' && typeof msg.ct === 'string') void answer(msg) + } + sock.onclose = () => { + clearInterval(ping) + if (ws !== sock || closed) return + onStatus('offline') + setTimeout(connect, delay) + delay = Math.min(delay * 2, 30_000) + } + } + connect() + + return { + link: `${origin}/studio#${new URLSearchParams({ relay: room, key: keyText })}`, + write: o.write, + stop() { + closed = true + clearInterval(ping) + try { ws?.close(1000, 'Stopped sharing') } catch { /* closed */ } + onStatus('offline') + }, + } +}