← reports

#6543 · Inherited-property settings checks and late RPC validation

BugPriority: MediumEffort: MediumpluginsGitHub issueOctober 29, 2026

Verdict: REPRODUCED · Root-cause confidence: high

Trusted base: 3bacfac9ed69d42392076e5b3da2815bec822cd8. Repeated by the same investigator in two separate clean worktrees. This is a service/hook-level reproduction, not a macOS live-app reproduction.

1. TL;DR

Plugin settings validation mistakes properties inherited from JavaScript’s object prototype for declared settings. Through the real plugin service, undeclared constructor and toString settings are accepted and written to a real migrated SQLite database, while an ordinary undeclared key is correctly refused. A plugin that explicitly declares constructor fails to start because registration incorrectly regards the inherited property as an existing setting. Separately, the real SDK query hook calls its host transport once for an unknown method or invalid input before reporting the corresponding validation error. Both clean runs show the same five expected regression failures and three passing controls; the performance comparison in the issue is not verified.

2. Claims vs findings

ClaimFindingEvidence
Undeclared built-in object names can be persisted as settingsVerifiedReal service updates accept constructor and toString; database reads contain the exact submitted values.
A plugin cannot declare constructor as its own settingVerifiedInstallation returns status error instead of running; registration uses the inherited-property-aware in operator.
Unknown RPC methods and invalid inputs reach the host before validationVerifiedEach invalid query invokes the recording transport once, then exposes unknown_method or invalid_input. A valid query also invokes it once and returns 7.
Keyed RPC results undergo a second general JSON checkVerified by source inspectioncallRpc uses jsonValueSchema.safeParse; the keyed read then uses jsonRecordSchema.parse. Not benchmarked.
A reported 1,000-row result improves from about 111 ms to 8.5 ms with a separate patchUnverifiedNo linked code was executed and no optimized parser was introduced. Neither timing nor speedup is claimed here.
Reserved __proto__ errors and all inherited names behave identicallyNot exhaustively testedRuntime probes cover constructor and toString only. Explicit reserved-name policy needs dedicated verification.

3. Environment

4. Minimal reproduction

  1. Prepare the trusted checkout and normal build prerequisites using these commands. The first full build in the investigation hit missing SDK dist entries; explicitly building the SDK first resolved that setup issue without production changes. Both full builds then passed (72 tasks each).
git clone https://github.com/get-bb/bb.git bb-6543
cd bb-6543
git checkout --detach 3bacfac9ed69d42392076e5b3da2815bec822cd8
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
# Save the complete tests shown below at their indicated paths.
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/slopcop-6543-settings.test.ts
pnpm exec turbo run test --filter=@get-bb/plugin-sdk -- src/testing/__tests__/slopcop-6543-rpc.test.tsx

The two final test commands intentionally exit 1 on this base. A repair should make all eight cases pass. In this base, settings has 3 failures and 2 passes; RPC has 2 failures and 1 pass.

Expected versus actual

Expected: undeclared settings updates fail and write no row; a valid own-property declaration loads; invalid RPC calls invoke transport zero times. Actual verbatim observations and test failures:

Settings observations

{"key":"constructor","failure":null,"stored":{"constructor":"\"probe\""}}
{"key":"toString","failure":null,"stored":{"toString":"\"probe\""}}
{"declared":"constructor","status":"error"}
AssertionError: expected null to be 'unknown setting "constructor"' // Object.is equality
AssertionError: expected null to be 'unknown setting "toString"' // Object.is equality
AssertionError: expected 'error' to be 'running' // Object.is equality
      Tests  3 failed | 2 passed (5)

RPC observations

{"method":"missing","input":{"count":1},"error":"unknown_method","calls":1}
{"method":"read","input":{"count":"bad"},"error":"invalid_input","calls":1}
AssertionError: expected "vi.fn()" to be called +0 times, but got 1 times
      Tests  2 failed | 1 passed (3)

The ordinary missing settings name and a normal declared setting pass, preventing a broken fixture or universal rejection from masquerading as the bug. The valid RPC case returns the expected value and passes.

Complete settings reproduction

Save as apps/server/test/services/plugins/slopcop-6543-settings.test.ts.

import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it } from "vitest";
import { createMigratedConnection } from "@bb/db/testing";
import { getPluginSettingsValues } from "@bb/db";
import { createPluginService } from "../../../src/services/plugins/plugin-service.js";
import { createAiServiceRegistry } from "../../../src/services/ai/ai-service-registry.js";
import { createNoopTelemetryService } from "../../../src/services/system/telemetry.js";
import { testLogger } from "../../helpers/test-app.js";

let db: ReturnType<typeof createMigratedConnection>;
let service: ReturnType<typeof createPluginService>;
let scratch: string;

beforeEach(async () => {
  db = createMigratedConnection();
  scratch = await mkdtemp(join(tmpdir(), "slopcop-settings-"));
  service = createPluginService({
    db,
    dataDir: join(scratch, "data"),
    aiServices: createAiServiceRegistry(),
    telemetry: createNoopTelemetryService(),
    logger: testLogger,
    appVersion: "0.9.0",
    loadTimeoutMs: 2000,
    hub: {
      getDaemonSessionIdForHost: () => null,
      notifyPluginChanged: () => {},
      onWatchedTargets: () => () => {},
      notifyPluginSignal: () => 0,
      notifySystem: () => {},
    },
  });
});

