mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 14:15:24 +00:00
* fix: keep concurrent ssh pool connects from overwriting each other (#1619) * fix: stop auto-accepting changed jump host keys (#1620) A jump hop whose key no longer matched the pinned fingerprint was silently accepted and the pin overwritten. Background status probes reconnect to jump hosts every cycle, so a MITM on that hop got the credentials with no user interaction. Changed jump host keys now go through the same path as any other host: prompt when there is a terminal socket, otherwise refuse. * fix(electron): validate external login URL scheme and callback port (#1621) * fix(plugins): read artifact manifest with the same tar parser as the unpack (#1622) The consent check read the first manifest.json with a hand-written tar reader, while the unpack keeps the last one and also follows pax and long-name headers. An archive with two manifests could pass the check with one capability list and get granted another. Read the manifest with node-tar, count only plain files, and refuse archives that hold more than one manifest.json. * fix: only trust the server's origin in the desktop login frame (#1624) The desktop sign-in iframe accepted AUTH_SUCCESS and system browser requests from whatever page it had navigated to, and posted replies (including 2FA temp tokens) to any origin. Messages must now come from the server's origin and replies are posted to it. The web UI also treated any framing page as the desktop app and posted the JWT to it. It now also requires the Termix-Desktop user agent. * fix: check trusted proxy login against nginx's peer, not nginx (#1625) The backend only sees the bundled nginx on loopback, so the allowlist could only work by trusting 127.0.0.1, which let any client that reached nginx log in as anyone by sending the identity headers. nginx now passes its own TCP peer (before real_ip rewriting) in X-Termix-Proxy-Peer, and loopback connections are judged by that address instead. * fix: keep foreign keys on during user data import (#1626) Import credentials before hosts and remap the file's credential ids to the ones created here, so hosts and protocol logins no longer point at another server's ids. With rows written in dependency order, the import no longer turns off SQLite foreign keys on the shared connection. The uploaded file is now removed on every exit path. * fix: enforce unique usernames (#1628) * fix: enforce unique usernames Registration checked for a taken name, hashed the password, then inserted, with nothing in the schema enforcing uniqueness. Concurrent sign-ups could create two accounts with one name, after which login, password reset, proxy login and admin lookups by username picked between them arbitrarily. Add a unique index on users.username for every dialect. Existing duplicates are renamed (later rows get a -<id> suffix, the oldest keeps the name) rather than deleted. Registration and admin user creation now return the same 409 when the insert loses the race. * fix: avoid username collisions during migration * fix: don't auto-enable synced plugins signed only by a server-sent key (#1623) * fix: don't auto-enable synced plugins signed only by a server-sent key Registry keys a linked server sends still let its plugins load on the desktop, but no longer count as a signer for switching them on or copying their grants. Keys the desktop added itself keep their trust. * fix: enforce local plugin trust across remote source labels * fix: require positive local trust for synced plugin keys * fix(desktop): harden external editor and session cookie IPC (#1627) * fix(desktop): stop the renderer choosing the external editor binary or reading the session cookie open-external-editor now launches only the editor saved from a file dialog and refuses to hand executable file types to the OS opener. The unused get-session-cookie and wait-session-cookie channels, which returned the httpOnly jwt, are removed. * fix: validate setting keys before editor authorization * fix(sidebar): sort hosts by IP address numerically (#1629) * fix(desktop): find spawn-helper in universal macOS builds (#1630) The universal build ships app-arm64.asar and app-x64.asar instead of app.asar, so node-pty's helper path rewrite never pointed at the unpacked copy and every local terminal failed with posix_spawnp failed. * fix(sync): send shared hosts with text columns in their stored form (#1631) resolveHostById turns forceKeyboardInteractive into a boolean, and the shared-host export passed it on as is. A desktop could not bind the boolean into the text column, so every shared host failed to apply. * fix: drop ssh_data.vault_profile_id so removing the vault plugin keeps hosts writable (#1633) The vault plugin renames vault_profiles to p_vault_profiles, and SQLite rewrites ssh_data's foreign key to follow it. Uninstalling the plugin then dropped p_vault_profiles and left ssh_data pointing at a missing table, so creating, cloning and deleting hosts failed with "no such table: main.p_vault_profiles". Postgres and MySQL refused the uninstall instead. The column was already copied into the vault plugin's host settings by 2.9, so retire it on every engine. The SQLite boot drop also repairs databases already in the broken state; MySQL drops the column's foreign key first. * fix(sync): let a linked desktop enable mirrored plugins it does not trust on its own (#1632) * fix(sync): let a linked desktop enable mirrored plugins it does not trust on its own * fix(sync): switch off an untrusted mirrored plugin when the server updates it * fix: require local consent for mirrored plugin activation * docs: describe consent fields on the plugin state endpoint * fix(i18n): keep Indonesian technical terms consistent (#1636) Use the English terms Indonesian users know for tunnel, snippet, deploy, file manager, remote desktop, jump host, passphrase, sidebar, toolbar, endpoint, browser and SSH agent, instead of mixing literal translations (terowongan, cuplikan, terapkan, bilah sisi, titik akhir, ...) with the English words. Match the split shortcuts to the split screen menu. Also fix the user data export description, which said secrets are encrypted while the English says they are decrypted. * fix(settings): leave user manage view when switching admin sections (#1649) The admin panel stays mounted across Settings pages, so an open user manage view kept replacing every other admin section until Back to users was clicked. Reset it whenever the selected section changes. * fix(sync): don't delete a local row when the server can't send its copy (#1650) * fix(sync): don't delete a local row when the server can't send its copy A push conflict on a live record whose server row failed to serialize came back as row: null, deleted: false, and the desktop treated that as a delete. The server now rejects that op as unavailable, the desktop never deletes on a conflict without a row, and serialization failures are logged. * fix(sync): retry temporarily unavailable records * fix: smooth host editor jumps to lower sections * chore: add changelog entries for 26.10.2 fixes * fix: stop building ssh2 native crypto in the docker image (#1644) * chore: test that an update keeps a changed auth type (#1601) * feat: option to hide the sidebar after opening a host (#1652) * feat: sort the dashboard host status card (Plugin-Host-Metrics#6) * fix: let the hover side menu overlay content instead of resizing it (Plugin-Remote-Desktop#2) * fix: say the server is down and keep retrying instead of a database error (#1637) * fix: show why a client tunnel failed to start (Plugin-Tunnels#2) * fix(sdk): skip comment-only chunks when splitting migrations * feat: setting to let the hover side menu push content again * fix: use the vite proxy for plugin sockets on any dev port * feat(sdk): let a plugin raise its public route rate limit * chore: update translations * chore: add the overview video to the readme * chore: update the overview video and add a play button to its thumbnail * feat: plugin builds bundle worker entries and import wasm and fonts as bytes * feat: plugin packs include LICENSE and NOTICE * chore: drop guacd from compose files and dev runner * chore: update remote desktop origin comment for the built-in engine * fix: show plugin names and descriptions in the UI language (#1658) * fix: show plugin names and descriptions in the UI language Read plugin.name and plugin.description from each plugin's own locale namespace, falling back to the manifest, everywhere core shows a plugin's name: the Plugins manager, onboarding picker, host editor tabs and sections, host filters and bulk actions, beta updates, interface presets and plugin crash/loading notices. * docs(sdk): document plugin.name and plugin.description locale keys --------- Co-authored-by: ZacharyZcR <zkl205305@gmail.com> * fix(hosts): reject or infer a missing authType on host create (#1664) Creating an SSH host through the API without authType hit the NOT NULL auth_type column and came back as a 500. The create route now infers the type from the credential, key or password in the body, falls back to the host defaults, and otherwise answers 400. A non-string authType is a 400 on create and update. * chore: changelog for merged plugin name and host auth type PRs * fix: move macOS split pane navigation to Cmd+Option+Arrow * fix: pick a free port for the desktop backend when 30001 is taken (#1663) * feat: build the Windows desktop app for ARM64 (#1615) * fix(sync): keep the changes cursor within the 32-bit seq column (#1665) The desktop learned the server's entity types by asking for changes after Number.MAX_SAFE_INTEGER. sync_records.seq is a 32-bit integer on Postgres, which rejects that bound value, so every pass needing the probe failed with 22003 out of range. The server now clamps the cursor to the largest seq the column holds and answers 400 for a cursor or limit that is not a non-negative integer. The desktop asks for a one-row page from its saved cursor instead. * fix(audit): coalesce identical plugin routine audits so they cannot flush the log (#1667) Successful plugin_as_user and plugin_service_* entries written by a plugin with the same user, action, resource and details are recorded once per 10 minutes. Failures and every other action are still written each time. * feat(plugins): publish host.created when a host is added (#1668) Plugins that keep an inventory of hosts had no way to hear about a new one short of polling. Core now publishes host.created with the same { hostId, userId } payload as host.updated wherever a host row is created: the host create route, ctx.hosts.create, JSON and SSH config bulk import, database file import, and sync writing a host it did not have yet. * fix: show the login for signed-out full-screen view links and return to them (#1669) A ?view= link opened without a session spun forever: the gate rendered the bare view when the session check failed, so the plugin runtime never started and the view never registered. A regular browser now keeps the link in sessionStorage, shows the normal login and opens the link again after any login, including redirect logins. Only same-origin paths with a view are restored. The desktop app, embedded sign-in frames and guest views keep their current behavior. * fix(desktop): apply linked server proxy headers and certificate exception to WebSockets (#1670) * fix(desktop): send linked server proxy headers on WebSocket upgrades isLinkedOrigin compared the request origin with the link's http(s) origin, so the terminal WebSocket (wss://host/...) never matched and its upgrade went out without the proxy headers and basic auth. Behind a forward-auth proxy that upgrade was redirected to the login and the terminal closed with "connection closed unexpectedly". ws and wss now count as http and https for the comparison, the same mapping the WebSocket handshake itself uses, with host and port still matched exactly. * fix(desktop): allow a linked server's self-signed certificate for its WebSockets isInvalidCertificateAllowedForUrl compared the URL with a local getOrigin copy, so wss://host never matched the link's https://host origin and an allowed self-signed certificate did not cover the terminal and tunnel sockets. It now uses linkedServer.isLinkedOrigin, which maps ws and wss the same way as the proxy headers, and the local copy is removed. * feat(sdk): let plugins mint a short-lived user session and read a user's locale (#1666) ctx.auth.issueUserToken(userId, { purpose, ttlSeconds }) gives background work a session for calling Termix's own API as an existing user. It needs users:impersonate, defaults to 300s and is capped at 900s, is stored as a normal session row marked as plugin-issued, and every issue is audited. Such sessions are refused on routes that change the user's password, second factors, API keys or linked logins. ctx.users.getLocale(userId) reads the user's UI language under users:read. SDK 1.0.11, plugin API 1.3.0. * chore: changelog for merged sync, audit, event and desktop PRs * feat: add shell.rightEdge slot so plugin panels can push the page over * chore: pin bundled plugins to the latest releases * chore: lint, format, and bump version to 26.10.2 --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Ferdina Kusumah <19812460+FerdinaKusumah@users.noreply.github.com> Co-authored-by: ZacharyZcR <zkl205305@gmail.com> Co-authored-by: Lukas <80832688+0skater0@users.noreply.github.com>
776 lines
24 KiB
TypeScript
776 lines
24 KiB
TypeScript
/**
|
|
* The DDL a table definition becomes, per dialect.
|
|
*
|
|
* Lives in the SDK because two things need the identical mapping: the CLI,
|
|
* which writes a plugin's migration files, and the server, which applies them.
|
|
* A second copy would drift and produce a migration the runner could not
|
|
* reproduce.
|
|
*
|
|
* The mapping itself is the one scripts/generate-dialect-schema.cjs applies to
|
|
* core's schema, kept deliberately in step with it.
|
|
*/
|
|
|
|
import { KEY_LENGTH, prefixedTableName, tablePrefix } from "./db.js";
|
|
import type {
|
|
PluginColumn,
|
|
PluginTableDefinition,
|
|
PluginTableIndex,
|
|
} from "./db.js";
|
|
|
|
/** Which engine the DDL is for. Matches core's DatabaseDialect exactly. */
|
|
export type SqlDialect = "sqlite" | "postgres" | "mysql";
|
|
|
|
/** The core tables a plugin may point a foreign key at, and nothing else. */
|
|
export const REFERENCEABLE = {
|
|
refUser: { table: "users", column: "id" },
|
|
refHost: { table: "ssh_data", column: "id" },
|
|
} as const;
|
|
|
|
function camelToSnake(value: string): string {
|
|
return value.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
}
|
|
|
|
/** The SQL column name for a declared property. */
|
|
export function columnName(property: string, column?: PluginColumn): string {
|
|
void column;
|
|
return camelToSnake(property);
|
|
}
|
|
|
|
function quote(dialect: SqlDialect, identifier: string): string {
|
|
if (dialect === "mysql") return "`" + identifier + "`";
|
|
return '"' + identifier + '"';
|
|
}
|
|
|
|
/**
|
|
* The physical type for a column on one dialect.
|
|
*
|
|
* Mirrors generate-dialect-schema.cjs: an autoincrement key is serial /
|
|
* auto_increment, a boolean is native off sqlite, and anything carrying a key
|
|
* has to be varchar because MySQL will not index TEXT.
|
|
*/
|
|
function columnType(
|
|
dialect: SqlDialect,
|
|
column: PluginColumn,
|
|
keyed: boolean,
|
|
): string {
|
|
switch (column.type) {
|
|
case "id":
|
|
if (dialect === "postgres") return "serial";
|
|
if (dialect === "mysql") return "int AUTO_INCREMENT";
|
|
return "integer";
|
|
case "integer":
|
|
return dialect === "mysql" ? "int" : "integer";
|
|
case "bigint":
|
|
return dialect === "sqlite" ? "integer" : "bigint";
|
|
case "real":
|
|
if (dialect === "sqlite") return "real";
|
|
return dialect === "mysql" ? "double" : "double precision";
|
|
case "boolean":
|
|
return dialect === "sqlite" ? "integer" : "boolean";
|
|
case "varchar":
|
|
return dialect === "sqlite"
|
|
? "text"
|
|
: `varchar(${column.length ?? KEY_LENGTH})`;
|
|
case "refUser":
|
|
return dialect === "sqlite" ? "text" : `varchar(${KEY_LENGTH})`;
|
|
case "refHost":
|
|
return dialect === "mysql" ? "int" : "integer";
|
|
default:
|
|
// A keyed string has to be indexable, so it narrows to varchar even
|
|
// though it was declared unbounded. defineTable refuses to index a
|
|
// text/json column, so in practice this only catches a primary key.
|
|
if (keyed && dialect !== "sqlite") return `varchar(${KEY_LENGTH})`;
|
|
// MySQL TEXT stops at 64KB, so free text, json and secrets go long.
|
|
if (dialect === "mysql" && column.type !== "timestamp") return "longtext";
|
|
return "text";
|
|
}
|
|
}
|
|
|
|
/** Column types that are TEXT or LONGTEXT on MySQL when nothing keys them. */
|
|
const TEXT_ON_MYSQL: ReadonlySet<PluginColumn["type"]> = new Set([
|
|
"text",
|
|
"json",
|
|
"encryptedText",
|
|
"timestamp",
|
|
]);
|
|
|
|
function defaultClause(dialect: SqlDialect, column: PluginColumn): string {
|
|
if (column.defaultNow) {
|
|
// MySQL rejects a bare DEFAULT CURRENT_TIMESTAMP on a text column; an
|
|
// expression default is written parenthesised. MariaDB takes either.
|
|
return dialect === "mysql"
|
|
? " DEFAULT (CURRENT_TIMESTAMP)"
|
|
: " DEFAULT CURRENT_TIMESTAMP";
|
|
}
|
|
if (column.defaultValue === undefined) return "";
|
|
const value = column.defaultValue;
|
|
if (value === null) return " DEFAULT NULL";
|
|
if (typeof value === "boolean") {
|
|
return dialect === "sqlite"
|
|
? ` DEFAULT ${value ? 1 : 0}`
|
|
: ` DEFAULT ${value ? "true" : "false"}`;
|
|
}
|
|
if (typeof value === "number") return ` DEFAULT ${value}`;
|
|
const literal = `'${String(value).replace(/'/g, "''")}'`;
|
|
// MySQL refuses a literal default on a TEXT column but takes an expression.
|
|
if (dialect === "mysql" && TEXT_ON_MYSQL.has(column.type)) {
|
|
return ` DEFAULT (${literal})`;
|
|
}
|
|
return ` DEFAULT ${literal}`;
|
|
}
|
|
|
|
/** Every column that carries a key, and so must be indexable on MySQL. */
|
|
export function keyedColumns(
|
|
definition: PluginTableDefinition,
|
|
): ReadonlySet<string> {
|
|
const keyed = new Set<string>();
|
|
for (const [property, column] of Object.entries(definition.columns)) {
|
|
if (column.primaryKey || column.unique) keyed.add(property);
|
|
if (column.type === "refUser" || column.type === "refHost") {
|
|
keyed.add(property);
|
|
}
|
|
}
|
|
for (const index of definition.indexes) {
|
|
for (const property of index.columns) keyed.add(property);
|
|
}
|
|
return keyed;
|
|
}
|
|
|
|
function indexStatement(
|
|
dialect: SqlDialect,
|
|
physical: string,
|
|
definition: PluginTableDefinition,
|
|
entry: PluginTableIndex,
|
|
): string {
|
|
const columns = entry.columns
|
|
.map((property) =>
|
|
quote(dialect, columnName(property, definition.columns[property])),
|
|
)
|
|
.join(", ");
|
|
const unique = entry.unique ? "UNIQUE " : "";
|
|
// MySQL has no CREATE INDEX IF NOT EXISTS. A plugin migration runs once,
|
|
// recorded in plugin_migrations, so the guard is the ledger, not the DDL.
|
|
const guard = dialect === "mysql" ? "" : "IF NOT EXISTS ";
|
|
return `CREATE ${unique}INDEX ${guard}${quote(dialect, entry.name)} ON ${quote(dialect, physical)} (${columns});`;
|
|
}
|
|
|
|
function createStatements(
|
|
dialect: SqlDialect,
|
|
physical: string,
|
|
definition: PluginTableDefinition,
|
|
): { table: string; indexes: string[] } {
|
|
const keyed = keyedColumns(definition);
|
|
|
|
const lines: string[] = [];
|
|
const constraints: string[] = [];
|
|
|
|
for (const [property, column] of Object.entries(definition.columns)) {
|
|
const name = columnName(property, column);
|
|
const type = columnType(dialect, column, keyed.has(property));
|
|
|
|
let line = ` ${quote(dialect, name)} ${type}`;
|
|
if (column.type === "id") {
|
|
line += " PRIMARY KEY";
|
|
if (dialect === "sqlite") line += " AUTOINCREMENT";
|
|
} else {
|
|
if (column.primaryKey) line += " PRIMARY KEY";
|
|
if (column.notNull) line += " NOT NULL";
|
|
if (column.unique) line += " UNIQUE";
|
|
line += defaultClause(dialect, column);
|
|
}
|
|
lines.push(line);
|
|
|
|
const reference =
|
|
column.type === "refUser"
|
|
? REFERENCEABLE.refUser
|
|
: column.type === "refHost"
|
|
? REFERENCEABLE.refHost
|
|
: null;
|
|
if (reference) {
|
|
constraints.push(
|
|
` FOREIGN KEY (${quote(dialect, name)}) REFERENCES ${quote(dialect, reference.table)} (${quote(dialect, reference.column)}) ON DELETE CASCADE`,
|
|
);
|
|
}
|
|
}
|
|
|
|
const body = [...lines, ...constraints].join(",\n");
|
|
return {
|
|
table: `CREATE TABLE IF NOT EXISTS ${quote(dialect, physical)} (\n${body}\n);`,
|
|
indexes: definition.indexes.map((entry) =>
|
|
indexStatement(dialect, physical, definition, entry),
|
|
),
|
|
};
|
|
}
|
|
|
|
/** The CREATE TABLE and CREATE INDEX statements for one definition. */
|
|
export function createTableSql(
|
|
dialect: SqlDialect,
|
|
pluginId: string,
|
|
definition: PluginTableDefinition,
|
|
): string[] {
|
|
const physical = prefixedTableName(pluginId, definition.name);
|
|
const { table, indexes } = createStatements(dialect, physical, definition);
|
|
return [table, ...indexes];
|
|
}
|
|
|
|
/**
|
|
* Takes over a legacy core table by renaming it into the plugin's namespace.
|
|
*
|
|
* A plain SQL migration cannot ask whether the legacy table exists, so it
|
|
* creates it first when it does not (a fresh install) and then renames either
|
|
* way. Both paths end with the same table and the same rows.
|
|
*
|
|
* Indexes are created on the legacy name with IF NOT EXISTS before the rename,
|
|
* which is why an adopted definition keeps the legacy index names: an index
|
|
* that already exists is left alone and follows the table. MySQL has no
|
|
* CREATE INDEX IF NOT EXISTS, so there none are emitted. That is safe because
|
|
* every legacy table reached MySQL through core's drizzle migrations, which
|
|
* already created its indexes.
|
|
*/
|
|
export function adoptTableSql(
|
|
dialect: SqlDialect,
|
|
pluginId: string,
|
|
definition: PluginTableDefinition,
|
|
): string[] {
|
|
const legacy = definition.adopts;
|
|
if (!legacy) {
|
|
throw new Error(`Table "${definition.name}" does not adopt a legacy table`);
|
|
}
|
|
const physical = prefixedTableName(pluginId, definition.name);
|
|
const { table, indexes } = createStatements(dialect, legacy, definition);
|
|
|
|
const rename =
|
|
dialect === "mysql"
|
|
? `RENAME TABLE ${quote(dialect, legacy)} TO ${quote(dialect, physical)};`
|
|
: `ALTER TABLE ${quote(dialect, legacy)} RENAME TO ${quote(dialect, physical)};`;
|
|
|
|
return [table, ...(dialect === "mysql" ? [] : indexes), rename];
|
|
}
|
|
|
|
/**
|
|
* Splits a migration file into statements.
|
|
*
|
|
* Deliberately simple: statements end at a semicolon that is not inside a
|
|
* string literal or a comment. A plugin needing more than that should put the
|
|
* logic in its own code, not in DDL.
|
|
*/
|
|
export function splitStatements(source: string): string[] {
|
|
const statements: string[] = [];
|
|
let current = "";
|
|
let quoteChar: string | null = null;
|
|
let lineComment = false;
|
|
let blockComment = false;
|
|
|
|
for (let i = 0; i < source.length; i++) {
|
|
const char = source[i];
|
|
const next = source[i + 1];
|
|
|
|
if (lineComment) {
|
|
current += char;
|
|
if (char === "\n") lineComment = false;
|
|
continue;
|
|
}
|
|
if (blockComment) {
|
|
current += char;
|
|
if (char === "*" && next === "/") {
|
|
current += next;
|
|
i++;
|
|
blockComment = false;
|
|
}
|
|
continue;
|
|
}
|
|
if (quoteChar) {
|
|
current += char;
|
|
// '' inside a quoted string is an escaped quote, not a terminator.
|
|
if (char === quoteChar) {
|
|
if (next === quoteChar) {
|
|
current += next;
|
|
i++;
|
|
} else {
|
|
quoteChar = null;
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (char === "-" && next === "-") {
|
|
lineComment = true;
|
|
current += char;
|
|
continue;
|
|
}
|
|
if (char === "/" && next === "*") {
|
|
blockComment = true;
|
|
current += char;
|
|
continue;
|
|
}
|
|
if (char === "'" || char === '"' || char === "`") {
|
|
quoteChar = char;
|
|
current += char;
|
|
continue;
|
|
}
|
|
if (char === ";") {
|
|
if (hasSql(current)) statements.push(current.trim());
|
|
current = "";
|
|
continue;
|
|
}
|
|
current += char;
|
|
}
|
|
|
|
if (hasSql(current)) statements.push(current.trim());
|
|
return statements;
|
|
}
|
|
|
|
/** False for a chunk that is only comments, which a driver refuses to run. */
|
|
function hasSql(chunk: string): boolean {
|
|
return (
|
|
chunk
|
|
.replace(/--[^\n]*/g, "")
|
|
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
.trim() !== ""
|
|
);
|
|
}
|
|
|
|
/** DROP statement for a definition, for removePluginData. */
|
|
export function dropTableSql(
|
|
dialect: SqlDialect,
|
|
pluginId: string,
|
|
definition: PluginTableDefinition,
|
|
): string {
|
|
const physical = prefixedTableName(pluginId, definition.name);
|
|
return `DROP TABLE IF EXISTS ${quote(dialect, physical)};`;
|
|
}
|
|
|
|
/** The ALTER that adds one newly declared column. */
|
|
export function addColumnSql(
|
|
dialect: SqlDialect,
|
|
pluginId: string,
|
|
definition: PluginTableDefinition,
|
|
property: string,
|
|
): string {
|
|
const physical = prefixedTableName(pluginId, definition.name);
|
|
const column = definition.columns[property];
|
|
const keyed = keyedColumns(definition).has(property);
|
|
const name = columnName(property, column);
|
|
|
|
let line = `${quote(dialect, name)} ${columnType(dialect, column, keyed)}`;
|
|
if (column.notNull) line += " NOT NULL";
|
|
line += defaultClause(dialect, column);
|
|
|
|
return `ALTER TABLE ${quote(dialect, physical)} ADD COLUMN ${line};`;
|
|
}
|
|
|
|
interface SqlToken {
|
|
/** As written: a bare word keeps its case, a quoted name loses its quotes. */
|
|
value: string;
|
|
kind: "word" | "quoted" | "punct";
|
|
}
|
|
|
|
/**
|
|
* Words and identifiers in one statement, with comments and string literals
|
|
* dropped. `"x"`, `` `x` `` and `[x]` all come out as the identifier x, so no
|
|
* quoting style hides a table name from the ownership check.
|
|
*/
|
|
function tokenize(source: string): SqlToken[] {
|
|
const tokens: SqlToken[] = [];
|
|
let i = 0;
|
|
while (i < source.length) {
|
|
const char = source[i];
|
|
const next = source[i + 1];
|
|
if (/\s/.test(char)) {
|
|
i++;
|
|
} else if (char === "-" && next === "-") {
|
|
while (i < source.length && source[i] !== "\n") i++;
|
|
} else if (char === "/" && next === "*") {
|
|
const end = source.indexOf("*/", i + 2);
|
|
i = end < 0 ? source.length : end + 2;
|
|
} else if (char === "'") {
|
|
i++;
|
|
while (i < source.length) {
|
|
if (source[i] === "'" && source[i + 1] === "'") i += 2;
|
|
else if (source[i] === "'") break;
|
|
else i++;
|
|
}
|
|
i++;
|
|
tokens.push({ value: "'", kind: "punct" });
|
|
} else if (char === '"' || char === "`" || char === "[") {
|
|
const close = char === "[" ? "]" : char;
|
|
let value = "";
|
|
i++;
|
|
while (i < source.length) {
|
|
if (source[i] === close && source[i + 1] === close && close !== "]") {
|
|
value += close;
|
|
i += 2;
|
|
} else if (source[i] === close) {
|
|
break;
|
|
} else {
|
|
value += source[i++];
|
|
}
|
|
}
|
|
i++;
|
|
tokens.push({ value, kind: "quoted" });
|
|
} else if (/[A-Za-z0-9_$]/.test(char)) {
|
|
let value = "";
|
|
while (i < source.length && /[A-Za-z0-9_$]/.test(source[i])) {
|
|
value += source[i++];
|
|
}
|
|
tokens.push({ value, kind: "word" });
|
|
} else {
|
|
tokens.push({ value: char, kind: "punct" });
|
|
i++;
|
|
}
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
/** Statements a plugin migration may never contain. */
|
|
const REFUSED_STATEMENTS = new Set([
|
|
"ATTACH",
|
|
"DETACH",
|
|
"PRAGMA",
|
|
"GRANT",
|
|
"REVOKE",
|
|
"COPY",
|
|
"LOAD",
|
|
"DO",
|
|
"CALL",
|
|
"HANDLER",
|
|
"WITH",
|
|
"SET",
|
|
"VACUUM",
|
|
]);
|
|
|
|
/** What a migration may CREATE, ALTER or DROP. Anything else is refused. */
|
|
const TABLE_OBJECTS = new Set(["TABLE", "VIEW"]);
|
|
/** Allowed, but only under the plugin's own prefix. */
|
|
const PREFIXED_OBJECTS = new Set(["SEQUENCE", "TYPE"]);
|
|
|
|
/**
|
|
* Functions that read files, change server settings or run a string as SQL.
|
|
* A SELECT calling one of them could do anything, so it is refused.
|
|
*/
|
|
const REFUSED_FUNCTIONS = new Set([
|
|
"SET_CONFIG",
|
|
"PG_READ_FILE",
|
|
"PG_READ_BINARY_FILE",
|
|
"PG_LS_DIR",
|
|
"PG_STAT_FILE",
|
|
"PG_FILE_WRITE",
|
|
"LO_IMPORT",
|
|
"LO_EXPORT",
|
|
"LO_FROM_BYTEA",
|
|
"DBLINK",
|
|
"DBLINK_EXEC",
|
|
"QUERY_TO_XML",
|
|
"QUERY_TO_XML_AND_XMLSCHEMA",
|
|
"PG_TERMINATE_BACKEND",
|
|
"PG_CANCEL_BACKEND",
|
|
"PG_RELOAD_CONF",
|
|
"LOAD_FILE",
|
|
"LOAD_EXTENSION",
|
|
"SYS_EXEC",
|
|
"SYS_EVAL",
|
|
]);
|
|
|
|
const CREATE_MODIFIERS = [
|
|
"OR",
|
|
"REPLACE",
|
|
"TEMP",
|
|
"TEMPORARY",
|
|
"UNLOGGED",
|
|
"GLOBAL",
|
|
"LOCAL",
|
|
"VIRTUAL",
|
|
"UNIQUE",
|
|
"CONCURRENTLY",
|
|
];
|
|
|
|
/**
|
|
* Every problem with the tables a migration writes to.
|
|
*
|
|
* The check has to hold against a plugin that is trying, not only one that
|
|
* made a typo, so it reads each statement the way the engine does rather
|
|
* than matching one pattern: a comment between a keyword and a name, bracket
|
|
* quoting, a second name in a DROP list, a schema-qualified name and
|
|
* `ALTER ... RENAME TO users` are all seen. Reads (FROM, JOIN, REFERENCES)
|
|
* are allowed; writes outside the plugin's prefix are not.
|
|
*
|
|
* `ownedLegacy` lists the legacy core tables this plugin adopts.
|
|
*/
|
|
export function findUnownedTableWrites(
|
|
pluginId: string,
|
|
sql: string,
|
|
ownedLegacy: ReadonlySet<string> = new Set(),
|
|
ownedIndexes: ReadonlySet<string> = new Set(),
|
|
): string[] {
|
|
const prefix = tablePrefix(pluginId);
|
|
const problems: string[] = [];
|
|
const indexes = new Set([
|
|
...ownedIndexes,
|
|
...collectOwnedIndexes(pluginId, [sql], ownedLegacy),
|
|
]);
|
|
|
|
// The splitter and tokenizer follow standard quoting only. MySQL backslash
|
|
// escapes, E'' strings and Postgres dollar quoting would let a string end
|
|
// somewhere else for the engine than for this check, so none are allowed.
|
|
if (sql.includes("\\")) {
|
|
problems.push("backslashes are not allowed in a plugin migration");
|
|
}
|
|
if (/\$[A-Za-z_0-9]*\$/.test(sql)) {
|
|
problems.push(
|
|
"dollar-quoted strings are not allowed in a plugin migration",
|
|
);
|
|
}
|
|
if (problems.length > 0) return problems;
|
|
|
|
for (const statement of splitStatements(sql)) {
|
|
const tokens = tokenize(statement);
|
|
if (tokens.length === 0) continue;
|
|
const upper = (at: number) =>
|
|
tokens[at]?.kind === "word" ? tokens[at].value.toUpperCase() : "";
|
|
|
|
/** Checks the table name at `at`, returns the index after it. */
|
|
const table = (at: number): number => {
|
|
const name = tokens[at];
|
|
if (!name || name.kind === "punct") {
|
|
problems.push("a statement writes to a table with no name");
|
|
return at + 1;
|
|
}
|
|
if (tokens[at + 1]?.value === ".") {
|
|
problems.push(
|
|
`"${name.value}.${tokens[at + 2]?.value ?? ""}" names a schema; a plugin may only write its own tables`,
|
|
);
|
|
return at + 3;
|
|
}
|
|
if (!name.value.startsWith(prefix) && !ownedLegacy.has(name.value)) {
|
|
problems.push(
|
|
`writes to "${name.value}", which is not prefixed "${prefix}"`,
|
|
);
|
|
}
|
|
return at + 1;
|
|
};
|
|
const skip = (at: number, words: string[]) => {
|
|
while (words.includes(upper(at))) at++;
|
|
return at;
|
|
};
|
|
const find = (word: string, from = 0) => {
|
|
for (let at = from; at < tokens.length; at++) {
|
|
if (upper(at) === word) return at;
|
|
}
|
|
return -1;
|
|
};
|
|
|
|
const first = upper(0);
|
|
if (REFUSED_STATEMENTS.has(first)) {
|
|
problems.push(`${first} is not allowed in a plugin migration`);
|
|
continue;
|
|
}
|
|
|
|
if (first !== "CREATE" && find("CASCADE") > 0) {
|
|
problems.push("CASCADE is not allowed in a plugin migration");
|
|
continue;
|
|
}
|
|
|
|
if (first === "CREATE" || first === "ALTER" || first === "DROP") {
|
|
let at = skip(1, CREATE_MODIFIERS);
|
|
const object = upper(at);
|
|
if (object === "INDEX") {
|
|
// The index name is free; the table after ON is what it writes to.
|
|
const on = find("ON", at);
|
|
if (on > 0) {
|
|
table(skip(on + 1, ["ONLY"]));
|
|
} else if (first === "CREATE") {
|
|
problems.push("CREATE INDEX without ON is not allowed");
|
|
} else {
|
|
// DROP INDEX name: only an index this plugin created.
|
|
const nameAt = skip(at + 1, ["IF", "EXISTS", "CONCURRENTLY"]);
|
|
const name = tokens[nameAt];
|
|
if (
|
|
!name ||
|
|
name.kind === "punct" ||
|
|
tokens[nameAt + 1]?.value === "." ||
|
|
(!name.value.startsWith(prefix) && !indexes.has(name.value))
|
|
) {
|
|
problems.push(
|
|
`${first} INDEX "${name?.value ?? ""}" is not an index this plugin created`,
|
|
);
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
if (PREFIXED_OBJECTS.has(object)) {
|
|
const name = tokens[skip(at + 1, ["IF", "NOT", "EXISTS"])];
|
|
if (!name || !name.value.startsWith(prefix)) {
|
|
problems.push(
|
|
`${first} ${object} "${name?.value ?? ""}" is not prefixed "${prefix}"`,
|
|
);
|
|
}
|
|
continue;
|
|
}
|
|
if (!TABLE_OBJECTS.has(object)) {
|
|
problems.push(
|
|
`${first} ${object || tokens[at]?.value || ""} is not allowed in a plugin migration`.trim(),
|
|
);
|
|
continue;
|
|
}
|
|
at = table(skip(at + 1, ["IF", "NOT", "EXISTS", "ONLY"]));
|
|
// DROP TABLE a, b drops both.
|
|
while (first === "DROP" && tokens[at]?.value === ",") {
|
|
at = table(at + 1);
|
|
}
|
|
// ALTER TABLE p_x RENAME TO users moves a table out of the namespace.
|
|
// RENAME [COLUMN] a TO b renames a column and is fine.
|
|
for (let rename = find("RENAME", at); rename > 0;) {
|
|
const next = upper(rename + 1);
|
|
if (next === "TO" || next === "AS") table(rename + 2);
|
|
rename = find("RENAME", rename + 1);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (first === "RENAME") {
|
|
// RENAME TABLE a TO b, c TO d
|
|
let at = skip(1, ["TABLE"]);
|
|
while (at < tokens.length) {
|
|
at = table(at);
|
|
if (upper(at) !== "TO") break;
|
|
at = table(at + 1);
|
|
if (tokens[at]?.value !== ",") break;
|
|
at++;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (first === "TRUNCATE") {
|
|
let at = table(skip(1, ["TABLE", "ONLY"]));
|
|
while (tokens[at]?.value === ",") at = table(at + 1);
|
|
continue;
|
|
}
|
|
|
|
if (first === "INSERT" || first === "REPLACE") {
|
|
const into = find("INTO");
|
|
if (into > 0) table(into + 1);
|
|
else problems.push(`${first} without INTO is not allowed`);
|
|
continue;
|
|
}
|
|
|
|
if (first === "UPDATE") {
|
|
// MySQL writes every table before SET: UPDATE a JOIN b ... SET b.x = 1.
|
|
const set = find("SET");
|
|
const end = set > 0 ? set : tokens.length;
|
|
for (let at = 1; at < end; at++) {
|
|
if (upper(at) === "JOIN" || tokens[at].value === ",") {
|
|
table(at + 1);
|
|
}
|
|
}
|
|
table(
|
|
skip(1, [
|
|
"OR",
|
|
"ROLLBACK",
|
|
"ABORT",
|
|
"REPLACE",
|
|
"FAIL",
|
|
"IGNORE",
|
|
"ONLY",
|
|
"LOW_PRIORITY",
|
|
]),
|
|
);
|
|
continue;
|
|
}
|
|
|
|
if (first === "DELETE") {
|
|
const from = find("FROM");
|
|
if (from < 0) {
|
|
problems.push("DELETE without FROM is not allowed");
|
|
continue;
|
|
}
|
|
// MySQL: DELETE a, b FROM ... deletes from a and b.
|
|
let at = skip(1, ["LOW_PRIORITY", "QUICK", "IGNORE"]);
|
|
if (at < from) {
|
|
while (at < from) {
|
|
at = table(at);
|
|
if (tokens[at]?.value !== ",") break;
|
|
at++;
|
|
}
|
|
continue;
|
|
}
|
|
at = table(skip(from + 1, ["ONLY"]));
|
|
// DELETE FROM a, b USING ... deletes from both.
|
|
while (tokens[at]?.value === ",") at = table(at + 1);
|
|
continue;
|
|
}
|
|
|
|
if (first === "SELECT") {
|
|
// SELECT ... INTO creates a table on Postgres and writes a file on
|
|
// MySQL.
|
|
if (find("INTO") > 0) {
|
|
problems.push("SELECT INTO is not allowed in a plugin migration");
|
|
continue;
|
|
}
|
|
for (let at = 0; at < tokens.length; at++) {
|
|
if (REFUSED_FUNCTIONS.has(upper(at)) && tokens[at + 1]?.value === "(") {
|
|
problems.push(
|
|
`${tokens[at].value}() is not allowed in a plugin migration`,
|
|
);
|
|
}
|
|
}
|
|
// setval can break a core table's ids, so only the plugin's own.
|
|
for (const match of statement.matchAll(/setval\s*\(\s*([^,]*)/gi)) {
|
|
const target = /'([^']*)'/.exec(match[1])?.[1];
|
|
if (!target || !target.startsWith(prefix)) {
|
|
problems.push("setval() may only target this plugin's own sequences");
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (first !== "COMMENT") {
|
|
problems.push(
|
|
`"${tokens[0].value}" statements are not allowed in a plugin migration`,
|
|
);
|
|
}
|
|
}
|
|
|
|
return problems;
|
|
}
|
|
|
|
/**
|
|
* Names of the indexes a plugin's migrations create on its own tables, so a
|
|
* later DROP INDEX with no ON clause can be checked against them.
|
|
*/
|
|
export function collectOwnedIndexes(
|
|
pluginId: string,
|
|
sqls: readonly string[],
|
|
ownedLegacy: ReadonlySet<string> = new Set(),
|
|
): Set<string> {
|
|
const prefix = tablePrefix(pluginId);
|
|
const owned = new Set<string>();
|
|
for (const sql of sqls) {
|
|
for (const statement of splitStatements(sql)) {
|
|
const tokens = tokenize(statement);
|
|
const upper = (at: number) =>
|
|
tokens[at]?.kind === "word" ? tokens[at].value.toUpperCase() : "";
|
|
if (upper(0) !== "CREATE") continue;
|
|
let at = 1;
|
|
while (CREATE_MODIFIERS.includes(upper(at))) at++;
|
|
if (upper(at) !== "INDEX") continue;
|
|
at++;
|
|
while (["IF", "NOT", "EXISTS"].includes(upper(at))) at++;
|
|
const name = tokens[at];
|
|
let on = at;
|
|
while (on < tokens.length && upper(on) !== "ON") on++;
|
|
if (upper(on + 1) === "ONLY") on++;
|
|
const target = tokens[on + 1];
|
|
if (
|
|
name &&
|
|
name.kind !== "punct" &&
|
|
target &&
|
|
tokens[on + 2]?.value !== "." &&
|
|
(target.value.startsWith(prefix) || ownedLegacy.has(target.value))
|
|
) {
|
|
owned.add(name.value);
|
|
}
|
|
}
|
|
}
|
|
return owned;
|
|
}
|