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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ All commands support `--json` for machine-readable output.
1. Export MySQL dump via SSH (`wp db export`)
2. Strip SSH MOTD from dump output
3. Convert MySQL → SQLite using `mysql2sqlite` (awk script)
4. Import directly into `.ht.sqlite` via `sqlite3` CLI
4. Import directly into `.ht.sqlite` via `better-sqlite3`, into a wiped `wp-content/database/` (the SQLite plugin migrates it into its secret dir on first boot; a leftover `db-path.php` would make WP ignore it)
5. Rename table prefix to `wp_` (tables + meta keys + option names)
6. Search-replace cloud URL → `http://127.0.0.1:<port>` across all tables
7. Pull wp-content via rsync (plugins, themes, uploads)
Expand All @@ -141,6 +141,7 @@ All commands support `--json` for machine-readable output.

### DB push flow (`local push --with-db`) — SQLite → MySQL (the reverse of clone)
Pushes the local Playground DB back to the cloud MySQL, OVERWRITING it. Implemented in `pushDatabase()` (`commands/local.ts`) + `lib/sqlite-to-mysql.ts`.
0. Locate the local DB with `resolveLocalSqlitePath()` (`lib/local-sqlite.ts`): sqlite-database-integration 3.x stores it at `wp-content/database/.ht.<hex>/.ht.sqlite`, recorded in `db-path.php` (parsed, never executed). Order: `db-path.php` → `.ht.*/.ht.sqlite` glob (newest mtime, always warns: WP never scans for these) → legacy `.ht.sqlite`. Push goes through `resolvePushSqlitePath()`, which REFUSES when `db-path.php` exists but was unusable (WP treats it as the authority, so any fallback is not the live DB). Also drives `isClone` in `local-env.ts`.
1. Read local siteurl from `wp_options` (authoritative; handles port drift)
2. Discover cloud `table_prefix` + existing tables via SSH — **MOTD-stripped** (`parseTablePrefix`/`parseSqlTableNames` in `lib/local-instance.ts`); a banner leaking in would mismatch every table → silent empty push
3. `generateMysqlDump()`: **data-only** (`TRUNCATE`+`INSERT`, no `CREATE TABLE`) for local `wp_*` tables whose cloud-prefixed name exists on the cloud (intersection — so a missing-table TRUNCATE can't abort the import). Pins `sql_mode` (backslash escaping), `safeIntegers(true)` (no >2^53 loss), BLOB→`0x` hex (empty→`''`), byte-budgeted INSERT batching
Expand Down
242 changes: 242 additions & 0 deletions src/__tests__/local-sqlite.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, utimesSync, symlinkSync, realpathSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { resolveLocalSqlitePath, resolvePushSqlitePath, parseDbPathPhp, isInsideDir } from '../lib/local-sqlite.js';
import { buildServerArgs } from '../lib/local-env.js';

let root: string;
let dbDir: string;
const instance = () => ({ path: root });

/** A non-empty stand-in for a SQLite file (the resolver only checks it is a non-empty regular file). */
function dbFile(p: string, tag = 'x'): string {
mkdirSync(path.dirname(p), { recursive: true });
writeFileSync(p, `SQLite format 3\0${tag}`);
return realpathSync(p);
}
/** Exactly what WP_SQLite_Storage::publish_database_path() writes. */
function dbPathPhp(rel: string): void {
writeFileSync(path.join(dbDir, 'db-path.php'),
`<?php\n\n/**\n * SQLite database path.\n *\n * IMPORTANT: Keep this path secret. When possible, point it outside the document root.\n */\nreturn __DIR__ . '/${rel}';\n`);
}

beforeEach(() => {
root = mkdtempSync(path.join(tmpdir(), 'iwp-sqlite-'));
dbDir = path.join(root, 'wp-content', 'database');
mkdirSync(dbDir, { recursive: true });
});
afterEach(() => rmSync(root, { recursive: true, force: true }));

describe('resolveLocalSqlitePath', () => {
it('uses the path recorded in db-path.php, over a stale legacy .ht.sqlite and another secret dir', () => {
const secret = '.ht.51e23a042b788a98d0283c084cb1962c';
const want = dbFile(path.join(dbDir, secret, '.ht.sqlite'), 'live');
dbPathPhp(`${secret}/.ht.sqlite`);
dbFile(path.join(dbDir, '.ht.sqlite'), 'stale');
const other = dbFile(path.join(dbDir, '.ht.ffff', '.ht.sqlite'), 'other');
const future = new Date(Date.now() + 60_000);
utimesSync(other, future, future); // newer than `want`: the recorded path must still win

const r = resolveLocalSqlitePath(instance());
expect(r).toMatchObject({ path: want, source: 'db-path.php', warnings: [], recordedPathIgnored: false });
});

it('finds the path literal in a db-path.php that has other statements (it is parsed, not run)', () => {
writeFileSync(path.join(dbDir, 'db-path.php'),
`<?php\ntouch('/tmp/x');\nreturn __DIR__ . '/.ht.abc/.ht.sqlite';\n`);
const want = dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite'));
expect(resolveLocalSqlitePath(instance()).path).toBe(want);
});

it('glob only (no db-path.php): finds .ht.<hex>/.ht.sqlite', () => {
const want = dbFile(path.join(dbDir, '.ht.0123abcd', '.ht.sqlite'));
// Plugin housekeeping files also start with ".ht." and must not be mistaken for dirs.
writeFileSync(path.join(dbDir, '.ht.sqlite.lock'), 'x');
writeFileSync(path.join(dbDir, '.ht.sqlite.maintenance'), '');
const r = resolveLocalSqlitePath(instance());
expect(r).toMatchObject({ path: want, source: 'secret-dir', recordedPathIgnored: false });
// WordPress never scans for .ht.* dirs, so even a lone match is flagged.
expect(r.warnings).toHaveLength(1);
expect(r.warnings[0]).toContain('No usable db-path.php');
});

it('order: with no db-path.php, a secret dir wins over a legacy .ht.sqlite', () => {
const want = dbFile(path.join(dbDir, '.ht.0123abcd', '.ht.sqlite'), 'secret');
dbFile(path.join(dbDir, '.ht.sqlite'), 'legacy');
expect(resolveLocalSqlitePath(instance())).toMatchObject({ path: want, source: 'secret-dir' });
});

it.skipIf(process.platform === 'win32')('works when the instance path itself is reached through a symlink', () => {
const want = dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite'));
dbPathPhp('.ht.abc/.ht.sqlite');
const link = path.join(mkdtempSync(path.join(tmpdir(), 'iwp-link-')), 'home');
symlinkSync(root, link);
try {
expect(resolveLocalSqlitePath({ path: link })).toMatchObject({ path: want, source: 'db-path.php' });
} finally {
rmSync(path.dirname(link), { recursive: true, force: true });
}
});

it.each([['.ht.aaaa', '.ht.bbbb'], ['.ht.bbbb', '.ht.aaaa']])(
'glob with several matches: picks the newest by mtime and warns (newest=%s)', (newestDir, olderDir) => {
// Run with each dir as the newest, so directory-listing order cannot explain the pick.
const newest = dbFile(path.join(dbDir, newestDir, '.ht.sqlite'));
const older = dbFile(path.join(dbDir, olderDir, '.ht.sqlite'));
utimesSync(older, new Date('2020-01-01'), new Date('2020-01-01'));
utimesSync(newest, new Date('2026-01-01'), new Date('2026-01-01'));
const r = resolveLocalSqlitePath(instance());
expect(r.path).toBe(newest);
expect(r.source).toBe('secret-dir');
expect(r.warnings).toHaveLength(1);
expect(r.warnings[0]).toContain('Found 2 SQLite databases');
expect(r.warnings[0]).toContain(older);
});

it('unparseable db-path.php: warns and falls back to the glob', () => {
writeFileSync(path.join(dbDir, 'db-path.php'), '<?php return getenv("X");');
const want = dbFile(path.join(dbDir, '.ht.feed', '.ht.sqlite'));
const r = resolveLocalSqlitePath(instance());
expect(r).toMatchObject({ path: want, source: 'secret-dir', recordedPathIgnored: true });
expect(r.warnings[0]).toContain('could not be read');
});

it('legacy: uses wp-content/database/.ht.sqlite when nothing newer exists', () => {
const want = dbFile(path.join(dbDir, '.ht.sqlite'));
expect(resolveLocalSqlitePath(instance())).toMatchObject({ path: want, source: 'legacy', warnings: [] });
});

it('none found: returns null and lists every location checked', () => {
// Empty files are not databases.
mkdirSync(path.join(dbDir, '.ht.0123'));
writeFileSync(path.join(dbDir, '.ht.0123', '.ht.sqlite'), '');
writeFileSync(path.join(dbDir, '.ht.sqlite'), '');
const r = resolveLocalSqlitePath(instance());
expect(r.path).toBeNull();
expect(r.source).toBeNull();
expect(r.checked).toEqual([
path.join(dbDir, 'db-path.php'),
path.join(dbDir, '.ht.*', '.ht.sqlite'),
path.join(dbDir, '.ht.sqlite'),
path.join(dbDir, '.ht.sqlite.php'),
]);
});

it('none found when wp-content/database does not exist', () => {
rmSync(dbDir, { recursive: true });
const r = resolveLocalSqlitePath(instance());
expect(r.path).toBeNull();
expect(r.checked).toContain(path.join(dbDir, 'db-path.php'));
expect(r.checked).toContain(path.join(dbDir, '.ht.sqlite'));
});

it('wp-content/database is a file, not a dir: not found, no throw (runs on every local start)', () => {
rmSync(dbDir, { recursive: true });
writeFileSync(dbDir, 'not a dir');
expect(resolveLocalSqlitePath(instance()).path).toBeNull();
});

it('rejects a db-path.php path that traverses outside wp-content/database', () => {
// A REAL database exists at the traversal target, so only the containment check can refuse it.
const outside = dbFile(path.join(root, 'outside', '.ht.sqlite'), 'secret');
dbPathPhp('../../outside/.ht.sqlite');
const legacy = dbFile(path.join(dbDir, '.ht.sqlite'));
const r = resolveLocalSqlitePath(instance());
expect(r.path).not.toBe(outside);
expect(r).toMatchObject({ path: legacy, source: 'legacy', recordedPathIgnored: true });
expect(r.warnings[0]).toContain('outside wp-content/database');
});

it.skipIf(process.platform === 'win32')('rejects a secret dir that is a symlink to outside wp-content/database', () => {
dbFile(path.join(root, 'elsewhere', '.ht.sqlite'), 'secret');
symlinkSync(path.join(root, 'elsewhere'), path.join(dbDir, '.ht.0123abcd'));
dbPathPhp('.ht.0123abcd/.ht.sqlite');
const r = resolveLocalSqlitePath(instance());
expect(r.path).toBeNull();
expect(r.warnings[0]).toContain('outside wp-content/database');
});
});

describe('resolvePushSqlitePath (what local push --with-db may overwrite the cloud with)', () => {
it('pushes the recorded database', () => {
const want = dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite'));
dbPathPhp('.ht.abc/.ht.sqlite');
expect(resolvePushSqlitePath(instance())).toEqual({ path: want, warnings: [] });
});

it('refuses when db-path.php exists but points outside, even though a legacy DB exists', () => {
dbFile(path.join(root, 'outside', '.ht.sqlite'));
dbPathPhp('../../outside/.ht.sqlite');
dbFile(path.join(dbDir, '.ht.sqlite'));
const r = resolvePushSqlitePath(instance());
expect('error' in r && r.error).toContain('db-path.php exists but does not point to a usable database');
});

it('refuses when the recorded file is missing, even though a secret dir exists', () => {
dbPathPhp('.ht.gone/.ht.sqlite');
dbFile(path.join(dbDir, '.ht.other', '.ht.sqlite'));
const r = resolvePushSqlitePath(instance());
expect('error' in r && r.error).toContain('db-path.php exists');
});

it('pushes a legacy DB when there is no db-path.php', () => {
const want = dbFile(path.join(dbDir, '.ht.sqlite'));
expect(resolvePushSqlitePath(instance())).toEqual({ path: want, warnings: [] });
});

it('none found: the error lists every path checked', () => {
const r = resolvePushSqlitePath(instance());
expect('error' in r).toBe(true);
const msg = 'error' in r ? r.error : '';
for (const p of [path.join(dbDir, 'db-path.php'), path.join(dbDir, '.ht.*', '.ht.sqlite'), path.join(dbDir, '.ht.sqlite')]) {
expect(msg).toContain(p);
}
});
});

describe('buildServerArgs isClone (start an instance with a persisted DB in clone mode)', () => {
const inst = () => ({ name: 't', port: 9400, php: '8.3', wp: 'latest', path: root, createdAt: '' });
const mountsWholeWpContent = (args: string[]) => args.some((a) => a.includes('before-install'));

it('a DB at the db-path.php location → clone-mode mounts (database dir mounted after install)', () => {
dbFile(path.join(dbDir, '.ht.abc', '.ht.sqlite'));
dbPathPhp('.ht.abc/.ht.sqlite');
const args = buildServerArgs(inst());
expect(mountsWholeWpContent(args)).toBe(false);
expect(args.join(' ')).toContain(dbDir);
});

it('no DB yet → fresh-mode mount of the whole wp-content before install', () => {
expect(mountsWholeWpContent(buildServerArgs(inst()))).toBe(true);
});
});

describe('parseDbPathPhp', () => {
it('reads the __DIR__ literal in either quote style', () => {
expect(parseDbPathPhp("return __DIR__ . '/.ht.ab/.ht.sqlite';")).toBe('.ht.ab/.ht.sqlite');
expect(parseDbPathPhp('return __DIR__."/.ht.ab/.ht.sqlite";')).toBe('.ht.ab/.ht.sqlite');
});
it('returns null for anything else', () => {
expect(parseDbPathPhp("return '/abs/.ht.sqlite';")).toBeNull();
expect(parseDbPathPhp('<?php return getenv("X");')).toBeNull();
});
});

describe('isInsideDir', () => {
it('posix', () => {
expect(isInsideDir('/a/db', '/a/db/.ht.x/.ht.sqlite', path.posix)).toBe(true);
expect(isInsideDir('/a/db', '/a/db', path.posix)).toBe(false);
expect(isInsideDir('/a/db', '/a/dbx/.ht.sqlite', path.posix)).toBe(false);
expect(isInsideDir('/a/db', '/a/outside', path.posix)).toBe(false);
});
it('windows', () => {
const w = path.win32;
expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\wp-content\\database\\.ht.x\\.ht.sqlite', w)).toBe(true);
expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\wp-content\\databasex\\.ht.sqlite', w)).toBe(false);
expect(isInsideDir('C:\\s\\wp-content\\database', 'D:\\s\\wp-content\\database\\.ht.sqlite', w)).toBe(false);
expect(isInsideDir('C:\\s\\wp-content\\database', 'C:\\s\\outside\\.ht.sqlite', w)).toBe(false);
// ..foo is a legal name inside the dir, not a traversal
expect(isInsideDir('C:\\s\\db', 'C:\\s\\db\\..foo\\.ht.sqlite', w)).toBe(true);
});
});
17 changes: 13 additions & 4 deletions src/commands/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { listLocalFiles } from '../lib/sftp-sync.js';
import { sanitizeName, defaultInstanceName, pushTargetRef, parseTablePrefix, parseSqlTableNames } from '../lib/local-instance.js';
import { generateMysqlDump } from '../lib/sqlite-to-mysql.js';
import { loadSqlite } from '../lib/sqlite.js';
import { resolvePushSqlitePath } from '../lib/local-sqlite.js';
import { success, error, table, spinner, info, isJsonMode } from '../lib/output.js';
import type { LocalInstance, SshConnection } from '../types.js';

Expand Down Expand Up @@ -624,7 +625,10 @@ export function registerLocalCommand(program: Command): void {
const dbDir = join(dir, 'wp-content', 'database');
const sqliteDbPath = join(dbDir, '.ht.sqlite');

// Clean slate for database dir
// Clean slate for database dir. Load-bearing: sqlite-database-integration 3.x
// reads the path recorded in db-path.php first and only migrates a legacy
// .ht.sqlite when no recorded DB exists — so a leftover db-path.php + .ht.<hex>/
// would make WordPress silently ignore the .ht.sqlite written below.
if (existsSync(dbDir)) rmSync(dbDir, { recursive: true, force: true });
mkdirSync(dbDir, { recursive: true });

Expand Down Expand Up @@ -810,11 +814,16 @@ function isShellSafeUrl(u: string): boolean {
* (serialization-safe). Honors --dry-run / --no-backup / --force.
*/
async function pushDatabase(instance: LocalInstance, site: any, conn: SshConnection, opts: any): Promise<'done' | 'cancelled' | 'dry'> {
const sqlitePath = join(instance.path, 'wp-content', 'database', '.ht.sqlite');
if (!existsSync(sqlitePath)) {
error('No local database found (expected wp-content/database/.ht.sqlite). Skipping DB push.');
// sqlite-database-integration 3.x keeps the DB in a secret .ht.<hex>/ dir recorded
// in db-path.php, not at the legacy .ht.sqlite — see resolveLocalSqlitePath().
const resolved = resolvePushSqlitePath(instance);
for (const w of resolved.warnings) console.error(chalk.yellow('! ' + w));
if ('error' in resolved) {
error('Skipping DB push. ' + resolved.error);
process.exit(1);
}
const sqlitePath = resolved.path;
info(`Local database: ${chalk.dim(sqlitePath)}`);

const wpPath = remoteDocRoot(conn);

Expand Down
7 changes: 5 additions & 2 deletions src/lib/local-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { homedir } from 'node:os';
import net from 'node:net';
import chalk from 'chalk';
import { isJsonMode } from './output.js';
import { resolveLocalSqlitePath } from './local-sqlite.js';
import type { LocalInstance } from '../types.js';

const LOCAL_BASE_DIR = join(homedir(), '.instawp', 'local');
Expand Down Expand Up @@ -186,10 +187,12 @@ export function buildMountArgs(
return [`${opts.beforeInstall ? '--mount-before-install' : '--mount'}=${hostPath}:${vfsPath}`];
}

function buildServerArgs(instance: LocalInstance, blueprint?: string): string[] {
export function buildServerArgs(instance: LocalInstance, blueprint?: string): string[] {
const wpContentDir = join(instance.path, 'wp-content');
// "Has a persisted DB" — at the db-path.php / .ht.<hex>/ location of
// sqlite-database-integration 3.x, or the legacy .ht.sqlite.
const isClone = existsSync(join(instance.path, 'sqlite-import.sql')) ||
existsSync(join(wpContentDir, 'database', '.ht.sqlite'));
resolveLocalSqlitePath(instance).path !== null;

const args = [
'server',
Expand Down
Loading
Loading