diff --git a/bin/antigravity-direct.mjs b/bin/antigravity-direct.mjs index 4d27b4af55..32c642df72 100755 --- a/bin/antigravity-direct.mjs +++ b/bin/antigravity-direct.mjs @@ -57,6 +57,16 @@ import crypto from 'node:crypto'; import zlib from 'node:zlib'; import { parseProxyPort, parseProxyMillis } from './proxy-port.mjs'; +// #2953 (define, don't assign): store an externally-spelled key with +// define semantics, so "__proto__" becomes an own property instead of +// invoking the Object.prototype setter and "constructor"/"toString" +// shadow like any other key. +const defineValue = (obj, key, value) => { + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + return value; +}; + + const HOST = process.env.ANTIGRAVITY_DIRECT_HOST || '127.0.0.1'; // #2823: both env values go through the house helpers, like every other // bin/* proxy. A bare Number() let 'abc'/'18941.9'/'99999' reach listen() @@ -344,7 +354,7 @@ const resolveSchemaRefs = (root) => { const target = $ref.startsWith('#') ? lookup($ref) : undefined; const merged = (target === undefined || chain.includes($ref) || chain.length >= 10) ? {} : { ...walkSchema(target, [...chain, $ref]) }; - for (const [k, v] of Object.entries(siblings)) merged[k] = walkSchema(v, chain); + for (const [k, v] of Object.entries(siblings)) defineValue(merged, k, walkSchema(v, chain)); return merged; } const out = {}; @@ -352,11 +362,11 @@ const resolveSchemaRefs = (root) => { if (SCHEMA_VALUE_KEYS.has(k)) { out[k] = v; continue; } if (SCHEMA_MAP_KEYS.has(k) && isSchemaRecord(v)) { const sub = {}; - for (const [name, s] of Object.entries(v)) sub[name] = walkSchema(s, chain); + for (const [name, s] of Object.entries(v)) defineValue(sub, name, walkSchema(s, chain)); out[k] = sub; continue; } - out[k] = walkSchema(v, chain); + defineValue(out, k, walkSchema(v, chain)); } return out; }; @@ -394,7 +404,7 @@ const convertSchemaNode = (node) => { if (k === 'properties') { if (isSchemaRecord(v)) { const props = {}; - for (const [name, sub] of Object.entries(v)) props[name] = convertSchemaNode(sub); + for (const [name, sub] of Object.entries(v)) defineValue(props, name, convertSchemaNode(sub)); out.properties = props; } continue; diff --git a/bin/provider-catalog-sync.mjs b/bin/provider-catalog-sync.mjs index aa93208c86..c10fc4e019 100644 --- a/bin/provider-catalog-sync.mjs +++ b/bin/provider-catalog-sync.mjs @@ -60,6 +60,16 @@ import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; +// #2953 (define, don't assign): store an externally-spelled key with +// define semantics, so "__proto__" becomes an own property instead of +// invoking the Object.prototype setter and "constructor"/"toString" +// shadow like any other key. +const defineValue = (obj, key, value) => { + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + return value; +}; + + // --------------------------------------------------------------------------- // Provider source table. `modelsDev` is the provider id in models.dev's // api.json used as cross-check (null = no meaningful cross-check). @@ -430,7 +440,7 @@ function commonSuffix(names) { const counts = {}; for (const n of names) { const m = n.match(/(\([^)]*\))\s*$/); - if (m) counts[m[1]] = (counts[m[1]] ?? 0) + 1; + if (m) defineValue(counts, m[1], (Object.hasOwn(counts, m[1]) ? counts[m[1]] : 0) + 1); } const best = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]; return best ? best[0] : null; @@ -596,7 +606,7 @@ export async function runSync({ configPath, modelsDevSpec, sourceDir, runtimeCon const entry = { config_count: configIds.length }; if (!src) { entry.status = 'no-source-configured'; - report.providers[providerId] = entry; + defineValue(report.providers, providerId, entry); continue; } entry.source = src.kind; @@ -614,7 +624,7 @@ export async function runSync({ configPath, modelsDevSpec, sourceDir, runtimeCon entry.status = 'unverifiable'; entry.note = src.note; report.totals.unverifiable += 1; - report.providers[providerId] = entry; + defineValue(report.providers, providerId, entry); continue; } if (src.kind === 'proxy') { @@ -645,7 +655,7 @@ export async function runSync({ configPath, modelsDevSpec, sourceDir, runtimeCon for (const k of ['additions_validated', 'additions_unverified', 'vanishings']) { report.totals[k] += entry[k]?.length ?? 0; } - report.providers[providerId] = entry; + defineValue(report.providers, providerId, entry); } return { report, configText, config }; } @@ -707,7 +717,7 @@ export function renderPrBody(report, addedByProvider) { // Apply validated additions to the config text. Returns { text, added }. export function applyAdditions(configText, config, report, modelsDev) { let text = configText; - const added = {}; + const added = new Map(); for (const [pid, e] of Object.entries(report.providers)) { const ids = e.additions_validated ?? []; if (!ids.length) continue; @@ -718,11 +728,12 @@ export function applyAdditions(configText, config, report, modelsDev) { const clonedFrom = entry._clonedFrom; delete entry._clonedFrom; text = insertModelEntry(text, pid, id, entry); - (added[pid] ??= []).push(id); + if (!added.has(pid)) added.set(pid, []); + added.get(pid).push(id); if (clonedFrom) console.error(`[catalog-sync] ${pid}/${id}: variants cloned from sibling ${clonedFrom}`); } } - return { text, added }; + return { text, added: Object.fromEntries(added) }; } // Catalog-only guard: parse before/after and prove nothing outside the @@ -908,9 +919,9 @@ async function main(argv) { console.log( `[catalog-sync] skipping ${pid}: ${entry.additions_validated.length} validated addition(s) owned by sync-models (runtime overlay)`, ); - applyReport.providers[pid] = { ...entry, additions_validated: [] }; + defineValue(applyReport.providers, pid, { ...entry, additions_validated: [] }); } else { - applyReport.providers[pid] = entry; + defineValue(applyReport.providers, pid, entry); } } const { text, added } = applyAdditions(configText, config, applyReport, modelsDev); diff --git a/bin/record.mjs b/bin/record.mjs index 127ec5e16e..0db844a4fd 100644 --- a/bin/record.mjs +++ b/bin/record.mjs @@ -32,6 +32,24 @@ // agent sessions cannot interleave partial lines. The target file (and // its parent directory) is created on first append. Target override: // AI_RECORDINGS_FILE (default ~/git/ai_recordings.jsonl). +// +// Define semantics for externally-spelled keys (#2953). A value keyed by a +// name a caller, document, feed, file, peer or user can spell is stored with +// define semantics, never assignment semantics: the store is built in a Map +// or a null-prototype object and converted at the boundary with +// Object.fromEntries / spread, or the entry is written with +// Object.defineProperty. The non-conforming forms for external keys are +// obj[key] = v, obj[key] ??= ..., dst[k] = src[k] copy loops, and +// Object.assign(dst, src) with an externally-keyed src — all go through +// [[Set]], and for the one spelling "__proto__" [[Set]] invokes the +// Object.prototype setter instead of creating an own property, silently +// dropping the entry or moving the container's prototype. Keys are data: +// preserve, don't reject. Code-constructed tables whose keys are all +// internal are exempt. Probe matrix for every covered site — keys +// "__proto__" (string value), "__proto__" (object value), "constructor", +// "toString", and an ordinary key: the entry exists as an own property with +// its value, a JSON round-trip preserves it, and neither the container's +// prototype nor Object.prototype moves or gains own properties. import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; diff --git a/bin/sync-models.mjs b/bin/sync-models.mjs index 446875cf62..f5072db018 100755 --- a/bin/sync-models.mjs +++ b/bin/sync-models.mjs @@ -3,6 +3,16 @@ import fs from 'node:fs'; import path from 'node:path'; import { execSync } from 'node:child_process'; +// #2953 (define, don't assign): store an externally-spelled key with +// define semantics, so "__proto__" becomes an own property instead of +// invoking the Object.prototype setter and "constructor"/"toString" +// shadow like any other key. +const defineValue = (obj, key, value) => { + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + return value; +}; + + const KNOWN_ARGS = new Set(['--dry-run', '--verbose', '-v']); const unknownArgs = process.argv.slice(2).filter(arg => !KNOWN_ARGS.has(arg)); if (unknownArgs.length > 0) { @@ -507,12 +517,12 @@ async function run() { } } if (!grouped[baseId]) { - grouped[baseId] = { + defineValue(grouped, baseId, { baseId, name: m.name.replace(/\s*\((Low|Medium|High|Extra-Low)\)$/i, ''), efforts: new Set(), variants: {} - }; + }); } if (effort) { grouped[baseId].efforts.add(effort); @@ -564,7 +574,7 @@ async function run() { if (!prov.models[baseId]) { console.log(`[sync-models] + Adding ${targetProvider}/${baseId}`); - prov.models[baseId] = modelEntry; + defineValue(prov.models, baseId, modelEntry); edits.push({ set: [...modelsPath, baseId], value: modelEntry }); totalAdded++; } else { @@ -610,7 +620,7 @@ async function run() { if (!codexProv.models[m.slug]) { console.log(`[sync-models] + Adding openai-codex/${m.slug}`); - codexProv.models[m.slug] = entry; + defineValue(codexProv.models, m.slug, entry); edits.push({ set: [...modelsPath, m.slug], value: entry }); totalAdded++; } else { @@ -642,7 +652,7 @@ async function run() { }; } console.log(`[sync-models] + Adding google/${mId}`); - gProv.models[mId] = entry; + defineValue(gProv.models, mId, entry); edits.push({ set: ['provider', 'google', 'models', mId], value: entry }); totalAdded++; } @@ -667,7 +677,7 @@ async function run() { }; } if (VERBOSE) console.log(`[sync-models] + Adding openai/${mId}`); - oProv.models[mId] = entry; + defineValue(oProv.models, mId, entry); edits.push({ set: ['provider', 'openai', 'models', mId], value: entry }); totalAdded++; } @@ -692,7 +702,7 @@ async function run() { }; } if (VERBOSE) console.log(`[sync-models] + Adding cloudflare-gateway/${mId}`); - cfProv.models[mId] = entry; + defineValue(cfProv.models, mId, entry); edits.push({ set: ['provider', 'cloudflare-gateway', 'models', mId], value: entry }); totalAdded++; } diff --git a/pkgs/id/web/src/world-records.test.ts b/pkgs/id/web/src/world-records.test.ts index c102fe69ef..b412d58845 100644 --- a/pkgs/id/web/src/world-records.test.ts +++ b/pkgs/id/web/src/world-records.test.ts @@ -175,6 +175,40 @@ describe("world page records fetch (#1458)", () => { expect(socket.sent("records")).toHaveLength(7); }); + it("define semantics (#2953): prototype-spelled record keys from a peer frame are stored, not set", () => { + // The frame is built by JSON.parse so "__proto__" is a genuine own + // key of the records object, exactly as a peer-supplied frame + // delivers it. With assignment semantics (Object.assign) the object + // value would move the records object's prototype and the string + // value would be silently dropped; neither would render. + q("[data-world-records-refresh]").click(); + const objectFrame = JSON.parse( + '{"type":"records","records":{"__proto__":{"polluted":"no"},"constructor":"c-value","toString":"t-value","ordinary":1},"next_after":null}', + ) as Record; + socket.deliver(objectFrame); + const rendered = renderedRecords(); + expect(Object.hasOwn(rendered, "__proto__")).toBe(true); + expect(rendered["__proto__"]).toEqual({ polluted: "no" }); + expect(rendered["constructor"]).toBe("c-value"); + expect(rendered["toString"]).toBe("t-value"); + expect(rendered["ordinary"]).toBe(1); + // JSON round-trip preserved every key, and nothing polluted the + // shared prototype. + expect(JSON.parse(JSON.stringify(rendered))).toEqual(rendered); + expect(Object.hasOwn(Object.prototype, "polluted")).toBe(false); + expect(({} as Record)["polluted"]).toBeUndefined(); + + q("[data-world-records-refresh]").click(); + const stringFrame = JSON.parse( + '{"type":"records","records":{"__proto__":"string-value"},"next_after":null}', + ) as Record; + socket.deliver(stringFrame); + const renderedString = renderedRecords(); + expect(Object.hasOwn(renderedString, "__proto__")).toBe(true); + expect(renderedString["__proto__"]).toBe("string-value"); + expect(Object.getPrototypeOf(renderedString)).toBe(Object.prototype); + }); + it("rejects malformed snapshots without partial state changes and accepts the next valid snapshot", () => { const status = q("[data-world-status]"); const participantList = q("[data-world-participants]"); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index f9071afb1f..294dc7b27c 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -267,7 +267,12 @@ function initWorld(): void { break; case "records": { if (!recordsPending) return; - Object.assign(records, frame.records ?? {}); + // #2953 (define, don't assign): frame.records is peer-supplied, so + // its keys are stored with define semantics — Object.assign would + // run a "__proto__" key through the setter instead of storing it. + for (const [k, v] of Object.entries(frame.records ?? {})) { + Object.defineProperty(records, k, { value: v, writable: true, enumerable: true, configurable: true }); + } recordsAfter = frame.next_after ?? null; if (recordsAfter === null) { recordsPending = false; @@ -437,7 +442,9 @@ function initWorld(): void { throw new Error("World records changed while paging; refresh the host view"); } recordsSequence = result.records_sequence; - Object.assign(allRecords, result.records); + for (const [k, v] of Object.entries(result.records)) { + Object.defineProperty(allRecords, k, { value: v, writable: true, enumerable: true, configurable: true }); + } if (firstPage) { firstPage = false; cursor = result.snapshot?.current_sequence ?? 0; diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index a217ba6017..3738b05dfc 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -803,3 +803,23 @@ test/ cache/degraded), fixtures story, /health boot (#1137, #1147) ``` + +## Store contract: define semantics (#2953) + +Define semantics for externally-spelled keys (#2953). A value keyed by a +name a caller, document, feed, file, peer or user can spell is stored with +define semantics, never assignment semantics: the store is built in a Map +or a null-prototype object and converted at the boundary with +Object.fromEntries / spread, or the entry is written with +Object.defineProperty. The non-conforming forms for external keys are +obj[key] = v, obj[key] ??= ..., dst[k] = src[k] copy loops, and +Object.assign(dst, src) with an externally-keyed src — all go through +[[Set]], and for the one spelling "__proto__" [[Set]] invokes the +Object.prototype setter instead of creating an own property, silently +dropping the entry or moving the container's prototype. Keys are data: +preserve, don't reject. Code-constructed tables whose keys are all +internal are exempt. Probe matrix for every covered site — keys +"__proto__" (string value), "__proto__" (object value), "constructor", +"toString", and an ordinary key: the entry exists as an own property with +its value, a JSON round-trip preserves it, and neither the container's +prototype nor Object.prototype moves or gains own properties.