Skip to content
Merged
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
18 changes: 14 additions & 4 deletions bin/antigravity-direct.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -344,19 +354,19 @@ 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 = {};
for (const [k, v] of Object.entries(node)) {
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;
};
Expand Down Expand Up @@ -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;
Expand Down
29 changes: 20 additions & 9 deletions bin/provider-catalog-sync.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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') {
Expand Down Expand Up @@ -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 };
}
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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);
Expand Down
18 changes: 18 additions & 0 deletions bin/record.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
24 changes: 17 additions & 7 deletions bin/sync-models.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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++;
}
Expand All @@ -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++;
}
Expand All @@ -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++;
}
Expand Down
34 changes: 34 additions & 0 deletions pkgs/id/web/src/world-records.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLButtonElement>("[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<string, unknown>;
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<string, unknown>)["polluted"]).toBeUndefined();

q<HTMLButtonElement>("[data-world-records-refresh]").click();
const stringFrame = JSON.parse(
'{"type":"records","records":{"__proto__":"string-value"},"next_after":null}',
) as Record<string, unknown>;
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<HTMLOutputElement>("[data-world-status]");
const participantList = q<HTMLElement>("[data-world-participants]");
Expand Down
11 changes: 9 additions & 2 deletions pkgs/id/web/src/world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
20 changes: 20 additions & 0 deletions pm-stack/aggregator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading