From 59721f97172acffffe960a6268a2916a90a6c554 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 14:37:25 +0000 Subject: [PATCH 1/2] fix(plugins): pin sync owners across source lifecycle awaits --- docs/plugin-platform/market-sources.md | 19 ++- electron/plugins/database.cjs | 27 +++- electron/plugins/database.test.cjs | 27 ++-- electron/plugins/pluginSyncSidecarService.cjs | 30 +++-- .../plugins/pluginSyncSidecarService.test.cjs | 18 +-- electron/plugins/sourceIsolation.test.cjs | 125 ++++++++++++++++++ 6 files changed, 211 insertions(+), 35 deletions(-) diff --git a/docs/plugin-platform/market-sources.md b/docs/plugin-platform/market-sources.md index 5f15b9e89..8218759f2 100644 --- a/docs/plugin-platform/market-sources.md +++ b/docs/plugin-platform/market-sources.md @@ -60,7 +60,7 @@ recovery and uninstall. Cross-source install or update is rejected, even when version and package bytes match. Local imports are a separate source. Private settings, view state, persistent and in-memory grants, secrets, and cloud -sidecars are namespaced by host-derived source identity. KV keys are qualified +sidecars are namespaced by host-derived source identity. Every source, including local imports, uses an opaque encoded owner; public plugin IDs are never storage-owner aliases in sync payloads. Before each sync entry and after every awaited contribution update/reset, the host rechecks that owner against the live source and contributions. Hydration captures its owner before yielding and never remaps a public ID for a later write. KV keys are qualified inside the existing per-plugin FK. Code, permissions and source configuration do not participate in cloud sync. Old-source cloud settings may remain orphaned; they cannot hydrate the same plugin ID from a different source. Generic KV still @@ -82,3 +82,20 @@ Tests use synthetic source responses and first-party packages. Passing tests is not a sandbox certification. Native UI, real third-party hosting, network availability and multi-device encrypted-sync acceptance must be reported separately. No real credentials or untrusted community code are needed for tests. + +## Source-owner integration + +Use `PluginDatabase.getActivePlugin(context.pluginId)` to require a current host +installation, then `database.privateOwner(plugin.id)` for an opaque data partition. +`plugin.source` is host-owned `{id, kind, name, origin}`. +`getRetainedPluginSource(pluginId)` returns a retained uninstall binding or null. +`publicPluginId(owner)` resolves only an encoded owner matching the current source; +it rejects raw public IDs and stale owners. Never accept owner/source from a plugin +request or invent a `pluginId` fallback. Capture owner/source at async operation +start and revalidate before committing; follow runtime lifecycle cancellation. + +Plugin database schema 7 atomically converts existing raw local private rows and +KV keys to the same encoded-owner model without deleting them. This is a one-time +conversion, not a parallel runtime compatibility path. A conflicting conversion +fails without publishing schema 7. Old raw-ID cloud entries remain orphaned and +cannot hydrate an installed plugin. Host/Vault/input schemas are unchanged. diff --git a/electron/plugins/database.cjs b/electron/plugins/database.cjs index ea1885e65..ff068f302 100644 --- a/electron/plugins/database.cjs +++ b/electron/plugins/database.cjs @@ -7,7 +7,7 @@ const { DatabaseSync } = require("node:sqlite"); const { LOCAL_SOURCE, assertSource, privateOwner } = require("./sourceIdentity.cjs"); -const SCHEMA_VERSION = 6; +const SCHEMA_VERSION = 7; const MAX_SECURITY_AUDIT_DETAILS_BYTES = 16 * 1024; const MAX_SECURITY_AUDIT_RECORDS_PER_PLUGIN = 1_000; const REQUIRED_SCHEMA_COLUMNS = Object.freeze({ @@ -241,6 +241,25 @@ class PluginDatabase { } this.db.exec("PRAGMA user_version = 6"); }); + if (version <= 6) this.transaction(() => { + // One-time conversion of existing local private rows; all sources now use + // immutable encoded owners. Never retain a raw-ID lookup fallback. + for (const table of ["plugin_settings", "plugin_view_state", "plugin_permission_grants", "plugin_secrets", "plugin_sync_sidecars"]) { + const rows = this.db.prepare(`SELECT DISTINCT plugin_id FROM ${table}`).all(); + for (const { plugin_id: id } of rows) { + if (/^[a-z0-9][a-z0-9.-]{1,127}$/u.test(id)) { + this.db.prepare(`UPDATE ${table} SET plugin_id = ? WHERE plugin_id = ?`).run(privateOwner(LOCAL_SOURCE, id), id); + } + } + } + for (const row of this.db.prepare("SELECT plugin_id, key FROM plugin_kv").all()) { + if (this.getPluginSource(row.plugin_id).id === "local") { + const prefix = `${privateOwner(LOCAL_SOURCE, row.plugin_id)}:`; + if (!row.key.startsWith(prefix)) this.db.prepare("UPDATE plugin_kv SET key = ? WHERE plugin_id = ? AND key = ?").run(prefix + row.key, row.plugin_id, row.key); + } + } + this.db.exec("PRAGMA user_version = 7"); + }); // Legacy-map backfill is deferred until PackageStore.recover() has finished // (hostService seeds after package initialize). Running here would promote // sole map candidates before recovered manifests are visible, then skip @@ -299,11 +318,11 @@ class PluginDatabase { // Opaque owners enter only from host sync storage, never plugin RPC identity. if (/^source:[a-f0-9]{64}:[a-z0-9][a-z0-9.-]{1,127}$/u.test(pluginId)) return pluginId; const source = this.getPluginSource(pluginId); - return source.id === "local" ? pluginId : privateOwner(source, pluginId); + return privateOwner(source, pluginId); } publicPluginId(owner) { - if (!owner.startsWith("source:")) return owner; + if (!/^source:[a-f0-9]{64}:[a-z0-9][a-z0-9.-]{1,127}$/u.test(owner)) return null; const pluginId = owner.slice(owner.lastIndexOf(":") + 1); return this.privateOwner(pluginId) === owner ? pluginId : null; } @@ -989,7 +1008,7 @@ class PluginDatabase { /** @type {Map>} */ const byProvider = new Map(); for (const row of legacyRows) { - const pluginId = row.plugin_id; + const pluginId = this.publicPluginId(row.plugin_id); const key = row.key; if (typeof pluginId !== "string" || typeof key !== "string") continue; if (!key.startsWith(legacyPrefix)) continue; diff --git a/electron/plugins/database.test.cjs b/electron/plugins/database.test.cjs index 8e8e94dad..1349c294b 100644 --- a/electron/plugins/database.test.cjs +++ b/electron/plugins/database.test.cjs @@ -6,6 +6,7 @@ const os = require("node:os"); const path = require("node:path"); const test = require("node:test"); const { DatabaseSync } = require("node:sqlite"); +const { privateOwner, LOCAL_SOURCE } = require("./sourceIdentity.cjs"); const { MAX_SECURITY_AUDIT_DETAILS_BYTES, @@ -488,7 +489,7 @@ test("schema upgrade backfills bindings from legacy sync-provider-map secrets", INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-provider-map:com.example.sync", "ref-legacy-map", Buffer.from("sealed"), @@ -499,7 +500,7 @@ test("schema upgrade backfills bindings from legacy sync-provider-map secrets", INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-credential", "ref-cred", Buffer.from("sealed-cred"), @@ -532,7 +533,7 @@ test("legacy map backfill does not overwrite an existing host binding", (context INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-provider-map:com.example.sync.foo", "ref-stale-parent-map", Buffer.from("sealed"), @@ -566,7 +567,7 @@ test("legacy map backfill skips when no candidate holds sync credentials", (cont database.db.prepare(` INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) - `).run(pluginId, key, `ref-${pluginId}`, Buffer.from("sealed"), now, now); + `).run(privateOwner(LOCAL_SOURCE, pluginId), key, `ref-${pluginId}`, Buffer.from("sealed"), now, now); } const promoted = database.backfillSyncProviderBindingsFromLegacySecrets(); assert.equal(promoted, 0, "map-only candidates must not bind without credentials"); @@ -589,7 +590,7 @@ test("legacy map backfill binds sole credential-backed owner when maps conflict" database.db.prepare(` INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) - `).run(pluginId, key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); + `).run(privateOwner(LOCAL_SOURCE, pluginId), key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); } const promoted = database.backfillSyncProviderBindingsFromLegacySecrets(); assert.equal(promoted, 1); @@ -618,7 +619,7 @@ test("legacy map backfill does not let longest map override credential-backed pa database.db.prepare(` INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) - `).run(pluginId, key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); + `).run(privateOwner(LOCAL_SOURCE, pluginId), key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); } const promoted = database.backfillSyncProviderBindingsFromLegacySecrets(); assert.equal(promoted, 1); @@ -648,7 +649,7 @@ test("legacy map backfill skips when multiple credential-backed candidates exist database.db.prepare(` INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) - `).run(pluginId, key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); + `).run(privateOwner(LOCAL_SOURCE, pluginId), key, `ref-${pluginId}-${key}`, Buffer.from(ciphertext), now, now); } const promoted = database.backfillSyncProviderBindingsFromLegacySecrets(); assert.equal(promoted, 0, "ambiguous credential-backed candidates must not auto-bind"); @@ -672,7 +673,7 @@ test("legacy map backfill still consumes maps after unbind tombstone blocks prom INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-provider-map:com.example.sync.foo", "ref-tombstone-map", Buffer.from("sealed"), @@ -683,7 +684,7 @@ test("legacy map backfill still consumes maps after unbind tombstone blocks prom INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-credential", "ref-cred", Buffer.from("secret"), @@ -711,7 +712,7 @@ test("legacy map backfill deletes promoted map markers so unbind cannot resurrec INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-provider-map:com.example.custom", "ref-plugin-owned", Buffer.from("plugin-owned-payload"), @@ -723,7 +724,7 @@ test("legacy map backfill deletes promoted map markers so unbind cannot resurrec INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-credential", "ref-cred-keep", Buffer.from("cred"), @@ -750,7 +751,7 @@ test("legacy map backfill does not resurrect after explicit unbind tombstone", ( INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) `).run( - "com.example", + privateOwner(LOCAL_SOURCE, "com.example"), "sync-provider-map:com.example.sync", "ref-leftover-map", Buffer.from("sealed"), @@ -823,7 +824,7 @@ test("inferPluginIdForSyncProvider never guesses from credential key prefixes", database.db.prepare(` INSERT INTO plugin_secrets(plugin_id, key, secret_ref, ciphertext, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) - `).run(pluginId, key, `ref-${pluginId}`, Buffer.from("x"), now, now); + `).run(privateOwner(LOCAL_SOURCE, pluginId), key, `ref-${pluginId}`, Buffer.from("x"), now, now); } // Parent prefix alone is not enough: a removed plugin may have owned // com.example.backup.sync while only com.example still has credentials. diff --git a/electron/plugins/pluginSyncSidecarService.cjs b/electron/plugins/pluginSyncSidecarService.cjs index 8d2b5249b..8f4f1f420 100644 --- a/electron/plugins/pluginSyncSidecarService.cjs +++ b/electron/plugins/pluginSyncSidecarService.cjs @@ -35,11 +35,16 @@ class PluginSyncSidecarService { sync: setting.sync === true, scope: setting.scope, })); - map.set(this.database.privateOwner?.(plugin.id) ?? plugin.id, fields); + map.set(this.database.privateOwner(plugin.id), fields); } return map; } + #isCurrentOwner(owner, publicId) { + return publicId !== null && this.database.publicPluginId(owner) === publicId + && this.#declaredSettingsByPlugin().has(owner); + } + /** * Build the sidecar bundle for inclusion in the encrypted cloud payload. */ @@ -170,12 +175,14 @@ class PluginSyncSidecarService { } } for (const entry of resetCandidates) { + const publicId = this.database.publicPluginId(entry.pluginId); + if (!this.#isCurrentOwner(entry.pluginId, publicId)) continue; const parsed = parseSettingsSidecarKey(entry.key); if (!parsed) continue; if (typeof this.contributionService?.resetSetting === "function") { try { await this.contributionService.resetSetting( - this.database.publicPluginId?.(entry.pluginId) ?? entry.pluginId, + publicId, parsed.settingId, parsed.scopeId, ); @@ -183,6 +190,7 @@ class PluginSyncSidecarService { // Validation rejected the reset (e.g. required setting) — still try // the stored-coordinate delete below for stale-scope rows. } + if (!this.#isCurrentOwner(entry.pluginId, publicId)) continue; // resetSetting normalizes against the *current* declared scope. After a // scope migration (application → device), that may miss the stale row // still stored under the old coordinates; always delete those too. @@ -201,6 +209,8 @@ class PluginSyncSidecarService { this.database.deleteSetting(entry.pluginId, parsed.settingId, parsed.scope, parsed.scopeId); } for (const entry of safe) { + const publicId = this.database.publicPluginId(entry.pluginId); + if (!this.#isCurrentOwner(entry.pluginId, publicId)) continue; if (entry.kind !== "settings") continue; const fields = declared.get(entry.pluginId); if (!fields) continue; @@ -218,12 +228,13 @@ class PluginSyncSidecarService { if (typeof this.contributionService?.updateSetting === "function") { try { await this.contributionService.updateSetting( - this.database.publicPluginId?.(entry.pluginId) ?? entry.pluginId, + publicId, parsed.settingId, entry.value, targetScopeId, { source: "host" }, ); + if (!this.#isCurrentOwner(entry.pluginId, publicId)) continue; // Preserve remote LWW timestamp after validated write (updateSetting uses clock). this.database.setSetting( entry.pluginId, @@ -312,12 +323,14 @@ class PluginSyncSidecarService { */ async hydrateInstalledPluginSettings(pluginId) { if (typeof pluginId !== "string" || pluginId.length < 1) return; - const declared = this.#declaredSettingsByPlugin().get(this.database.privateOwner?.(pluginId) ?? pluginId); + const owner = this.database.privateOwner(pluginId); + const declared = this.#declaredSettingsByPlugin().get(owner); if (!declared) return; const rows = typeof this.database.listSyncSidecars === "function" ? this.database.listSyncSidecars(pluginId) : []; for (const entry of rows) { + if (!this.#isCurrentOwner(owner, pluginId)) return; if (entry.kind !== "settings") continue; const parsed = parseSettingsSidecarKey(entry.key); if (!parsed) continue; @@ -347,8 +360,9 @@ class PluginSyncSidecarService { targetScopeId, { source: "host" }, ); + if (!this.#isCurrentOwner(owner, pluginId)) return; this.database.setSetting( - pluginId, + owner, parsed.settingId, targetScope, targetScopeId, @@ -358,7 +372,7 @@ class PluginSyncSidecarService { if (targetScope !== parsed.scope || targetScopeId !== parsed.scopeId) { try { this.database.deleteSetting( - pluginId, + owner, parsed.settingId, parsed.scope, parsed.scopeId, @@ -369,14 +383,14 @@ class PluginSyncSidecarService { if (typeof this.database.setSyncSidecar === "function") { try { this.database.setSyncSidecar( - pluginId, + owner, "settings", nextKey, entry.value, entry.updatedAt, ); if (nextKey !== entry.key && typeof this.database.deleteSyncSidecar === "function") { - this.database.deleteSyncSidecar(pluginId, "settings", entry.key); + this.database.deleteSyncSidecar(owner, "settings", entry.key); } } catch { // Sidecar re-key is best-effort after settings write. diff --git a/electron/plugins/pluginSyncSidecarService.test.cjs b/electron/plugins/pluginSyncSidecarService.test.cjs index 163687811..a85e876da 100644 --- a/electron/plugins/pluginSyncSidecarService.test.cjs +++ b/electron/plugins/pluginSyncSidecarService.test.cjs @@ -33,7 +33,7 @@ test("sidecar table has no package cascade and survives removePlugin", (context) database.removePlugin("com.example.sync"); assert.deepEqual(database.getSyncSidecar("com.example.sync", "account_baseline", "account"), { - pluginId: "com.example.sync", + pluginId: database.privateOwner("com.example.sync"), kind: "account_baseline", key: "account", value: { id: "acct" }, @@ -68,7 +68,7 @@ test("collectForSync excludes secrets and preserves missing-plugin baselines", ( const service = new PluginSyncSidecarService({ database, contributionService }); const bundle = service.collectForSync(); assert.equal(bundle.version, 1); - assert.ok(bundle.entries.some((entry) => entry.kind === "crdt_baseline" && entry.pluginId === "com.missing.plugin")); + assert.ok(bundle.entries.some((entry) => entry.kind === "crdt_baseline" && entry.pluginId === database.privateOwner("com.missing.plugin"))); assert.ok(bundle.entries.some((entry) => entry.kind === "settings" && entry.value === "dark")); assert.equal(bundle.entries.some((entry) => entry.value === "secret"), false); // Collected settings must land in the non-cascade table for post-uninstall collect. @@ -187,7 +187,7 @@ test("collectForSync omits deleted settings for installed plugins but keeps miss const bundle = service.collectForSync(); assert.equal(bundle.entries.some((e) => e.value === "stale"), false); assert.ok(bundle.entries.some((e) => e.value === "ok")); - assert.ok(bundle.entries.some((e) => e.pluginId === "com.missing.plugin" && e.value === "keep")); + assert.ok(bundle.entries.some((e) => e.pluginId === database.privateOwner("com.missing.plugin") && e.value === "keep")); }); test("applyFromSync preserves remote updatedAt when writing settings", async (context) => { @@ -210,7 +210,7 @@ test("applyFromSync preserves remote updatedAt when writing settings", async (co await service.applyFromSync({ version: 1, entries: [{ - pluginId: "com.example.sync", + pluginId: database.privateOwner("com.example.sync"), kind: "settings", key: "com.example.sync.theme\0application\0application", value: "dark", @@ -234,7 +234,7 @@ test("applyFromSync does not drop local baselines for plugins absent remotely", await service.applyFromSync({ version: 1, entries: [{ - pluginId: "com.remote.plugin", + pluginId: database.privateOwner("com.remote.plugin"), kind: "settings", key: "com.remote.plugin.theme\0application\0application", value: "light", @@ -243,8 +243,8 @@ test("applyFromSync does not drop local baselines for plugins absent remotely", }); const all = database.listAllSyncSidecars(); - assert.ok(all.some((entry) => entry.pluginId === "com.local.only")); - assert.ok(all.some((entry) => entry.pluginId === "com.remote.plugin" && entry.value === "light")); + assert.ok(all.some((entry) => entry.pluginId === database.privateOwner("com.local.only"))); + assert.ok(all.some((entry) => entry.pluginId === database.privateOwner("com.remote.plugin") && entry.value === "light")); }); test("hydrateInstalledPluginSettings applies retained sidecars through contribution service", async (context) => { @@ -449,7 +449,7 @@ test("applyFromSync does not resurrect missing-plugin keys deleted on another de await service.applyFromSync({ version: 1, entries: [{ - pluginId: "com.missing.plugin", + pluginId: database.privateOwner("com.missing.plugin"), kind: "settings", key: "com.missing.plugin.kept\0application\0application", value: "remote-new", @@ -498,7 +498,7 @@ test("applyFromSync keeps newer local baseline over older remote (LWW)", async ( await service.applyFromSync({ version: 1, entries: [{ - pluginId: "com.example.plugin", + pluginId: database.privateOwner("com.example.plugin"), kind: "crdt_baseline", key: "crdt", value: { clock: 50 }, diff --git a/electron/plugins/sourceIsolation.test.cjs b/electron/plugins/sourceIsolation.test.cjs index 76f1df0f4..f9b5d8331 100644 --- a/electron/plugins/sourceIsolation.test.cjs +++ b/electron/plugins/sourceIsolation.test.cjs @@ -6,6 +6,7 @@ const os = require("node:os"); const path = require("node:path"); const { PluginDatabase } = require("./database.cjs"); const { thirdPartySource, LOCAL_SOURCE } = require("./sourceIdentity.cjs"); +const { PluginContributionService } = require("./contributionService.cjs"); const { PluginSyncSidecarService } = require("./pluginSyncSidecarService.cjs"); const { settingsSidecarKey } = require("./pluginSyncSidecarHelpers.cjs"); const id = "example.plugin"; @@ -110,3 +111,127 @@ test("old-source cloud settings remain orphaned and cannot hydrate a new source" assert.equal(calls[0][0], id); assert.equal(db.getSetting(id, "greeting", "application", "application"), "new source"); }); + +test("in-flight sync cannot apply local B after A yields and B changes source", { timeout: 10000 }, async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-source-sync-race-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const db = new PluginDatabase(path.join(root, "db.sqlite")); + t.after(() => db.close()); + const a = "aa.plugin", b = "bb.plugin"; + const put = (pluginId, source) => db.installVersion({ pluginId, version: "1.0.0", manifest: { + id: pluginId, version: "1.0.0", main: { browser: "index.js" }, + contributes: { settings: [{ id: `${pluginId}.greeting`, label: "Greeting", control: "text", scope: "application", sync: true }] }, + }, archiveSha256: "a".repeat(64), packageRelativePath: `${pluginId}/1.0.0`, source }, { enable: true }); + put(a, LOCAL_SOURCE); put(b, LOCAL_SOURCE); + let release, entered; + const waiting = new Promise(resolve => { entered = resolve; }); + const paused = new Promise(resolve => { release = resolve; }); + const calls = []; + const contributionService = new PluginContributionService({ database: db, runtimeSupervisor: { + async notify(pluginId) { + calls.push(pluginId); + if (pluginId === a) { entered(); await paused; } + }, + } }); + const service = new PluginSyncSidecarService({ database: db, contributionService }); + const entries = [a, b].map(pluginId => ({ pluginId: db.privateOwner(pluginId), kind: "settings", key: settingsSidecarKey(`${pluginId}.greeting`, "application", "application"), value: `OLD ${pluginId}`, updatedAt: 1000 })); + const applying = service.applyFromSync({ version: 1, entries }); + await waiting; + db.removePlugin(b); db.clearUninstalledSourceData(b, "local"); put(b, first); + release(); await applying; + assert.deepEqual(calls, [a]); + assert.equal(db.getSetting(b, `${b}.greeting`, "application", "application"), undefined); +}); + +for (const mode of ["apply", "hydrate", "reset"]) { + test(`${mode} drops post-await writes after the current plugin changes source`, async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-source-await-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const db = new PluginDatabase(path.join(root, "db.sqlite")); + t.after(() => db.close()); + install(db, LOCAL_SOURCE); + const oldOwner = db.privateOwner(id); + const key = settingsSidecarKey("greeting", "application", "application"); + db.setSyncSidecar(id, "settings", key, "OLD", 1000); + db.setSetting(id, "greeting", "application", "application", "OLD", 1000); + let release, entered; + const waiting = new Promise(resolve => { entered = resolve; }); + const paused = new Promise(resolve => { release = resolve; }); + const service = new PluginSyncSidecarService({ database: db, contributionService: { + snapshot: () => ({ plugins: [{ id, settings: [{ id: "greeting", scope: "application", sync: true }] }] }), + async updateSetting(pluginId, settingId, value) { + db.setSetting(pluginId, settingId, "application", "application", value); + entered(); await paused; + }, + async resetSetting(pluginId, settingId) { + db.deleteSetting(pluginId, settingId, "application", "application"); + entered(); await paused; + }, + } }); + const applying = mode === "hydrate" ? service.hydrateInstalledPluginSettings(id) + : service.applyFromSync({ version: 1, entries: mode === "reset" ? [] : [{ pluginId: oldOwner, kind: "settings", key, value: "OLD REMOTE", updatedAt: 2000 }] }); + await waiting; + db.removePlugin(id); db.clearUninstalledSourceData(id, "local"); install(db, first); + db.setSetting(id, "greeting", "application", "application", "NEW", 3000); + release(); await applying; + assert.equal(db.getSetting(id, "greeting", "application", "application"), "NEW"); + assert.equal(db.listAllSettings().some(row => row.pluginId === oldOwner), false, "a completed reset must not be undone by stale LWW writes"); + }); +} + +test("local owners are encoded and raw remote IDs never resolve into another source", async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-source-local-owner-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const db = new PluginDatabase(path.join(root, "db.sqlite")); + t.after(() => db.close()); + install(db, LOCAL_SOURCE); + const owner = db.privateOwner(id); + assert.notEqual(owner, id); + assert.equal(db.publicPluginId(id), null); + assert.equal(db.publicPluginId(owner), id); + db.removePlugin(id); db.clearUninstalledSourceData(id, "local"); install(db, first); + assert.equal(db.publicPluginId(owner), null); + const calls = []; + const service = new PluginSyncSidecarService({ database: db, contributionService: { + snapshot: () => ({ plugins: [{ id, settings: [{ id: "greeting", scope: "application", sync: true }] }] }), + updateSetting: (...args) => calls.push(args), + } }); + await service.applyFromSync({ version: 1, entries: [{ pluginId: id, kind: "settings", key: settingsSidecarKey("greeting", "application", "application"), value: "RAW OLD LOCAL", updatedAt: 1000 }] }); + assert.deepEqual(calls, []); + assert.equal(db.getSetting(id, "greeting", "application", "application"), undefined); +}); + +test("schema-6 raw local data converts atomically without a runtime fallback", (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-source-owner-upgrade-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const file = path.join(root, "db.sqlite"); + let db = new PluginDatabase(file); + install(db, LOCAL_SOURCE); + db.setSetting(id, "greeting", "application", "application", "RETAIN"); + db.setValue(id, "key", "KEEP KV"); + const owner = db.privateOwner(id); + db.db.prepare("UPDATE plugin_settings SET plugin_id = ? WHERE plugin_id = ?").run(id, owner); + db.db.prepare("UPDATE plugin_kv SET key = 'key' WHERE plugin_id = ?").run(id); + db.db.exec("PRAGMA user_version = 6"); + db.close(); + db = new PluginDatabase(file); t.after(() => db.close()); + assert.equal(db.getSetting(id, "greeting", "application", "application"), "RETAIN"); + assert.equal(db.getValue(id, "key"), "KEEP KV"); + assert.deepEqual(db.listKeys(id), ["key"]); + assert.equal(db.listAllSettings()[0].pluginId, owner); + assert.equal(db.db.prepare("PRAGMA user_version").get().user_version, 7); +}); + +test("owner conversion conflict preserves schema-6 rows and does not publish schema 7", (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-source-owner-conflict-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const file = path.join(root, "db.sqlite"); + const db = new PluginDatabase(file); t.after(() => db.close()); + install(db, LOCAL_SOURCE); + db.setSetting(id, "greeting", "application", "application", "ENCODED"); + db.db.prepare("INSERT INTO plugin_settings(plugin_id,setting_id,scope,scope_id,value_json,updated_at) VALUES(?, 'greeting', 'application', 'application', ?, 1)").run(id, JSON.stringify("RAW")); + db.db.exec("PRAGMA user_version = 6"); + assert.throws(() => new PluginDatabase(file, { database: db.db }), /UNIQUE constraint/); + assert.equal(db.db.prepare("PRAGMA user_version").get().user_version, 6); + assert.equal(db.db.prepare("SELECT count(*) AS count FROM plugin_settings").get().count, 2); +}); From 4213d8e6726c44e7a479418ece3adf16ea494782 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 14:48:46 +0000 Subject: [PATCH 2/2] fix(plugins): distinguish third-party catalog status copy --- application/i18n/locales/en/core.ts | 3 +++ application/i18n/locales/es/core.ts | 3 +++ application/i18n/locales/ru/core.ts | 3 +++ application/i18n/locales/zh-CN/core.ts | 3 +++ application/i18n/locales/zh-TW/core.ts | 3 +++ .../tabs/PluginInfo.interaction.test.tsx | 22 ++++++++++++++++++- .../settings/tabs/PluginMarketplace.tsx | 4 ++-- components/settings/tabs/PluginStatus.tsx | 6 ++--- 8 files changed, 41 insertions(+), 6 deletions(-) diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 0c994c869..07a899f80 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -1298,6 +1298,9 @@ Highlight the focused split pane: "settings.plugins.manager.data": "Local KV stays on this device. Only non-secret settings explicitly marked for sync participate in encrypted cloud sidecars. Packages and permission grants do not sync.", "settings.plugins.market.results": "{count} plugins", "settings.plugins.manager.lastError": "Last recorded error", + "settings.plugins.sources.offline": "Source unavailable. If a previously validated catalog exists for this source, it remains available for browsing only. Installation is unavailable until refresh succeeds.", + "settings.plugins.sources.note": "This catalog is provided by the selected third party, not curated by Netcatty. Review the source domain and permissions before installing. Updates are manual.", + "settings.plugins.sources.sourceOnly": "Source-only entry from this provider. No downloadable package is available; review the author’s build and import instructions.", "settings.plugins.market.offline": "Registry unavailable. Showing the last valid catalog or bundled examples. Installation is unavailable until refresh succeeds.", "settings.plugins.manager.details": "View details", "settings.plugins.manager.noDescription": "No description provided.", diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index 16e90785d..a83b9c8f7 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -1298,6 +1298,9 @@ Resalta el panel dividido enfocado: "settings.plugins.manager.data": "Los datos KV permanecen en este dispositivo. Solo los ajustes no secretos marcados para sincronización participan en los datos auxiliares cifrados. Los paquetes y las autorizaciones no se sincronizan.", "settings.plugins.market.results": "{count} plugins", "settings.plugins.manager.lastError": "Último error registrado", + "settings.plugins.sources.offline": "Fuente no disponible. Si existe un catálogo validado en caché de esta fuente, solo se permite consultarlo. La instalación no estará disponible hasta que se actualice correctamente.", + "settings.plugins.sources.note": "Este catálogo lo proporciona el tercero seleccionado; Netcatty no lo selecciona ni revisa. Comprueba el dominio y los permisos antes de instalar. Las actualizaciones son manuales.", + "settings.plugins.sources.sourceOnly": "Entrada de código fuente de este proveedor. No hay un paquete descargable; consulta las instrucciones de compilación e importación del autor.", "settings.plugins.market.offline": "El registro no está disponible. Se muestra el último catálogo válido o los ejemplos incluidos. La instalación requiere una actualización correcta.", "settings.plugins.manager.details": "Ver detalles", "settings.plugins.manager.noDescription": "No se proporcionó una descripción.", diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index ad07f9a05..16e67ff4e 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -1193,6 +1193,9 @@ export const ruCoreMessages: Messages = { "settings.plugins.manager.data": "Данные KV остаются на устройстве. Синхронизируются только явно отмеченные несекретные настройки в зашифрованных данных. Пакеты и разрешения не синхронизируются.", "settings.plugins.market.results": "Плагинов: {count}", "settings.plugins.manager.lastError": "Последняя записанная ошибка", + "settings.plugins.sources.offline": "Источник недоступен. Ранее проверенный каталог этого источника, если он есть в кэше, доступен только для просмотра. Установка недоступна до успешного обновления.", + "settings.plugins.sources.note": "Этот каталог предоставляет выбранная третья сторона; Netcatty не отбирает его содержимое. Перед установкой проверьте домен источника и разрешения. Обновления выполняются вручную.", + "settings.plugins.sources.sourceOnly": "Запись с исходным кодом от этого поставщика. Пакет для загрузки отсутствует; см. инструкции автора по сборке и импорту.", "settings.plugins.market.offline": "Реестр недоступен. Показан последний корректный каталог или встроенные примеры. Для установки необходимо успешно обновить каталог.", "settings.plugins.manager.details": "Подробнее", "settings.plugins.manager.noDescription": "Описание не предоставлено.", diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index dd870b5e3..cae321640 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -1213,6 +1213,9 @@ Vaults 标签保持扁平,不使用这块背景。 "settings.plugins.manager.data": "本地 KV 仅保留在此设备。只有明确标记为同步的非秘密设置进入加密云 sidecar。插件包和权限授权不参与同步。", "settings.plugins.market.results": "{count} 个插件", "settings.plugins.manager.lastError": "上次记录的错误", + "settings.plugins.sources.offline": "来源暂不可用。如已缓存此来源通过校验的目录,仅可继续浏览;刷新成功前无法安装。", + "settings.plugins.sources.note": "此目录由所选第三方提供,不属于 Netcatty 精选目录。安装前请核对来源域名和权限,更新需手动确认。", + "settings.plugins.sources.sourceOnly": "此提供方仅提供源码条目,没有可下载插件包;请查看作者的构建和导入说明。", "settings.plugins.market.offline": "官方目录暂时不可用,正在显示上次有效目录或内置示例。刷新成功前不能从市场安装。", "settings.plugins.manager.details": "查看详情", "settings.plugins.manager.noDescription": "作者暂未提供功能简介。", diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index 5b6a84809..be472f3fb 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -1241,6 +1241,9 @@ Vaults 分頁維持扁平,不使用這塊背景。 'settings.plugins.loading': '正在載入外掛程式設定…', "settings.plugins.market.results": "{count} 個插件", "settings.plugins.manager.lastError": "上次記錄的錯誤", + "settings.plugins.sources.offline": "來源暫不可用。如已快取此來源通過驗證的目錄,僅可繼續瀏覽;重新整理成功前無法安裝。", + "settings.plugins.sources.note": "此目錄由所選第三方提供,不屬於 Netcatty 精選目錄。安裝前請核對來源網域和權限,更新需手動確認。", + "settings.plugins.sources.sourceOnly": "此提供方僅提供原始碼項目,沒有可下載外掛套件;請查看作者的建置和匯入說明。", "settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市場安裝。", "settings.plugins.manager.details": "查看詳情", "settings.plugins.manager.noDescription": "作者尚未提供功能簡介。", diff --git a/components/settings/tabs/PluginInfo.interaction.test.tsx b/components/settings/tabs/PluginInfo.interaction.test.tsx index ce6f6910d..1c96364b2 100644 --- a/components/settings/tabs/PluginInfo.interaction.test.tsx +++ b/components/settings/tabs/PluginInfo.interaction.test.tsx @@ -104,8 +104,28 @@ test('information previews on hover/focus, pins on click and Escape returns focu await act(async () => { healthy.click(); await settle(); }); assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /Updates are manual/); await act(async () => { document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); await settle(); }); + const thirdParty: NetcattyPluginSource = { id: 'third-party:synthetic', kind: 'third-party', name: 'Independent source', origin: 'https://example.com' }; + await act(async () => { root.render( {}} />); await settle(); }); + const thirdStatus = document.querySelector('button[aria-label$="Notices: 1"]')!; + await act(async () => { thirdStatus.focus(); await settle(); }); + const thirdPreview = document.querySelector('[role="tooltip"]')?.textContent ?? ''; + assert.match(thirdPreview, /provided by the selected third party/); + assert.match(thirdPreview, /If a previously validated catalog exists for this source/); + assert.doesNotMatch(thirdPreview, /bundled examples|Curated open-source|First-party/); + assert.equal(document.querySelector('[role="tooltip"] button'), null); + await act(async () => { thirdStatus.click(); await settle(); }); + assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /ECONNREFUSED/); + assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /Retry/); + assert.doesNotMatch(document.querySelector('[role="dialog"]')?.textContent ?? '', /bundled examples|Curated open-source/); + await act(async () => { document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); await settle(); }); + await act(async () => { root.render( {}} />); await settle(); }); + const sourceInfo = document.querySelector('button[aria-label="Source example"]')!; + await act(async () => { sourceInfo.click(); await settle(); }); + assert.match(document.querySelector('[role="dialog"]')?.textContent ?? '', /Source-only entry from this provider/); + assert.doesNotMatch(document.querySelector('[role="dialog"]')?.textContent ?? '', /First-party/); + await act(async () => { document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); await settle(); }); } finally { - await act(async () => root.unmount()); + await act(async () => { root.unmount(); await settle(); }); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); diff --git a/components/settings/tabs/PluginMarketplace.tsx b/components/settings/tabs/PluginMarketplace.tsx index 479f89b12..5f2f248cc 100644 --- a/components/settings/tabs/PluginMarketplace.tsx +++ b/components/settings/tabs/PluginMarketplace.tsx @@ -67,7 +67,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec }; const refresh = !entry && ; return
- {toolbarContainer ? createPortal(<>{refresh}, toolbarContainer) :
{refresh}
} + {toolbarContainer ? createPortal(<>{refresh}, toolbarContainer) :
{refresh}
} {catalog.error &&

{catalog.error}

}
{!entry &&
@@ -98,7 +98,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec

{entry.description}

{entry.repository} @ {entry.commit.slice(0, 12)} {conflictingInstall &&

{t('settings.plugins.sources.conflict')} {conflictingInstall.source?.origin ?? t('settings.plugins.sources.local')}

} - {entry.artifact ?

{t('settings.plugins.market.installNote')}

{catalog.listError &&

{t('settings.plugins.market.offlineShort')}

}
:
{t('settings.plugins.market.sourceBadge')}{t('settings.plugins.market.sourceOnly')}
} + {entry.artifact ?

{t('settings.plugins.market.installNote')}

{catalog.listError &&

{t('settings.plugins.market.offlineShort')}

}
:
{t('settings.plugins.market.sourceBadge')}{t(marketSource?.kind === 'third-party' ? 'settings.plugins.sources.sourceOnly' : 'settings.plugins.market.sourceOnly')}
}

{t('settings.plugins.market.manifest')}

README

{t('settings.plugins.market.readmeNote')}
{catalog.readmeStatus === 'loading' &&

{t('settings.plugins.loading')}

} {catalog.readmeStatus === 'error' &&

{catalog.readmeError}

} diff --git a/components/settings/tabs/PluginStatus.tsx b/components/settings/tabs/PluginStatus.tsx index 6d69ea7a1..7fc6ce527 100644 --- a/components/settings/tabs/PluginStatus.tsx +++ b/components/settings/tabs/PluginStatus.tsx @@ -3,12 +3,12 @@ import { useI18n } from '../../../application/i18n/I18nProvider'; import { Button } from '../../ui/button'; import { PluginInfo } from './PluginInfo'; -export function PluginStatus({ noVault, offlineError, retry }: { noVault?: boolean; offlineError?: string | null; retry?: () => void }) { +export function PluginStatus({ noVault, offlineError, retry, sourceKind }: { sourceKind?: NetcattyPluginSource['kind']; noVault?: boolean; offlineError?: string | null; retry?: () => void }) { const { t } = useI18n(); const count = Number(Boolean(noVault)) + Number(Boolean(offlineError)); - const explanation = <>{noVault &&

{t('settings.plugins.manager.noVault')}

}{offlineError && <>

{t('settings.plugins.market.offline')}

{offlineError}

}; + const explanation = <>{noVault &&

{t('settings.plugins.manager.noVault')}

}{offlineError && <>

{t(sourceKind === 'third-party' ? 'settings.plugins.sources.offline' : 'settings.plugins.market.offline')}

{offlineError}

}; const label = count ? `${t('settings.plugins.info')} · ${t('settings.plugins.status', { count })}` : t('settings.plugins.info'); - const help = <>

{t('settings.plugins.manager.preview')}

{t('settings.plugins.market.note')}

; + const help = <>

{t('settings.plugins.manager.preview')}

{t(sourceKind === 'third-party' ? 'settings.plugins.sources.note' : 'settings.plugins.market.note')}

; const preview = <>{count > 0 &&

{t('settings.plugins.status', { count })}

}{explanation}{help}; return {explanation}{offlineError && retry && }{count > 0 &&
}{help}
; }