afterEach(async () => {
  await service.stop();
  db.$client.close();
  await rm(scratch, { recursive: true, force: true });
});

async function install(settingName: string) {
  const root = join(scratch, "fixture");
  await mkdir(root);
  await writeFile(
    join(root, "package.json"),
    JSON.stringify({
      name: "bb-plugin-slopcop-settings",
      version: "0.1.0",
      bb: {
        name: "Settings regression",
        description: "Temporary isolated fixture",
        branding: { icon: "Zap" },
        server: "./server.ts",
      },
    }),
  );
  await writeFile(
    join(root, "server.ts"),
    `
    export default function plugin(bb) {
      bb.settings.define({ [${JSON.stringify(settingName)}]: { type: "string", label: "Value" } });
    }
  `,
  );
  return service.installPath(root);
}

it.each(["constructor", "toString", "ordinaryMissing"])(
  "rejects an undeclared settings key without storing it: %s",
  async (key) => {
    const entry = await install("declared");
    expect(entry.status).toBe("running");
    const failure = await service
      .updateSettings(entry.id, { [key]: "probe" })
      .then(
        () => null,
        (error: Error) => error.message,
      );
    const stored = getPluginSettingsValues(db, entry.id);
    console.log(JSON.stringify({ key, failure, stored }));
    expect(failure).toBe(`unknown setting "${key}"`);
    expect(Object.hasOwn(stored, key)).toBe(false);
  },
);

it("allows a declared own-property name despite an inherited namesake", async () => {
  const entry = await install("constructor");
  console.log(
    JSON.stringify({ declared: "constructor", status: entry.status }),
  );
  expect(entry.status).toBe("running");
  await service.updateSettings(entry.id, { constructor: "declared value" });
  expect(getPluginSettingsValues(db, entry.id).constructor).toBe(
    '"declared value"',
  );
});

it("stores a normal declared setting as a positive control", async () => {
  const entry = await install("declared");
  expect(entry.status).toBe("running");
  await service.updateSettings(entry.id, { declared: "control" });
  expect(getPluginSettingsValues(db, entry.id).declared).toBe('"control"');
});

Complete RPC reproduction

Save as packages/plugin-sdk/src/testing/__tests__/slopcop-6543-rpc.test.tsx.

// @vitest-environment jsdom
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient } from "@tanstack/react-query";
import { expect, it, vi } from "vitest";
import { z } from "zod";
import { createRpcQueryHooks } from "../../internal/rpc-query-host.js";
import type { PluginRpcContract } from "../../rpc-contract.js";

it.each([
  { method: "missing", input: { count: 1 }, error: "unknown_method", calls: 0 },
  { method: "read", input: { count: "bad" }, error: "invalid_input", calls: 0 },
  { method: "read", input: { count: 1 }, error: null, calls: 1 },
])("validates before transport: $method / $error", async (sample) => {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false, gcTime: 0 } },
  });
  const call = vi.fn(async () => 7);
  const host = {
    pluginId: "regression",
    queryClient,
    call,
    subscribe: () => () => {},
  };
  const contract: PluginRpcContract = {
    read: { input: z.object({ count: z.number() }), output: z.number() },
  };
  const hooks = createRpcQueryHooks(() => host);
  const probe = renderHook(() =>
    hooks.experimental_useRpcQuery({
      contract,
      method: sample.method,
      input: sample.input,
    }),
  );
  try {
    await waitFor(() => expect(probe.result.current.isFetching).toBe(false));
    const error = probe.result.current.error?.code ?? null;
    console.log(
      JSON.stringify({
        method: sample.method,
        input: sample.input,
        error,
        calls: call.mock.calls.length,
      }),
    );
    expect(error).toBe(sample.error);
    if (sample.error === null) expect(probe.result.current.data).toBe(7);
    expect(call).toHaveBeenCalledTimes(sample.calls);
  } finally {
    probe.unmount();
    queryClient.clear();
  }
});

All reproduction source is inline to comply with the reports repository’s prohibition on publishing raw test files and logs. Raw local evidence remains outside the reports repository.

5. Root cause

Settings membership is prototype-aware rather than declaration-aware

packages/plugin-sdk/src/internal/host-policy.ts:273 uses key in target when registering settings. An empty ordinary object already inherits constructor and toString, so legitimate declarations collide before descriptor parsing.

if (key in target) {
  throw new Error(`setting "${key}" is already defined`);
}

packages/plugin-sdk/src/internal/host-policy.ts:358 looks up descriptors[key] and only checks its truthiness. For the tested inherited names, this produces a function instead of no descriptor. A string update falls through the descriptor-type-specific checks and passes validation.

apps/server/src/services/plugins/plugin-service.ts:1996 calls that validator and then the settings writer. apps/server/src/services/plugins/plugin-settings.ts:102 repeats a prototype-aware descriptor lookup and builds a row update. packages/db/src/data/plugin-storage.ts:90 persists these own enumerable row updates. The database observation therefore comes from the actual writer, not from a mocked store.

RPC transport precedes method/input checks

packages/plugin-sdk/src/internal/rpc-query-host.ts:107 awaits host.call, checks JSON response validity, and only afterward resolves the method contract and validates its input. A JSON-returning host therefore necessarily receives both rejected requests. A transport error can also win before local validation, but that additional behavior was not separately probed.

raw = await host.call(pluginId, method, input);
const result = jsonValueSchema.safeParse(raw);
const methodContract = contract[method];
const parsedInput = await methodContract.input["~standard"].validate(input);

packages/plugin-sdk/src/internal/rpc-query-host.ts:261 additionally parses keyed results with jsonRecordSchema.parse(response.result), after callRpc has already parsed JSON. packages/domain/src/json-value.ts:15 defines the recursive union schema. This establishes repeated traversal from source, not a quantified performance defect.

6. Proposed fix and automatic-fix safety

Use own-property membership for registered settings and settings lookups; define reserved-name behavior explicitly rather than relying on the object prototype. Resolve only owned RPC methods and validate the input before invoking transport, preserving response validation and error normalization. Keep JSON-parser optimization separate until acceptance semantics and benchmarks are established.

No automatic fix PR: the verified repair changes validation at the plugin/host trust boundary, which the caller explicitly excludes from simple automatic fixes. No production patch, fix branch, code push, protocol change, stored-data migration, or dependency change was made. No vulnerability or authorization bypass is asserted by this report. The tests demonstrate failures before any repair, not a passing post-fix result.

7. Linked PR review

PR #6547 is closed and unmerged. GitHub metadata reports 12 changed files, 1,827 additions and 41 deletions. No open linked pull request was found in the issue timeline or an open-PR search during this investigation.

Static inspection only: its production diff changes descriptor checks to own-property checks and moves RPC method/input checks ahead of transport, aligning with the causes verified here. It also adds general JSON parsing helpers, tag-validation changes, and extensive tests; these broader changes are outside this report’s executed evidence. Verdict: targeted direction for the two verified defects, not runtime-verified or approved as a complete patch. Its branch, test code and binaries were never checked out or executed; there are no claimed execution findings against that PR.

8. Verification

The same investigator created a second clean detached checkout at the exact full base commit, with a separate frozen dependency installation. Production files were unchanged (git diff --exit-code passed); only the two newly authored reproduction files were added. Every settings case created fresh temporary data. No ports were reused because neither reproduction started a listener.

pnpm exec turbo run test --force --filter=@bb/server -- test/services/plugins/slopcop-6543-settings.test.ts
pnpm exec turbo run test --force --filter=@get-bb/plugin-sdk -- src/testing/__tests__/slopcop-6543-rpc.test.tsx

--force ensured the second test processes actually ran instead of replaying cached test results. Both produced the same observed defects:

{"key":"constructor","failure":null,"stored":{"constructor":"\"probe\""}}
{"key":"toString","failure":null,"stored":{"toString":"\"probe\""}}
{"declared":"constructor","status":"error"}
AssertionError: expected null to be 'unknown setting "constructor"' // Object.is equality
AssertionError: expected null to be 'unknown setting "toString"' // Object.is equality
AssertionError: expected 'error' to be 'running' // Object.is equality
      Tests  3 failed | 2 passed (5)

{"method":"missing","input":{"count":1},"error":"unknown_method","calls":1}
{"method":"read","input":{"count":"bad"},"error":"invalid_input","calls":1}
AssertionError: expected "vi.fn()" to be called +0 times, but got 1 times
      Tests  2 failed | 1 passed (3)

Existing trusted-main suites were also run: plugin-settings-storage.test.ts passed 16/16 tests, and rpc-query-host.test.tsx passed 11/11. These passing adjacent suites do not cover the demonstrated edge cases.

Harness correction before the final first run: the new test’s database cleanup initially referenced a nonexistent sqlite property. It was corrected to the real db.$client.close(); the final results above have no cleanup failures. No production code changed. The second clean run required no correction.

This is repeat verification by the same agent, not independent verification. Confidence is high for the demonstrated service persistence and transport ordering; macOS live-app behavior, actual remote handler execution, all prototype keys, reserved-name UX, and performance timing remain outside scope.

9. Related issues and trust boundary

No additional issue was fetched from untrusted links. The verified mechanisms here are settings membership/persistence and SDK transport ordering; no duplicate issue is claimed. The supplied issue contained executable commands and external-branch instructions; they were treated as untrusted evidence and ignored. Only trusted origin/main code and the new probes derived from repository evidence were executed.

10. Appendix

Existing-suite commands:

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-settings-storage.test.ts
pnpm exec turbo run test --filter=@get-bb/plugin-sdk -- src/testing/__tests__/rpc-query-host.test.tsx
git diff --check
git diff --exit-code

Source links were checked against the recorded base, not a moving branch. GitHub metadata and the closed PR diff were read only. No issue-provided code, scripts, patches, branches, or test files were executed. There are no screenshots because this is a nonvisual validation defect.