Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Support Vault secret values up to 64 KiB (#6488)

Hazenixe3ea7e6660e6
diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml
index 56177b60e6..93a31f4a93 100644
--- a/.github/workflows/prepare-release.yml
+++ b/.github/workflows/prepare-release.yml
@@ -88,6 +88,8 @@ jobs:
- name: Commit the version bump
env:
+ GH_TOKEN: ${{ github.token }}
+ PREVIOUS_VERSION: ${{ steps.version.outputs.current }}
VERSION: ${{ steps.version.outputs.next }}
run: |
npm pkg set "version=$VERSION"
@@ -97,9 +99,19 @@ jobs:
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "release/v$VERSION"
node scripts/tighten-ratchets.mjs
- node scripts/record-data-format.mjs
+ published_format=()
+ previous_format=$(node -p 'const {reads, writes} = require("./server/data-format-released.json"); [reads, writes].join(":")')
+ if [[ "$previous_format" == "2:1" ]]; then
+ published_tag=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq ".[] | select(.tag_name == \"v$PREVIOUS_VERSION\" and .draft == false and .prerelease == false) | .tag_name")
+ if [[ -n "$published_tag" ]]; then
+ git fetch --no-tags origin "refs/tags/$published_tag:refs/tags/$published_tag"
+ git show "refs/tags/$published_tag:server/data-format-released.json" > "$RUNNER_TEMP/published-format.json"
+ published_format=("$RUNNER_TEMP/published-format.json")
+ fi
+ fi
+ node scripts/record-data-format.mjs "${published_format[@]}"
node scripts/generate-locale.mjs --record-hashes
- git add package.json server/data-format-released.json scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts src/locales/source-hashes.json
+ git add package.json server/data-format.ts server/data-format-released.json scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts src/locales/source-hashes.json
git commit -m "chore(release): bump version to $VERSION"
git push --set-upstream origin "release/v$VERSION"
@@ -109,11 +121,18 @@ jobs:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ steps.version.outputs.next }}
run: |
+ body="Bumps OpenMausBot to \`$VERSION\`. Merging this PR automatically starts the existing release workflow and assembles a draft release from the exact merge commit."
+ # A bump that raises the written data format changes what the app does, so its PR says so.
+ if ! git diff --quiet HEAD~1 HEAD -- server/data-format.ts; then
+ body="$body
+
+ **This bump also raises the data format this version writes** (\`server/data-format.ts\`). Data it writes can be read only by the previous published release and newer; older versions refuse to start on it."
+ fi
url=$(gh pr create \
--base main \
--head "release/v$VERSION" \
--title "chore(release): bump version to $VERSION" \
- --body "Bumps OpenMausBot to \`$VERSION\`. Merging this PR automatically starts the existing release workflow and assembles a draft release from the exact merge commit.")
+ --body "$body")
echo "url=$url" >> "$GITHUB_OUTPUT"
echo "### Release PR" >> "$GITHUB_STEP_SUMMARY"
echo "$url" >> "$GITHUB_STEP_SUMMARY"
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1b0ed470f6..4c8df3d28d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -149,6 +149,9 @@ Such a change ships in **two releases**:
2. **Write it one release later.** Start writing the new format and raise
`writes` to match. The release before can already read it.
+For Vault values over 4 KiB, **Prepare next release** advances `writes` to 2
+when the preceding published release's tag confirms format 2 read support.
+
The rule is between one release and the next. The stable channel may skip
releases, so going back from one stable version to the one before it can cross
both steps; there the updater's copy of the data is the way back, and the
@@ -175,9 +178,9 @@ sessions into `engine-homes/`, the old data folder's rename). They stay as
they are. The marker does not replace them; it adds the one thing they cannot
do, which is to stop an older version at the door.
-**What the marker protects today: nothing yet.** Both numbers are 1 and no
-version writes format 2, so the marker has never stopped a server, and a
-rollback of one release can still lose data without it noticing:
+**What the marker protects.** Once a release writes format 2, it stops
+older servers that cannot read it. Unrecorded format changes can still
+cause data loss on rollback:
- Many JSON stores accept only `"version": 1` and throw, or start empty, on
anything else: among them `server/command-allowlist.ts`, `server/fleet.ts`,
@@ -196,8 +199,10 @@ rollback of one release can still lose data without it noticing:
made, restored into an older server, is not stopped by it.
- A marker that cannot be read (empty or full of NULs after a power loss, not
readable by the server's user) counts as format 1 while `writes` is 1, and
- a marker that cannot be written is said in the log and skipped: the check
- must never be the reason a healthy install does not start.
+ a marker that cannot be written is said in the log and skipped: while a
+ version writes nothing newer, the check must never be the reason a healthy
+ install does not start. Once `writes` is 2, an unreadable marker, or one
+ that cannot be written, stops startup before any store opens.
For the rule to hold by itself, these would have to change:
diff --git a/scripts/record-data-format.mjs b/scripts/record-data-format.mjs
index 2d8ae7c8d9..61d9a30155 100644
--- a/scripts/record-data-format.mjs
+++ b/scripts/record-data-format.mjs
@@ -4,10 +4,12 @@ import { readFileSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
const ROOT = new URL("../", import.meta.url);
+const FORMAT_SOURCE = new URL("server/data-format.ts", ROOT);
+const FORMAT_DECLARATION = /export const DATA_FORMAT = \{ writes: (\d+), reads: (\d+) \} as const;/;
/** The numbers of `export const DATA_FORMAT = { writes: N, reads: M }` in server/data-format.ts. */
export function declaredDataFormat(source) {
- const match = /export const DATA_FORMAT = \{ writes: (\d+), reads: (\d+) \} as const;/.exec(source);
+ const match = FORMAT_DECLARATION.exec(source);
if (!match) throw new Error("server/data-format.ts no longer declares DATA_FORMAT as { writes: N, reads: M }");
return { writes: Number(match[1]), reads: Number(match[2]) };
}
@@ -16,7 +18,21 @@ export function releasedRecord(version, source) {
return `${JSON.stringify({ version, ...declaredDataFormat(source) }, null, 2)}\n`;
}
+export function enableLargeVaultWrites(source, previous, published) {
+ const { writes, reads } = declaredDataFormat(source);
+ if (writes !== 1 || reads !== 2 || previous.reads !== 2) return source;
+ if (!published || published.version !== previous.version || published.reads !== 2 || published.writes !== previous.writes) return source;
+ return source.replace(FORMAT_DECLARATION, "export const DATA_FORMAT = { writes: 2, reads: 2 } as const;");
+}
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const { version } = JSON.parse(readFileSync(new URL("package.json", ROOT), "utf8"));
- writeFileSync(new URL("server/data-format-released.json", ROOT), releasedRecord(version, readFileSync(new URL("server/data-format.ts", ROOT), "utf8")));
+ const record = new URL("server/data-format-released.json", ROOT);
+ const source = readFileSync(FORMAT_SOURCE, "utf8");
+ const publishedPath = process.argv[2];
+ const next = publishedPath
+ ? enableLargeVaultWrites(source, JSON.parse(readFileSync(record, "utf8")), JSON.parse(readFileSync(publishedPath, "utf8")))
+ : source;
+ if (next !== source) writeFileSync(FORMAT_SOURCE, next);
+ writeFileSync(record, releasedRecord(version, next));
}
diff --git a/scripts/testing/record-data-format.test.ts b/scripts/testing/record-data-format.test.ts
index ac35a71d43..3a294d1cb7 100644
--- a/scripts/testing/record-data-format.test.ts
+++ b/scripts/testing/record-data-format.test.ts
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { declaredDataFormat, releasedRecord } from "../record-data-format.mjs";
+import { declaredDataFormat, enableLargeVaultWrites, releasedRecord } from "../record-data-format.mjs";
import { DATA_FORMAT } from "../../server/data-format.ts";
const source = readFileSync(join(import.meta.dirname, "..", "..", "server", "data-format.ts"), "utf8");
@@ -17,4 +17,15 @@ describe("record-data-format", () => {
it("records them under the version being released", () => {
expect(JSON.parse(releasedRecord("9.9.9", source))).toEqual({ version: "9.9.9", ...DATA_FORMAT });
});
+
+ it("enables large Vault writes only after the previous release published a compatible reader", () => {
+ const readFirst = "export const DATA_FORMAT = { writes: 1, reads: 2 } as const;";
+ const previous = { version: "0.1.170", writes: 1, reads: 2 };
+ expect(enableLargeVaultWrites(readFirst, previous, undefined)).toBe(readFirst);
+ expect(enableLargeVaultWrites(readFirst, previous, { ...previous, reads: 1 })).toBe(readFirst);
+ expect(enableLargeVaultWrites(readFirst, previous, { ...previous, version: "0.1.169" })).toBe(readFirst);
+ const promoted = enableLargeVaultWrites(readFirst, previous, previous);
+ expect(JSON.parse(releasedRecord("0.1.171", promoted))).toEqual({ version: "0.1.171", writes: 2, reads: 2 });
+ expect(enableLargeVaultWrites(promoted, previous, previous)).toBe(promoted);
+ });
});
diff --git a/server/data-format.test.ts b/server/data-format.test.ts
index de8d1381a6..07e1b679ab 100644
--- a/server/data-format.test.ts
+++ b/server/data-format.test.ts
@@ -4,14 +4,19 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { encryptBrowserState } from "./browser-sites.ts";
import {
checkDataFormat, DATA_FORMAT, DATA_FORMAT_FILE, DataFormatError, dataFormatStepProblem, readDataFormat, stampDataFormat, type ReleasedDataFormat,
} from "./data-format.ts";
import { freePortBlock } from "./testing/ports.ts";
+import { LOGINS_FILE, LOGINS_KEY_FILE } from "./vault-store.ts";
const ROOT = join(import.meta.dirname, "..");
const { version: VERSION } = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
const released = JSON.parse(readFileSync(join(import.meta.dirname, "data-format-released.json"), "utf8")) as ReleasedDataFormat;
+/** Whether this tree still writes format 1. A plain boolean: the release bump changes DATA_FORMAT, and a literal
+ * comparison against its `as const` numbers would stop compiling on the other side of that change. */
+const WRITES_ONE = (DATA_FORMAT.writes as number) === 1;
const dirs: string[] = [];
const dataDir = () => {
const dir = mkdtempSync(join(tmpdir(), "omb-data-format-"));
@@ -85,15 +90,18 @@ describe("the data folder's format marker", () => {
// What a power loss, an editor or a restore by hand can leave behind.
const GARBLED = ["", "\0".repeat(64), "{", "{}", "null", '{"format":"2"}', '{"format":0}', '{"format":1.5}'];
- it("takes a marker it cannot read as format 1 while no version writes a newer one, and puts a good one back", () => {
+ it("takes a marker it cannot read as format 1 while this version writes nothing newer, and puts a good one back", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
- for (const text of GARBLED) {
- const dir = dataDir();
- writeFileSync(join(dir, DATA_FORMAT_FILE), text);
- expect(() => checkDataFormat(dir, "0.1.152", 1, 1), JSON.stringify(text)).not.toThrow();
- stampDataFormat(dir, "0.1.152", { writes: 1, reads: 1 });
- expect(readDataFormat(dir), JSON.stringify(text)).toMatchObject({ format: 1, writtenBy: "0.1.152" });
+ // Before format 2 existed, and the release that reads format 2 but still writes 1.
+ for (const format of [{ writes: 1, reads: 1 }, { writes: 1, reads: 2 }]) {
+ for (const text of GARBLED) {
+ const dir = dataDir();
+ writeFileSync(join(dir, DATA_FORMAT_FILE), text);
+ expect(() => checkDataFormat(dir, "0.1.152", format.reads, format.writes), JSON.stringify(text)).not.toThrow();
+ stampDataFormat(dir, "0.1.152", format);
+ expect(readDataFormat(dir, format.writes), JSON.stringify(text)).toMatchObject({ format: 1, writtenBy: "0.1.152" });
+ }
}
expect(warn).toHaveBeenCalledWith(expect.stringContaining("cannot be read; taking the data as format 1"));
} finally {
@@ -101,11 +109,12 @@ describe("the data folder's format marker", () => {
}
});
- it("refuses a marker it cannot read once a version writes a newer format, since the data may then be in it", () => {
+ it("refuses a marker it cannot read once this version writes format 2, since the data may then be in it", () => {
for (const text of GARBLED) {
const dir = dataDir();
writeFileSync(join(dir, DATA_FORMAT_FILE), text);
expect(() => checkDataFormat(dir, "0.1.160", 2, 2), JSON.stringify(text)).toThrow(/cannot be read, so this version cannot tell/);
+ expect(() => stampDataFormat(dir, "0.1.160", { reads: 2, writes: 2 })).toThrow(DataFormatError);
expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(text);
}
});
@@ -115,7 +124,7 @@ describe("the data folder's format marker", () => {
writeFileSync(join(dir, DATA_FORMAT_FILE), `\uFEFF${JSON.stringify({ format: 1, writtenBy: "0.1.151", writtenAt: "" })}`);
expect(readDataFormat(dir)).toMatchObject({ format: 1, writtenBy: "0.1.151" });
writeFileSync(join(dir, DATA_FORMAT_FILE), `\uFEFF${JSON.stringify({ format: 3, writtenBy: "0.2.0", writtenAt: "" })}`);
- expect(() => checkDataFormat(dir, "0.1.152", 1, 1)).toThrow("written by a newer OpenMausBot (0.2.0)");
+ expect(() => checkDataFormat(dir, "0.1.152", 1)).toThrow("written by a newer OpenMausBot (0.2.0)");
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("starts on a marker this user cannot read, and on a folder it cannot write", () => {
@@ -125,9 +134,12 @@ describe("the data folder's format marker", () => {
chmodSync(join(dir, DATA_FORMAT_FILE), 0o000);
chmodSync(dir, 0o555);
try {
- expect(() => checkDataFormat(dir, "0.1.152", 1, 1)).not.toThrow();
+ // The release that reads format 2 and writes 1; this tree's own numbers too, while it writes 1.
+ expect(() => checkDataFormat(dir, "0.1.152", 2, 1)).not.toThrow();
+ if (WRITES_ONE) expect(() => checkDataFormat(dir, "0.1.152")).not.toThrow();
// The stamp cannot replace it (EACCES): said in the log, and the start goes on.
- expect(() => stampDataFormat(dir, "0.1.152", { writes: 1, reads: 1 })).not.toThrow();
+ expect(() => stampDataFormat(dir, "0.1.152", { writes: 1, reads: 2 })).not.toThrow();
+ if (WRITES_ONE) expect(() => stampDataFormat(dir, "0.1.152")).not.toThrow();
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/could not write .*data-format\.json .*starting without it/));
expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
} finally {
@@ -137,7 +149,7 @@ describe("the data folder's format marker", () => {
}
});
- it("never ends a start over a marker it cannot write: a Windows file held open, a full disk", () => {
+ it("continues when writing a format 1 marker fails", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
for (const code of ["EPERM", "EACCES", "ENOSPC", "EROFS"]) {
@@ -145,7 +157,7 @@ describe("the data folder's format marker", () => {
const failing = () => {
throw Object.assign(new Error(`${code}: operation not permitted, rename`), { code });
};
- expect(() => stampDataFormat(dir, "0.1.152", DATA_FORMAT, failing), code).not.toThrow();
+ expect(() => stampDataFormat(dir, "0.1.152", { writes: 1, reads: 2 }, failing), code).not.toThrow();
expect(readDataFormat(dir)).toBeNull();
}
} finally {
@@ -157,6 +169,24 @@ describe("the data folder's format marker", () => {
expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
});
+ it.each([false, true])("requires a successful format 2 stamp (existing format 1 marker: %s)", (hasMarker) => {
+ const dir = dataDir();
+ const file = join(dir, DATA_FORMAT_FILE);
+ const marker = JSON.stringify({ format: 1, writtenBy: "0.1.170", writtenAt: "" });
+ if (hasMarker) writeFileSync(file, marker);
+ const format = { writes: 2, reads: 2 };
+ const fail = () => { throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" }); };
+
+ expect(() => stampDataFormat(dir, "0.1.171", format, fail)).toThrow(DataFormatError);
+ if (hasMarker) expect(readFileSync(file, "utf8")).toBe(marker);
+ else expect(existsSync(file)).toBe(false);
+
+ stampDataFormat(dir, "0.1.171", format);
+ expect(readDataFormat(dir)?.format).toBe(2);
+ expect(() => checkDataFormat(dir, "0.1.169", 1)).toThrow(DataFormatError);
+ expect(() => stampDataFormat(dir, "0.1.171", format, fail)).not.toThrow();
+ });
+
it("lets the Admin roll a Cloud back one image, and forward again, on the same data", () => {
const dir = dataDir();
stampDataFormat(dir, VERSION, DATA_FORMAT);
@@ -206,7 +236,7 @@ describe("a server starting on a data folder", () => {
expect(readdirSync(data)).toEqual([DATA_FORMAT_FILE]);
}, 60_000);
- it("starts, and puts a good marker back, on a marker a power loss left empty or full of NULs", async () => {
+ it.runIf(WRITES_ONE)("starts, and puts a good marker back, on a marker a power loss left empty or full of NULs", async () => {
for (const text of ["", "\0".repeat(64)]) {
const dir = dataDir();
const data = join(dir, "data");
@@ -219,11 +249,35 @@ describe("a server starting on a data folder", () => {
}
}, 120_000);
+ it.runIf(!WRITES_ONE)("refuses to open a Vault with a large value and an unreadable format marker", async () => {
+ for (const text of ["", "\0".repeat(64)]) {
+ const dir = dataDir();
+ const data = join(dir, "data");
+ mkdirSync(data);
+ const marker = join(data, DATA_FORMAT_FILE);
+ writeFileSync(marker, text);
+ const key = "ab".repeat(32);
+ const vault = join(data, LOGINS_FILE);
+ const sealed = encryptBrowserState(JSON.stringify({ version: 1, logins: [], secrets: [
+ { id: "small-fixture", name: "Small fixture", value: "fixture-only", source: "settings", bots: "all", createdAt: 1, updatedAt: 1 },
+ { id: "large-fixture", name: "Large fixture", value: "x".repeat(65_536), source: "settings", bots: "all", createdAt: 1, updatedAt: 1 },
+ ] }), key);
+ writeFileSync(join(data, LOGINS_KEY_FILE), key);
+ writeFileSync(vault, sealed);
+ const { code, stderr } = await start(dir, () => existsSync(join(data, "environment-id")) && readFileSync(marker, "utf8").includes('"format"'));
+ expect(code).toBe(1);
+ expect(stderr).toContain("cannot be read, so this version cannot tell");
+ expect(readFileSync(marker, "utf8")).toBe(text);
+ expect(readFileSync(vault).equals(sealed)).toBe(true);
+ expect(existsSync(join(data, "environment-id"))).toBe(false);
+ }
+ }, 120_000);
+
it("starts on data the next version marked, as after the Admin rolls a Cloud back one image", async () => {
const dir = dataDir();
const data = join(dir, "data");
mkdirSync(data);
- const marker = `${JSON.stringify({ format: DATA_FORMAT.writes, writtenBy: "99.0.0", writtenAt: "2027-01-01T00:00:00.000Z" }, null, 2)}\n`;
+ const marker = `${JSON.stringify({ format: DATA_FORMAT.reads, writtenBy: "99.0.0", writtenAt: "2027-01-01T00:00:00.000Z" }, null, 2)}\n`;
writeFileSync(join(data, DATA_FORMAT_FILE), marker);
const { stderr } = await start(dir, () => existsSync(join(data, "environment-id")));
expect(stderr).not.toContain("startup failed");
diff --git a/server/data-format.ts b/server/data-format.ts
index 8824f5b70a..c5dc28eeab 100644
--- a/server/data-format.ts
+++ b/server/data-format.ts
@@ -1,7 +1,7 @@
// The data folder's format marker, and the rule that makes an update safe to roll back: what version N writes, version
// N-1 can still read (CONTRIBUTING.md, "Changing how data is stored"). A server that finds data in a format it cannot
// read refuses to start before it touches a file.
-import { existsSync, readFileSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { join } from "node:path";
import { writeFileAtomic } from "./atomic.ts";
@@ -10,7 +10,7 @@ import { writeFileAtomic } from "./atomic.ts";
* one ahead. A change the previous release cannot read takes two releases: raise `reads` (and ship the code that reads
* the new format) in one, raise `writes` in the next. server/data-format.test.ts fails on any other step.
*/
-export const DATA_FORMAT = { writes: 1, reads: 1 } as const;
+export const DATA_FORMAT = { writes: 1, reads: 2 } as const;
export const DATA_FORMAT_FILE = "data-format.json";
@@ -30,23 +30,23 @@ export class DataFormatError extends Error {
/** The marker in the folder; null when there is none, "unreadable" when there is one whose format cannot be told. */
function markerIn(dataDir: string): DataFormatMarker | null | "unreadable" {
const file = join(dataDir, DATA_FORMAT_FILE);
- if (!existsSync(file)) return null;
try {
// A byte-order mark is what some editors put in front of JSON; the format behind it is still readable.
const marker = JSON.parse(readFileSync(file, "utf8").replace(/^\uFEFF/, "")) as Partial<DataFormatMarker> | null;
if (marker && typeof marker.format === "number" && Number.isInteger(marker.format) && marker.format >= 1) {
return { format: marker.format, writtenBy: typeof marker.writtenBy === "string" ? marker.writtenBy : "unknown", writtenAt: typeof marker.writtenAt === "string" ? marker.writtenAt : "" };
}
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
}
return "unreadable";
}
/**
* Null when the folder has no marker. A marker that cannot be read (empty or NUL-filled after a power loss, not
- * readable by this user) is format 1 while no version writes anything newer (`writes` 1): there is then no newer format
- * it could have recorded, and refusing would stop a healthy install. Once a version writes format 2 its format is
- * unknown, and this throws.
+ * readable by this user) is format 1 while this version writes nothing newer (`writes` 1): every version before this
+ * one already takes such a marker as format 1, so refusing here would protect no data and stop a healthy install. Once
+ * this version writes format 2 its format is unknown, and this throws.
*/
export function readDataFormat(dataDir: string, writes: number = DATA_FORMAT.writes): DataFormatMarker | null {
const marker = markerIn(dataDir);
@@ -56,7 +56,7 @@ export function readDataFormat(dataDir: string, writes: number = DATA_FORMAT.wri
console.warn(`[data-format] ${file} cannot be read; taking the data as format 1, the only format any version has written.`);
return null;
}
- throw new DataFormatError(`OpenMausBot startup failed: ${file} cannot be read, so this version cannot tell whether it understands the data in ${dataDir}. Nothing was changed. Restore that file from a backup, or the whole folder from the copy taken before the last update.`);
+ throw new DataFormatError(`OpenMausBot startup failed: ${file} cannot be read, so this version cannot tell whether it understands the data in ${dataDir}. Nothing was changed. Restore the marker from the same snapshot as the data, or restore the whole data folder from a backup.`);
}
/** Throws, having changed nothing, when a newer version left the data in a format `reads` does not cover. */
@@ -74,8 +74,8 @@ function newerData(dataDir: string, version: string, marker: DataFormatMarker):
/**
* Records that this version has run on the folder. Never lowers a marker: an older version that could read the data
- * leaves it. Throws only DataFormatError, for data it cannot read; a marker it cannot write (a read-only folder, a file
- * Windows holds open past the retries) is said in the log and the start goes on, since the data itself is fine.
+ * leaves it. A marker is optional for format 1. A server writing a newer format needs the marker to protect that data
+ * against rollback, so a failed write throws DataFormatError before stores can open.
*/
export function stampDataFormat(
dataDir: string,
@@ -91,7 +91,11 @@ export function stampDataFormat(
try {
write(file, `${JSON.stringify(next, null, 2)}\n`);
} catch (error) {
- console.warn(`[data-format] could not write ${file} (${error instanceof Error ? error.message : String(error)}); starting without it.`);
+ const detail = error instanceof Error ? error.message : String(error);
+ if (format.writes > 1) {
+ throw new DataFormatError(`OpenMausBot startup failed: could not write data format ${format.writes} to ${file} (${detail}). Fix the marker write error, then restart.`);
+ }
+ console.warn(`[data-format] could not write ${file} (${detail}); starting without it.`);
}
}
diff --git a/server/decider-rooms.e2e.test.ts b/server/decider-rooms.e2e.test.ts
index c30cfd7810..1a6dfa8071 100644
--- a/server/decider-rooms.e2e.test.ts
+++ b/server/decider-rooms.e2e.test.ts
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { DECIDER_LOG_DIR, type DeciderLogRow } from "./decider/log.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
@@ -40,6 +41,17 @@ let openrouterScript: RouteScript = {};
const routeRequests = () => jevRequests.filter((request) => request.body?.questions?.answer?.type === "choice");
const keyChecks = () => jevRequests.filter((request) => request.body?.questions?.answer?.type === "noul");
+async function expectDeciderLog(...expected: Partial<DeciderLogRow>[]): Promise<string> {
+ const dir = join(data, DECIDER_LOG_DIR);
+ let log = "";
+ await expect.poll(() => {
+ if (!existsSync(dir)) return [];
+ log = readdirSync(dir).map((name) => readFileSync(join(dir, name), "utf8")).join("");
+ return log.split("\n").slice(0, -1).map((line) => JSON.parse(line));
+ }, { timeout: 5_000 }).toEqual(expect.arrayContaining(expected.map((row) => expect.objectContaining(row))));
+ return log;
+}
+
const api = async (method: string, path: string, body?: unknown): Promise<{ status: number; body: any; text: string }> => {
const response = await fetch(`${base}${path}`, {
method,
@@ -281,11 +293,10 @@ describe("Auto rooms ask the decision model who answers", { timeout: 90_000 }, (
const dump = readFileSync(engineDump, "utf8");
expect(JSON.parse(dump).env).not.toHaveProperty("OMB_JEV_API_KEY");
expect(dump).not.toContain(KEY);
- const dir = join(data, "decider-log");
- const log = readdirSync(dir).map((name) => readFileSync(join(dir, name), "utf8")).join("");
- const rows = log.trim().split("\n").map((line) => JSON.parse(line));
- expect(rows.some((row) => row.seam === "roomRouting" && row.ok && row.choice === bots.Theo!.id)).toBe(true);
- expect(rows.some((row) => row.seam === "roomRouting" && !row.ok && row.reason === "overloaded")).toBe(true);
+ const log = await expectDeciderLog(
+ { seam: "roomRouting", ok: true, choice: bots.Theo!.id },
+ { seam: "roomRouting", ok: false, reason: "overloaded" },
+ );
expect(log).not.toContain(KEY);
expect(log).not.toContain("Safari");
expect(output).not.toContain(KEY);
@@ -403,10 +414,7 @@ describe("Auto rooms ask the decision model who answers", { timeout: 90_000 }, (
.toEqual([bots.Maya!.id, bots.Theo!.id, bots.Ravi!.id, "__everyone__"]);
expect(jevRequests.every((jevRequest) => jevRequest.auth !== `Bearer ${OR_KEY}`)).toBe(true);
- const dir = join(data, "decider-log");
- const log = readdirSync(dir).map((name) => readFileSync(join(dir, name), "utf8")).join("");
- const rows = log.trim().split("\n").map((line) => JSON.parse(line));
- expect(rows.some((row) => row.provider === "openrouter" && row.model === MODEL && row.seam === "roomRouting" && row.ok && row.choice === bots.Theo!.id)).toBe(true);
+ const log = await expectDeciderLog({ provider: "openrouter", model: MODEL, seam: "roomRouting", ok: true, choice: bots.Theo!.id });
expect(log).not.toContain(OR_KEY);
expect(log).not.toContain("pricing page");
expect(output).not.toContain(OR_KEY);
@@ -417,9 +425,7 @@ describe("Auto rooms ask the decision model who answers", { timeout: 90_000 }, (
const { replies } = await round(room.id, "Who owns the invoice emails?");
expect(replies.map((reply) => reply.from!.name)).toEqual(["Ravi"]);
expect(replies[0]!.routedBy).toBeUndefined();
- const dir = join(data, "decider-log");
- const rows = readdirSync(dir).map((name) => readFileSync(join(dir, name), "utf8")).join("").trim().split("\n").map((line) => JSON.parse(line));
- expect(rows.some((row) => row.provider === "openrouter" && !row.ok && row.reason === "http_error" && row.status === 402)).toBe(true);
+ await expectDeciderLog({ provider: "openrouter", ok: false, reason: "http_error", status: 402 });
});
it("a decisions model is tested through the Decisions API, and saved with its API", async () => {
diff --git a/server/doctor/checks/data-format.test.ts b/server/doctor/checks/data-format.test.ts
index 158b7404b8..e5326be8cf 100644
--- a/server/doctor/checks/data-format.test.ts
+++ b/server/doctor/checks/data-format.test.ts
@@ -1,7 +1,8 @@
import { existsSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { DATA_FORMAT } from "../../data-format.ts";
import { context, dataFolder, NOW, UUID } from "../../testing/doctor-folders.ts";
import { DOCTOR_BACKUPS_DIR } from "../backup.ts";
import { runDoctor } from "../run.ts";
@@ -16,9 +17,21 @@ describe("data-format check", () => {
expect(dataFormatCheck().check(context(data)).status).toBe("ok");
});
+ it("takes a marker it cannot read as format 1 while this version writes 1, and blocks repair once it writes 2", () => {
+ const data = dataFolder();
+ writeFileSync(join(data, "data-format.json"), "\0".repeat(64));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ expect(dataFormatCheck({ writes: 1, reads: 2 }).check(context(data))).toMatchObject({ status: "ok" });
+ } finally {
+ warn.mockRestore();
+ }
+ expect(dataFormatCheck({ writes: 2, reads: 2 }).check(context(data))).toMatchObject({ status: "problem", blocking: true });
+ });
+
it("refuses a newer format, never fixes it, and then lets no other fix run", () => {
const data = dataFolder();
- writeFileSync(join(data, "data-format.json"), JSON.stringify({ format: 2, writtenBy: "0.2.0", writtenAt: "" }));
+ writeFileSync(join(data, "data-format.json"), JSON.stringify({ format: DATA_FORMAT.reads + 1, writtenBy: "0.2.0", writtenAt: "" }));
const finding = dataFormatCheck().check(context(data));
expect(finding).toMatchObject({ status: "problem", blocking: true });
expect(finding.fixable).toBeFalsy();
diff --git a/server/env-path.ts b/server/env-path.ts
index c942779637..2c20a9326f 100644
--- a/server/env-path.ts
+++ b/server/env-path.ts
@@ -167,7 +167,7 @@ function probeLoginShellPath(): void {
// Applied once the shell has exited cleanly and its whole answer has arrived, not when stdout closes: its rc may leave a
// background job holding it. Reading stops there, so that job's later output is never part of the answer.
const applyIfDone = (): void => {
- if (exitCode !== 0) return;
+ if (finished || exitCode !== 0) return;
const m = /__OMB_PATH__([^\n]*?)__OMB_END__/.exec(stdout);
if (!m) return;
if (m[1] && m[1] !== loginShellPath) {
diff --git a/server/host/secret-cards.test.ts b/server/host/secret-cards.test.ts
index b25bca2934..bc0d538ccd 100644
--- a/server/host/secret-cards.test.ts
+++ b/server/host/secret-cards.test.ts
@@ -1,7 +1,7 @@
import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import "../server-line-packs.ts";
import type { BotRecord, Message } from "../store.ts";
@@ -16,6 +16,11 @@ import { OnePasswordLogins, sdkOnePasswordClient } from "../onepassword.ts";
import { fakeOnePasswordSdk } from "../testing/fake-onepassword.ts";
import type { LoginBots } from "../../shared/logins.ts";
+vi.mock("../data-format.ts", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../data-format.ts")>(),
+ DATA_FORMAT: { reads: 2, writes: 2 },
+}));
+
const dirs: string[] = [];
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
@@ -108,6 +113,18 @@ describe("a secret a card saves to the Vault", () => {
one.cards.requestCredential(one.bot, threadId, { label: "Stripe secret key", reason: "For test charges.", delivery: "ref", ...extra });
const refIn = (text: unknown) => /secret-ref:[0-9a-f]{32}/u.exec(String(text))?.[0];
+ it("accepts a 64 KiB custom value without putting it in the card or resume message", async () => {
+ const one = fixture();
+ const card = await ask(one, "t1");
+ const id = String(card.body.messageId);
+ const value = "large-fixture--!".repeat(4_096);
+ expect(one.cards.saveCustomSecret("ledger", "t1", id, value + "x").status).toBe(400);
+ const saved = one.cards.saveCustomSecret("ledger", "t1", id, value);
+ expect(saved.status).toBe(200);
+ expect(one.vaultStore.secretValues()[0] === value).toBe(true);
+ expect(JSON.stringify([one.lines, one.resumed, saved])).not.toContain("large-fixture--!");
+ });
+
it("is kept for the asking bot, and its next ask, in any conversation and after any ref is spent, gets a fresh one with no card", async () => {
const one = fixture();
const card = await ask(one, "t1");
diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.ts
index 6d06b42e70..850ef7bd2f 100644
--- a/server/host/secret-cards.ts
+++ b/server/host/secret-cards.ts
@@ -39,6 +39,7 @@ import type { VaultReader, VaultStore } from "../vault-store.ts";
import { loginUsableBy } from "../../shared/logins.ts";
import { vaultNameKey, type VaultChoice } from "../../shared/vault.ts";
import { fittingChoices } from "../vault/choices.ts";
+import { VAULT_VALUE_MAX_BYTES } from "../vault/value-limits.ts";
import { linkedSecretNames } from "../vault/providers.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { serverLine } from "../server-lines.ts";
@@ -257,8 +258,8 @@ export function createSecretCards(deps: SecretCardsDeps) {
const message = openCustomCard(botId, threadId, messageId);
if ("status" in message) return message;
const value = typeof raw === "string" ? raw.trim() : "";
- if (!value || Buffer.byteLength(value) > SECRET_VALUE_MAX_BYTES) {
- return { status: 400, body: { ...userError("serverError.secret.valueSize", { bytes: SECRET_VALUE_MAX_BYTES }) } };
+ if (!value || Buffer.byteLength(value) > VAULT_VALUE_MAX_BYTES) {
+ return { status: 400, body: { ...userError("serverError.secret.valueSize", { bytes: VAULT_VALUE_MAX_BYTES }) } };
}
try {
storeCustomSecret(message, botId, threadId, value);
diff --git a/server/routes/secret-cards.ts b/server/routes/secret-cards.ts
index 15bfb27336..8ad1ac0be3 100644
--- a/server/routes/secret-cards.ts
+++ b/server/routes/secret-cards.ts
@@ -7,7 +7,7 @@ import { CUSTOM_SECRET_TARGET, credentialResumeOutcome, isCredentialTargetId } f
import { phoneSecretEnvelopeSchema, type SecretCards } from "../host/secret-cards.ts";
import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";
import type { RequestAuth } from "../request-auth.ts";
-import { SECRET_VALUE_MAX_BYTES } from "../secret-vault.ts";
+import { VAULT_VALUE_BODY_MAX_BYTES } from "../vault/value-limits.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
/** Whose a conversation is, for who may type a secret into its card. */
@@ -70,7 +70,7 @@ export function createSecretCardRoutes(deps: SecretCardRouteDeps): RouteHandler
// JSON only, so a form posted from another local page cannot save one.
const mediaType = String(req.headers["content-type"] ?? "").split(";", 1)[0]!.trim().toLowerCase();
if (mediaType !== "application/json") return json(res, 415, { error: "content-type must be application/json" });
- const raw = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);
+ const raw = await readBody(req, VAULT_VALUE_BODY_MAX_BYTES);
const fields = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
const threadId = String(fields.threadId ?? "");
if (!deps.threadVisible(auth, threadId) || !secretMessage(m[1]!, threadId, m[2]!)) return json(res, 404, { ...userError("serverError.secret.missing") });
diff --git a/server/routes/vault.test.ts b/server/routes/vault.test.ts
index ef3a72a013..dea530c639 100644
--- a/server/routes/vault.test.ts
+++ b/server/routes/vault.test.ts
@@ -3,7 +3,7 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { BotLogins } from "../bot-logins.ts";
import { json, readBody } from "../harness/http.ts";
@@ -16,6 +16,11 @@ import { createLoginRoutes } from "./logins.ts";
import { dispatchRoutes } from "./table.ts";
import { createVaultRoutes, VAULT_ERRORS } from "./vault.ts";
+vi.mock("../data-format.ts", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../data-format.ts")>(),
+ DATA_FORMAT: { reads: 2, writes: 2 },
+}));
+
const VALUE = "sk_test_fake-route-secret-1";
const NEW_VALUE = "sk_test_fake-route-secret-2";
const LINKED_VALUE = "secret_fake-linked-route-3";
@@ -58,10 +63,27 @@ async function serve(onePasswordToken: string | null = null, team = false) {
answers.push(text);
return { status: response.status, body: JSON.parse(text), cache: response.headers.get("cache-control") };
};
- return { store, call, answers };
+ return { store, call, answers, reopen: () => new VaultStore({ dataDir: dir }) };
}
describe("the Vault routes", () => {
+ it("saves and replaces a large secret under format 2 without exposing its value", async () => {
+ const { call, reopen, answers } = await serve();
+ const original = "πŸ”‘".repeat(16_384);
+ const created = await call("POST", "/api/vault/secrets", { name: "Large fixture", value: original });
+ expect(created).toMatchObject({ status: 201, body: { secret: { name: "Large fixture" } } });
+ const { id } = created.body.secret;
+ expect(reopen().secret(id)?.value === original).toBe(true);
+
+ const value = "a" + "\u0001".repeat(65_534) + "b";
+ const path = `/api/vault/secrets/${id}`;
+ expect(await call("PATCH", path, { value })).toMatchObject({ status: 200 });
+ expect(await call("PATCH", path, { value: value + "c" })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });
+ expect(reopen().secret(id)?.value === value).toBe(true);
+ expect((await call("GET", "/api/vault")).body.secrets).toMatchObject([{ id }]);
+ for (const answer of answers) expect(answer).not.toMatch(/"value":|πŸ”‘|\\u0001/u);
+ });
+
it("deleting a secret says which MCP servers lost their key, and a move's secret keeps its id and who may use it", async () => {
const { store, call } = await serve();
const added = await call("POST", "/api/vault/secrets", { id: "55555555-5555-4555-8555-555555555555", name: "Stripe", value: VALUE, bots: ["pepper"], source: "card", refOnly: true });
@@ -105,7 +127,7 @@ describe("the Vault routes", () => {
expect((await call("POST", "/api/vault/secrets", { name: "K", value: VALUE }, "text/plain")).status).toBe(415);
expect(await call("POST", "/api/vault/secrets", { name: " ", value: VALUE })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.name } });
expect(await call("POST", "/api/vault/secrets", { name: "K", value: " " })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });
- expect(await call("POST", "/api/vault/secrets", { name: "K", value: "x".repeat(4_097) })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });
+ expect(await call("POST", "/api/vault/secrets", { name: "K", value: "x".repeat(65_537) })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });
expect((await call("POST", "/api/vault/secrets", { name: "K", value: VALUE, bots: ["ghost"] })).status).toBe(400);
const id = (await call("POST", "/api/vault/secrets", { name: "K", value: VALUE })).body.secret.id;
expect((await call("PATCH", `/api/vault/secrets/${id}`, { value: "" })).status).toBe(400);
diff --git a/server/routes/vault.ts b/server/routes/vault.ts
index 74bec22ff8..4a85bb26a0 100644
--- a/server/routes/vault.ts
+++ b/server/routes/vault.ts
@@ -1,8 +1,9 @@
// No answer ever carries a saved value: a saved secret is only ever replaced. A Team Cloud member sees and deletes only
// the secrets of their own; an admin, only the team's and their own.
-import { SECRET_VALUE_MAX_BYTES, VAULT_SECRET_NAME_MAX, type LinkedSecret } from "../../shared/vault.ts";
+import { VAULT_SECRET_NAME_MAX, type LinkedSecret } from "../../shared/vault.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { McpKeys } from "../vault/mcp-keys.ts";
+import { VAULT_VALUE_BODY_MAX_BYTES, VAULT_VALUE_MAX_BYTES } from "../vault/value-limits.ts";
import { TEAM_READER, type VaultReader, type VaultStore } from "../vault-store.ts";
import { isJson, parseBots, type LoginRouteDeps } from "./logins.ts";
import { PASS, type RouteHandler } from "./table.ts";
@@ -23,7 +24,7 @@ const ID = /^[\w-]{1,128}$/u;
export const VAULT_ERRORS = {
name: `Give the secret a name of at most ${VAULT_SECRET_NAME_MAX} characters.`,
- value: `Enter the secret. It can be at most ${SECRET_VALUE_MAX_BYTES} bytes.`,
+ value: `Enter the secret. It can be at most ${VAULT_VALUE_MAX_BYTES} bytes.`,
} as const;
type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };
@@ -38,7 +39,7 @@ function parseName(raw: unknown): Parsed<string | undefined> {
function parseValue(raw: unknown): Parsed<string | undefined> {
if (raw === undefined) return { ok: true, value: undefined };
const value = typeof raw === "string" ? raw.trim() : "";
- return value && Buffer.byteLength(value) <= SECRET_VALUE_MAX_BYTES ? { ok: true, value } : { ok: false, error: VAULT_ERRORS.value };
+ return value && Buffer.byteLength(value) <= VAULT_VALUE_MAX_BYTES ? { ok: true, value } : { ok: false, error: VAULT_ERRORS.value };
}
export function createVaultRoutes(deps: VaultRouteDeps): RouteHandler {
@@ -60,7 +61,7 @@ export function createVaultRoutes(deps: VaultRouteDeps): RouteHandler {
if (method !== "GET" && method !== "DELETE" && !isJson(req)) return json(res, 415, { error: "content-type must be application/json" });
if (path === SECRETS) {
if (method !== "POST") return json(res, 405, { error: "method not allowed" });
- const body = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);
+ const body = await readBody(req, VAULT_VALUE_BODY_MAX_BYTES);
if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the secret as a JSON object" });
const name = parseName(body.name);
if (!name.ok || name.value === undefined) return json(res, 400, { error: VAULT_ERRORS.name });
@@ -83,7 +84,7 @@ export function createVaultRoutes(deps: VaultRouteDeps): RouteHandler {
return json(res, 200, { ok: true, ...(keysOff.length ? { keysOff } : {}) });
}
if (method !== "PATCH") return json(res, 405, { error: "method not allowed" });
- const body = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);
+ const body = await readBody(req, VAULT_VALUE_BODY_MAX_BYTES);
if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the change as a JSON object" });
const name = parseName(body.name);
if (!name.ok) return json(res, 400, { error: name.error });
diff --git a/server/routine-failure-spacing.test.ts b/server/routine-failure-spacing.test.ts
index 42b23b9deb..f7d68e52f5 100644
--- a/server/routine-failure-spacing.test.ts
+++ b/server/routine-failure-spacing.test.ts
@@ -151,10 +151,12 @@ describe("a routine every 5 minutes whose tool server is dead", () => {
describe("a routine every minute by cron whose tool server is dead", () => {
it("is accepted, stays on, and is spaced out the same way", async () => {
+ vi.stubEnv("OMB_ROUTINE_FAILURE_SPACING_MS", String(2 * MINUTE));
+ vi.stubEnv("OMB_ROUTINE_FAILURE_SPACING_MAX_MS", String(4 * MINUTE));
const h = harness(undefined, { type: "cron", expression: "* * * * *", timeZone: "UTC" });
- await h.passTo(START + 6 * HOUR, h.fail(DEAD_TOOL));
- console.log(`turns started in 6 hours by a routine every minute with a dead tool server: ${h.started.length}`);
- expect(h.started).toHaveLength(5);
+ await h.passTo(START + 12 * MINUTE, h.fail(DEAD_TOOL));
+ const startMinutes = h.rows().filter((run) => run.startedAt != null).map((run) => (run.scheduledFor - START) / MINUTE);
+ expect(startMinutes).toEqual([1, 2, 3, 6, 11]);
expect(h.routine()).toMatchObject({ enabled: true, schedule: { type: "cron", expression: "* * * * *" } });
});
});
diff --git a/server/vault-store.test.ts b/server/vault-store.test.ts
index 4655ea6730..24fc0b4fc0 100644
--- a/server/vault-store.test.ts
+++ b/server/vault-store.test.ts
@@ -9,6 +9,7 @@ import { addHeldSecretScrubber, redactSecretsInText } from "../shared/redact.ts"
import { decryptBrowserState, encryptBrowserState } from "./browser-sites.ts";
import { HeldSecrets, LOGINS_FILE, LOGINS_KEY_FILE, MEMBER_SECRETS_FILE, TEAM_READER, VaultStore, secretForms } from "./vault-store.ts";
import { parseTotpKey } from "./totp.ts";
+import { VAULT_VALUE_MAX_BYTES } from "./vault/value-limits.ts";
// Obvious fakes only: nothing here is anyone's real login.
const PASSWORD = "fake-Pa55word&<\"quoted\">";
@@ -172,6 +173,46 @@ describe("the saved logins store", () => {
describe("the Vault's saved secrets", () => {
const STRIPE = "sk_test_fake-vault-secret-1";
+ it("opens a Vault with 64 KiB values and preserves them when it saves another change", () => {
+ const person = "p_ada0000000000000000000";
+ const member = { person, team: false };
+ const largeValue = "fixture-".repeat(8_192);
+ const store = new VaultStore({ dataDir: dir });
+ const login = store.create({ ...at("example.com"), username: "alice", password: PASSWORD, source: "settings", bots: "all" });
+ const small = store.saveSecret({ name: "Small secret", value: STRIPE, source: "settings", bots: "all" });
+ const teamSecret = { ...small, id: "large-team", name: "Large team secret", value: largeValue };
+ const memberSecret = { ...teamSecret, id: "large-member", name: "Large member secret", person };
+ const key = readFileSync(join(dir, LOGINS_KEY_FILE), "utf8").trim();
+ const file = join(dir, LOGINS_FILE);
+ const disk = JSON.parse(decryptBrowserState(readFileSync(file), key));
+ disk.secrets.push(teamSecret);
+ writeFileSync(file, encryptBrowserState(JSON.stringify(disk), key));
+ writeFileSync(join(dir, MEMBER_SECRETS_FILE), encryptBrowserState(JSON.stringify({ version: 1, secrets: [memberSecret] }), key));
+
+ const reopened = new VaultStore({ dataDir: dir });
+ expect(reopened.list()).toEqual([login]);
+ expect(reopened.listSecrets(TEAM_READER).map(({ id }) => id)).toEqual([teamSecret.id, small.id]);
+ expect(reopened.listSecrets(member)).toMatchObject([{ id: memberSecret.id }]);
+ expect(JSON.stringify(reopened.listSecrets(member))).not.toContain("fixture-");
+ expect(reopened.updateSecret(small.id, { name: "Renamed secret" })).toMatchObject({ name: "Renamed secret" });
+ const afterSave = new VaultStore({ dataDir: dir });
+ expect(afterSave.secret(teamSecret.id)?.value === largeValue).toBe(true);
+ expect(afterSave.secret(memberSecret.id)?.value === largeValue).toBe(true);
+ expect(afterSave.list()).toEqual([login]);
+ });
+
+ it("enforces the UTF-8 byte limit for newly saved, received and replaced values", () => {
+ const store = new VaultStore({ dataDir: dir });
+ const value = "πŸ”‘".repeat(VAULT_VALUE_MAX_BYTES / 4);
+ const input = { name: "Fixture secret", value, source: "settings", bots: "all" } as const;
+ const saved = store.saveSecret(input);
+ const tooLarge = value + "x";
+ expect(() => store.saveSecret({ ...input, value: tooLarge })).toThrow(RangeError);
+ expect(() => store.receiveSecret({ ...input, id: saved.id, value: tooLarge })).toThrow(RangeError);
+ expect(() => store.updateSecret(saved.id, { value: tooLarge })).toThrow(RangeError);
+ expect(new VaultStore({ dataDir: dir }).secret(saved.id)?.value).toBe(value);
+ });
+
it("live in the same sealed file beside the logins, still version 1, which the previous release reads without losing a login", () => {
const store = new VaultStore({ dataDir: dir, now: () => 5 });
store.create({ ...at("example.com"), username: "alice", password: PASSWORD, source: "settings", bots: "all" });
diff --git a/server/vault-store.ts b/server/vault-store.ts
index f2622345d3..03b292ae60 100644
--- a/server/vault-store.ts
+++ b/server/vault-store.ts
@@ -9,10 +9,11 @@ import { z } from "zod";
import { HELD_SECRET_MASK } from "../shared/redact.ts";
import { LOGIN_FIELD_MAX, LOGIN_HOSTS_MAX, loginMatchesHost, loginPlace, loginSite, loginUsableBy, type BitwardenCredentials, type LoginBots, type LoginPlace, type LoginSummary } from "../shared/logins.ts";
-import { SECRET_VALUE_MAX_BYTES, VAULT_SECRET_NAME_MAX, vaultNameKey, type VaultSecret } from "../shared/vault.ts";
+import { VAULT_SECRET_NAME_MAX, vaultNameKey, type VaultSecret } from "../shared/vault.ts";
import { writeFileAtomic } from "./atomic.ts";
import { decryptBrowserState, encryptBrowserState } from "./browser-sites.ts";
import type { TotpKey } from "./totp.ts";
+import { STORED_VAULT_VALUE_MAX_BYTES, VAULT_VALUE_MAX_BYTES } from "./vault/value-limits.ts";
export const LOGINS_FILE = "logins.json.enc";
export const LOGINS_KEY_FILE = "logins-key";
@@ -29,6 +30,12 @@ const totpSchema = z.object({
const botsSchema = z.union([z.literal("all"), z.array(z.string())]);
+function checkNewSecretValue(value: string): void {
+ if (Buffer.byteLength(value) > VAULT_VALUE_MAX_BYTES) {
+ throw new RangeError(`A new Vault secret value can be at most ${VAULT_VALUE_MAX_BYTES} bytes.`);
+ }
+}
+
// The previous release reads `version: 1` records by `host` alone and replaces a file it cannot parse, so every record
// keeps `host` (its first sign-in host) and the version stays 1: going back a release never loses a saved login.
const diskLoginSchema = z.object({
@@ -50,7 +57,7 @@ const diskLoginSchema = z.object({
const diskSecretSchema = z.object({
id: z.string().min(1),
name: z.string().min(1).max(VAULT_SECRET_NAME_MAX),
- value: z.string().min(1).max(SECRET_VALUE_MAX_BYTES),
+ value: z.string().min(1).refine((value) => Buffer.byteLength(value) <= STORED_VAULT_VALUE_MAX_BYTES),
source: z.enum(["card", "settings"]),
bots: botsSchema,
refOnly: z.literal(true).optional(),
@@ -371,6 +378,7 @@ export class VaultStore {
/** The same name saved again for the same bots and the same person replaces its value; otherwise it is a new secret. */
saveSecret(input: NewSecret): VaultSecret {
+ checkNewSecretValue(input.value);
const data = this.read();
const secrets = data.secrets ?? [];
const at = this.now();
@@ -398,6 +406,7 @@ export class VaultStore {
const at = this.now();
const current = secrets.find((secret) => secret.id === input.id);
if (current?.person) return null;
+ checkNewSecretValue(input.value);
const received: StoredSecret = {
id: input.id, name: input.name, value: input.value, source: input.source, bots: input.bots, ...(input.refOnly ? { refOnly: true } : {}),
createdAt: current?.createdAt ?? at, updatedAt: at, ...(current?.lastUsedAt === undefined ? {} : { lastUsedAt: current.lastUsedAt }),
@@ -411,6 +420,7 @@ export class VaultStore {
const data = this.read();
const current = data.secrets?.find((secret) => secret.id === id);
if (!data.secrets || !current) return null;
+ if (patch.value !== undefined) checkNewSecretValue(patch.value);
const next: StoredSecret = {
...current,
...(patch.name === undefined ? {} : { name: patch.name }),
diff --git a/server/vault/value-limits.ts b/server/vault/value-limits.ts
new file mode 100644
index 0000000000..f646cdfbe8
--- /dev/null
+++ b/server/vault/value-limits.ts
@@ -0,0 +1,8 @@
+import { SECRET_VALUE_MAX_BYTES } from "../../shared/vault.ts";
+import { DATA_FORMAT } from "../data-format.ts";
+
+export const STORED_VAULT_VALUE_MAX_BYTES = 65_536;
+export const VAULT_VALUE_MAX_BYTES = DATA_FORMAT.writes >= 2 ? STORED_VAULT_VALUE_MAX_BYTES : SECRET_VALUE_MAX_BYTES;
+
+// A JSON string may encode one byte as six (\u0000). Leave room for the other request fields.
+export const VAULT_VALUE_BODY_MAX_BYTES = DATA_FORMAT.writes >= 2 ? VAULT_VALUE_MAX_BYTES * 6 + 16_384 : 16_384;