Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(config-sync): replace WebDAV with S3 backup and sync

vastsa047cd033bfce
diff --git a/Cargo.lock b/Cargo.lock
index 82d87adbb..b89823961 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -605,6 +605,7 @@ dependencies = [
"rand",
"regex",
"reqwest",
+ "ring",
"rusqlite",
"serde",
"serde_json",
diff --git a/apps/desktop/electron/main/ipc/config-sync-ipc.ts b/apps/desktop/electron/main/ipc/config-sync-ipc.ts
index f869668cc..001ee9235 100644
--- a/apps/desktop/electron/main/ipc/config-sync-ipc.ts
+++ b/apps/desktop/electron/main/ipc/config-sync-ipc.ts
@@ -8,7 +8,7 @@ export type ConfigSyncIpcDependencies = {
sendToRenderer: (channel: string, payload?: unknown) => void;
};
-/** Keep WebDAV credentials and vault passwords inside Host IPC calls. */
+/** Keep S3 credentials and vault passwords inside transient Host IPC calls. */
export function registerConfigSyncIpc({
registrar,
getHost,
@@ -24,7 +24,7 @@ export function registerConfigSyncIpc({
const host = getHost();
if (!host) throw new Error("host unavailable");
const result = await fn(...args);
- if (channel !== IPC.invoke.configSyncTest) {
+ if (channel !== IPC.invoke.configSyncTest && channel !== IPC.invoke.configSyncListHistory) {
sendToRenderer(IPC.event.configSyncChanged, result);
}
return result;
diff --git a/apps/desktop/src/components/settings/ConfigSyncConnectionFields.tsx b/apps/desktop/src/components/settings/ConfigSyncConnectionFields.tsx
new file mode 100644
index 000000000..4620c9124
--- /dev/null
+++ b/apps/desktop/src/components/settings/ConfigSyncConnectionFields.tsx
@@ -0,0 +1,82 @@
+import { useTranslation } from "react-i18next";
+import type { ConfigSyncForm } from "../../features/settings/config-sync-form";
+import { Checkbox, Field, Input, PasswordInput } from "../ui";
+import { SettingsMenuSelect } from "./SettingsMenuSelect";
+
+type Props = {
+ form: ConfigSyncForm;
+ configured: boolean;
+ locked: boolean;
+ disabled: boolean;
+ onChange: <K extends keyof ConfigSyncForm>(key: K, value: ConfigSyncForm[K]) => void;
+};
+
+export function ConfigSyncConnectionFields({ form, configured, locked, disabled, onChange }: Props) {
+ const { t } = useTranslation();
+ return (
+ <div className="settings-config-sync-form">
+ <Field label={t("settings.configSync.mode")} hint={t("settings.configSync.modeHint")}>
+ <SettingsMenuSelect
+ fullWidth label={t("settings.configSync.mode")} value={form.mode} disabled={disabled}
+ options={[
+ { id: "sync", label: t("settings.configSync.modeSync") },
+ { id: "backup", label: t("settings.configSync.modeBackup") },
+ ]}
+ onChange={(value) => { if (value === "sync" || value === "backup") onChange("mode", value); }}
+ />
+ </Field>
+ <Field label={t("settings.configSync.endpoint")}>
+ <Input value={form.endpoint} onChange={(event) => onChange("endpoint", event.target.value)}
+ placeholder={t("settings.configSync.endpointPlaceholder")} aria-label={t("settings.configSync.endpoint")}
+ autoComplete="url" disabled={disabled} />
+ </Field>
+ {(["region", "bucket", "prefix", "accessKeyId"] as const).map((key) => (
+ <Field key={key} label={t(`settings.configSync.${key}`)}>
+ <Input value={form[key]} onChange={(event) => onChange(key, event.target.value)}
+ aria-label={t(`settings.configSync.${key}`)} autoComplete="off" disabled={disabled} />
+ </Field>
+ ))}
+ <Field label={t("settings.configSync.addressing")} hint={t("settings.configSync.addressingHint")}>
+ <SettingsMenuSelect fullWidth label={t("settings.configSync.addressing")}
+ value={form.pathStyle ? "path" : "virtual"} disabled={disabled}
+ options={[
+ { id: "path", label: t("settings.configSync.pathStyle") },
+ { id: "virtual", label: t("settings.configSync.virtualHosted") },
+ ]}
+ onChange={(value) => onChange("pathStyle", value === "path")} />
+ </Field>
+ <Field label={t("settings.configSync.secretAccessKey")}
+ hint={configured ? t("settings.configSync.secretSavedHint") : undefined}>
+ <PasswordInput value={form.secretAccessKey}
+ onChange={(event) => onChange("secretAccessKey", event.target.value)}
+ aria-label={t("settings.configSync.secretAccessKey")} autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")} hideLabel={t("settings.configSync.hidePassword")}
+ disabled={disabled} />
+ </Field>
+ <Field label={t("settings.configSync.sessionToken")} hint={t("settings.configSync.sessionTokenHint")}>
+ <PasswordInput value={form.sessionToken}
+ onChange={(event) => onChange("sessionToken", event.target.value)}
+ aria-label={t("settings.configSync.sessionToken")} autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")} hideLabel={t("settings.configSync.hidePassword")}
+ disabled={disabled || form.clearSessionToken} />
+ {configured ? <Checkbox checked={form.clearSessionToken}
+ onChange={(event) => onChange("clearSessionToken", event.target.checked)}
+ label={t("settings.configSync.clearSessionToken")} disabled={disabled} /> : null}
+ </Field>
+ <Field label={t("settings.configSync.deviceLabel")}>
+ <Input value={form.deviceLabel} onChange={(event) => onChange("deviceLabel", event.target.value)}
+ placeholder={t("settings.configSync.defaultDevice")} aria-label={t("settings.configSync.deviceLabel")}
+ autoComplete="off" disabled={disabled} />
+ </Field>
+ <Field label={configured ? t("settings.configSync.backupPasswordUnlock") : t("settings.configSync.backupPassword")}
+ hint={configured && !locked ? t("settings.configSync.backupPasswordOptional") : t("settings.configSync.backupPasswordHint")}>
+ <PasswordInput value={form.backupPassword} onChange={(event) => onChange("backupPassword", event.target.value)}
+ aria-label={t("settings.configSync.backupPassword")} autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")} hideLabel={t("settings.configSync.hidePassword")}
+ disabled={disabled} />
+ </Field>
+ <Checkbox checked={form.automaticSync} onChange={(event) => onChange("automaticSync", event.target.checked)}
+ label={t("settings.configSync.automaticSync")} disabled={disabled} />
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/settings/ConfigSyncPage.tsx b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
index ed46d3fb5..054a639ee 100644
--- a/apps/desktop/src/components/settings/ConfigSyncPage.tsx
+++ b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
@@ -6,11 +6,10 @@ import type {
ConfigSyncHistoryEntry,
ConfigSyncPendingApproval,
ConfigSyncProgress,
- ConfigSyncRemoteMode,
ConfigSyncState,
} from "@pi-desktop/shared";
import { api } from "../../lib/api";
-import { Badge, Button, Checkbox, Field, Input, PasswordInput, SettingsToggle } from "../ui";
+import { Badge, Button, Checkbox, PasswordInput, SettingsToggle } from "../ui";
import { IconCloudDown, IconRefresh, IconShield, IconTrash } from "../icons";
import { SettingsCard, SettingsRow } from "../../features/settings/primitives";
import { configSyncProgressView } from "../../features/settings/config-sync-progress";
@@ -26,7 +25,17 @@ import {
writeConfigSyncDraft,
} from "../../features/settings/config-sync-preferences";
import { ConfigSyncError } from "./ConfigSyncError";
-import { SettingsMenuSelect } from "./SettingsMenuSelect";
+import { ConfigSyncConnectionFields } from "./ConfigSyncConnectionFields";
+import {
+ type ConfigSyncForm,
+ clearConfigSyncFormSecrets,
+ configSyncConfigureInput,
+ configSyncTestInput,
+ draftFromForm,
+ draftFromState,
+ initialConfigSyncForm,
+ selectionFromDraft,
+} from "../../features/settings/config-sync-form";
function formatStamp(value: string): string {
const date = new Date(value);
@@ -48,68 +57,6 @@ const CATEGORIES: Array<{
{ id: "automation", label: "settings.configSync.categoryAutomation" },
];
-const DEFAULT_SELECTION: ConfigSyncCategorySelection = {
- application: true,
- providers: true,
- credentials: false,
- mcp: true,
- skills: true,
- subagents: true,
- instructions: true,
- projects: true,
- plugins: true,
- automation: true,
- memory: false,
-};
-
-type ConfigSyncForm = {
- endpoint: string;
- username: string;
- appPassword: string;
- directory: string;
- deviceLabel: string;
- backupPassword: string;
- currentBackupPassword: string;
- newBackupPassword: string;
-};
-
-function selectionFromDraft(
- categories?: Partial<ConfigSyncCategorySelection>,
-): ConfigSyncCategorySelection {
- return {
- ...DEFAULT_SELECTION,
- ...(categories ?? {}),
- };
-}
-
-function initialConfigSyncForm(draft = readConfigSyncDraft()): ConfigSyncForm {
- return {
- endpoint: draft.endpoint ?? "",
- username: draft.username ?? "",
- appPassword: "",
- directory: draft.directory ?? "pi-desktop",
- deviceLabel: draft.deviceLabel ?? "",
- backupPassword: "",
- currentBackupPassword: "",
- newBackupPassword: "",
- };
-}
-
-function draftFromState(next: ConfigSyncState) {
- return {
- endpoint: next.endpoint ?? "",
- username: next.username ?? "",
- directory: next.directory ?? "pi-desktop",
- deviceLabel: next.deviceLabel ?? "",
- remoteMode: next.remoteMode,
- categories: {
- ...next.categories,
- credentials: next.includeSecrets,
- memory: next.includeMemory,
- },
- saved: true,
- };
-}
function statusTone(
status: ConfigSyncState["status"],
@@ -159,9 +106,6 @@ export function ConfigSyncPage() {
const [selection, setSelection] = useState<ConfigSyncCategorySelection>(() =>
selectionFromDraft(initialDraft.categories),
);
- const [remoteMode, setRemoteMode] = useState<ConfigSyncRemoteMode>(
- () => initialDraft.remoteMode ?? "strict",
- );
const mountedRef = useRef(true);
const formDirtyRef = useRef(initialDraft.saved === false);
const stateRequestRef = useRef(0);
@@ -172,7 +116,10 @@ export function ConfigSyncPage() {
// still in flight. Invalidating that request prevents stale state from
// replacing the result the user just triggered.
stateRequestRef.current += 1;
- cacheConfigSyncState(next);
+ if (cacheConfigSyncState(next)) {
+ historyRequestRef.current += 1;
+ setHistory([]);
+ }
setState(next);
setLoading(false);
}, []);
@@ -182,13 +129,16 @@ export function ConfigSyncPage() {
const draft = draftFromState(next);
setForm((current) => ({
...current,
- endpoint: draft.endpoint,
- username: draft.username,
- directory: draft.directory,
- deviceLabel: draft.deviceLabel,
+ ...initialConfigSyncForm(draft),
+ // Background status refreshes must not erase a password being entered.
+ secretAccessKey: current.secretAccessKey,
+ sessionToken: current.sessionToken,
+ clearSessionToken: current.clearSessionToken,
+ backupPassword: current.backupPassword,
+ currentBackupPassword: current.currentBackupPassword,
+ newBackupPassword: current.newBackupPassword,
}));
setSelection(selectionFromDraft(draft.categories));
- setRemoteMode(draft.remoteMode);
writeConfigSyncDraft({ ...draft, saved: true });
}, []);
@@ -262,6 +212,7 @@ export function ConfigSyncPage() {
}, [applyState, clearHistory, hydrateSavedFields, refresh, refreshHistory]);
useEffect(() => {
+ mountedRef.current = true;
return () => {
mountedRef.current = false;
historyRequestRef.current += 1;
@@ -272,7 +223,7 @@ export function ConfigSyncPage() {
// automatic run stays silent; the subscription is dropped with the page.
useEffect(() => api.onConfigSyncProgress((next) => setProgress(next)), []);
- const updateForm = (key: keyof ConfigSyncForm, value: string) => {
+ const updateForm = <K extends keyof ConfigSyncForm,>(key: K, value: ConfigSyncForm[K]) => {
formDirtyRef.current = true;
setForm((current) => ({ ...current, [key]: value }));
};
@@ -282,95 +233,34 @@ export function ConfigSyncPage() {
setSelection((current) => ({ ...current, [key]: value }));
};
- const updateRemoteMode = (value: ConfigSyncRemoteMode) => {
- formDirtyRef.current = true;
- setRemoteMode(value);
- };
-
useEffect(() => {
if (!formDirtyRef.current) return;
- writeConfigSyncDraft({
- endpoint: form.endpoint,
- username: form.username,
- directory: form.directory,
- deviceLabel: form.deviceLabel,
- remoteMode,
- categories: selection,
- saved: false,
- });
- }, [
- form.deviceLabel,
- form.directory,
- form.endpoint,
- form.username,
- remoteMode,
- selection,
- ]);
+ writeConfigSyncDraft(draftFromForm(form, selection));
+ }, [form, selection]);
const run = async (
operation: "test" | "configure" | "sync" | "unlock" | "disconnect",
) => {
- if (
- operation === "configure" &&
- remoteMode === "appendOnly" &&
- !window.confirm(t("settings.configSync.appendOnlyConfirm"))
- ) {
- return;
- }
setBusy(operation);
setError(null);
try {
if (operation === "test") {
- const result = await api.configSyncTest({
- endpoint: form.endpoint,
- username: form.username,
- appPassword: form.appPassword || undefined,
- directory: form.directory,
- deviceLabel: form.deviceLabel || t("settings.configSync.defaultDevice"),
- categories: selection,
- includeSecrets: selection.credentials,
- includeMemory: selection.memory,
- automaticSync: true,
- remoteMode,
- });
- const supported =
- remoteMode === "appendOnly" ? result.appendOnly : result.conditionalWrites;
- showToast(
- t(
- remoteMode === "appendOnly"
- ? supported
- ? "settings.configSync.testAppendOnlySuccess"
- : "settings.configSync.testAppendOnlyUnsupported"
- : supported
- ? "settings.configSync.testSuccess"
- : "settings.configSync.testUnsupported",
- ),
- { variant: supported ? "success" : "warning" },
- );
+ await api.configSyncTest(configSyncTestInput(form, selection, t("settings.configSync.defaultDevice")));
+ showToast(t("settings.configSync.testSuccess"), { variant: "success" });
} else if (operation === "configure") {
clearHistory();
- const configuredState = await api.configSyncConfigure({
- endpoint: form.endpoint,
- username: form.username,
- appPassword: form.appPassword || undefined,
- directory: form.directory,
- deviceLabel: form.deviceLabel || t("settings.configSync.defaultDevice"),
- backupPassword: form.backupPassword,
- categories: selection,
- includeSecrets: selection.credentials,
- includeMemory: selection.memory,
- automaticSync: true,
- remoteMode,
- });
+ const configuredState = await api.configSyncConfigure(
+ configSyncConfigureInput(form, selection, t("settings.configSync.defaultDevice")),
+ );
// Show the saved connection immediately while the first full sync is
// still running. The previous flow kept the page in its unconfigured
// shape until sync completed, which made a slow first setup look stuck.
applyState(configuredState);
formDirtyRef.current = false;
hydrateSavedFields(configuredState);
+ setForm(clearConfigSyncFormSecrets);
applyState(await api.configSyncSyncNow());
void refreshHistory(false);
- setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));
showToast(t("settings.configSync.configured"), { variant: "success" });
} else if (operation === "sync") {
applyState(await api.configSyncSyncNow());
@@ -382,7 +272,6 @@ export function ConfigSyncPage() {
applyState(await api.configSyncDisconnect());
clearConfigSyncDraft();
clearHistory();
- setRemoteMode("strict");
formDirtyRef.current = false;
setForm(initialConfigSyncForm());
setSelection(selectionFromDraft());
@@ -422,14 +311,15 @@ export function ConfigSyncPage() {
};
const restore = async (entry: ConfigSyncHistoryEntry) => {
- if (!window.confirm(t("settings.configSync.restoreConfirm"))) return;
+ const propagate = state?.mode === "sync";
+ if (!window.confirm(t(propagate ? "settings.configSync.restoreConfirm" : "settings.configSync.restoreBackupConfirm"))) return;
setBusy("restore");
setError(null);
try {
applyState(
await api.configSyncRestore({
revisionId: entry.revisionId,
- acknowledgePropagation: true,
+ acknowledgePropagation: propagate,
}),
);
await refreshHistory(true);
@@ -536,6 +426,7 @@ export function ConfigSyncPage() {
const locked = state?.locked === true;
const stateReady = state !== null;
const categories = selection;
+ const connectionReady = Boolean(form.endpoint.trim() && form.region.trim() && form.bucket.trim() && form.accessKeyId.trim());
const vaultPasswordReady =
form.backupPassword.length === 0
? configured && !locked
@@ -566,114 +457,13 @@ export function ConfigSyncPage() {
title={t("settings.configSync.connectionTitle")}
description={t("settings.configSync.connectionDescription")}
>
- <div className="settings-config-sync-form">
- <Field label={t("settings.configSync.endpoint")}>
- <Input
- value={form.endpoint}
- onChange={(event) => updateForm("endpoint", event.target.value)}
- placeholder={t("settings.configSync.endpointPlaceholder")}
- aria-label={t("settings.configSync.endpoint")}
- autoComplete="url"
- disabled={busy !== null}
- />
- </Field>
- <Field
- label={t("settings.configSync.remoteMode")}
- hint={t("settings.configSync.remoteModeHint")}
- >
- <SettingsMenuSelect
- fullWidth
- label={t("settings.configSync.remoteMode")}
- value={remoteMode}
- disabled={busy !== null}
- options={[
- {
- id: "strict",
- label: t("settings.configSync.remoteModeStrict"),
- },
- {
- id: "appendOnly",
- label: t("settings.configSync.remoteModeAppendOnly"),
- },
- ]}
- onChange={(value) => updateRemoteMode(value as ConfigSyncRemoteMode)}
- />
- </Field>
- {remoteMode === "appendOnly" ? (
- <div className="settings-config-sync-warning" role="alert">
- {t("settings.configSync.appendOnlyWarning")}
- </div>
- ) : null}
- <Field label={t("settings.configSync.username")}>
- <Input
- value={form.username}
- onChange={(event) => updateForm("username", event.target.value)}
- aria-label={t("settings.configSync.username")}
- autoComplete="username"
- disabled={busy !== null}
- />
- </Field>
- <Field
- label={t("settings.configSync.appPassword")}
- hint={configured ? t("settings.configSync.appPasswordSavedHint") : undefined}
- >
- <PasswordInput
- value={form.appPassword}
- onChange={(event) => updateForm("appPassword", event.target.value)}
- aria-label={t("settings.configSync.appPassword")}
- autoComplete="current-password"
- showLabel={t("settings.configSync.showPassword")}
- hideLabel={t("settings.configSync.hidePassword")}
- disabled={busy !== null}
- />
- </Field>
- <Field label={t("settings.configSync.directory")}>
- <Input
- value={form.directory}
- onChange={(event) => updateForm("directory", event.target.value)}
- aria-label={t("settings.configSync.directory")}
- autoComplete="off"
- disabled={busy !== null}
- />
- </Field>
- <Field label={t("settings.configSync.deviceLabel")}>
- <Input
- value={form.deviceLabel}
- onChange={(event) => updateForm("deviceLabel", event.target.value)}
- placeholder={t("settings.configSync.defaultDevice")}
- aria-label={t("settings.configSync.deviceLabel")}
- autoComplete="off"
- disabled={busy !== null}
- />
- </Field>
- <Field
- label={
- configured
- ? t("settings.configSync.backupPasswordUnlock")
- : t("settings.configSync.backupPassword")
- }
- hint={
- configured && !locked
- ? t("settings.configSync.backupPasswordOptional")
- : t("settings.configSync.backupPasswordHint")
- }
- >
- <PasswordInput
- value={form.backupPassword}
- onChange={(event) => updateForm("backupPassword", event.target.value)}
- aria-label={t("settings.configSync.backupPassword")}
- autoComplete="new-password"
- showLabel={t("settings.configSync.showPassword")}
- hideLabel={t("settings.configSync.hidePassword")}
- disabled={busy !== null}
- />
- </Field>
- </div>
+ <ConfigSyncConnectionFields form={form} configured={configured} locked={locked}
+ disabled={busy !== null} onChange={updateForm} />
<div className="settings-config-sync-actions">
<Button
variant="secondary"
onClick={() => void run("test")}
- disabled={busy !== null || loading || !stateReady || !form.endpoint}
+ disabled={busy !== null || loading || !stateReady || !connectionReady}
>
<IconRefresh size={14} />
{t("settings.configSync.test")}
@@ -682,7 +472,7 @@ export function ConfigSyncPage() {
variant="primary"
onClick={() => void run("configure")}
disabled={
- busy !== null || loading || !stateReady || !form.endpoint || !vaultPasswordReady
+ busy !== null || loading || !stateReady || !connectionReady || !vaultPasswordReady
}
>
<IconCloudDown size={14} />
@@ -694,7 +484,7 @@ export function ConfigSyncPage() {
onClick={() => void run("sync")}
disabled={busy !== null || state?.paused}
>
- {t("settings.configSync.syncNow")}
+ {t(state?.mode === "backup" ? "settings.configSync.backupNow" : "settings.configSync.syncNow")}
</Button>
) : null}
</div>
@@ -847,6 +637,7 @@ export function ConfigSyncPage() {
key={category.id}
className="settings-config-sync-category"
checked={categories[category.id] !== false}
+ disabled={busy !== null}
onChange={(event) =>
updateSelection(category.id, event.target.checked)
}
@@ -856,6 +647,7 @@ export function ConfigSyncPage() {
<Checkbox
className="settings-config-sync-category"
checked={selection.memory}
+ disabled={busy !== null}
onChange={(event) =>
updateSelection("memory", event.target.checked)
}
@@ -864,6 +656,7 @@ export function ConfigSyncPage() {
<Checkbox
className="settings-config-sync-category settings-config-sync-sensitive"
checked={selection.credentials}
+ disabled={busy !== null}
onChange={(event) =>
updateSelection("credentials", event.target.checked)
}
@@ -1019,7 +812,7 @@ export function ConfigSyncPage() {
size="sm"
variant="secondary"
onClick={() => void restore(entry)}
- disabled={busy !== null || entry.current || locked}
+ disabled={busy !== null || (entry.current && state.mode === "sync") || locked}
>
{t("settings.configSync.restore")}
</Button>
diff --git a/apps/desktop/src/features/settings/config-sync-form.ts b/apps/desktop/src/features/settings/config-sync-form.ts
new file mode 100644
index 000000000..7b1972414
--- /dev/null
+++ b/apps/desktop/src/features/settings/config-sync-form.ts
@@ -0,0 +1,82 @@
+import type { ConfigSyncCategorySelection, ConfigSyncConfigureInput, ConfigSyncConnection, ConfigSyncMode, ConfigSyncState, ConfigSyncTestInput } from "@pi-desktop/shared";
+import type { ConfigSyncDraft } from "./config-sync-preferences";
+
+/** Transient form memory only. Never serialize this object directly. */
+export type ConfigSyncForm = ConfigSyncConnection & {
+ mode: ConfigSyncMode;
+ automaticSync: boolean;
+ deviceLabel: string;
+ secretAccessKey: string;
+ sessionToken: string;
+ clearSessionToken: boolean;
+ backupPassword: string;
+ currentBackupPassword: string;
+ newBackupPassword: string;
+};
+
+export function selectionFromDraft(categories?: Partial<ConfigSyncCategorySelection>): ConfigSyncCategorySelection {
+ return {
+ application: true, providers: true, credentials: false, mcp: true,
+ skills: true, subagents: true, instructions: true, projects: true,
+ plugins: true, automation: true, memory: false,
+ ...categories,
+ };
+}
+
+export function initialConfigSyncForm(draft: ConfigSyncDraft = {}): ConfigSyncForm {
+ return {
+ endpoint: draft.endpoint ?? "",
+ region: draft.region ?? "us-east-1",
+ bucket: draft.bucket ?? "",
+ prefix: draft.prefix ?? "pi-desktop/config",
+ accessKeyId: draft.accessKeyId ?? "",
+ pathStyle: draft.pathStyle ?? true,
+ mode: draft.mode ?? "sync",
+ automaticSync: draft.automaticSync ?? true,
+ deviceLabel: draft.deviceLabel ?? "",
+ secretAccessKey: "", sessionToken: "", clearSessionToken: false,
+ backupPassword: "", currentBackupPassword: "", newBackupPassword: "",
+ };
+}
+
+export function draftFromState(next: ConfigSyncState): ConfigSyncDraft {
+ return {
+ endpoint: next.endpoint, region: next.region, bucket: next.bucket,
+ prefix: next.prefix, accessKeyId: next.accessKeyId, pathStyle: next.pathStyle,
+ mode: next.mode, automaticSync: next.automaticSync, deviceLabel: next.deviceLabel,
+ categories: { ...next.categories, credentials: next.includeSecrets, memory: next.includeMemory },
+ saved: true,
+ };
+}
+
+export function draftFromForm(form: ConfigSyncForm, categories: ConfigSyncCategorySelection): ConfigSyncDraft {
+ return {
+ endpoint: form.endpoint, region: form.region, bucket: form.bucket,
+ prefix: form.prefix, accessKeyId: form.accessKeyId, pathStyle: form.pathStyle,
+ mode: form.mode, automaticSync: form.automaticSync, deviceLabel: form.deviceLabel,
+ categories, saved: false,
+ };
+}
+
+/** One request projection for connection tests and saves. Secrets stay byte-exact. */
+export function configSyncTestInput(form: ConfigSyncForm, categories: ConfigSyncCategorySelection, defaultDevice: string): ConfigSyncTestInput {
+ return {
+ endpoint: form.endpoint.trim(), region: form.region.trim(), bucket: form.bucket.trim(),
+ prefix: form.prefix.trim(), accessKeyId: form.accessKeyId.trim(), pathStyle: form.pathStyle,
+ mode: form.mode, automaticSync: form.automaticSync,
+ deviceLabel: form.deviceLabel.trim() || defaultDevice,
+ secretAccessKey: form.secretAccessKey || undefined,
+ // A complete replacement must not accidentally reuse an old temporary token.
+ sessionToken: form.clearSessionToken ? "" : form.sessionToken || (form.secretAccessKey ? "" : undefined),
+ categories, includeSecrets: categories.credentials, includeMemory: categories.memory,
+ };
+}
+
+export function configSyncConfigureInput(form: ConfigSyncForm, categories: ConfigSyncCategorySelection, defaultDevice: string): ConfigSyncConfigureInput {
+ return { ...configSyncTestInput(form, categories, defaultDevice), backupPassword: form.backupPassword };
+}
+
+export function clearConfigSyncFormSecrets(form: ConfigSyncForm): ConfigSyncForm {
+ return { ...form, secretAccessKey: "", sessionToken: "", clearSessionToken: false,
+ backupPassword: "", currentBackupPassword: "", newBackupPassword: "" };
+}
diff --git a/apps/desktop/src/features/settings/config-sync-preferences.ts b/apps/desktop/src/features/settings/config-sync-preferences.ts
index c1b612f96..fdd8c8dc0 100644
--- a/apps/desktop/src/features/settings/config-sync-preferences.ts
+++ b/apps/desktop/src/features/settings/config-sync-preferences.ts
@@ -2,22 +2,26 @@ import type {
ConfigSyncCategory,
ConfigSyncCategorySelection,
ConfigSyncHistoryEntry,
- ConfigSyncRemoteMode,
+ ConfigSyncMode,
ConfigSyncState,
} from "@pi-desktop/shared";
/**
* The draft is deliberately limited to non-sensitive connection fields.
- * The WebDAV app password and derived vault key stay in Host-owned secret
- * storage; the passwords are never copied into renderer persistence, even as a
+ * S3 secrets and derived vault keys stay in Host-owned secret storage;
+ * passwords are never copied into renderer persistence, even as a
* convenience cache.
*/
export type ConfigSyncDraft = {
endpoint?: string;
- username?: string;
- directory?: string;
+ region?: string;
+ bucket?: string;
+ prefix?: string;
+ accessKeyId?: string;
+ pathStyle?: boolean;
+ automaticSync?: boolean;
deviceLabel?: string;
- remoteMode?: ConfigSyncRemoteMode;
+ mode?: ConfigSyncMode;
categories?: Partial<ConfigSyncCategorySelection>;
/** False means the user left an unsaved draft; true mirrors Host state. */
saved?: boolean;
@@ -25,9 +29,12 @@ export type ConfigSyncDraft = {
type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
-export const CONFIG_SYNC_DRAFT_STORAGE_KEY = "pi.desktop.configSyncDraft";
+export const CONFIG_SYNC_DRAFT_STORAGE_KEY = "pi.desktop.configSyncS3Draft.v1";
export const CONFIG_SYNC_HISTORY_CACHE_TTL_MS = 30_000;
+const TEXT_FIELDS = ["endpoint", "region", "bucket", "prefix", "accessKeyId", "deviceLabel"] as const;
+const BOOLEAN_FIELDS = ["pathStyle", "automaticSync", "saved"] as const;
+
const CATEGORY_KEYS: ConfigSyncCategory[] = [
"application",
"providers",
@@ -61,8 +68,8 @@ function text(value: unknown): string | undefined {
return value;
}
-function remoteMode(value: unknown): ConfigSyncRemoteMode | undefined {
- return value === "strict" || value === "appendOnly" ? value : undefined;
+function syncMode(value: unknown): ConfigSyncMode | undefined {
+ return value === "sync" || value === "backup" ? value : undefined;
}
export function readConfigSyncDraft(store: StorageLike | null = storage()): ConfigSyncDraft {
@@ -74,13 +81,15 @@ export function readConfigSyncDraft(store: StorageLike | null = storage()): Conf
if (!object(parsed)) return {};
const draft: ConfigSyncDraft = {};
- for (const key of ["endpoint", "username", "directory", "deviceLabel"] as const) {
+ for (const key of TEXT_FIELDS) {
const value = text(parsed[key]);
if (value !== undefined) draft[key] = value;
}
- const mode = remoteMode(parsed.remoteMode);
- if (mode) draft.remoteMode = mode;
- if (typeof parsed.saved === "boolean") draft.saved = parsed.saved;
+ const mode = syncMode(parsed.mode);
+ if (mode) draft.mode = mode;
+ for (const key of BOOLEAN_FIELDS) {
+ if (typeof parsed[key] === "boolean") draft[key] = parsed[key];
+ }
if (object(parsed.categories)) {
const categories: Partial<ConfigSyncCategorySelection> = {};
@@ -105,13 +114,15 @@ export function writeConfigSyncDraft(
if (!store) return;
try {
const value: Record<string, unknown> = {};
- for (const key of ["endpoint", "username", "directory", "deviceLabel"] as const) {
+ for (const key of TEXT_FIELDS) {
const next = text(draft[key]);
if (next !== undefined) value[key] = next;
}
- const mode = remoteMode(draft.remoteMode);
- if (mode) value.remoteMode = mode;
- if (typeof draft.saved === "boolean") value.saved = draft.saved;
+ const mode = syncMode(draft.mode);
+ if (mode) value.mode = mode;
+ for (const key of BOOLEAN_FIELDS) {
+ if (typeof draft[key] === "boolean") value[key] = draft[key];
+ }
if (draft.categories && object(draft.categories)) {
const categories: Partial<ConfigSyncCategorySelection> = {};
for (const key of CATEGORY_KEYS) {
@@ -144,8 +155,19 @@ export function getCachedConfigSyncState(): ConfigSyncState | null {
return cachedState;
}
-export function cacheConfigSyncState(next: ConfigSyncState): void {
+/** Returns true when callers must invalidate their in-flight history request. */
+export function cacheConfigSyncState(next: ConfigSyncState): boolean {
+ const previous = cachedState;
+ const changed = previous === null ||
+ ["configured", "endpoint", "region", "bucket", "prefix", "accessKeyId", "pathStyle", "mode"].some(
+ (key) => previous[key as keyof ConfigSyncState] !== next[key as keyof ConfigSyncState],
+ );
+ if (changed) {
+ cachedHistory = null;
+ cachedHistoryAt = 0;
+ }
cachedState = next;
+ return changed;
}
export function getCachedConfigSyncHistory(): ConfigSyncHistoryEntry[] {
diff --git a/apps/desktop/src/features/settings/config-sync-progress.ts b/apps/desktop/src/features/settings/config-sync-progress.ts
index 106d1d422..a0455af2b 100644
--- a/apps/desktop/src/features/settings/config-sync-progress.ts
+++ b/apps/desktop/src/features/settings/config-sync-progress.ts
@@ -17,7 +17,6 @@ export const CONFIG_SYNC_PHASE_KEYS: Record<ConfigSyncPhase, string> = {
merge: "settings.configSync.progress.phase.merge",
upload: "settings.configSync.progress.phase.upload",
apply: "settings.configSync.progress.phase.apply",
- cleanup: "settings.configSync.progress.phase.cleanup",
};
/** What the card renders for one report. */
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 8115a5433..01be49a1d 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -2,6 +2,8 @@ import { projectPlanHistory } from "./plan-history";
import { guardRemoteInvocation } from "./remote-ipc-safety";
import { isRemoteSession, safeSessionSummary } from "./remote-session-safety";
import type {
+ ConfigSyncTestInput,
+ ConfigSyncTestResult,
ScheduledTaskRun,
ActivationScope,
AgentCapabilityMove,
@@ -692,16 +694,8 @@ export const api = {
configSyncGetState: () => invoke<ConfigSyncState>(IPC.invoke.configSyncGetState),
configSyncConfigure: (input: ConfigSyncConfigureInput) =>
invoke<ConfigSyncState>(IPC.invoke.configSyncConfigure, input),
- configSyncTest: (input: Omit<ConfigSyncConfigureInput, "backupPassword"> & { backupPassword?: string }) =>
- invoke<{
- ok: boolean;
- conditionalWrites: boolean;
- appendOnly: boolean;
- message?: string;
- }>(
- IPC.invoke.configSyncTest,
- input,
- ),
+ configSyncTest: (input: ConfigSyncTestInput) =>
+ invoke<ConfigSyncTestResult>(IPC.invoke.configSyncTest, input),
configSyncSyncNow: () => invoke<ConfigSyncState>(IPC.invoke.configSyncSyncNow),
configSyncPause: (paused: boolean) =>
invoke<ConfigSyncState>(IPC.invoke.configSyncPause, { paused }),
diff --git a/apps/desktop/test/config-sync-form.test.mjs b/apps/desktop/test/config-sync-form.test.mjs
new file mode 100644
index 000000000..fa71d18c8
--- /dev/null
+++ b/apps/desktop/test/config-sync-form.test.mjs
@@ -0,0 +1,49 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { initialConfigSyncForm, configSyncTestInput, configSyncConfigureInput, clearConfigSyncFormSecrets, selectionFromDraft, draftFromForm, draftFromState } = await import("../src/features/settings/config-sync-form.ts");
+
+const selection = selectionFromDraft();
+const input = (form) => configSyncTestInput(form, selection, "This device");
+
+test("blank credentials mean reuse; replacement and clearing are explicit", () => {
+ const form = initialConfigSyncForm();
+ assert.equal(input(form).secretAccessKey, undefined);
+ assert.equal(input(form).sessionToken, undefined);
+ assert.equal(input({ ...form, secretAccessKey: " exact secret " }).secretAccessKey, " exact secret ");
+ assert.equal(input({ ...form, secretAccessKey: "replacement" }).sessionToken, "");
+ assert.equal(input({ ...form, sessionToken: "temporary" }).sessionToken, "temporary");
+ assert.equal(input({ ...form, sessionToken: "temporary", clearSessionToken: true }).sessionToken, "");
+});
+
+test("test and save share choices but never send vault passwords in a probe", () => {
+ const form = { ...initialConfigSyncForm(), endpoint: " https://s3.example.com ", bucket: "private",
+ secretAccessKey: "secret", sessionToken: "token", backupPassword: " password ",
+ currentBackupPassword: "current", newBackupPassword: "new", mode: "backup", automaticSync: false };
+ const probe = input(form);
+ const saved = configSyncConfigureInput(form, selection, "This device");
+ assert.deepEqual(saved, { ...probe, backupPassword: " password " });
+ assert.equal(probe.endpoint, "https://s3.example.com");
+ assert.equal(probe.mode, "backup");
+ assert.equal(probe.automaticSync, false);
+ assert.equal(probe.includeSecrets, false);
+ assert.equal(probe.includeMemory, false);
+ assert.doesNotMatch(JSON.stringify(probe), /[Pp]assword|current|newBackup/);
+ assert.doesNotMatch(JSON.stringify(draftFromForm(form, selection)), /secretAccessKey|sessionToken|[Pp]assword/);
+ const cleared = clearConfigSyncFormSecrets(form);
+ for (const key of ["secretAccessKey", "sessionToken", "backupPassword", "currentBackupPassword", "newBackupPassword"]) assert.equal(cleared[key], "");
+ assert.equal(cleared.bucket, form.bucket);
+});
+
+test("saved choices hydrate without turning off opt-ins or turning on automatic runs", () => {
+ const state = { ...initialConfigSyncForm(), automaticSync: false, categories: selection,
+ includeSecrets: true, includeMemory: true, mode: "backup" };
+ const draft = draftFromState(state);
+ const form = initialConfigSyncForm(draft);
+ assert.equal(form.automaticSync, false);
+ assert.equal(form.mode, "backup");
+ assert.equal(draft.categories.credentials, true);
+ assert.equal(draft.categories.memory, true);
+ assert.equal(draft.saved, true);
+});
diff --git a/apps/desktop/test/config-sync-ipc.test.mjs b/apps/desktop/test/config-sync-ipc.test.mjs
new file mode 100644
index 000000000..bb55960c8
--- /dev/null
+++ b/apps/desktop/test/config-sync-ipc.test.mjs
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { IPC } from "@pi-desktop/shared";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { registerConfigSyncIpc } = await import("../electron/main/ipc/config-sync-ipc.ts");
+
+test("history and probe results never masquerade as configuration state events", async () => {
+ const handlers = new Map();
+ const events = [];
+ const calls = [];
+ const state = { configured: true, mode: "backup", pendingApprovals: [] };
+ const history = [{ revisionId: "revision-a", current: true }];
+ registerConfigSyncIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => ({ async call(method, input) {
+ calls.push([method, input]);
+ if (method === "configSync.listHistory") return history;
+ if (method === "configSync.test") return { ok: true, conditionalWrites: true };
+ return state;
+ } }),
+ sendToRenderer: (channel, value) => events.push([channel, value]),
+ });
+ assert.deepEqual(await handlers.get(IPC.invoke.configSyncListHistory)(), history);
+ assert.deepEqual(await handlers.get(IPC.invoke.configSyncTest)({ bucket: "private" }), { ok: true, conditionalWrites: true });
+ assert.deepEqual(events, []);
+ assert.equal(await handlers.get(IPC.invoke.configSyncConfigure)({ mode: "backup" }), state);
+ assert.deepEqual(events, [[IPC.event.configSyncChanged, state]]);
+ assert.deepEqual(calls.at(-1), ["configSync.configure", { mode: "backup" }]);
+});
diff --git a/apps/desktop/test/config-sync-preferences.test.mjs b/apps/desktop/test/config-sync-preferences.test.mjs
index eb400d966..834a9fe3c 100644
--- a/apps/desktop/test/config-sync-preferences.test.mjs
+++ b/apps/desktop/test/config-sync-preferences.test.mjs
@@ -9,87 +9,88 @@ const source = await readFile(
);
const require = createRequire(new URL("../../../packages/agent-runtime/package.json", import.meta.url));
const { transform } = require("esbuild");
-const compiled = await transform(source, {
- loader: "ts",
- format: "esm",
- target: "es2022",
-});
-const preferences = await import(
- `data:text/javascript,${encodeURIComponent(compiled.code)}`,
-);
+const compiled = await transform(source, { loader: "ts", format: "esm", target: "es2022" });
+const preferences = await import(`data:text/javascript,${encodeURIComponent(compiled.code)}`);
function fakeStorage() {
const values = new Map();
return {
values,
- getItem(key) {
- return values.get(key) ?? null;
- },
- setItem(key, value) {
- values.set(key, value);
- },
- removeItem(key) {
- values.delete(key);
- },
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, value),
+ removeItem: (key) => values.delete(key),
};
}
-test("config sync draft persists connection choices without secrets", () => {
- const store = fakeStorage();
- preferences.writeConfigSyncDraft(
- {
- endpoint: "http://127.0.0.1:49152/dav/",
- username: "alice",
- directory: "pi-desktop",
- deviceLabel: "MacBook",
- remoteMode: "strict",
- categories: { providers: true, credentials: false },
- saved: false,
- },
- store,
- );
+const connection = {
+ endpoint: "https://s3.example.com",
+ region: "us-east-1",
+ bucket: "private-config",
+ prefix: "pi-desktop/config",
+ accessKeyId: "test-access-id",
+ pathStyle: true,
+ mode: "sync",
+};
+const entries = [{ revisionId: "revision-a", current: true }];
- const raw = store.values.get(preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY);
- assert.ok(raw);
- assert.doesNotMatch(raw, /password|secret/i);
- assert.deepEqual(preferences.readConfigSyncDraft(store), {
- endpoint: "http://127.0.0.1:49152/dav/",
- username: "alice",
- directory: "pi-desktop",
+test("S3 draft round-trips only typed non-sensitive choices", () => {
+ const store = fakeStorage();
+ const draft = {
+ ...connection,
deviceLabel: "MacBook",
- remoteMode: "strict",
+ automaticSync: false,
categories: { providers: true, credentials: false },
saved: false,
- });
+ };
+ preferences.writeConfigSyncDraft({
+ ...draft,
+ secretAccessKey: "never-persist-secret",
+ sessionToken: "never-persist-token",
+ backupPassword: "never-persist-password",
+ currentBackupPassword: "never-persist-current",
+ newBackupPassword: "never-persist-new",
+ }, store);
+ const raw = store.values.get(preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY);
+ assert.doesNotMatch(raw, /never-persist|secretAccessKey|sessionToken|[Pp]assword/);
+ assert.deepEqual(preferences.readConfigSyncDraft(store), draft);
+});
+
+test("old WebDAV drafts are ignored and left untouched", () => {
+ const store = fakeStorage();
+ const legacy = JSON.stringify({ endpoint: "https://dav.example.com", username: "alice", directory: "old" });
+ store.setItem("pi.desktop.configSyncDraft", legacy);
+ assert.deepEqual(preferences.readConfigSyncDraft(store), {});
+ preferences.clearConfigSyncDraft(store);
+ assert.equal(store.getItem("pi.desktop.configSyncDraft"), legacy);
});
-test("config sync draft ignores malformed or overlong local storage values", () => {
+test("draft rejects malformed fields and strips injected credentials on read", () => {
const store = fakeStorage();
- store.setItem(
- preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY,
- JSON.stringify({
- endpoint: "x".repeat(2049),
- remoteMode: "unsafe",
- categories: { providers: "yes", mcp: true },
- saved: "no",
- }),
- );
- assert.deepEqual(preferences.readConfigSyncDraft(store), {
- categories: { mcp: true },
- });
+ store.setItem(preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY, JSON.stringify({
+ endpoint: "x".repeat(2049), mode: "unsafe", pathStyle: "yes",
+ categories: { providers: "yes", mcp: true }, saved: "no",
+ secretAccessKey: "hidden", sessionToken: "hidden",
+ }));
+ assert.deepEqual(preferences.readConfigSyncDraft(store), { categories: { mcp: true } });
+ store.setItem(preferences.CONFIG_SYNC_DRAFT_STORAGE_KEY, "{");
+ assert.deepEqual(preferences.readConfigSyncDraft(store), {});
});
-test("config sync history cache expires without blocking the state cache", () => {
- const entries = [{
- revisionId: "revision-a",
- createdAt: "2026-09-25T00:00:00.000Z",
- parentRevisionIds: [],
- entityCount: 1,
- resourceCount: 1,
- current: true,
- }];
+test("history expires and connection or mode changes invalidate it immediately", () => {
+ preferences.cacheConfigSyncState({ ...connection, configured: true });
preferences.cacheConfigSyncHistory(entries, 1000);
assert.equal(preferences.hasFreshConfigSyncHistory(1000), true);
assert.equal(preferences.hasFreshConfigSyncHistory(1000 + preferences.CONFIG_SYNC_HISTORY_CACHE_TTL_MS), false);
+ preferences.cacheConfigSyncState({ ...connection, configured: true, status: "syncing" });
assert.deepEqual(preferences.getCachedConfigSyncHistory(), entries);
+ for (const [field, value] of Object.entries({
+ endpoint: "https://other.example.com", region: "eu-west-1", bucket: "other-bucket",
+ prefix: "other-prefix", accessKeyId: "other-id", pathStyle: false, mode: "backup", configured: false,
+ })) {
+ preferences.cacheConfigSyncState({ ...connection, configured: true });
+ preferences.cacheConfigSyncHistory(entries, 1000);
+ assert.equal(preferences.cacheConfigSyncState({ ...connection, configured: true, [field]: value }), true);
+ assert.deepEqual(preferences.getCachedConfigSyncHistory(), [], field);
+ assert.equal(preferences.hasFreshConfigSyncHistory(1000), false, field);
+ }
});
diff --git a/apps/desktop/test/config-sync-progress.test.mjs b/apps/desktop/test/config-sync-progress.test.mjs
index 302cf530e..ff2933512 100644
--- a/apps/desktop/test/config-sync-progress.test.mjs
+++ b/apps/desktop/test/config-sync-progress.test.mjs
@@ -30,7 +30,6 @@ test("every phase names a catalog key", () => {
assert.deepEqual(Object.keys(CONFIG_SYNC_PHASE_KEYS).sort(), [
"apply",
"capture",
- "cleanup",
"download",
"merge",
"upload",
@@ -71,8 +70,7 @@ test("a download without a byte total falls back to the object count", () => {
});
test("a report with no announced total stays indeterminate", () => {
- // merge and cleanup are always counted per run, not per unit; so is a phase
- // whose total the host has not learned yet.
+ // A phase whose total the host has not learned yet stays indeterminate.
const view = configSyncProgressView(report("merge", { done: 4, bytesDone: 512 }));
assert.equal(view.determinate, false);
diff --git a/apps/desktop/test/config-sync-settings.test.mjs b/apps/desktop/test/config-sync-settings.test.mjs
index 36ef04946..32f5c1bb3 100644
--- a/apps/desktop/test/config-sync-settings.test.mjs
+++ b/apps/desktop/test/config-sync-settings.test.mjs
@@ -14,6 +14,7 @@ const read = (relativePath) =>
const settingsPage = await read("../src/features/settings/SettingsPage.tsx");
const settingsIndex = await read("../src/lib/settings-search.ts");
const syncPage = await read("../src/components/settings/ConfigSyncPage.tsx");
+const connectionFields = await read("../src/components/settings/ConfigSyncConnectionFields.tsx");
const syncPreferences = await read(
"../src/features/settings/config-sync-preferences.ts",
);
@@ -43,13 +44,10 @@ test("cloud sync rendering follows the settings visibility gate", () => {
test("cloud sync keeps credentials and vault operations on the host boundary", () => {
assert.match(syncPage, /api\.configSyncConfigure\(/);
assert.match(syncPage, /applyState\(await api\.configSyncSyncNow\(\)\)/);
- // The plaintext opt-in is the network mode now, not a WebDAV switch: the page
- // carries no per-endpoint HTTP acknowledgement of its own.
- assert.doesNotMatch(syncPage, /allowInsecureHttp/);
- assert.match(syncPage, /settings\.configSync\.remoteMode/);
- assert.match(syncPage, /settings\.configSync\.appendOnlyWarning/);
- assert.match(syncPage, /settings\.configSync\.appendOnlyConfirm/);
- assert.match(syncPage, /remoteMode/);
+ // HTTP policy remains Host-owned; unsafe conditional-write fallback is gone.
+ assert.doesNotMatch(syncPage + connectionFields, /allowInsecureHttp|appendOnly|remoteMode/);
+ assert.match(connectionFields, /settings\.configSync\.modeBackup/);
+ assert.match(connectionFields, /settings\.configSync\.modeSync/);
assert.match(syncPage, /api\.configSyncUnlock\(/);
assert.match(syncPage, /api\.configSyncMapProject\(/);
assert.match(syncPage, /api\.configSyncListHistory\(/);
@@ -68,7 +66,7 @@ test("cloud sync keeps a non-sensitive draft and paints cached state first", ()
assert.match(syncPage, /getCachedConfigSyncState\(\)/);
assert.match(syncPage, /getCachedConfigSyncHistory\(\)/);
assert.match(syncPage, /writeConfigSyncDraft\(/);
- assert.match(syncPage, /appPasswordSavedHint/);
+ assert.match(connectionFields, /secretSavedHint/);
assert.doesNotMatch(syncPage, /if \(loading\) \{[\s\S]{0,180}return \(/);
assert.match(syncPreferences, /passwords are never copied into renderer persistence/);
assert.match(syncPreferences, /CONFIG_SYNC_DRAFT_STORAGE_KEY/);
@@ -151,7 +149,6 @@ test("the sync card reports each phase with a readable fraction", () => {
"merge",
"upload",
"apply",
- "cleanup",
]) {
assert.match(
progressModel,
diff --git a/apps/desktop/test/config-sync-user-path.test.mjs b/apps/desktop/test/config-sync-user-path.test.mjs
new file mode 100644
index 000000000..629aeb488
--- /dev/null
+++ b/apps/desktop/test/config-sync-user-path.test.mjs
@@ -0,0 +1,214 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const fixture = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared";
+import { ConfigSyncPage } from "../../apps/desktop/src/components/settings/ConfigSyncPage";
+import { selectionFromDraft } from "../../apps/desktop/src/features/settings/config-sync-form";
+import { CONFIG_SYNC_DRAFT_STORAGE_KEY } from "../../apps/desktop/src/features/settings/config-sync-preferences";
+
+await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } }, interpolation: { escapeValue: false } });
+const label = (key) => i18n.t("settings.configSync." + key);
+const listeners = new Map();
+const calls = [];
+const confirmations = [];
+const initial = { configured: false, enabled: false, paused: false, locked: false,
+ status: "notConfigured", mode: "sync", pathStyle: true, automaticSync: true,
+ categories: selectionFromDraft(), includeSecrets: false,
+ includeMemory: false, pendingApprovals: [], mappings: [] };
+let state = initial;
+let releaseSync;
+let holdSync = true;
+let holdHistory = false;
+let releaseHistory;
+const history = () => [
+ { revisionId: "current-" + state.prefix, createdAt: "2026-01-02T00:00:00Z", entityCount: 1, current: true },
+ { revisionId: "older-" + state.prefix, createdAt: "2026-01-01T00:00:00Z", entityCount: 1, current: false },
+];
+window.confirm = (message) => { confirmations.push(message); return true; };
+window.piDesktop = { platform: "darwin", channels: IPC,
+ on(channel, callback) {
+ if (!listeners.has(channel)) listeners.set(channel, new Set());
+ listeners.get(channel).add(callback);
+ return () => listeners.get(channel).delete(callback);
+ },
+ async invoke(channel, input) {
+ calls.push({ channel, input: input === undefined ? undefined : JSON.parse(JSON.stringify(input)) });
+ let data;
+ if (channel === IPC.invoke.configSyncGetState) data = state;
+ else if (channel === IPC.invoke.configSyncTest) data = { ok: true, conditionalWrites: true };
+ else if (channel === IPC.invoke.configSyncConfigure) {
+ const { secretAccessKey, sessionToken, backupPassword, ...publicFields } = input;
+ state = { ...state, ...publicFields, configured: true, enabled: true, status: "upToDate" };
+ data = state;
+ } else if (channel === IPC.invoke.configSyncSyncNow) {
+ if (holdSync) await new Promise((resolve) => { releaseSync = resolve; });
+ data = state;
+ } else if (channel === IPC.invoke.configSyncListHistory) {
+ const captured = history();
+ if (holdHistory) {
+ holdHistory = false;
+ await new Promise((resolve) => { releaseHistory = resolve; });
+ }
+ data = captured;
+ } else if (channel === IPC.invoke.configSyncRestore) data = state;
+ else if (channel === IPC.invoke.configSyncDisconnect) data = state = initial;
+ else throw new Error("Unexpected IPC: " + channel);
+ return { ok: true, data };
+ },
+};
+localStorage.setItem("pi.desktop.configSyncDraft", JSON.stringify({ endpoint: "https://legacy.example.com" }));
+let view;
+const mount = () => { view = createRoot(document.getElementById("root")); flushSync(() => view.render(React.createElement(ConfigSyncPage))); };
+const check = (value, message) => { if (!value) throw new Error(message); };
+const frame = () => new Promise(requestAnimationFrame);
+const until = async (condition, message) => {
+ const end = performance.now() + 5000;
+ while (!condition()) { if (performance.now() > end) throw new Error(message); await frame(); }
+};
+const input = (key) => document.querySelector('input[aria-label="' + label(key) + '"]');
+const button = (key) => [...document.querySelectorAll("button")].find((node) => node.textContent.trim() === label(key));
+const last = (name) => calls.filter((call) => call.channel === IPC.invoke[name]).at(-1)?.input;
+const fill = async (key, value) => {
+ const element = input(key); check(element, "missing input " + key);
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(element, value);
+ element.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await frame();
+};
+const toggle = async (key) => {
+ const container = [...document.querySelectorAll("label")].find((node) => node.textContent.trim() === label(key));
+ check(container?.querySelector("input"), "missing checkbox " + key);
+ flushSync(() => container.querySelector("input").click()); await frame();
+};
+const choose = async (key, value) => {
+ const trigger = [...document.querySelectorAll("button")].find((node) => node.getAttribute("aria-label") === label(key));
+ flushSync(() => trigger.click()); await frame();
+ const option = [...document.querySelectorAll('[role="option"]')].find((node) => node.textContent.trim() === label(value));
+ check(option, "missing option " + value); flushSync(() => option.click()); await frame();
+};
+const click = async (key) => { check(button(key) && !button(key).disabled, "action unavailable " + key); flushSync(() => button(key).click()); await frame(); };
+const ready = () => until(() => button("save") && !button("save").disabled, "save did not settle");
+const verifyNoSecrets = () => {
+ const cache = localStorage.getItem(CONFIG_SYNC_DRAFT_STORAGE_KEY) ?? "";
+ check(!/test-secret|test-token|test-password|secretAccessKey|sessionToken|[Pp]assword/.test(cache), "secret leaked into draft");
+};
+mount();
+window.configSyncProbe = async () => {
+ await until(() => button("enable"), "initial page missing");
+ check(input("endpoint").value === "", "legacy draft reused as S3");
+ for (const [key, value] of Object.entries({ endpoint: "https://s3.example.com", bucket: "private-config",
+ accessKeyId: "test-access", secretAccessKey: "test-secret", sessionToken: "test-token", backupPassword: "test-password" })) await fill(key, value);
+ await choose("mode", "modeBackup");
+ await choose("addressing", "virtualHosted");
+ await toggle("automaticSync");
+ verifyNoSecrets();
+ await click("test");
+ await until(() => !button("test").disabled, "probe did not settle");
+ const probe = last("configSyncTest");
+ check(probe.mode === "backup" && probe.pathStyle === false && probe.automaticSync === false, "probe lost choices");
+ check(probe.secretAccessKey === "test-secret" && probe.sessionToken === "test-token" && !('backupPassword' in probe), "probe credential contract");
+ await click("enable");
+ await until(() => releaseSync, "first run did not start");
+ check(input("secretAccessKey").value === "" && input("sessionToken").value === "" && input("backupPassword").value === "", "saved secrets outlived configure");
+ check(last("configSyncConfigure").backupPassword === "test-password", "vault password missing");
+ holdSync = false; releaseSync(); await ready();
+ await until(() => document.body.textContent.includes("older-pi-desktop/config"), "history missing");
+ flushSync(() => view.unmount()); mount(); await ready();
+ check(input("bucket").value === "private-config", "saved connection not hydrated");
+ check(input("secretAccessKey").value === "", "secret returned on reopen");
+ await toggle("clearSessionToken"); await click("save"); await ready();
+ check(last("configSyncConfigure").sessionToken === "" && !('secretAccessKey' in last("configSyncConfigure")), "explicit token clear or key reuse lost");
+ check(last("configSyncConfigure").automaticSync === false, "automatic runs reenabled");
+ verifyNoSecrets();
+ await choose("mode", "modeSync");
+ await click("restore"); await ready();
+ check(confirmations.at(-1) === label("restoreBackupConfirm"), "unsaved mode changed restore semantics");
+ check(last("configSyncRestore").acknowledgePropagation === false, "backup restore propagated");
+ await click("save"); await ready();
+ await until(() => [...document.querySelectorAll("button")].some((node) => node.textContent.trim() === label("restore") && !node.disabled), "sync history missing");
+ const restore = [...document.querySelectorAll("button")].find((node) => node.textContent.trim() === label("restore") && !node.disabled);
+ flushSync(() => restore.click()); await ready();
+ check(confirmations.at(-1) === label("restoreConfirm") && last("configSyncRestore").acknowledgePropagation === true, "sync restore acknowledgment missing");
+ holdHistory = true; await click("refreshHistory");
+ await until(() => releaseHistory, "history request not held");
+ state = { ...state, prefix: "other-prefix" };
+ flushSync(() => { for (const callback of listeners.get(IPC.event.configSyncChanged) ?? []) callback(state); });
+ await until(() => document.body.textContent.includes("older-other-prefix"), "new connection history not loaded");
+ releaseHistory(); await ready();
+ check(!document.body.textContent.includes("older-pi-desktop/config"), "stale history overwrote new connection");
+ await click("disconnect");
+ await until(() => button("enable") && input("endpoint").value === "", "disconnect did not clear form");
+ check(localStorage.getItem(CONFIG_SYNC_DRAFT_STORAGE_KEY) === null, "disconnect retained draft");
+ check(localStorage.getItem("pi.desktop.configSyncDraft") !== null, "legacy draft deleted");
+ flushSync(() => view.unmount());
+ check(listeners.get(IPC.event.configSyncChanged)?.size === 0 && listeners.get(IPC.event.configSyncProgress)?.size === 0, "subscriptions leaked");
+ return { passed: true };
+};
+`;
+
+test("S3 settings user path preserves credentials, modes, history and legacy data", {
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
+}, async () => {
+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "s3-settings-"));
+ try {
+ await build({
+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ "@pi-desktop/shared": join(root, "packages/shared/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow, session } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ session.defaultSession.webRequest.onBeforeRequest({ urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"] }, (_details, callback) => callback({ cancel: true }));
+ const win = new BrowserWindow({ show: false, width: 1000, height: 900,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ console.log("S3_SETTINGS_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.configSyncProbe()")));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8"); stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); }
+ finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-6000));
+ assert.match(output, /S3_SETTINGS_PROBE \{"passed":true\}/);
+ } finally { await rm(temp, { recursive: true, force: true }); }
+});
diff --git a/crates/host-core/Cargo.toml b/crates/host-core/Cargo.toml
index ad0a6f24b..b77102b9d 100644
--- a/crates/host-core/Cargo.toml
+++ b/crates/host-core/Cargo.toml
@@ -18,6 +18,7 @@ globset = "0.4"
hex = "0.4"
ignore = "0.4"
regex = "1"
+ring = "0.17"
rusqlite = { version = "0.40", features = ["bundled", "functions"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/crates/host-core/src/config_sync/apply.rs b/crates/host-core/src/config_sync/apply.rs
index 0585b6d28..4ab673807 100644
--- a/crates/host-core/src/config_sync/apply.rs
+++ b/crates/host-core/src/config_sync/apply.rs
@@ -123,7 +123,14 @@ fn apply_entity(
current.remove(*field);
}
}
- current.extend(incoming.clone());
+ current.extend(
+ incoming
+ .iter()
+ .filter(|(name, _)| {
+ domains::PORTABLE_APPLICATION_FIELDS.contains(&name.as_str())
+ })
+ .map(|(name, value)| (name.clone(), value.clone())),
+ );
}
return st.db.set_setting("app", &current);
}
@@ -139,12 +146,18 @@ fn apply_entity(
return Ok(());
}
let mut payload = entity.payload.clone();
- let secret_value = payload
- .get("portableApiKey")
- .and_then(Value::as_str)
- .map(str::to_string);
+ let secret_value = config
+ .include_secrets
+ .then(|| {
+ payload
+ .get("portableApiKey")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .flatten();
if let Some(object) = payload.as_object_mut() {
object.remove("portableApiKey");
+ object.remove("secretValue");
object.insert("id".into(), Value::String(provider_id.into()));
if let Some(secret) = secret_value.as_ref() {
object.insert("secretValue".into(), Value::String(secret.clone()));
@@ -184,6 +197,12 @@ fn apply_entity(
}
if entity.domain == domains::DOMAIN_MCP {
let mut payload = entity.payload.clone();
+ if !config.include_secrets {
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("env");
+ object.remove("headers");
+ }
+ }
if let Some(path) = mapped_project_path(config, &payload)? {
if let Some(object) = payload.as_object_mut() {
object.remove("projectLogicalId");
@@ -227,6 +246,7 @@ fn apply_entity(
.payload
.get("packageFiles")
.and_then(Value::as_array)
+ .filter(|_| !entity.deleted)
.map(|descriptors| {
descriptors
.iter()
@@ -261,6 +281,15 @@ fn apply_entity(
.level
.as_deref()
.and_then(|value| CapabilityLevel::parse(Some(value)).ok());
+ let expected_package_files = if entity.deleted {
+ Vec::new()
+ } else {
+ st.user_skills.package_files(
+ &id,
+ level.unwrap_or(CapabilityLevel::Global),
+ package_project_path.as_deref(),
+ )?
+ };
if entity.deleted {
if !id.is_empty() {
st.user_skills
@@ -270,10 +299,11 @@ fn apply_entity(
st.user_skills.create(input)?;
}
if !entity.deleted {
- st.user_skills.write_package_files(
+ st.user_skills.replace_package_files(
&id,
level.unwrap_or(CapabilityLevel::Global),
package_project_path.as_deref(),
+ &expected_package_files,
&package_files,
)?;
}
@@ -514,7 +544,7 @@ fn apply_entity(
} else {
// Installation and activation remain explicit user actions. The
// portable intent is retained locally, but no plugin bytes or
- // permissions are pulled from WebDAV.
+ // permissions are pulled from S3.
config
.plugin_intents
.insert(plugin_id.to_string(), entity.payload.clone());
@@ -670,14 +700,17 @@ fn apply_bundle_locked(
applied.insert(key_id);
continue;
}
- if current_map
- .get(&logical_key)
- .map(|value| value.digest.as_str())
- != Some(before.digest.as_str())
- {
+ let unchanged = if before.deleted {
+ !current_map.contains_key(&logical_key)
+ } else {
+ current_map
+ .get(&logical_key)
+ .is_some_and(|current| merge::same_version(current, before))
+ };
+ if !unchanged {
continue;
}
- if entity.digest == before.digest {
+ if merge::same_version(entity, before) {
// The candidate already matches the coherent local snapshot.
// Treat it as acknowledged without re-applying it; this is
// important for path-bound entities whose local overlay is
@@ -701,22 +734,14 @@ fn apply_bundle_locked(
}
}
}
+ conflicts::record(config, bundle, &applied);
let next_base = acknowledged_manifest(base, &bundle.manifest, &applied);
- store_base(st, key, &next_base)?;
let remaining: Vec<_> = staged
.approvals
.iter()
.filter(|item| !item.approved)
.cloned()
.collect();
- if remaining.is_empty() {
- clear_pending(st)?;
- } else {
- let mut next = staged;
- next.approvals = remaining;
- next.journal_state = "staged".into();
- store_pending(st, key, &next)?;
- }
let after = domains::capture(
st,
key,
@@ -725,12 +750,34 @@ fn apply_bundle_locked(
&config.plugin_intents,
&identity_overrides(config),
)?;
+ let previous = baseline::load(st, key)?;
+ let applied_logical = bundle
+ .manifest
+ .entities
+ .iter()
+ .filter(|entity| applied.contains(&entity_key(entity)))
+ .map(logical_entity_key)
+ .collect();
+ let observed = baseline::advance_observed(
+ previous.as_ref().map(|value| &value.observed),
+ &after.manifest,
+ &applied_logical,
+ );
+ baseline::store(st, key, &next_base, &observed)?;
config.last_local_digest = Some(domains::snapshot_digest(&after));
config.local_change_seen_at = None;
config.last_success_at = Some(Utc::now().to_rfc3339());
config.last_revision_id = Some(bundle.remote_revision_id.clone());
clear_error(config);
save_config(st, config)?;
+ if remaining.is_empty() {
+ clear_pending(st)?;
+ } else {
+ let mut next = staged;
+ next.approvals = remaining;
+ next.journal_state = "staged".into();
+ store_pending(st, key, &next)?;
+ }
Ok(())
}
diff --git a/crates/host-core/src/config_sync/baseline.rs b/crates/host-core/src/config_sync/baseline.rs
new file mode 100644
index 000000000..d01a92672
--- /dev/null
+++ b/crates/host-core/src/config_sync/baseline.rs
@@ -0,0 +1,141 @@
+//! A cloud acknowledgement and its local projection are one atomic record.
+//! Credential opt-outs and device overlays must not manufacture local edits.
+use super::*;
+
+#[derive(Serialize, Deserialize)]
+pub(super) struct Baseline {
+ pub shared: RevisionManifest,
+ pub observed: RevisionManifest,
+}
+
+pub(super) fn load(st: &AppState, key: &VaultKey) -> Result<Option<Baseline>> {
+ load_encrypted(st, key, "local-base", &local_path(st, "base.bin")?)
+}
+
+pub(super) fn store(
+ st: &AppState,
+ key: &VaultKey,
+ shared: &RevisionManifest,
+ observed: &RevisionManifest,
+) -> Result<()> {
+ persist_encrypted(
+ st,
+ key,
+ "local-base",
+ &local_path(st, "base.bin")?,
+ &Baseline {
+ shared: shared.clone(),
+ observed: observed.clone(),
+ },
+ )
+}
+
+pub(super) fn merge_input(
+ local: &mut RevisionManifest,
+ baseline: &Baseline,
+ include_secrets: bool,
+) {
+ let observed = logical_manifest_map(Some(&baseline.observed));
+ let shared = logical_manifest_map(Some(&baseline.shared));
+ for entity in &mut local.entities {
+ let id = logical_entity_key(entity);
+ let (Some(before), Some(acknowledged)) = (observed.get(&id), shared.get(&id)) else {
+ continue;
+ };
+ if merge::same_version(entity, before) {
+ *entity = acknowledged.clone();
+ } else if !include_secrets && !entity.deleted && !acknowledged.deleted {
+ // A metadata edit by an unsubscribed device must not remove cloud
+ // credentials it never imported. Only the cloud baseline supplies
+ // these fields; no device-local secret is exported here.
+ let fields: &[&str] = match entity.domain.as_str() {
+ domains::DOMAIN_PROVIDERS => &["portableApiKey"],
+ domains::DOMAIN_MCP => &["env", "headers", "envKeys", "headerKeys"],
+ _ => &[],
+ };
+ if !fields.is_empty() {
+ if let (Some(payload), Some(source)) = (
+ entity.payload.as_object_mut(),
+ acknowledged.payload.as_object(),
+ ) {
+ for field in fields {
+ payload.remove(*field);
+ if let Some(value) = source.get(*field) {
+ payload.insert((*field).into(), value.clone());
+ }
+ }
+ entity.secret_bearing = acknowledged.secret_bearing;
+ entity.requires_approval |= acknowledged.requires_approval;
+ domains::refresh_digest(entity);
+ }
+ }
+ }
+ }
+}
+
+pub(super) fn advance_observed(
+ previous: Option<&RevisionManifest>,
+ current: &RevisionManifest,
+ applied: &BTreeSet<(String, String)>,
+) -> RevisionManifest {
+ let mut observed = logical_manifest_map(previous);
+ let current_values = logical_manifest_map(Some(current));
+ for id in applied {
+ if let Some(entity) = current_values.get(id) {
+ observed.insert(id.clone(), entity.clone());
+ } else {
+ observed.remove(id);
+ }
+ }
+ RevisionManifest {
+ entities: observed.into_values().collect(),
+ ..current.clone()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unacknowledged_local_edits_are_not_hidden_by_the_baseline() {
+ let entity = PortableEntity {
+ domain: domains::DOMAIN_APPLICATION.into(),
+ entity_id: "application".into(),
+ label: "Preferences".into(),
+ deleted: false,
+ requires_approval: false,
+ secret_bearing: false,
+ mapping_required: false,
+ digest: "old".into(),
+ payload: json!({"theme":"light"}),
+ resource_ids: vec![],
+ };
+ let before = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: "before".into(),
+ created_at: String::new(),
+ parents: vec![],
+ entities: vec![entity.clone()],
+ resource_ids: vec![],
+ };
+ let mut current = before.clone();
+ current.entities[0].payload = json!({"theme":"dark"});
+ domains::refresh_digest(&mut current.entities[0]);
+ let observed = advance_observed(Some(&before), &current, &BTreeSet::new());
+ assert_eq!(observed.entities, before.entities);
+ let baseline = Baseline {
+ shared: before,
+ observed,
+ };
+ let mut candidate = current.clone();
+ merge_input(&mut candidate, &baseline, false);
+ assert_eq!(candidate.entities, current.entities);
+ let applied = BTreeSet::from([entity_key(&entity)]);
+ assert_eq!(
+ advance_observed(Some(&baseline.observed), &current, &applied).entities,
+ current.entities
+ );
+ }
+}
diff --git a/crates/host-core/src/config_sync/conflicts.rs b/crates/host-core/src/config_sync/conflicts.rs
new file mode 100644
index 000000000..49cc3a9b6
--- /dev/null
+++ b/crates/host-core/src/config_sync/conflicts.rs
@@ -0,0 +1,140 @@
+//! Explicit conflict choices are scoped to the exact pair the user approved.
+use super::*;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ConflictResolution {
+ domain: String,
+ entity_id: String,
+ local_digest: String,
+ remote_digest: String,
+ choose_local: bool,
+}
+
+pub(super) fn record(
+ config: &mut StoredConfig,
+ bundle: &PendingBundle,
+ applied: &BTreeSet<(String, String)>,
+) {
+ for approval in &bundle.approvals {
+ let entity = &approval.entity;
+ if !approval.approved || !applied.contains(&entity_key(entity)) {
+ continue;
+ }
+ let Some(id) = conflict_base_id(&entity.entity_id) else {
+ continue;
+ };
+ let find = |suffix: &str| {
+ bundle.manifest.entities.iter().find(|candidate| {
+ candidate.domain == entity.domain && candidate.entity_id == format!("{id}:{suffix}")
+ })
+ };
+ let (Some(local), Some(remote)) = (find("local"), find("remote")) else {
+ continue;
+ };
+ config
+ .resolved_conflicts
+ .retain(|value| value.domain != entity.domain || value.entity_id != id);
+ config.resolved_conflicts.push(ConflictResolution {
+ domain: entity.domain.clone(),
+ entity_id: id.into(),
+ local_digest: local.digest.clone(),
+ remote_digest: remote.digest.clone(),
+ choose_local: entity.entity_id.ends_with(":local"),
+ });
+ }
+}
+
+/// Fold only an explicitly resolved, unchanged pair. A different remote edit
+/// or an already canonical remote entity must continue through three-way merge.
+pub(super) fn reconcile(resolutions: &[ConflictResolution], remote: &mut RevisionManifest) -> bool {
+ let mut changed = false;
+ for resolution in resolutions {
+ let find = |id: &str| {
+ remote
+ .entities
+ .iter()
+ .find(|entity| entity.domain == resolution.domain && entity.entity_id == id)
+ };
+ if find(&resolution.entity_id).is_some() {
+ continue;
+ }
+ let (Some(local), Some(other)) = (
+ find(&format!("{}:local", resolution.entity_id)),
+ find(&format!("{}:remote", resolution.entity_id)),
+ ) else {
+ continue;
+ };
+ if local.digest != resolution.local_digest || other.digest != resolution.remote_digest {
+ continue;
+ }
+ let mut chosen = if resolution.choose_local {
+ local.clone()
+ } else {
+ other.clone()
+ };
+ chosen.entity_id = resolution.entity_id.clone();
+ domains::refresh_digest(&mut chosen);
+ remote.entities.retain(|entity| {
+ entity.domain != resolution.domain
+ || conflict_base_id(&entity.entity_id) != Some(&resolution.entity_id)
+ });
+ remote.entities.push(chosen);
+ changed = true;
+ }
+ remote.entities.sort_by_key(entity_key);
+ changed
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolution_does_not_choose_a_new_or_unapproved_conflict() {
+ let entity = PortableEntity {
+ domain: "application".into(),
+ entity_id: "app:local".into(),
+ label: "Preferences".into(),
+ deleted: false,
+ requires_approval: false,
+ secret_bearing: false,
+ mapping_required: false,
+ digest: "local".into(),
+ payload: json!({"theme":"light"}),
+ resource_ids: vec![],
+ };
+ let mut other = entity.clone();
+ other.entity_id = "app:remote".into();
+ other.digest = "remote".into();
+ other.payload = json!({"theme":"dark"});
+ let manifest = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: "r".into(),
+ parents: vec![],
+ created_at: String::new(),
+ entities: vec![entity, other],
+ resource_ids: vec![],
+ };
+ let resolution = ConflictResolution {
+ domain: "application".into(),
+ entity_id: "app".into(),
+ local_digest: "local".into(),
+ remote_digest: "remote".into(),
+ choose_local: true,
+ };
+ let mut remote = manifest.clone();
+ assert!(!reconcile(&[], &mut remote));
+ assert_eq!(remote.entities, manifest.entities);
+ remote.entities[1].digest = "new-remote".into();
+ assert!(!reconcile(std::slice::from_ref(&resolution), &mut remote));
+ assert_eq!(remote.entities.len(), 2);
+ remote = manifest;
+ assert!(reconcile(std::slice::from_ref(&resolution), &mut remote));
+ assert_eq!(remote.entities.len(), 1);
+ assert_eq!(remote.entities[0].entity_id, "app");
+ assert_eq!(remote.entities[0].payload["theme"], "light");
+ assert!(!reconcile(&[resolution], &mut remote));
+ }
+}
diff --git a/crates/host-core/src/config_sync/connection.rs b/crates/host-core/src/config_sync/connection.rs
new file mode 100644
index 000000000..e65ca862b
--- /dev/null
+++ b/crates/host-core/src/config_sync/connection.rs
@@ -0,0 +1,348 @@
+use super::*;
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct S3Connection {
+ pub endpoint: String,
+ pub region: String,
+ pub bucket: String,
+ pub prefix: String,
+ pub access_key_id: String,
+ pub path_style: bool,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(super) struct ConnectionCredentials {
+ pub secret_access_key: String,
+ pub session_token: Option<String>,
+}
+
+fn input_text(input: &Value, name: &str, fallback: &str) -> Result<String> {
+ match input.get(name) {
+ Some(Value::String(value)) => Ok(value.trim().to_string()),
+ Some(_) => bail!("CONFIG_SYNC_INVALID: {name} must be text"),
+ None => Ok(fallback.to_string()),
+ }
+}
+
+fn input_bool(input: &Value, name: &str, fallback: bool) -> Result<bool> {
+ match input.get(name) {
+ Some(Value::Bool(value)) => Ok(*value),
+ Some(_) => bail!("CONFIG_SYNC_INVALID: {name} must be a boolean"),
+ None => Ok(fallback),
+ }
+}
+
+impl S3Connection {
+ pub(super) fn from_input(existing: Option<&Self>, input: &Value) -> Result<Self> {
+ let value = Self {
+ endpoint: input_text(input, "endpoint", existing.map_or("", |v| &v.endpoint))?
+ .trim_end_matches('/')
+ .to_string(),
+ region: input_text(input, "region", existing.map_or("us-east-1", |v| &v.region))?,
+ bucket: input_text(input, "bucket", existing.map_or("", |v| &v.bucket))?,
+ prefix: input_text(
+ input,
+ "prefix",
+ existing.map_or("pi-desktop/config", |v| &v.prefix),
+ )?
+ .trim_matches('/')
+ .to_string(),
+ access_key_id: input_text(
+ input,
+ "accessKeyId",
+ existing.map_or("", |v| &v.access_key_id),
+ )?,
+ path_style: input_bool(input, "pathStyle", existing.is_none_or(|v| v.path_style))?,
+ };
+ if value.endpoint.is_empty()
+ || value.region.is_empty()
+ || value.bucket.is_empty()
+ || value.access_key_id.is_empty()
+ {
+ bail!(
+ "CONFIG_SYNC_INVALID: S3 endpoint, region, bucket and access key ID are required"
+ );
+ }
+ Ok(value)
+ }
+}
+
+pub(super) fn credential_ref(config: &StoredConfig) -> String {
+ format!("secret:config-sync:s3:{}:connection", config.state_id)
+}
+
+pub(super) fn stored_credentials(
+ st: &AppState,
+ config: &StoredConfig,
+) -> Result<ConnectionCredentials> {
+ let value = st
+ .secrets
+ .get(&credential_ref(config))?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_AUTH: S3 credentials are not available"))?;
+ serde_json::from_str(&value)
+ .map_err(|_| anyhow!("CONFIG_SYNC_AUTH: stored S3 credentials are invalid"))
+}
+
+pub(super) fn connection_credentials(
+ st: &AppState,
+ existing: Option<&StoredConfig>,
+ connection: &S3Connection,
+ input: &Value,
+) -> Result<ConnectionCredentials> {
+ // A complete replacement must recover even when the old secret was lost.
+ // Omitted fields still mean reuse, never silently dropping a session token.
+ let needs_saved = input.get("secretAccessKey").is_none() || input.get("sessionToken").is_none();
+ let saved = if needs_saved {
+ existing
+ .filter(|saved| saved.connection == *connection)
+ .map(|saved| stored_credentials(st, saved))
+ .transpose()?
+ } else {
+ None
+ };
+ let secret_access_key = match input.get("secretAccessKey") {
+ Some(Value::String(value)) if !value.is_empty() => value.clone(),
+ Some(_) => bail!("CONFIG_SYNC_AUTH: enter the S3 secret access key"),
+ None => saved
+ .as_ref()
+ .map(|saved| saved.secret_access_key.clone())
+ .ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_AUTH: enter the S3 secret access key for this connection")
+ })?,
+ };
+ let session_token = match input.get("sessionToken") {
+ Some(Value::String(value)) => (!value.is_empty()).then(|| value.clone()),
+ Some(_) => bail!("CONFIG_SYNC_INVALID: S3 session token must be text"),
+ None => saved.and_then(|saved| saved.session_token),
+ };
+ Ok(ConnectionCredentials {
+ secret_access_key,
+ session_token,
+ })
+}
+
+pub(super) fn transport_with_credentials(
+ connection: &S3Connection,
+ credentials: ConnectionCredentials,
+) -> Result<S3Transport> {
+ S3Transport::new(&S3Config {
+ endpoint: connection.endpoint.clone(),
+ region: connection.region.clone(),
+ bucket: connection.bucket.clone(),
+ prefix: connection.prefix.clone(),
+ access_key_id: connection.access_key_id.clone(),
+ secret_access_key: credentials.secret_access_key,
+ session_token: credentials.session_token,
+ path_style: connection.path_style,
+ allow_insecure_http: crate::network_policy::relaxed(),
+ })
+}
+
+pub(super) fn configured_transport(st: &AppState, config: &StoredConfig) -> Result<S3Transport> {
+ transport_with_credentials(&config.connection, stored_credentials(st, config)?)
+}
+
+pub(super) fn config_from_input(
+ existing: Option<&StoredConfig>,
+ input: &Value,
+ header: VaultHeader,
+) -> Result<StoredConfig> {
+ if !input.is_object() {
+ bail!("CONFIG_SYNC_INVALID: configuration must be an object");
+ }
+ for removed in ["username", "appPassword", "directory", "remoteMode"] {
+ if input.get(removed).is_some() {
+ bail!("CONFIG_SYNC_INVALID: legacy connection fields are no longer supported");
+ }
+ }
+ let connection = S3Connection::from_input(existing.map(|value| &value.connection), input)?;
+ let device_label = input_text(
+ input,
+ "deviceLabel",
+ existing.map_or("This device", |v| &v.device_label),
+ )?;
+ if device_label.is_empty() || device_label.len() > 128 {
+ bail!("CONFIG_SYNC_INVALID: device label must contain 1 to 128 bytes");
+ }
+ let mode = match input.get("mode") {
+ None => existing.map(|value| value.mode).unwrap_or_default(),
+ Some(Value::String(value)) if value == "sync" => SyncMode::Sync,
+ Some(Value::String(value)) if value == "backup" => SyncMode::Backup,
+ _ => bail!("CONFIG_SYNC_INVALID: unsupported configuration mode"),
+ };
+ let same_state = existing.filter(|saved| saved.connection == connection && saved.mode == mode);
+ let include_memory = input_bool(
+ input,
+ "includeMemory",
+ existing.is_some_and(|v| v.include_memory),
+ )?;
+ let include_secrets = input_bool(
+ input,
+ "includeSecrets",
+ existing.is_some_and(|v| v.include_secrets),
+ )?;
+ let mut categories = existing
+ .map(|value| value.categories.clone())
+ .unwrap_or_else(default_categories);
+ if let Some(value) = input.get("categories") {
+ let object = value
+ .as_object()
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: categories must be an object"))?;
+ for (name, selected) in object {
+ if !domains::ALL_DOMAINS.contains(&name.as_str()) && name != "credentials" {
+ bail!("CONFIG_SYNC_INVALID: unsupported configuration category");
+ }
+ categories.insert(
+ name.clone(),
+ selected.as_bool().ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_INVALID: category selection must be a boolean")
+ })?,
+ );
+ }
+ }
+ categories.insert("credentials".into(), include_secrets);
+ categories.insert(domains::DOMAIN_MEMORY.into(), include_memory);
+ Ok(StoredConfig {
+ format: FORMAT.into(),
+ version: 1,
+ connection,
+ mode,
+ state_id: same_state
+ .map(|value| value.state_id.clone())
+ .unwrap_or_else(new_device_id),
+ device_label,
+ device_id: existing
+ .map(|value| value.device_id.clone())
+ .unwrap_or_else(new_device_id),
+ categories,
+ include_secrets,
+ include_memory,
+ automatic_sync: input_bool(
+ input,
+ "automaticSync",
+ existing.is_none_or(|v| v.automatic_sync),
+ )?,
+ enabled: true,
+ paused: existing.is_some_and(|value| value.paused),
+ vault_id: header.vault_id.clone(),
+ vault_header: header,
+ last_run_at: same_state.and_then(|v| v.last_run_at.clone()),
+ last_success_at: same_state.and_then(|v| v.last_success_at.clone()),
+ last_revision_id: same_state.and_then(|v| v.last_revision_id.clone()),
+ last_error: None,
+ last_error_code: None,
+ last_local_digest: same_state.and_then(|v| v.last_local_digest.clone()),
+ local_change_seen_at: None,
+ retry_count: 0,
+ next_retry_at: None,
+ project_mappings: same_state
+ .map(|v| v.project_mappings.clone())
+ .unwrap_or_default(),
+ project_group_mappings: same_state
+ .map(|v| v.project_group_mappings.clone())
+ .unwrap_or_default(),
+ dismissed: same_state.map(|v| v.dismissed.clone()).unwrap_or_default(),
+ resolved_conflicts: same_state
+ .map(|v| v.resolved_conflicts.clone())
+ .unwrap_or_default(),
+ plugin_intents: same_state
+ .map(|v| v.plugin_intents.clone())
+ .unwrap_or_default(),
+ recovery_points: same_state
+ .map(|v| v.recovery_points.clone())
+ .unwrap_or_default(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn input() -> Value {
+ json!({"endpoint":"https://s3.example.test", "region":"us-east-1", "bucket":"config-bucket",
+ "accessKeyId":"fixture-access", "prefix":"config", "deviceLabel":"Test"})
+ }
+
+ #[test]
+ fn credentials_are_scoped_to_the_complete_connection() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let state = AppState::open(directory.path())?;
+ let (header, _) = create_vault("backup-password", "test-vault")?;
+ let config = config_from_input(None, &input(), header)?;
+ state.secrets.set(
+ &credential_ref(&config),
+ &serde_json::to_string(&ConnectionCredentials {
+ secret_access_key: "fixture-secret".into(),
+ session_token: Some("fixture-session".into()),
+ })?,
+ )?;
+ let reused = connection_credentials(&state, Some(&config), &config.connection, &json!({}))?;
+ assert_eq!(reused.secret_access_key, "fixture-secret");
+ for (name, value) in [
+ ("endpoint", "https://other.example.test"),
+ ("region", "eu-west-1"),
+ ("bucket", "other-bucket"),
+ ("prefix", "other-prefix"),
+ ("accessKeyId", "other-access"),
+ ] {
+ let changed =
+ S3Connection::from_input(Some(&config.connection), &json!({(name):value}))?;
+ assert!(connection_credentials(&state, Some(&config), &changed, &json!({})).is_err());
+ }
+ let changed =
+ S3Connection::from_input(Some(&config.connection), &json!({"pathStyle":false}))?;
+ assert!(connection_credentials(&state, Some(&config), &changed, &json!({})).is_err());
+ let cleared = connection_credentials(
+ &state,
+ Some(&config),
+ &config.connection,
+ &json!({"sessionToken":""}),
+ )?;
+ assert!(cleared.session_token.is_none());
+ Ok(())
+ }
+
+ #[test]
+ fn complete_replacement_recovers_missing_or_invalid_stored_credentials() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let state = AppState::open(directory.path())?;
+ let (header, _) = create_vault("backup-password", "test-vault")?;
+ let config = config_from_input(None, &input(), header)?;
+ for invalid in [None, Some("not-json")] {
+ if let Some(invalid) = invalid {
+ state.secrets.set(&credential_ref(&config), invalid)?;
+ }
+ let replaced = connection_credentials(
+ &state,
+ Some(&config),
+ &config.connection,
+ &json!({"secretAccessKey":"replacement", "sessionToken":""}),
+ )?;
+ assert_eq!(replaced.secret_access_key, "replacement");
+ assert!(replaced.session_token.is_none());
+ assert!(
+ connection_credentials(&state, Some(&config), &config.connection, &json!({}))
+ .is_err()
+ );
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn destination_and_mode_changes_get_a_fresh_local_baseline() -> Result<()> {
+ let (header, _) = create_vault("backup-password", "test-vault")?;
+ let mut config = config_from_input(None, &input(), header.clone())?;
+ config.paused = true;
+ let saved = config_from_input(Some(&config), &input(), header.clone())?;
+ assert_eq!(saved.state_id, config.state_id);
+ assert!(saved.paused);
+ for change in [json!({"mode":"backup"}), json!({"bucket":"other-bucket"})] {
+ let changed = config_from_input(Some(&config), &change, header.clone())?;
+ assert_ne!(changed.state_id, config.state_id);
+ assert!(changed.last_revision_id.is_none());
+ }
+ Ok(())
+ }
+}
diff --git a/crates/host-core/src/config_sync/coordinator.rs b/crates/host-core/src/config_sync/coordinator.rs
index 46ffdbc1e..851876d91 100644
--- a/crates/host-core/src/config_sync/coordinator.rs
+++ b/crates/host-core/src/config_sync/coordinator.rs
@@ -37,7 +37,7 @@ pub(super) async fn sync_once(
send_state_notification(tx, &mut st);
}
for _attempt in 0..MAX_RETRIES {
- let (config, key, base, local, local_digest) = {
+ let (config, key, base, local, local_before, local_digest) = {
let mut st = state.lock().await;
let mut config = load_config(&st)?
.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
@@ -54,7 +54,8 @@ pub(super) async fn sync_once(
} else {
false
};
- let base = load_base(&st, &key)?;
+ let baseline = baseline::load(&st, &key)?;
+ let base = baseline.as_ref().map(|value| value.shared.clone());
observer.report(SyncProgress::started(SyncPhase::Capture));
let mut local = domains::capture(
&mut st,
@@ -65,6 +66,12 @@ pub(super) async fn sync_once(
&identity_overrides(&config),
)?;
let local_digest = domains::snapshot_digest(&local);
+ let local_before = local.manifest.clone();
+ if config.mode == SyncMode::Sync {
+ if let Some(baseline) = &baseline {
+ baseline::merge_input(&mut local.manifest, baseline, config.include_secrets);
+ }
+ }
observer.report(SyncProgress::counted(
SyncPhase::Capture,
local.manifest.entities.len() as u64,
@@ -84,81 +91,56 @@ pub(super) async fn sync_once(
merge::snapshot_with_tombstones(base.as_ref(), &mut local, &selection(&config));
config.last_run_at = Some(Utc::now().to_rfc3339());
save_config(&st, &config)?;
- (config, key, base, local, local_digest)
+ (config, key, base, local, local_before, local_digest)
};
- let transport_password = {
+ let transport = {
let st = state.lock().await;
- webdav_password(&st, &config)?
+ configured_transport(&st, &config)?
};
- let transport = transport_with_password(&config, transport_password)?;
- ensure_remote_collections(&transport, &config).await?;
- let (remote_head, remote, remote_resources, remote_parent_ids, remote_conflicts) = if config
- .remote_mode
- == RemoteMode::AppendOnly
- {
- let append_only = read_append_only_remote(&transport, &config, &key, observer).await?;
- if let Some(append_only) = append_only {
- let remote_merge = merge_append_only_tips(base.as_ref(), &append_only.tips)?;
- let remote = RevisionManifest {
- format: REVISION_FORMAT.into(),
- version: 1,
- revision_id: append_only
- .tip_ids
- .first()
- .cloned()
- .unwrap_or_else(|| "remote-merge".into()),
- parents: append_only.tip_ids.clone(),
- created_at: Utc::now().to_rfc3339(),
- entities: remote_merge.entities,
- resource_ids: append_only.resources.keys().cloned().collect(),
- };
- (
- None,
- Some(remote),
- append_only.resources,
- append_only.tip_ids,
- remote_merge.conflicts,
- )
- } else {
- (None, None, BTreeMap::new(), Vec::new(), Vec::new())
- }
- } else {
- let remote_head = read_remote_head(&transport, &config, &key).await?;
- let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
- let value =
+ let remote_head = read_remote_head(&transport, &config, &key).await?;
+ if remote_head.is_none() && config.last_revision_id.is_some() {
+ bail!(
+ "CONFIG_SYNC_REMOTE: configured remote head is missing; refusing to overwrite recovery history"
+ );
+ }
+ let (mut remote, remote_resources) = if config.mode == SyncMode::Sync {
+ if let Some((head, _)) = remote_head.as_ref() {
+ let (manifest, resources) =
read_remote_revision(&transport, &config, &key, &head.revision_id, observer)
.await?;
- (Some(value.0), value.1)
+ (Some(manifest), resources)
} else {
(None, BTreeMap::new())
- };
- let parent_ids = remote_head
- .as_ref()
- .map(|(head, _)| vec![head.revision_id.clone()])
- .unwrap_or_default();
- (
- remote_head,
- remote,
- remote_resources,
- parent_ids,
- Vec::new(),
- )
+ }
+ } else {
+ (None, BTreeMap::new())
};
+ let resolved_conflicts = remote
+ .as_mut()
+ .is_some_and(|remote| conflicts::reconcile(&config.resolved_conflicts, remote));
+ let remote_parent_ids = remote_head
+ .as_ref()
+ .map(|(head, _)| vec![head.revision_id.clone()])
+ .unwrap_or_default();
observer.report(SyncProgress::started(SyncPhase::Merge));
- let merge::MergeResult {
- entities: local_entities,
- conflicts: local_conflicts,
- } = merge::three_way(base.as_ref(), &local.manifest, remote.as_ref())?;
- let merged = merge::MergeResult {
- entities: local_entities,
- conflicts: remote_conflicts
- .into_iter()
- .chain(local_conflicts)
- .collect(),
+ let merged = if config.mode == SyncMode::Backup {
+ if config.last_local_digest.as_deref() == Some(&local_digest) && remote_head.is_some() {
+ let mut st = state.lock().await;
+ let mut next_config = config.clone();
+ next_config.last_success_at = Some(Utc::now().to_rfc3339());
+ clear_error(&mut next_config);
+ save_config(&st, &next_config)?;
+ send_state_notification(tx, &mut st);
+ return Ok(());
+ }
+ merge::MergeResult {
+ entities: local.manifest.entities.clone(),
+ conflicts: Vec::new(),
+ }
+ } else {
+ merge::three_way(base.as_ref(), &local.manifest, remote.as_ref())?
};
- let can_skip_publication =
- config.remote_mode == RemoteMode::Strict || remote_parent_ids.len() <= 1;
- if can_skip_publication {
+ {
observer.report(SyncProgress::counted(
SyncPhase::Merge,
merged.entities.len() as u64,
@@ -174,15 +156,15 @@ pub(super) async fn sync_once(
// remote content still has to stage it for approval and
// activation, even though the merge result equals the remote
// entities.
- let no_selected_change =
- selected_manifests_equal(base.as_ref(), Some(remote), &selection(&config))
- && selected_manifests_equal(
- Some(&local.manifest),
- Some(remote),
- &selection(&config),
- )
- && merged.conflicts.is_empty()
- && remote.entities == merged.entities;
+ let no_selected_change = !resolved_conflicts
+ && selected_manifests_equal(base.as_ref(), Some(remote), &selection(&config))
+ && selected_manifests_equal(
+ Some(&local.manifest),
+ Some(remote),
+ &selection(&config),
+ )
+ && merged.conflicts.is_empty()
+ && remote.entities == merged.entities;
if no_selected_change {
let mut st = state.lock().await;
let mut next_config = config.clone();
@@ -199,6 +181,12 @@ pub(super) async fn sync_once(
}
let mut resources = local.resources.clone();
resources.extend(remote_resources);
+ let referenced = merged
+ .entities
+ .iter()
+ .flat_map(|entity| entity.resource_ids.iter().cloned())
+ .collect::<BTreeSet<_>>();
+ resources.retain(|id, _| referenced.contains(id));
let revision_id = Uuid::new_v4().to_string();
let candidate = LocalSnapshot {
manifest: RevisionManifest {
@@ -213,31 +201,18 @@ pub(super) async fn sync_once(
resources,
};
upload_snapshot(&transport, &config, &key, &candidate, observer).await?;
- let published = if config.remote_mode == RemoteMode::AppendOnly {
- publish_append_only_head(
- &transport,
- &config,
- &key,
- &config.device_id,
- &candidate.manifest.revision_id,
- )
- .await
- .map(|_| true)?
- } else {
- let head = RemoteHead {
- format: FORMAT.into(),
- version: 1,
- revision_id: candidate.manifest.revision_id.clone(),
- };
- publish_head(
- &transport,
- &config,
- &key,
- &head,
- remote_head.as_ref().map(|(_, etag)| etag.as_str()),
- )
- .await?
- };
+ let head = next_head(
+ &candidate.manifest.revision_id,
+ remote_head.as_ref().map(|(head, _)| head),
+ );
+ let published = publish_head(
+ &transport,
+ &config,
+ &key,
+ &head,
+ remote_head.as_ref().map(|(_, etag)| etag.as_str()),
+ )
+ .await?;
if !published {
let jitter_ms = u64::from(Uuid::new_v4().as_bytes()[0] % 31);
tokio::time::sleep(std::time::Duration::from_millis(
@@ -246,10 +221,23 @@ pub(super) async fn sync_once(
.await;
continue;
}
+ if config.mode == SyncMode::Backup {
+ let mut st = state.lock().await;
+ let mut next_config = config.clone();
+ baseline::store(&st, &key, &candidate.manifest, &local_before)?;
+ next_config.last_success_at = Some(Utc::now().to_rfc3339());
+ next_config.last_revision_id = Some(candidate.manifest.revision_id.clone());
+ next_config.last_local_digest = Some(local_digest);
+ next_config.local_change_seen_at = None;
+ clear_error(&mut next_config);
+ save_config(&st, &next_config)?;
+ send_state_notification(tx, &mut st);
+ return Ok(());
+ }
let pending = build_pending(
&config,
base.as_ref(),
- &local.manifest,
+ &local_before,
remote.as_ref(),
&merged,
&candidate.manifest.revision_id,
@@ -265,7 +253,7 @@ pub(super) async fn sync_once(
let candidate_revision_id = candidate.manifest.revision_id.clone();
let apply_bundle_state = PendingBundle {
manifest: candidate.manifest,
- local_before: Some(local.manifest.clone()),
+ local_before: Some(local_before.clone()),
resources: candidate.resources,
approvals: pending.approvals,
conflicts: pending.conflicts,
@@ -279,7 +267,7 @@ pub(super) async fn sync_once(
&mut next_config,
&key,
base.as_ref(),
- &local.manifest,
+ &local_before,
&apply_bundle_state,
)
.await?;
@@ -290,12 +278,6 @@ pub(super) async fn sync_once(
0,
0,
));
- if config.remote_mode == RemoteMode::Strict {
- observer.report(SyncProgress::started(SyncPhase::Cleanup));
- if let Err(error) = cleanup_history(state, &transport, &config, &key).await {
- tracing::warn!(error = %error, "config sync history cleanup failed after sync");
- }
- }
let mut st = state.lock().await;
send_state_notification(tx, &mut st);
return Ok(());
diff --git a/crates/host-core/src/config_sync/engine.rs b/crates/host-core/src/config_sync/engine.rs
index 24fb22443..b2c8a36c9 100644
--- a/crates/host-core/src/config_sync/engine.rs
+++ b/crates/host-core/src/config_sync/engine.rs
@@ -2,7 +2,7 @@ use super::domains::{self, CategorySelection, LocalSnapshot, PortableEntity, Rev
use super::merge::{self, MergeConflict};
use super::{
create_vault, decrypt_object, encrypt_object, rewrap_vault, unlock_vault, vault_key_b64,
- vault_key_from_b64, VaultHeader, VaultKey, WebDavConfig, WebDavTransport,
+ vault_key_from_b64, S3Config, S3Transport, VaultHeader, VaultKey,
};
use crate::agent_capabilities::CapabilityLevel;
use crate::mcp_servers::McpServerInput;
@@ -23,6 +23,16 @@ use std::sync::{
use tokio::sync::{mpsc, Mutex};
use uuid::Uuid;
+#[path = "baseline.rs"]
+mod baseline;
+#[path = "conflicts.rs"]
+mod conflicts;
+#[path = "connection.rs"]
+mod connection;
+use connection::{
+ config_from_input, configured_transport, connection_credentials, credential_ref,
+ transport_with_credentials, S3Connection,
+};
#[path = "apply.rs"]
mod apply;
#[path = "coordinator.rs"]
@@ -36,6 +46,9 @@ mod progress;
#[path = "engine_remote.rs"]
mod remote;
#[cfg(test)]
+#[path = "engine_s3_tests.rs"]
+mod s3_tests;
+#[cfg(test)]
pub(crate) use apply::validate_application_references;
pub(crate) use apply::{apply_bundle, recover_import_journal};
pub(crate) use coordinator::{sync_if_enabled, sync_now};
@@ -43,32 +56,28 @@ pub(crate) use handlers::{
approve, change_password, configure, disconnect, get_state, list_history, map_project, pause,
reject, restore, test, unlock,
};
-use history::cleanup_history;
use progress::{NoSyncProgress, ProgressNotifier, SyncPhase, SyncProgress, SyncProgressObserver};
+use remote::next_head;
use remote::{
- ensure_remote_collections, merge_append_only_tips, object_path, publish_append_only_head,
- publish_head, read_append_only_remote, read_remote_head, read_remote_manifest,
- read_remote_revision, revision_path, upload_snapshot, validate_remote_id,
+ publish_head, read_remote_head, read_remote_manifest, read_remote_revision, upload_snapshot,
+ validate_remote_id,
};
-const CONFIG_NS: &str = "configSync";
+const CONFIG_NS: &str = "configSyncS3";
const CONFIG_KEY: &str = "config";
-const WEBDAV_SECRET_REF: &str = "secret:config-sync:webdav-password";
-const FORMAT: &str = "pi-desktop-config-sync";
+const FORMAT: &str = "pi-desktop-config-sync-s3";
const REVISION_FORMAT: &str = "pi-desktop-config-revision";
const MAX_ENTITIES: usize = 4096;
const MAX_RESOURCES: usize = 4096;
const MAX_RETRIES: usize = 3;
-const MAX_HISTORY_SCAN: usize = 256;
const MAX_RETAINED_REVISIONS: usize = 30;
-const HISTORY_GRACE_SECONDS: i64 = 60 * 60;
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
-pub(crate) enum RemoteMode {
+pub(crate) enum SyncMode {
#[default]
- Strict,
- AppendOnly,
+ Sync,
+ Backup,
}
fn new_device_id() -> String {
@@ -77,20 +86,15 @@ fn new_device_id() -> String {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
-pub struct StoredConfig {
+pub(crate) struct StoredConfig {
pub format: String,
pub version: u32,
- pub endpoint: String,
- pub username: String,
- pub directory: String,
+ #[serde(flatten)]
+ pub connection: S3Connection,
+ pub mode: SyncMode,
+ pub state_id: String,
pub device_label: String,
- #[serde(default)]
- pub remote_mode: RemoteMode,
- #[serde(default = "new_device_id")]
pub device_id: String,
- /// Endpoint-specific compatibility for servers that report missing GETs as 502.
- #[serde(default)]
- pub missing_object_status: Option<u16>,
pub categories: BTreeMap<String, bool>,
pub include_secrets: bool,
pub include_memory: bool,
@@ -123,6 +127,8 @@ pub struct StoredConfig {
pub project_group_mappings: BTreeMap<String, Vec<String>>,
#[serde(default)]
pub dismissed: BTreeMap<String, String>,
+ #[serde(default)]
+ pub resolved_conflicts: Vec<conflicts::ConflictResolution>,
/// Approved plugin installation intent without plugin bytes or grants.
#[serde(default)]
pub plugin_intents: BTreeMap<String, Value>,
@@ -136,6 +142,7 @@ pub struct RemoteHead {
pub format: String,
pub version: u32,
pub revision_id: String,
+ pub history: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -224,13 +231,17 @@ struct PublicState {
#[serde(skip_serializing_if = "Option::is_none")]
endpoint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- username: Option<String>,
+ region: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ bucket: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ prefix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- directory: Option<String>,
+ access_key_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
device_label: Option<String>,
- allow_insecure_http: bool,
- remote_mode: RemoteMode,
+ mode: SyncMode,
+ path_style: bool,
categories: BTreeMap<String, bool>,
include_secrets: bool,
include_memory: bool,
@@ -268,12 +279,20 @@ fn identity_overrides(config: &StoredConfig) -> domains::ProjectIdentityOverride
)
}
-fn config_dir(st: &AppState) -> PathBuf {
- st.data_dir.join("config-sync")
+fn config_dir(st: &AppState) -> Result<PathBuf> {
+ let config =
+ load_config(st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: S3 sync is not configured"))?;
+ Uuid::parse_str(&config.state_id)
+ .map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid local S3 state identity"))?;
+ Ok(st
+ .data_dir
+ .join("config-sync")
+ .join("s3")
+ .join(config.state_id))
}
-fn local_path(st: &AppState, name: &str) -> PathBuf {
- config_dir(st).join(name)
+fn local_path(st: &AppState, name: &str) -> Result<PathBuf> {
+ Ok(config_dir(st)?.join(name))
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
@@ -356,33 +375,6 @@ fn local_vault_key(st: &AppState, config: &StoredConfig) -> Result<Option<VaultK
Ok(Some(vault_key_from_b64(&encoded)?))
}
-fn webdav_password(st: &AppState, config: &StoredConfig) -> Result<String> {
- if config.username.is_empty() {
- return Ok(String::new());
- }
- st.secrets
- .get(WEBDAV_SECRET_REF)?
- .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: WebDAV app password is not available"))
-}
-
-/// Build the WebDAV transport from a stored configuration.
-///
-/// The plaintext hop is no longer the per-endpoint acknowledgement the sync
-/// settings used to carry: `networkPolicy.mode` decides. `relaxed` keeps an
-/// `http` endpoint reachable when it is a loopback, `.local` or private LAN
-/// host, `strict` refuses plaintext outright, and a public `http` host is
-/// refused in both modes.
-fn transport_with_password(config: &StoredConfig, password: String) -> Result<WebDavTransport> {
- WebDavTransport::new(&WebDavConfig {
- endpoint: config.endpoint.clone(),
- username: config.username.clone(),
- password,
- directory: config.directory.clone(),
- allow_insecure_http: crate::network_policy::relaxed(),
- missing_object_status: config.missing_object_status,
- })
-}
-
fn entity_key(entity: &PortableEntity) -> (String, String) {
(entity.domain.clone(), entity.entity_id.clone())
}
@@ -494,12 +486,12 @@ fn build_pending(
let remote_changed = remote_entity.is_some_and(|remote| {
base_map
.get(&key)
- .is_none_or(|base| base.digest != remote.digest)
+ .is_none_or(|base| !merge::same_version(base, remote))
});
let new_device = base.is_none() && remote_entity.is_some();
let local_same = local_map
.get(&key)
- .is_some_and(|local| local.digest == entity.digest);
+ .is_some_and(|local| merge::same_version(local, entity));
let conflict = entity.entity_id.ends_with(":local")
|| entity.entity_id.ends_with(":remote")
|| conflict_ids.contains(&key);
@@ -650,11 +642,13 @@ pub fn public_state(st: &mut AppState) -> Result<Value> {
locked: false,
status: "notConfigured".into(),
endpoint: None,
- username: None,
- directory: None,
+ region: None,
+ bucket: None,
+ prefix: None,
+ access_key_id: None,
device_label: None,
- allow_insecure_http: crate::network_policy::relaxed(),
- remote_mode: RemoteMode::Strict,
+ mode: SyncMode::Sync,
+ path_style: true,
categories: default_categories(),
include_secrets: false,
include_memory: false,
@@ -744,12 +738,14 @@ pub fn public_state(st: &mut AppState) -> Result<Value> {
syncing,
local_changes_pending,
),
- endpoint: Some(config_ref.endpoint.clone()),
- username: Some(config_ref.username.clone()),
- directory: Some(config_ref.directory.clone()),
+ endpoint: Some(config_ref.connection.endpoint.clone()),
+ region: Some(config_ref.connection.region.clone()),
+ bucket: Some(config_ref.connection.bucket.clone()),
+ prefix: Some(config_ref.connection.prefix.clone()),
+ access_key_id: Some(config_ref.connection.access_key_id.clone()),
device_label: Some(config_ref.device_label.clone()),
- allow_insecure_http: crate::network_policy::relaxed(),
- remote_mode: config_ref.remote_mode,
+ mode: config_ref.mode,
+ path_style: config_ref.connection.path_style,
categories: config_ref.categories.clone(),
include_secrets: config_ref.include_secrets,
include_memory: config_ref.include_memory,
@@ -764,147 +760,6 @@ pub fn public_state(st: &mut AppState) -> Result<Value> {
})?)
}
-fn parse_category_selection(
- value: Option<&Value>,
- existing: Option<&BTreeMap<String, bool>>,
- include_memory: bool,
-) -> BTreeMap<String, bool> {
- let mut selected = existing.cloned().unwrap_or_else(default_categories);
- if let Some(object) = value.and_then(Value::as_object) {
- for (key, value) in object {
- if domains::ALL_DOMAINS.contains(&key.as_str()) && value.is_boolean() {
- selected.insert(key.clone(), value.as_bool().unwrap_or(true));
- }
- }
- }
- selected.insert("credentials".into(), false);
- selected.insert(domains::DOMAIN_MEMORY.into(), include_memory);
- selected
-}
-
-fn config_from_input(
- existing: Option<&StoredConfig>,
- input: &Value,
- header: VaultHeader,
-) -> Result<StoredConfig> {
- let endpoint = input
- .get("endpoint")
- .and_then(Value::as_str)
- .or_else(|| existing.map(|value| value.endpoint.as_str()))
- .unwrap_or_default()
- .trim()
- .to_string();
- let username = input
- .get("username")
- .and_then(Value::as_str)
- .or_else(|| existing.map(|value| value.username.as_str()))
- .unwrap_or_default()
- .trim()
- .to_string();
- let directory = input
- .get("directory")
- .and_then(Value::as_str)
- .or_else(|| existing.map(|value| value.directory.as_str()))
- .unwrap_or_default()
- .trim()
- .to_string();
- let device_label = input
- .get("deviceLabel")
- .and_then(Value::as_str)
- .or_else(|| existing.map(|value| value.device_label.as_str()))
- .unwrap_or("This device")
- .trim()
- .to_string();
- if endpoint.is_empty() || device_label.is_empty() {
- bail!("CONFIG_SYNC_INVALID: endpoint and device label are required");
- }
- let include_memory = input
- .get("includeMemory")
- .and_then(Value::as_bool)
- .or_else(|| existing.map(|value| value.include_memory))
- .unwrap_or(false);
- let include_secrets = input
- .get("includeSecrets")
- .and_then(Value::as_bool)
- .or_else(|| existing.map(|value| value.include_secrets))
- .unwrap_or(false);
- let remote_mode = input
- .get("remoteMode")
- .and_then(Value::as_str)
- .map(parse_remote_mode)
- .transpose()?
- .or_else(|| existing.map(|value| value.remote_mode))
- .unwrap_or_default();
- let mut categories = parse_category_selection(
- input.get("categories"),
- existing.map(|value| &value.categories),
- include_memory,
- );
- categories.insert("credentials".into(), include_secrets);
- Ok(StoredConfig {
- format: FORMAT.into(),
- version: 1,
- endpoint,
- username,
- directory,
- device_label,
- // `allowInsecureHttp` used to live here as a per-endpoint
- // acknowledgement. The plaintext decision now belongs to
- // `networkPolicy.mode`, so the key a stored configuration may still
- // carry is ignored rather than rewritten.
- remote_mode,
- device_id: existing
- .map(|value| value.device_id.clone())
- .filter(|value| !value.is_empty())
- .unwrap_or_else(new_device_id),
- missing_object_status: existing.and_then(|value| value.missing_object_status),
- categories,
- include_secrets,
- include_memory,
- automatic_sync: input
- .get("automaticSync")
- .and_then(Value::as_bool)
- .or_else(|| existing.map(|value| value.automatic_sync))
- .unwrap_or(true),
- enabled: true,
- paused: existing.is_some_and(|value| value.paused),
- vault_id: header.vault_id.clone(),
- vault_header: header,
- last_run_at: existing.and_then(|value| value.last_run_at.clone()),
- last_success_at: existing.and_then(|value| value.last_success_at.clone()),
- last_revision_id: existing.and_then(|value| value.last_revision_id.clone()),
- last_error: None,
- last_error_code: None,
- last_local_digest: existing.and_then(|value| value.last_local_digest.clone()),
- local_change_seen_at: existing.and_then(|value| value.local_change_seen_at.clone()),
- retry_count: existing.map(|value| value.retry_count).unwrap_or(0),
- next_retry_at: existing.and_then(|value| value.next_retry_at.clone()),
- project_mappings: existing
- .map(|value| value.project_mappings.clone())
- .unwrap_or_default(),
- project_group_mappings: existing
- .map(|value| value.project_group_mappings.clone())
- .unwrap_or_default(),
- dismissed: existing
- .map(|value| value.dismissed.clone())
- .unwrap_or_default(),
- plugin_intents: existing
- .map(|value| value.plugin_intents.clone())
- .unwrap_or_default(),
- recovery_points: existing
- .map(|value| value.recovery_points.clone())
- .unwrap_or_default(),
- })
-}
-
-fn parse_remote_mode(value: &str) -> Result<RemoteMode> {
- match value {
- "strict" => Ok(RemoteMode::Strict),
- "appendOnly" => Ok(RemoteMode::AppendOnly),
- _ => bail!("CONFIG_SYNC_INVALID: unsupported WebDAV sync mode"),
- }
-}
-
fn mark_error(config: &mut StoredConfig, error: &anyhow::Error) {
let message = error.to_string();
config.last_error_code = if message.starts_with("CONFIG_SYNC_UNSUPPORTED")
@@ -947,11 +802,11 @@ fn retry_deadline(config: &StoredConfig) -> Option<chrono::DateTime<Utc>> {
}
fn load_base(st: &AppState, key: &VaultKey) -> Result<Option<RevisionManifest>> {
- load_encrypted(st, key, "local-base", &local_path(st, "base.bin"))
+ Ok(baseline::load(st, key)?.map(|baseline| baseline.shared))
}
fn load_pending(st: &AppState, key: &VaultKey) -> Result<Option<PendingBundle>> {
- load_encrypted(st, key, "local-pending", &local_path(st, "pending.bin"))
+ load_encrypted(st, key, "local-pending", &local_path(st, "pending.bin")?)
}
fn store_pending(st: &AppState, key: &VaultKey, pending: &PendingBundle) -> Result<()> {
@@ -959,23 +814,19 @@ fn store_pending(st: &AppState, key: &VaultKey, pending: &PendingBundle) -> Resu
st,
key,
"local-pending",
- &local_path(st, "pending.bin"),
+ &local_path(st, "pending.bin")?,
pending,
)
}
fn clear_pending(st: &AppState) -> Result<()> {
- let path = local_path(st, "pending.bin");
+ let path = local_path(st, "pending.bin")?;
if path.exists() {
fs::remove_file(path)?;
}
Ok(())
}
-fn store_base(st: &AppState, key: &VaultKey, manifest: &RevisionManifest) -> Result<()> {
- persist_encrypted(st, key, "local-base", &local_path(st, "base.bin"), manifest)
-}
-
fn recovery_path(st: &AppState, filename: &str) -> Result<PathBuf> {
if !filename.starts_with("recovery-")
|| !filename.ends_with(".bin")
@@ -985,7 +836,7 @@ fn recovery_path(st: &AppState, filename: &str) -> Result<PathBuf> {
{
bail!("CONFIG_SYNC_INVALID: local recovery filename is unsafe");
}
- Ok(local_path(st, filename))
+ local_path(st, filename)
}
fn create_recovery_point(
@@ -1115,7 +966,7 @@ mod tests {
.starts_with("CONFIG_SYNC_DEPENDENCY: defaultProviderId"));
}
- fn pending_approvals(value: &Value) -> Vec<(String, String, String)> {
+ pub(super) fn pending_approvals(value: &Value) -> Vec<(String, String, String)> {
value
.get("pendingApprovals")
.and_then(Value::as_array)
@@ -1140,30 +991,32 @@ mod tests {
.collect()
}
- async fn configure_test_device(
+ pub(super) async fn configure_test_device(
data_dir: &Path,
endpoint: &str,
) -> Result<Arc<Mutex<AppState>>> {
- configure_test_device_mode(data_dir, endpoint, "strict").await
+ configure_test_device_mode(data_dir, endpoint, "sync").await
}
- async fn configure_test_device_mode(
+ pub(super) async fn configure_test_device_mode(
data_dir: &Path,
endpoint: &str,
- remote_mode: &str,
+ mode: &str,
) -> Result<Arc<Mutex<AppState>>> {
let state = Arc::new(Mutex::new(AppState::open(data_dir)?));
configure(
state.clone(),
json!({
"endpoint": endpoint,
- "username": "",
- "appPassword": "",
- "directory": "config-sync-test",
+ "region": "us-east-1",
+ "bucket": "fixture-bucket",
+ "accessKeyId": "fixture-access",
+ "secretAccessKey": "fixture-secret",
+ "prefix": "config-sync-test",
"deviceLabel": "test-device",
"backupPassword": "portable-backup-password",
- "allowInsecureHttp": true,
- "remoteMode": remote_mode,
+ "pathStyle": true,
+ "mode": mode,
"categories": {
"application": true,
"providers": true,
@@ -1180,7 +1033,7 @@ mod tests {
Ok(state)
}
- fn run_in_isolated_process(test_name: &str) -> Result<bool> {
+ pub(super) fn run_in_isolated_process(test_name: &str) -> Result<bool> {
const ISOLATED_PROCESS: &str = "PI_DESKTOP_CONFIG_SYNC_TEST_CHILD";
if std::env::var(ISOLATED_PROCESS).as_deref() == Ok(test_name) {
return Ok(false);
@@ -1192,6 +1045,8 @@ mod tests {
.args(["--exact", test_name, "--nocapture"])
.env(ISOLATED_PROCESS, test_name)
.env(crate::agent_capabilities::AGENTS_DIR_ENV, agents_dir.path())
+ .env("HOME", agents_dir.path())
+ .env("USERPROFILE", agents_dir.path())
.output()?;
anyhow::ensure!(
output.status.success(),
@@ -1203,54 +1058,20 @@ mod tests {
}
#[tokio::test]
- async fn append_only_mode_syncs_with_a_server_that_ignores_preconditions() -> Result<()> {
+ async fn unsupported_conditional_writes_are_rejected() -> Result<()> {
if run_in_isolated_process(
- "config_sync::engine::tests::append_only_mode_syncs_with_a_server_that_ignores_preconditions",
+ "config_sync::engine::tests::unsupported_conditional_writes_are_rejected",
)? {
return Ok(());
}
let fixture = crate::config_sync::transport::tests::fixture_ignoring_preconditions().await;
- let device_a_dir = tempfile::tempdir()?;
- let device_b_dir = tempfile::tempdir()?;
- let device_a =
- configure_test_device_mode(device_a_dir.path(), &fixture.endpoint, "appendOnly")
- .await?;
- let device_b =
- configure_test_device_mode(device_b_dir.path(), &fixture.endpoint, "appendOnly")
- .await?;
- let (tx, _rx) = mpsc::unbounded_channel();
-
- let (a_state, b_state) = tokio::join!(
- sync_now(device_a.clone(), tx.clone()),
- sync_now(device_b.clone(), tx.clone())
- );
- assert!(
- a_state.is_ok(),
- "device A compatibility sync failed: {a_state:?}"
- );
- assert!(
- b_state.is_ok(),
- "device B compatibility sync failed: {b_state:?}"
- );
-
- let state = device_a.lock().await;
- let config = load_config(&state)?.expect("configured device");
- let key = local_vault_key(&state, &config)?.expect("unlocked device");
- let transport = transport_with_password(&config, String::new())?;
- let remote = read_append_only_remote(&transport, &config, &key, &NoSyncProgress)
- .await?
- .expect("compatibility revisions");
- assert!(!remote.tip_ids.is_empty());
- assert!(remote.tip_ids.len() <= 2);
- assert!(
- transport
- .list_children(&remote::compatibility_heads_path(&config))
- .await?
- .len()
- >= 2
- );
-
- fixture.task.abort();
+ let device_dir = tempfile::tempdir()?;
+ let result = configure_test_device(device_dir.path(), &fixture.endpoint).await;
+ assert!(result
+ .err()
+ .expect("unsupported server")
+ .to_string()
+ .starts_with("CONFIG_SYNC_UNSUPPORTED:"));
Ok(())
}
@@ -1319,7 +1140,8 @@ mod tests {
let device_a = configure_test_device(device_a_dir.path(), &fixture.endpoint).await?;
let device_b = configure_test_device(device_b_dir.path(), &fixture.endpoint).await?;
let device_a_state = get_state(device_a.clone()).await?;
- assert_eq!(device_a_state.get("allowInsecureHttp"), Some(&json!(true)));
+ assert_eq!(device_a_state.get("pathStyle"), Some(&json!(true)));
+ assert_eq!(device_a_state.get("mode"), Some(&json!("sync")));
let project_a = device_a_dir.path().join("project");
let project_b = device_b_dir.path().join("project");
std::fs::create_dir_all(&project_a)?;
@@ -1465,7 +1287,7 @@ mod tests {
let state = device_b.lock().await;
let config = load_config(&state)?.expect("configured device");
let key = local_vault_key(&state, &config)?.expect("unlocked device");
- let transport = transport_with_password(&config, String::new())?;
+ let transport = configured_transport(&state, &config)?;
let (head, _) = read_remote_head(&transport, &config, &key)
.await?
.expect("remote head");
@@ -1616,7 +1438,7 @@ mod tests {
let state = device_b.lock().await;
let config = load_config(&state)?.expect("configured device");
let key = local_vault_key(&state, &config)?.expect("unlocked device");
- let transport = transport_with_password(&config, String::new())?;
+ let transport = configured_transport(&state, &config)?;
let (head, _) = read_remote_head(&transport, &config, &key)
.await?
.expect("remote head after device B edit");
diff --git a/crates/host-core/src/config_sync/engine_history.rs b/crates/host-core/src/config_sync/engine_history.rs
index 87c6ea892..f7dd09bef 100644
--- a/crates/host-core/src/config_sync/engine_history.rs
+++ b/crates/host-core/src/config_sync/engine_history.rs
@@ -1,182 +1,34 @@
use super::*;
-pub(super) async fn history_chain(
- transport: &WebDavTransport,
- config: &StoredConfig,
- key: &VaultKey,
- head_revision_id: &str,
-) -> Result<Vec<RevisionManifest>> {
- let mut pending = vec![head_revision_id.to_string()];
- let mut seen = BTreeSet::new();
- let mut result = Vec::new();
- while let Some(revision_id) = pending.pop() {
- if !seen.insert(revision_id.clone()) {
- continue;
- }
- if seen.len() > MAX_HISTORY_SCAN {
- bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote history is too large");
- }
- let manifest = read_remote_manifest(transport, config, key, &revision_id).await?;
- for parent in manifest.parents.iter().rev() {
- pending.push(parent.clone());
- }
- result.push(manifest);
- }
- Ok(result)
-}
-
-fn older_than_grace(manifest: &RevisionManifest) -> bool {
- let Ok(created_at) = chrono::DateTime::parse_from_rfc3339(&manifest.created_at) else {
- return false;
- };
- Utc::now()
- .signed_duration_since(created_at.with_timezone(&Utc))
- .num_seconds()
- >= HISTORY_GRACE_SECONDS
-}
-
-pub(super) async fn cleanup_history(
- state: &Arc<Mutex<AppState>>,
- transport: &WebDavTransport,
- config: &StoredConfig,
- key: &VaultKey,
-) -> Result<()> {
- if config.remote_mode == RemoteMode::AppendOnly {
- // There is no cross-device acknowledgement protocol for an
- // unconditional WebDAV backend. Retaining every immutable revision
- // keeps a late device head recoverable instead of deleting a branch
- // that another device has not observed yet.
- return Ok(());
- }
- let Some((head, _)) = read_remote_head(transport, config, key).await? else {
- return Ok(());
- };
- let history = history_chain(transport, config, key, &head.revision_id).await?;
- if history.len() <= MAX_RETAINED_REVISIONS {
- return Ok(());
- }
- let (base_id, protected_ids, protected_resources) = {
- let st = state.lock().await;
- let base_id = load_base(&st, key)?.map(|value| value.revision_id);
- let pending = load_pending(&st, key)?;
- let mut protected = BTreeSet::new();
- let mut resources = BTreeSet::new();
- if let Some(pending) = pending {
- protected.insert(pending.manifest.revision_id);
- protected.insert(pending.remote_revision_id);
- resources.extend(pending.manifest.resource_ids);
- }
- for filename in &config.recovery_points {
- let path = recovery_path(&st, filename)?;
- if let Some(point) = load_encrypted::<RecoveryPoint>(&st, key, "local-recovery", &path)?
- {
- if let Some(base) = point.base {
- protected.insert(base.revision_id);
- resources.extend(base.resource_ids);
- }
- }
- }
- (base_id, protected, resources)
- };
- let mut keep = BTreeSet::new();
- for manifest in history.iter().take(MAX_RETAINED_REVISIONS) {
- keep.insert(manifest.revision_id.clone());
- }
- keep.insert(head.revision_id.clone());
- if let Some(base_id) = base_id {
- keep.insert(base_id);
- }
- keep.extend(protected_ids);
-
- let mut deletable = Vec::new();
- for manifest in history {
- if !keep.contains(&manifest.revision_id) && older_than_grace(&manifest) {
- deletable.push(manifest);
- }
- }
- if deletable.is_empty() {
- return Ok(());
- }
- let mut retained_resources: BTreeSet<String> =
- history_chain(transport, config, key, &head.revision_id)
- .await?
- .into_iter()
- .filter(|manifest| keep.contains(&manifest.revision_id))
- .flat_map(|manifest| manifest.resource_ids)
- .collect();
- retained_resources.extend(protected_resources);
- let mut candidate_resources = BTreeSet::new();
- for manifest in &deletable {
- candidate_resources.extend(manifest.resource_ids.iter().cloned());
- transport
- .delete(&revision_path(config, &manifest.revision_id)?)
- .await?;
- }
- for resource_id in candidate_resources.difference(&retained_resources) {
- transport.delete(&object_path(config, resource_id)?).await?;
- }
- Ok(())
-}
-
+/// History is a bounded, authenticated index, not a recursive parent walk.
+/// Immutable objects are retained: deleting shared resources without a durable
+/// cross-device acknowledgement protocol can race an offline or publishing peer.
pub(super) async fn list_history(state: Arc<Mutex<AppState>>) -> Result<Value> {
- let (config, key, transport_password) = {
+ let (config, key, transport) = {
let st = state.lock().await;
let config = load_config(&st)?
- .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: S3 backup is not configured"))?;
let key = local_vault_key(&st, &config)?
.ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
- let password = webdav_password(&st, &config)?;
- (config, key, password)
+ let transport = configured_transport(&st, &config)?;
+ (config, key, transport)
};
- let transport = transport_with_password(&config, transport_password)?;
- if config.remote_mode == RemoteMode::AppendOnly {
- let Some(remote) =
- read_append_only_remote(&transport, &config, &key, &NoSyncProgress).await?
- else {
- return Ok(json!([]));
- };
- let current = remote.tip_ids.iter().cloned().collect::<BTreeSet<_>>();
- let mut by_id = BTreeMap::new();
- for tip_id in &remote.tip_ids {
- for manifest in history_chain(&transport, &config, &key, tip_id).await? {
- by_id
- .entry(manifest.revision_id.clone())
- .or_insert(manifest);
- }
- }
- let mut history = by_id.into_values().collect::<Vec<_>>();
- history.sort_by(|left, right| right.created_at.cmp(&left.created_at));
- return Ok(serde_json::to_value(
- history
- .into_iter()
- .map(|manifest| PublicHistoryEntry {
- current: current.contains(&manifest.revision_id),
- revision_id: manifest.revision_id,
- created_at: manifest.created_at,
- parent_revision_ids: manifest.parents,
- entity_count: manifest.entities.len(),
- resource_count: manifest.resource_ids.len(),
- })
- .collect::<Vec<_>>(),
- )?);
- }
let Some((head, _)) = read_remote_head(&transport, &config, &key).await? else {
return Ok(json!([]));
};
- let history = history_chain(&transport, &config, &key, &head.revision_id).await?;
- Ok(serde_json::to_value(
- history
- .into_iter()
- .map(|manifest| PublicHistoryEntry {
- current: manifest.revision_id == head.revision_id,
- revision_id: manifest.revision_id,
- created_at: manifest.created_at,
- parent_revision_ids: manifest.parents,
- entity_count: manifest.entities.len(),
- resource_count: manifest.resource_ids.len(),
- })
- .collect::<Vec<_>>(),
- )?)
+ let mut entries = Vec::new();
+ for revision_id in &head.history {
+ let manifest = read_remote_manifest(&transport, &config, &key, revision_id).await?;
+ entries.push(PublicHistoryEntry {
+ current: revision_id == &head.revision_id,
+ revision_id: manifest.revision_id,
+ created_at: manifest.created_at,
+ parent_revision_ids: manifest.parents,
+ entity_count: manifest.entities.len(),
+ resource_count: manifest.resource_ids.len(),
+ });
+ }
+ Ok(serde_json::to_value(entries)?)
}
fn add_restore_approvals(
@@ -199,16 +51,17 @@ fn add_restore_approvals(
}
let changed = local_map
.get(&entity_key(entity))
- .is_none_or(|current| current.digest != entity.digest);
+ .is_none_or(|current| !merge::same_version(current, entity));
if changed && !existing.contains(&entity_key(entity)) {
pending.approvals.push(PendingApproval {
approval_id: Uuid::new_v4().to_string(),
entity: entity.clone(),
reason: if entity.mapping_required {
- "mapping".into()
+ "mapping"
} else {
- "securityChange".into()
- },
+ "securityChange"
+ }
+ .into(),
approved: false,
});
}
@@ -216,10 +69,7 @@ fn add_restore_approvals(
}
pub(super) async fn change_password(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
- let sync_lock = {
- let st = state.lock().await;
- st.config_sync_lock.clone()
- };
+ let sync_lock = state.lock().await.config_sync_lock.clone();
let _sync_guard = sync_lock.lock().await;
let current_password = params
.get("currentPassword")
@@ -232,55 +82,44 @@ pub(super) async fn change_password(state: Arc<Mutex<AppState>>, params: Value)
if new_password.len() < 8 {
bail!("CONFIG_SYNC_INVALID: new backup password must be at least 8 characters");
}
- let (mut config, key, transport_password) = {
+ let (mut config, key, transport) = {
let st = state.lock().await;
let config = load_config(&st)?
- .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: S3 backup is not configured"))?;
let key = unlock_vault(&config.vault_header, current_password)?;
- let password = webdav_password(&st, &config)?;
- (config, key, password)
+ let transport = configured_transport(&st, &config)?;
+ (config, key, transport)
};
- let transport = transport_with_password(&config, transport_password)?;
- let Some((remote_header_bytes, remote_etag)) = transport.get("header").await? else {
+ let Some((bytes, etag)) = transport.get("header").await? else {
bail!("CONFIG_SYNC_REMOTE: remote vault header is missing");
};
- let remote_header: VaultHeader =
- serde_json::from_slice(&remote_header_bytes).context("decode remote vault header")?;
- if remote_header.vault_id != config.vault_id {
- bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
+ let remote: VaultHeader =
+ serde_json::from_slice(&bytes).context("decode remote vault header")?;
+ if remote.vault_id != config.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: selected S3 prefix belongs to another vault");
}
- let remote_key = unlock_vault(&remote_header, current_password)?;
+ let remote_key = unlock_vault(&remote, current_password)?;
if remote_key.as_bytes() != key.as_bytes() {
bail!("CONFIG_SYNC_CONFLICT: local and remote vault keys do not match");
}
- let next_header = rewrap_vault(&remote_header, &key, new_password)?;
- let published = if config.remote_mode == RemoteMode::AppendOnly {
- transport
- .put_unconditional("header", serde_json::to_vec(&next_header)?)
- .await?;
- true
- } else {
- let remote_etag = remote_etag.ok_or_else(|| {
- anyhow!("CONFIG_SYNC_UNSUPPORTED: remote vault header does not expose a strong ETag")
- })?;
- transport
- .put_if_match("header", &remote_etag, serde_json::to_vec(&next_header)?)
- .await?
- };
- if !published {
+ let next_header = rewrap_vault(&remote, &key, new_password)?;
+ let etag =
+ etag.ok_or_else(|| anyhow!("CONFIG_SYNC_UNSUPPORTED: vault header needs a strong ETag"))?;
+ if !transport
+ .put_if_match("header", &etag, serde_json::to_vec(&next_header)?)
+ .await?
+ {
bail!("CONFIG_SYNC_CONFLICT: remote vault header changed while changing password");
}
- let Some((stored_header, _)) = transport.get("header").await? else {
+ let Some((stored, _)) = transport.get("header").await? else {
bail!("CONFIG_SYNC_REMOTE: remote vault header disappeared after password change");
};
- let stored_header: VaultHeader = serde_json::from_slice(&stored_header)?;
- if stored_header.vault_id != config.vault_id {
+ let stored: VaultHeader = serde_json::from_slice(&stored)?;
+ if stored.vault_id != config.vault_id
+ || unlock_vault(&stored, new_password)?.as_bytes() != key.as_bytes()
+ {
bail!("CONFIG_SYNC_CONFLICT: remote vault changed while changing password");
}
- let stored_key = unlock_vault(&stored_header, new_password)?;
- if stored_key.as_bytes() != key.as_bytes() {
- bail!("CONFIG_SYNC_CONFLICT: remote vault key changed while changing password");
- }
config.vault_header = next_header;
let mut st = state.lock().await;
save_config(&st, &config)?;
@@ -292,29 +131,30 @@ pub(super) async fn restore(
params: Value,
tx: mpsc::UnboundedSender<String>,
) -> Result<Value> {
- if !params
- .get("acknowledgePropagation")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- bail!("CONFIG_SYNC_INVALID: restore propagation warning must be acknowledged");
- }
let revision_id = params
.get("revisionId")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: revisionId is required"))?;
validate_remote_id(revision_id, "revision")?;
- let sync_lock = {
- let st = state.lock().await;
- st.config_sync_lock.clone()
- };
+ let sync_lock = state.lock().await.config_sync_lock.clone();
let _sync_guard = sync_lock.lock().await;
- let (mut config, key, base, local, transport_password) = {
+ let (mut config, key, base, local, transport) = {
let mut st = state.lock().await;
let config = load_config(&st)?
- .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: S3 backup is not configured"))?;
+ if config.mode == SyncMode::Sync
+ && !params
+ .get("acknowledgePropagation")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ bail!("CONFIG_SYNC_INVALID: restore propagation warning must be acknowledged");
+ }
let key = local_vault_key(&st, &config)?
.ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ if load_pending(&st, &key)?.is_some() {
+ bail!("CONFIG_SYNC_CONFLICT: resolve pending changes before restoring");
+ }
let base = load_base(&st, &key)?;
let local = domains::capture(
&mut st,
@@ -324,63 +164,43 @@ pub(super) async fn restore(
&config.plugin_intents,
&identity_overrides(&config),
)?;
- let password = webdav_password(&st, &config)?;
- (config, key, base, local, password)
+ let transport = configured_transport(&st, &config)?;
+ (config, key, base, local, transport)
};
- let transport = transport_with_password(&config, transport_password)?;
- let (parent_ids, current_etag) = if config.remote_mode == RemoteMode::AppendOnly {
- let Some(remote) =
- read_append_only_remote(&transport, &config, &key, &NoSyncProgress).await?
- else {
- bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
- };
- if remote.tip_ids.is_empty() {
- bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
- }
- (remote.tip_ids, None)
- } else {
- let Some((current_head, current_etag)) =
- read_remote_head(&transport, &config, &key).await?
- else {
- bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
- };
- (vec![current_head.revision_id], Some(current_etag))
+ let Some((current_head, etag)) = read_remote_head(&transport, &config, &key).await? else {
+ bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
};
- let (target, target_resources) =
+ let (target, resources) =
read_remote_revision(&transport, &config, &key, revision_id, &NoSyncProgress).await?;
- let candidate_id = Uuid::new_v4().to_string();
+ {
+ let st = state.lock().await;
+ create_recovery_point(&st, &mut config, &key, base.clone(), local.clone())?;
+ save_config(&st, &config)?;
+ }
+ let candidate_id = if config.mode == SyncMode::Sync {
+ Uuid::new_v4().to_string()
+ } else {
+ target.revision_id.clone()
+ };
let candidate = LocalSnapshot {
manifest: RevisionManifest {
format: REVISION_FORMAT.into(),
version: 1,
revision_id: candidate_id.clone(),
- parents: parent_ids,
+ parents: vec![current_head.revision_id.clone()],
created_at: Utc::now().to_rfc3339(),
entities: target.entities.clone(),
- resource_ids: target_resources.keys().cloned().collect(),
+ resource_ids: resources.keys().cloned().collect(),
},
- resources: target_resources,
+ resources,
};
- upload_snapshot(&transport, &config, &key, &candidate, &NoSyncProgress).await?;
- if config.remote_mode == RemoteMode::AppendOnly {
- publish_append_only_head(&transport, &config, &key, &config.device_id, &candidate_id)
- .await?;
- } else if !publish_head(
- &transport,
- &config,
- &key,
- &RemoteHead {
- format: FORMAT.into(),
- version: 1,
- revision_id: candidate_id.clone(),
- },
- current_etag.as_deref(),
- )
- .await?
- {
- bail!("CONFIG_SYNC_CONFLICT: remote head changed while restoring");
+ if config.mode == SyncMode::Sync {
+ upload_snapshot(&transport, &config, &key, &candidate, &NoSyncProgress).await?;
+ let head = next_head(&candidate_id, Some(&current_head));
+ if !publish_head(&transport, &config, &key, &head, Some(&etag)).await? {
+ bail!("CONFIG_SYNC_CONFLICT: remote head changed while restoring");
+ }
}
-
let merged = merge::MergeResult {
entities: candidate.manifest.entities.clone(),
conflicts: Vec::new(),
@@ -394,19 +214,16 @@ pub(super) async fn restore(
&candidate_id,
candidate.resources.clone(),
);
- pending.manifest = candidate.manifest.clone();
+ pending.manifest = candidate.manifest;
pending.local_before = Some(local.manifest.clone());
add_restore_approvals(&config, &local.manifest, &target, &mut pending);
let should_apply = pending.approvals.is_empty();
+ pending.journal_state = if should_apply { "applying" } else { "staged" }.into();
{
let st = state.lock().await;
- create_recovery_point(&st, &mut config, &key, base.clone(), local.clone())?;
- let mut journal = pending.clone();
- journal.journal_state = if should_apply { "applying" } else { "staged" }.into();
- store_pending(&st, &key, &journal)?;
+ store_pending(&st, &key, &pending)?;
if !should_apply {
- config.last_success_at = Some(Utc::now().to_rfc3339());
- config.last_revision_id = Some(candidate_id.clone());
+ config.last_revision_id = Some(candidate_id);
clear_error(&mut config);
save_config(&st, &config)?;
}
@@ -422,11 +239,6 @@ pub(super) async fn restore(
)
.await?;
}
- if config.remote_mode == RemoteMode::Strict {
- if let Err(error) = cleanup_history(&state, &transport, &config, &key).await {
- tracing::warn!(error = %error, "config sync history cleanup failed after restore");
- }
- }
let mut st = state.lock().await;
send_state_notification(&tx, &mut st);
public_state(&mut st)
diff --git a/crates/host-core/src/config_sync/engine_remote.rs b/crates/host-core/src/config_sync/engine_remote.rs
index 5d484d07f..9ce1dadf5 100644
--- a/crates/host-core/src/config_sync/engine_remote.rs
+++ b/crates/host-core/src/config_sync/engine_remote.rs
@@ -32,23 +32,6 @@ pub(super) fn validate_remote_id(value: &str, kind: &str) -> Result<()> {
Ok(())
}
-pub(super) async fn ensure_remote_collections(
- transport: &WebDavTransport,
- config: &StoredConfig,
-) -> Result<()> {
- validate_remote_id(&config.vault_id, "vault")?;
- transport.ensure_collection("vault").await?;
- transport
- .ensure_collection(&format!("vault/{}", config.vault_id))
- .await?;
- for child in ["objects", "revisions", "heads"] {
- transport
- .ensure_collection(&format!("vault/{}/{}", config.vault_id, child))
- .await?;
- }
- Ok(())
-}
-
pub(super) fn revision_path(config: &StoredConfig, revision_id: &str) -> Result<String> {
validate_remote_id(&config.vault_id, "vault")?;
validate_remote_id(revision_id, "revision")?;
@@ -62,17 +45,42 @@ pub(super) fn object_path(config: &StoredConfig, object_id: &str) -> Result<Stri
}
pub(super) fn head_path(config: &StoredConfig) -> String {
- remote_path(config, "head")
+ remote_path(
+ config,
+ if config.mode == SyncMode::Backup {
+ "backup-head"
+ } else {
+ "head"
+ },
+ )
}
-pub(super) fn compatibility_heads_path(config: &StoredConfig) -> String {
- remote_path(config, "heads")
+fn head_purpose(config: &StoredConfig) -> &'static str {
+ if config.mode == SyncMode::Backup {
+ "backup-head"
+ } else {
+ "head"
+ }
}
-pub(super) fn compatibility_head_path(config: &StoredConfig, device_id: &str) -> Result<String> {
- validate_remote_id(&config.vault_id, "vault")?;
- validate_remote_id(device_id, "device")?;
- Ok(remote_path(config, &format!("heads/{device_id}")))
+pub(super) fn next_head(revision_id: &str, previous: Option<&RemoteHead>) -> RemoteHead {
+ let mut history = vec![revision_id.to_string()];
+ if let Some(previous) = previous {
+ for id in &previous.history {
+ if history.len() >= MAX_RETAINED_REVISIONS {
+ break;
+ }
+ if !history.contains(id) {
+ history.push(id.clone());
+ }
+ }
+ }
+ RemoteHead {
+ format: FORMAT.into(),
+ version: 1,
+ revision_id: revision_id.into(),
+ history,
+ }
}
pub(super) fn serialize_json<T: Serialize>(value: &T) -> Result<Vec<u8>> {
@@ -80,7 +88,7 @@ pub(super) fn serialize_json<T: Serialize>(value: &T) -> Result<Vec<u8>> {
}
pub(super) async fn read_remote_head(
- transport: &WebDavTransport,
+ transport: &S3Transport,
config: &StoredConfig,
key: &VaultKey,
) -> Result<Option<(RemoteHead, String)>> {
@@ -88,225 +96,28 @@ pub(super) async fn read_remote_head(
let Some((ciphertext, etag)) = transport.get(&head_path(config)).await? else {
return Ok(None);
};
- let etag = etag.ok_or_else(|| {
- anyhow!("CONFIG_SYNC_UNSUPPORTED: WebDAV head does not expose a strong ETag")
- })?;
- let plain = decrypt_object(key, "head", &config.vault_id, &ciphertext)?;
+ let etag = etag
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_UNSUPPORTED: S3 head does not expose a strong ETag"))?;
+ let plain = decrypt_object(key, head_purpose(config), &config.vault_id, &ciphertext)?;
let head: RemoteHead = serde_json::from_slice(&plain).context("decode remote head")?;
if head.format != FORMAT || head.version != 1 {
bail!("CONFIG_SYNC_UNSUPPORTED: remote head format is not supported");
}
validate_remote_id(&head.revision_id, "revision")?;
- Ok(Some((head, etag)))
-}
-
-#[derive(Debug)]
-pub(super) struct AppendOnlyRemote {
- pub tip_ids: Vec<String>,
- pub tips: Vec<RevisionManifest>,
- pub resources: BTreeMap<String, Vec<u8>>,
-}
-
-fn is_ancestor(
- manifests: &BTreeMap<String, RevisionManifest>,
- ancestor: &str,
- descendant: &str,
-) -> bool {
- let mut pending = vec![descendant.to_string()];
- let mut seen = BTreeSet::new();
- while let Some(revision_id) = pending.pop() {
- if !seen.insert(revision_id.clone()) {
- continue;
- }
- if revision_id == ancestor {
- return true;
- }
- if let Some(manifest) = manifests.get(&revision_id) {
- pending.extend(manifest.parents.iter().cloned());
- }
- }
- false
-}
-
-pub(super) async fn read_append_only_remote(
- transport: &WebDavTransport,
- config: &StoredConfig,
- key: &VaultKey,
- observer: &dyn SyncProgressObserver,
-) -> Result<Option<AppendOnlyRemote>> {
- let mut head_revision_ids = BTreeSet::new();
- for device_id in transport
- .list_children(&compatibility_heads_path(config))
- .await?
+ if head.history.first() != Some(&head.revision_id)
+ || head.history.len() > MAX_RETAINED_REVISIONS
+ || head.history.iter().collect::<BTreeSet<_>>().len() != head.history.len()
{
- validate_remote_id(&device_id, "device")?;
- let path = compatibility_head_path(config, &device_id)?;
- let Some((ciphertext, _)) = transport.get(&path).await? else {
- bail!("CONFIG_SYNC_REMOTE: compatibility head disappeared");
- };
- let plain = decrypt_object(
- key,
- &format!("append-head/{device_id}"),
- &config.vault_id,
- &ciphertext,
- )?;
- let head: RemoteHead =
- serde_json::from_slice(&plain).context("decode compatibility head")?;
- if head.format != FORMAT || head.version != 1 {
- bail!("CONFIG_SYNC_UNSUPPORTED: compatibility head format is not supported");
- }
- validate_remote_id(&head.revision_id, "revision")?;
- head_revision_ids.insert(head.revision_id);
- }
-
- // A vault created by strict mode may be joined explicitly in append-only
- // mode. Treat the old shared head as one input while the first
- // compatibility head is published; strict-mode devices are warned in the
- // UI and must not remain subscribed to the same vault.
- if let Some((ciphertext, _)) = transport.get(&head_path(config)).await? {
- let plain = decrypt_object(key, "head", &config.vault_id, &ciphertext)?;
- let head: RemoteHead = serde_json::from_slice(&plain).context("decode legacy head")?;
- if head.format != FORMAT || head.version != 1 {
- bail!("CONFIG_SYNC_UNSUPPORTED: legacy head format is not supported");
- }
- validate_remote_id(&head.revision_id, "revision")?;
- head_revision_ids.insert(head.revision_id);
- }
-
- if head_revision_ids.is_empty() {
- return Ok(None);
- }
-
- let mut manifests = BTreeMap::new();
- let mut pending = head_revision_ids.iter().cloned().collect::<Vec<_>>();
- while let Some(revision_id) = pending.pop() {
- if manifests.contains_key(&revision_id) {
- continue;
- }
- if manifests.len() >= MAX_HISTORY_SCAN {
- bail!("CONFIG_SYNC_LIMIT_EXCEEDED: compatibility history is too large");
- }
- let manifest = read_remote_manifest(transport, config, key, &revision_id).await?;
- pending.extend(manifest.parents.iter().cloned());
- manifests.insert(revision_id, manifest);
- }
-
- let tip_ids = head_revision_ids
- .iter()
- .filter(|candidate| {
- !head_revision_ids
- .iter()
- .any(|other| *candidate != other && is_ancestor(&manifests, candidate, other))
- })
- .cloned()
- .collect::<Vec<_>>();
-
- let mut tips = Vec::new();
- let mut resources = BTreeMap::new();
- let tip_total = tip_ids.len() as u64;
- for (index, revision_id) in tip_ids.iter().enumerate() {
- // Count tips, not the objects inside them: the tips are read one after
- // another, so a per-object count inside each of them would restart and
- // walk the bar backwards on a vault with more than one tip.
- observer.report(SyncProgress::counted(
- SyncPhase::Download,
- index as u64,
- tip_total,
- 0,
- 0,
- ));
- let (manifest, revision_resources) =
- read_remote_revision(transport, config, key, revision_id, &NoSyncProgress).await?;
- for (object_id, bytes) in revision_resources {
- if let Some(existing) = resources.get(&object_id) {
- if existing != &bytes {
- bail!("CONFIG_SYNC_CRYPTO: compatibility resource id collision");
- }
- } else {
- resources.insert(object_id, bytes);
- }
- }
- tips.push(manifest);
- }
- observer.report(SyncProgress::counted(
- SyncPhase::Download,
- tip_total,
- tip_total,
- 0,
- 0,
- ));
- if resources.len() > MAX_RESOURCES {
- bail!("CONFIG_SYNC_LIMIT_EXCEEDED: compatibility revision references too many resources");
+ bail!("CONFIG_SYNC_INVALID: remote history index is invalid");
}
- Ok(Some(AppendOnlyRemote {
- tip_ids,
- tips,
- resources,
- }))
-}
-
-pub(super) fn merge_append_only_tips(
- base: Option<&RevisionManifest>,
- tips: &[RevisionManifest],
-) -> Result<merge::MergeResult> {
- let Some(first) = tips.first() else {
- return Ok(merge::MergeResult {
- entities: Vec::new(),
- conflicts: Vec::new(),
- });
- };
- let mut accumulator = first.clone();
- let mut conflicts = Vec::new();
- for tip in tips.iter().skip(1) {
- let merged = merge::three_way(base, &accumulator, Some(tip))?;
- accumulator.entities = merged.entities;
- conflicts.extend(merged.conflicts);
+ for id in &head.history {
+ validate_remote_id(id, "revision")?;
}
- Ok(merge::MergeResult {
- entities: accumulator.entities,
- conflicts,
- })
-}
-
-pub(super) async fn publish_append_only_head(
- transport: &WebDavTransport,
- config: &StoredConfig,
- key: &VaultKey,
- device_id: &str,
- revision_id: &str,
-) -> Result<()> {
- let path = compatibility_head_path(config, device_id)?;
- validate_remote_id(revision_id, "revision")?;
- let head = RemoteHead {
- format: FORMAT.into(),
- version: 1,
- revision_id: revision_id.into(),
- };
- let encrypted = encrypt_object(
- key,
- &format!("append-head/{device_id}"),
- &config.vault_id,
- &serialize_json(&head)?,
- )?;
- transport.put_unconditional(&path, encrypted).await?;
- let Some((stored, _)) = transport.get(&path).await? else {
- bail!("CONFIG_SYNC_REMOTE: compatibility head disappeared after upload");
- };
- let plain = decrypt_object(
- key,
- &format!("append-head/{device_id}"),
- &config.vault_id,
- &stored,
- )?;
- let stored: RemoteHead = serde_json::from_slice(&plain)?;
- if stored.revision_id != revision_id {
- bail!("CONFIG_SYNC_CONFLICT: compatibility head was changed during publication");
- }
- Ok(())
+ Ok(Some((head, etag)))
}
pub(super) async fn read_remote_revision(
- transport: &WebDavTransport,
+ transport: &S3Transport,
config: &StoredConfig,
key: &VaultKey,
revision_id: &str,
@@ -352,7 +163,7 @@ pub(super) async fn read_remote_revision(
}
pub(super) async fn read_remote_manifest(
- transport: &WebDavTransport,
+ transport: &S3Transport,
config: &StoredConfig,
key: &VaultKey,
revision_id: &str,
@@ -422,7 +233,7 @@ pub(super) async fn read_remote_manifest(
}
pub(super) async fn upload_snapshot(
- transport: &WebDavTransport,
+ transport: &S3Transport,
config: &StoredConfig,
key: &VaultKey,
snapshot: &LocalSnapshot,
@@ -437,7 +248,15 @@ pub(super) async fn upload_snapshot(
.iter()
.cloned()
.collect::<BTreeSet<_>>();
- if declared_resources != snapshot.resources.keys().cloned().collect() {
+ let referenced_resources = snapshot
+ .manifest
+ .entities
+ .iter()
+ .flat_map(|entity| entity.resource_ids.iter().cloned())
+ .collect::<BTreeSet<_>>();
+ if declared_resources != snapshot.resources.keys().cloned().collect()
+ || declared_resources != referenced_resources
+ {
bail!("CONFIG_SYNC_INVALID: local revision resource references do not match");
}
for entity in &snapshot.manifest.entities {
@@ -472,13 +291,7 @@ pub(super) async fn upload_snapshot(
&config.vault_id,
bytes,
)?;
- if config.remote_mode == RemoteMode::AppendOnly {
- if transport.get(&path).await?.is_none() {
- transport.put_unconditional(&path, encrypted).await?;
- }
- } else {
- transport.put_if_none(&path, encrypted).await?;
- }
+ transport.put_if_none(&path, encrypted).await?;
let Some((existing, _)) = transport.get(&path).await? else {
bail!("CONFIG_SYNC_REMOTE: immutable resource disappeared after upload");
};
@@ -509,11 +322,7 @@ pub(super) async fn upload_snapshot(
&manifest_bytes,
)?;
let path = revision_path(config, &snapshot.manifest.revision_id)?;
- if config.remote_mode == RemoteMode::AppendOnly {
- transport.put_unconditional(&path, encrypted).await?;
- } else {
- transport.put_if_none(&path, encrypted).await?;
- }
+ transport.put_if_none(&path, encrypted).await?;
let Some((existing, _)) = transport.get(&path).await? else {
bail!("CONFIG_SYNC_REMOTE: immutable revision disappeared after upload");
};
@@ -530,14 +339,19 @@ pub(super) async fn upload_snapshot(
}
pub(super) async fn publish_head(
- transport: &WebDavTransport,
+ transport: &S3Transport,
config: &StoredConfig,
key: &VaultKey,
head: &RemoteHead,
etag: Option<&str>,
) -> Result<bool> {
validate_remote_id(&config.vault_id, "vault")?;
- let encrypted = encrypt_object(key, "head", &config.vault_id, &serialize_json(head)?)?;
+ let encrypted = encrypt_object(
+ key,
+ head_purpose(config),
+ &config.vault_id,
+ &serialize_json(head)?,
+ )?;
if let Some(etag) = etag {
transport
.put_if_match(&head_path(config), etag, encrypted)
@@ -550,65 +364,20 @@ pub(super) async fn publish_head(
#[cfg(test)]
mod tests {
use super::*;
- use serde_json::json;
-
- fn application_entity(payload: serde_json::Value) -> PortableEntity {
- let mut entity = PortableEntity {
- domain: domains::DOMAIN_APPLICATION.to_string(),
- entity_id: "application".to_string(),
- label: "Application".to_string(),
- deleted: false,
- requires_approval: false,
- secret_bearing: false,
- mapping_required: false,
- digest: String::new(),
- payload,
- resource_ids: Vec::new(),
- };
- domains::refresh_digest(&mut entity);
- entity
- }
-
- fn manifest(
- revision_id: &str,
- parents: Vec<String>,
- entity: PortableEntity,
- ) -> RevisionManifest {
- RevisionManifest {
- format: REVISION_FORMAT.to_string(),
- version: 1,
- revision_id: revision_id.to_string(),
- parents,
- created_at: "2026-09-22T00:00:00Z".to_string(),
- entities: vec![entity],
- resource_ids: Vec::new(),
- }
- }
#[test]
- fn append_only_tips_merge_disjoint_application_fields() {
- let base = manifest(
- "base",
- Vec::new(),
- application_entity(json!({"theme": "light", "language": "en"})),
- );
- let theme_tip = manifest(
- "theme-tip",
- vec!["base".to_string()],
- application_entity(json!({"theme": "dark", "language": "en"})),
- );
- let language_tip = manifest(
- "language-tip",
- vec!["base".to_string()],
- application_entity(json!({"theme": "light", "language": "zh-CN"})),
- );
-
- let merged = merge_append_only_tips(Some(&base), &[theme_tip, language_tip])
- .expect("append-only tips merge");
- assert!(merged.conflicts.is_empty());
+ fn history_index_stays_bounded_without_traversing_deleted_ancestors() {
+ let mut head = next_head("first", None);
+ for index in 0..300 {
+ head = next_head(&format!("revision-{index}"), Some(&head));
+ }
+ assert_eq!(head.history.len(), MAX_RETAINED_REVISIONS);
+ assert_eq!(head.history[0], "revision-299");
assert_eq!(
- merged.entities[0].payload,
- json!({"theme": "dark", "language": "zh-CN"})
+ head.history.last().map(String::as_str),
+ Some("revision-270")
);
+ let repeated = next_head(&head.revision_id, Some(&head));
+ assert_eq!(repeated.history, head.history);
}
}
diff --git a/crates/host-core/src/config_sync/engine_s3_tests.rs b/crates/host-core/src/config_sync/engine_s3_tests.rs
new file mode 100644
index 000000000..fea93a079
--- /dev/null
+++ b/crates/host-core/src/config_sync/engine_s3_tests.rs
@@ -0,0 +1,363 @@
+use super::tests::{
+ configure_test_device, configure_test_device_mode, pending_approvals, run_in_isolated_process,
+};
+use super::*;
+use crate::config_sync::transport::tests::fixture;
+
+fn theme(state: &AppState) -> Result<Value> {
+ Ok(state.db.get_setting("app")?.unwrap_or_else(|| json!({}))["theme"].clone())
+}
+
+async fn approve_all(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+) -> Result<()> {
+ let value = get_state(state.clone()).await?;
+ for (id, digest, _) in pending_approvals(&value) {
+ approve(
+ state.clone(),
+ json!({"approvalId":id,"digest":digest}),
+ tx.clone(),
+ )
+ .await?;
+ }
+ assert!(pending_approvals(&get_state(state.clone()).await?).is_empty());
+ Ok(())
+}
+
+#[test]
+fn unconfigured_device_uses_s3_defaults() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let mut state = AppState::open(directory.path())?;
+ let public = public_state(&mut state)?;
+ assert_eq!(public["configured"], false);
+ assert_eq!(public["mode"], "sync");
+ assert_eq!(public["pathStyle"], true);
+ assert!(load_config(&state)?.is_none());
+ Ok(())
+}
+
+#[tokio::test]
+async fn backup_does_not_apply_remote_settings_and_restore_is_local_only() -> Result<()> {
+ if run_in_isolated_process(
+ "config_sync::engine::s3_tests::backup_does_not_apply_remote_settings_and_restore_is_local_only",
+ )? {
+ return Ok(());
+ }
+ let fixture = fixture(false).await;
+ let directory_a = tempfile::tempdir()?;
+ let directory_b = tempfile::tempdir()?;
+ let device_a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;
+ let device_b =
+ configure_test_device_mode(directory_b.path(), &fixture.endpoint, "backup").await?;
+ device_a
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"light"}))?;
+ device_b
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"dark"}))?;
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let sync_revision = sync_now(device_a.clone(), tx.clone()).await?["lastRevisionId"].clone();
+ let first_backup = sync_now(device_b.clone(), tx.clone()).await?["lastRevisionId"].clone();
+ assert_eq!(theme(&*device_b.lock().await)?, "dark");
+ assert_eq!(
+ list_history(device_a.clone()).await?[0]["revisionId"],
+ sync_revision
+ );
+ assert_eq!(
+ list_history(device_b.clone()).await?[0]["revisionId"],
+ first_backup
+ );
+ device_b
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"system"}))?;
+ let second_backup = sync_now(device_b.clone(), tx.clone()).await?["lastRevisionId"].clone();
+ assert_ne!(first_backup, second_backup);
+ restore(
+ device_b.clone(),
+ json!({"revisionId": first_backup}),
+ tx.clone(),
+ )
+ .await?;
+ assert_eq!(theme(&*device_b.lock().await)?, "dark");
+ assert_eq!(
+ list_history(device_b.clone()).await?[0]["revisionId"],
+ second_backup
+ );
+ assert_eq!(
+ list_history(device_a.clone()).await?[0]["revisionId"],
+ sync_revision
+ );
+ sync_now(device_a.clone(), tx).await?;
+ assert_eq!(theme(&*device_a.lock().await)?, "light");
+ assert!(!load_config(&*device_b.lock().await)?
+ .unwrap()
+ .recovery_points
+ .is_empty());
+ Ok(())
+}
+
+#[tokio::test]
+async fn sync_restore_requires_acknowledgement_and_propagates_as_a_new_revision() -> Result<()> {
+ if run_in_isolated_process(
+ "config_sync::engine::s3_tests::sync_restore_requires_acknowledgement_and_propagates_as_a_new_revision",
+ )? {
+ return Ok(());
+ }
+ let fixture = fixture(false).await;
+ let directory_a = tempfile::tempdir()?;
+ let directory_b = tempfile::tempdir()?;
+ let device_a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;
+ let device_b = configure_test_device(directory_b.path(), &fixture.endpoint).await?;
+ let (tx, _rx) = mpsc::unbounded_channel();
+ device_a
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"light"}))?;
+ let first = sync_now(device_a.clone(), tx.clone()).await?["lastRevisionId"].clone();
+ sync_now(device_b.clone(), tx.clone()).await?;
+ device_a
+ .lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"dark"}))?;
+ sync_now(device_a.clone(), tx.clone()).await?;
+ sync_now(device_b.clone(), tx.clone()).await?;
+ assert_eq!(theme(&*device_b.lock().await)?, "dark");
+ assert!(
+ restore(device_a.clone(), json!({"revisionId":first}), tx.clone())
+ .await
+ .is_err()
+ );
+ assert_eq!(theme(&*device_a.lock().await)?, "dark");
+ let restored = restore(
+ device_a.clone(),
+ json!({"revisionId":first,"acknowledgePropagation":true}),
+ tx.clone(),
+ )
+ .await?;
+ assert_ne!(restored["lastRevisionId"], first);
+ assert_eq!(theme(&*device_a.lock().await)?, "light");
+ sync_now(device_b.clone(), tx).await?;
+ assert_eq!(theme(&*device_b.lock().await)?, "light");
+ Ok(())
+}
+
+#[tokio::test]
+async fn credentials_opt_out_survives_approval_and_remote_deletion_converges() -> Result<()> {
+ if run_in_isolated_process(
+ "config_sync::engine::s3_tests::credentials_opt_out_survives_approval_and_remote_deletion_converges",
+ )? {
+ return Ok(());
+ }
+ let fixture = fixture(false).await;
+ let directory_a = tempfile::tempdir()?;
+ let directory_b = tempfile::tempdir()?;
+ let device_a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;
+ let device_b = configure_test_device(directory_b.path(), &fixture.endpoint).await?;
+ configure(device_b.clone(), json!({"includeSecrets":false})).await?;
+ let provider_id =
+ {
+ let state = device_a.lock().await;
+ providers::create_provider(&state.db, &state.secrets, serde_json::from_value(json!({
+ "name":"S3 regression", "type":"openai_compatible", "protocol":"openai_compatible",
+ "baseUrl":"https://provider.example.test/v1", "authKind":"api_key_and_base_url",
+ "secretValue":"source-only-key", "models":[]
+ }))?)?.id
+ };
+ let (tx, _rx) = mpsc::unbounded_channel();
+ sync_now(device_a.clone(), tx.clone()).await?;
+ let received = sync_now(device_b.clone(), tx.clone()).await?;
+ assert!(!pending_approvals(&received).is_empty());
+ {
+ let state = device_b.lock().await;
+ assert!(providers::get_provider(&state.db, &state.secrets, &provider_id)?.is_none());
+ }
+ approve_all(&device_b, &tx).await?;
+ {
+ let state = device_b.lock().await;
+ let imported = providers::get_provider(&state.db, &state.secrets, &provider_id)?.unwrap();
+ assert!(!imported.has_secret);
+ assert!(!imported.enabled);
+ }
+ // The publishing device acknowledges the receiver's secret-free metadata
+ // before deletion, without losing its own device-local credential.
+ sync_now(device_a.clone(), tx.clone()).await?;
+ approve_all(&device_a, &tx).await?;
+ {
+ let state = device_a.lock().await;
+ assert!(
+ providers::get_provider(&state.db, &state.secrets, &provider_id)?
+ .unwrap()
+ .has_secret
+ );
+ providers::delete_provider(&state.db, &state.secrets, &provider_id)?;
+ }
+ sync_now(device_a.clone(), tx.clone()).await?;
+ sync_now(device_b.clone(), tx.clone()).await?;
+ approve_all(&device_b, &tx).await?;
+ for _ in 0..2 {
+ sync_now(device_b.clone(), tx.clone()).await?;
+ sync_now(device_a.clone(), tx.clone()).await?;
+ }
+ let state = device_b.lock().await;
+ assert!(providers::get_provider(&state.db, &state.secrets, &provider_id)?.is_none());
+ Ok(())
+}
+
+#[tokio::test]
+async fn resource_updates_and_packaged_skill_deletion_reach_the_other_device() -> Result<()> {
+ if run_in_isolated_process(
+ "config_sync::engine::s3_tests::resource_updates_and_packaged_skill_deletion_reach_the_other_device",
+ )? {
+ return Ok(());
+ }
+ let fixture = fixture(false).await;
+ let directory_a = tempfile::tempdir()?;
+ let directory_b = tempfile::tempdir()?;
+ let device_a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;
+ let device_b = configure_test_device(directory_b.path(), &fixture.endpoint).await?;
+ let project_a = directory_a.path().join("project");
+ let project_b = directory_b.path().join("project");
+ fs::create_dir_all(&project_a)?;
+ fs::create_dir_all(&project_b)?;
+ let project_a = project_a.canonicalize()?.to_string_lossy().into_owned();
+ let project_b = project_b.canonicalize()?.to_string_lossy().into_owned();
+ {
+ let mut state = device_a.lock().await;
+ state.db.ensure_project(&project_a, false)?;
+ state
+ .user_skills
+ .create(crate::user_skills::UserSkillInput {
+ id: Some("changing-skill".into()),
+ name: Some("Changing skill".into()),
+ level: Some("project".into()),
+ project_path: Some(project_a.clone()),
+ body: Some("Fixture instructions".into()),
+ shape: Some("dir".into()),
+ ..Default::default()
+ })?;
+ state.user_skills.write_package_files(
+ "changing-skill",
+ CapabilityLevel::Project,
+ Some(&project_a),
+ &[("data.txt".into(), b"first".to_vec())],
+ )?;
+ }
+ let (tx, _rx) = mpsc::unbounded_channel();
+ sync_now(device_a.clone(), tx.clone()).await?;
+ let received = sync_now(device_b.clone(), tx.clone()).await?;
+ let mapping = received["pendingApprovals"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find_map(|item| item["mappingKey"].as_str())
+ .unwrap();
+ map_project(
+ device_b.clone(),
+ json!({"logicalId":mapping,"paths":[project_b]}),
+ )
+ .await?;
+ approve_all(&device_b, &tx).await?;
+ {
+ let mut state = device_a.lock().await;
+ let skill = state
+ .user_skills
+ .list(CapabilityLevel::Project, Some(&project_a))?
+ .remove(0);
+ fs::write(
+ Path::new(&skill.path).parent().unwrap().join("data.txt"),
+ b"updated",
+ )?;
+ }
+ sync_now(device_a.clone(), tx.clone()).await?;
+ sync_now(device_b.clone(), tx.clone()).await?;
+ approve_all(&device_b, &tx).await?;
+ {
+ let mut state = device_b.lock().await;
+ assert_eq!(
+ state.user_skills.package_files(
+ "changing-skill",
+ CapabilityLevel::Project,
+ Some(&project_b)
+ )?,
+ vec![("data.txt".into(), b"updated".to_vec())]
+ );
+ }
+ device_a.lock().await.user_skills.remove(
+ "changing-skill",
+ Some(CapabilityLevel::Project),
+ Some(&project_a),
+ )?;
+ sync_now(device_a.clone(), tx.clone()).await?;
+ sync_now(device_b.clone(), tx.clone()).await?;
+ approve_all(&device_b, &tx).await?;
+ assert!(device_b
+ .lock()
+ .await
+ .user_skills
+ .list(CapabilityLevel::Project, Some(&project_b))?
+ .is_empty());
+ sync_now(device_b.clone(), tx).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn chosen_conflict_is_published_without_reopening_old_candidates() -> Result<()> {
+ if run_in_isolated_process(
+ "config_sync::engine::s3_tests::chosen_conflict_is_published_without_reopening_old_candidates",
+ )? {
+ return Ok(());
+ }
+ let fixture = fixture(false).await;
+ let directory_a = tempfile::tempdir()?;
+ let directory_b = tempfile::tempdir()?;
+ let a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;
+ let b = configure_test_device(directory_b.path(), &fixture.endpoint).await?;
+ let (tx, _rx) = mpsc::unbounded_channel();
+ a.lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"dark"}))?;
+ sync_now(a.clone(), tx.clone()).await?;
+ sync_now(b.clone(), tx.clone()).await?;
+ a.lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"light"}))?;
+ b.lock()
+ .await
+ .db
+ .set_setting("app", &json!({"theme":"system"}))?;
+ sync_now(a.clone(), tx.clone()).await?;
+ let conflict = sync_now(b.clone(), tx.clone()).await?;
+ let item = conflict["pendingApprovals"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["entityId"].as_str().unwrap().ends_with(":local"))
+ .unwrap();
+ approve(
+ b.clone(),
+ json!({"approvalId":item["id"],"digest":item["digest"]}),
+ tx.clone(),
+ )
+ .await?;
+ assert_eq!(theme(&*b.lock().await)?, "system");
+ assert!(pending_approvals(&sync_now(b.clone(), tx.clone()).await?).is_empty());
+ let received = sync_now(a.clone(), tx.clone()).await?;
+ assert!(pending_approvals(&received).is_empty());
+ assert_eq!(theme(&*a.lock().await)?, "system");
+ for _ in 0..2 {
+ assert!(pending_approvals(&sync_now(b.clone(), tx.clone()).await?).is_empty());
+ assert!(pending_approvals(&sync_now(a.clone(), tx.clone()).await?).is_empty());
+ }
+ Ok(())
+}
diff --git a/crates/host-core/src/config_sync/handlers.rs b/crates/host-core/src/config_sync/handlers.rs
index 059beedc8..b9dbfff89 100644
--- a/crates/host-core/src/config_sync/handlers.rs
+++ b/crates/host-core/src/config_sync/handlers.rs
@@ -22,222 +22,104 @@ pub(crate) async fn restore(
}
pub(crate) async fn test(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
- let (config, password) = {
+ let transport = {
let st = state.lock().await;
let existing = load_config(&st)?;
- let endpoint = params
- .get("endpoint")
- .and_then(Value::as_str)
- .unwrap_or_else(|| {
- existing
- .as_ref()
- .map(|value| value.endpoint.as_str())
- .unwrap_or_default()
- });
- let username = params
- .get("username")
- .and_then(Value::as_str)
- .unwrap_or_else(|| {
- existing
- .as_ref()
- .map(|value| value.username.as_str())
- .unwrap_or_default()
- });
- let directory = params
- .get("directory")
- .and_then(Value::as_str)
- .unwrap_or_else(|| {
- existing
- .as_ref()
- .map(|value| value.directory.as_str())
- .unwrap_or_default()
- });
- let remote_mode = params
- .get("remoteMode")
- .and_then(Value::as_str)
- .map(parse_remote_mode)
- .transpose()?
- .or_else(|| existing.as_ref().map(|value| value.remote_mode))
- .unwrap_or_default();
- let password = connection_password(
- &st,
- existing.as_ref(),
- endpoint.trim(),
- username.trim(),
- &params,
- )?;
- let vault_id = Uuid::new_v4().to_string();
- let header = create_vault("temporary-test-password", &vault_id)?.0;
- (
- StoredConfig {
- format: FORMAT.into(),
- version: 1,
- endpoint: endpoint.trim().into(),
- username: username.trim().into(),
- directory: directory.trim().into(),
- device_label: "test".into(),
- remote_mode,
- device_id: Uuid::new_v4().to_string(),
- missing_object_status: None,
- categories: default_categories(),
- include_secrets: false,
- include_memory: false,
- automatic_sync: false,
- enabled: false,
- paused: false,
- vault_id,
- vault_header: header,
- last_run_at: None,
- last_success_at: None,
- last_revision_id: None,
- last_error: None,
- last_error_code: None,
- last_local_digest: None,
- local_change_seen_at: None,
- retry_count: 0,
- next_retry_at: None,
- project_mappings: BTreeMap::new(),
- project_group_mappings: BTreeMap::new(),
- dismissed: BTreeMap::new(),
- plugin_intents: BTreeMap::new(),
- recovery_points: Vec::new(),
- },
- password,
- )
+ let connection =
+ S3Connection::from_input(existing.as_ref().map(|v| &v.connection), &params)?;
+ let credentials = connection_credentials(&st, existing.as_ref(), &connection, &params)?;
+ transport_with_credentials(&connection, credentials)?
};
- let transport = transport_with_password(&config, password)?;
let probe = transport.probe().await?;
- Ok(json!({
- "ok": true,
- "conditionalWrites": probe.conditional_writes,
- "appendOnly": probe.append_only,
- }))
+ if !probe.conditional_writes {
+ bail!("CONFIG_SYNC_UNSUPPORTED: S3 storage did not prove reliable conditional writes");
+ }
+ Ok(json!({"ok": true, "conditionalWrites": true}))
}
pub(crate) async fn configure(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
- let sync_lock = {
- let st = state.lock().await;
- st.config_sync_lock.clone()
- };
+ let sync_lock = state.lock().await.config_sync_lock.clone();
let _sync_guard = sync_lock.lock().await;
- let backup_password = params
- .get("backupPassword")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
+ let backup_password = match params.get("backupPassword") {
+ None => "",
+ Some(Value::String(value)) => value.as_str(),
+ Some(_) => bail!("CONFIG_SYNC_INVALID: backup password must be text"),
+ };
if !backup_password.is_empty() && backup_password.len() < 8 {
bail!("CONFIG_SYNC_INVALID: backup password must be at least 8 characters");
}
- let (mut config, mut key, transport_password, had_existing) = {
+ let (mut config, mut key, credentials, previous) = {
let st = state.lock().await;
let existing = load_config(&st)?;
- let (header, key, had_existing) = if backup_password.is_empty() {
- let saved = existing.as_ref().ok_or_else(|| {
- anyhow!("CONFIG_SYNC_LOCKED: enter the vault password to set up sync")
- })?;
- let key = local_vault_key(&st, saved)?
- .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
- (saved.vault_header.clone(), key, true)
- } else {
- let vault_id = existing
- .as_ref()
- .map(|value| value.vault_id.clone())
- .unwrap_or_else(|| Uuid::new_v4().to_string());
- let (header, key) = if let Some(saved) = existing.as_ref() {
- (
- saved.vault_header.clone(),
- unlock_vault(&saved.vault_header, backup_password)?,
- )
+ let (header, key) = if let Some(saved) = existing.as_ref() {
+ let key = if backup_password.is_empty() {
+ local_vault_key(&st, saved)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?
} else {
- create_vault(backup_password, &vault_id)?
+ unlock_vault(&saved.vault_header, backup_password)?
};
- (header, key, existing.is_some())
+ (saved.vault_header.clone(), key)
+ } else {
+ if backup_password.is_empty() {
+ bail!("CONFIG_SYNC_LOCKED: enter the vault password to set up S3 backup");
+ }
+ create_vault(backup_password, &Uuid::new_v4().to_string())?
};
let config = config_from_input(existing.as_ref(), &params, header)?;
- let transport_password = connection_password(
- &st,
- existing.as_ref(),
- &config.endpoint,
- &config.username,
- &params,
- )?;
- (config, key, transport_password, had_existing)
- };
- let app_password = params
- .get("appPassword")
- .and_then(Value::as_str)
- .map(str::to_string);
- let transport = transport_with_password(&config, transport_password.clone())?;
- let probe = transport.probe().await?;
- match config.remote_mode {
- RemoteMode::Strict if !probe.conditional_writes => {
- bail!(
- "CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove reliable conditional writes"
- );
- }
- RemoteMode::AppendOnly if !probe.append_only => {
- bail!(
- "CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove append-only directory listing"
- );
+ if existing
+ .as_ref()
+ .is_some_and(|saved| saved.state_id != config.state_id)
+ && load_pending(&st, &key)?.is_some()
+ {
+ bail!("CONFIG_SYNC_CONFLICT: resolve pending changes before changing the destination or mode");
}
- _ => {}
+ let credentials =
+ connection_credentials(&st, existing.as_ref(), &config.connection, &params)?;
+ (config, key, credentials, existing)
+ };
+ let transport = transport_with_credentials(&config.connection, credentials.clone())?;
+ if !transport.probe().await?.conditional_writes {
+ bail!("CONFIG_SYNC_UNSUPPORTED: S3 storage did not prove reliable conditional writes");
}
- let transport = transport.with_probe_result(&probe);
- config.missing_object_status = probe.missing_object_status;
- transport.ensure_collection("vault").await?;
- let remote_header = transport.get("header").await?;
- if let Some((bytes, _)) = remote_header {
+ if let Some((bytes, _)) = transport.get("header").await? {
let remote: VaultHeader =
serde_json::from_slice(&bytes).context("decode remote vault header")?;
- if had_existing && config.vault_id != remote.vault_id {
- bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
+ if previous.is_some() && config.vault_id != remote.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: selected S3 prefix belongs to another vault; disconnect first");
}
adopt_remote_vault(&mut key, &mut config, remote, backup_password)?;
} else {
- if config.remote_mode == RemoteMode::AppendOnly {
- if had_existing {
- bail!(
- "CONFIG_SYNC_CONFLICT: remote vault header is missing; compatibility mode will not reinitialize an existing vault"
- );
- }
- transport
- .put_unconditional("header", serde_json::to_vec(&config.vault_header)?)
- .await?;
- } else {
- let created = transport
- .put_if_none("header", serde_json::to_vec(&config.vault_header)?)
- .await?;
- if !created {
- let Some((bytes, _)) = transport.get("header").await? else {
- bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization");
- };
- let remote: VaultHeader = serde_json::from_slice(&bytes)?;
- adopt_remote_vault(&mut key, &mut config, remote, backup_password)?;
- }
+ if previous
+ .as_ref()
+ .is_some_and(|saved| saved.connection == config.connection)
+ {
+ bail!("CONFIG_SYNC_REMOTE: configured vault header is missing; refusing to reinitialize it");
}
- if config.remote_mode == RemoteMode::AppendOnly {
+ if !transport
+ .put_if_none("header", serde_json::to_vec(&config.vault_header)?)
+ .await?
+ {
let Some((bytes, _)) = transport.get("header").await? else {
bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization");
};
- let remote: VaultHeader = serde_json::from_slice(&bytes)?;
- if had_existing && config.vault_id != remote.vault_id {
- bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
- }
+ let remote: VaultHeader =
+ serde_json::from_slice(&bytes).context("decode remote vault header")?;
adopt_remote_vault(&mut key, &mut config, remote, backup_password)?;
}
}
- ensure_remote_collections(&transport, &config).await?;
let mut st = state.lock().await;
- if config.username.is_empty() {
- st.secrets.delete(WEBDAV_SECRET_REF)?;
- } else if let Some(password) = app_password {
- st.secrets.set(WEBDAV_SECRET_REF, &password)?;
- }
+ st.secrets.set(
+ &credential_ref(&config),
+ &serde_json::to_string(&credentials)?,
+ )?;
st.secrets.set(
&secret_ref_for_vault(&config.vault_id),
&vault_key_b64(&key),
)?;
save_config(&st, &config)?;
+ if let Some(previous) = previous.filter(|saved| saved.state_id != config.state_id) {
+ st.secrets.delete(&credential_ref(&previous))?;
+ }
public_state(&mut st)
}
@@ -505,46 +387,19 @@ pub(crate) async fn disconnect(state: Arc<Mutex<AppState>>) -> Result<Value> {
let _sync_guard = sync_lock.lock().await;
let mut st = state.lock().await;
if let Some(config) = load_config(&st)? {
- st.secrets.delete(WEBDAV_SECRET_REF)?;
+ st.secrets.delete(&credential_ref(&config))?;
st.secrets.delete(&secret_ref_for_vault(&config.vault_id))?;
- st.db.kv_delete(CONFIG_NS, CONFIG_KEY)?;
for file in ["base.bin", "pending.bin"] {
- let path = local_path(&st, file);
+ let path = local_path(&st, file)?;
if path.exists() {
fs::remove_file(path)?;
}
}
+ st.db.kv_delete(CONFIG_NS, CONFIG_KEY)?;
}
public_state(&mut st)
}
-/// A saved WebDAV password belongs to one endpoint and account. Changing either
-/// must not send the previous server's secret.
-fn connection_password(
- st: &AppState,
- existing: Option<&StoredConfig>,
- endpoint: &str,
- username: &str,
- params: &Value,
-) -> Result<String> {
- if username.is_empty() {
- return Ok(String::new());
- }
- let explicit = params.get("appPassword").and_then(Value::as_str);
- let password = match explicit {
- Some(value) => Some(value.to_string()),
- None if existing
- .is_some_and(|saved| saved.endpoint == endpoint && saved.username == username) =>
- {
- st.secrets.get(WEBDAV_SECRET_REF)?
- }
- None => None,
- };
- password.filter(|value| !value.is_empty()).ok_or_else(|| {
- anyhow!("CONFIG_SYNC_AUTH: enter the WebDAV app password for this server and account")
- })
-}
-
fn adopt_remote_vault(
key: &mut VaultKey,
config: &mut StoredConfig,
@@ -563,59 +418,3 @@ fn adopt_remote_vault(
config.vault_header = remote;
Ok(())
}
-
-#[cfg(test)]
-mod credential_tests {
- use super::*;
-
- #[test]
- fn stored_password_stays_on_its_server_and_pause_survives_a_resave() -> Result<()> {
- let dir = tempfile::tempdir()?;
- let state = AppState::open(dir.path())?;
- state.secrets.set(WEBDAV_SECRET_REF, "original-secret")?;
- let (header, _) = create_vault("backup-password", "test-vault")?;
- let mut config = config_from_input(
- None,
- &json!({
- "endpoint": "https://original.example/dav/",
- "username": "alice",
- "deviceLabel": "test"
- }),
- header.clone(),
- )?;
- config.paused = true;
- assert_eq!(
- connection_password(&state, Some(&config), &config.endpoint, "alice", &json!({}))?,
- "original-secret"
- );
- let resent = config_from_input(
- Some(&config),
- &json!({
- "endpoint": config.endpoint,
- "username": "alice",
- "deviceLabel": "test"
- }),
- header,
- )?;
- assert!(resent.paused);
- for (endpoint, username) in [
- ("https://other.example/dav/", "alice"),
- ("https://original.example/dav/", "bob"),
- ] {
- let error = connection_password(&state, Some(&config), endpoint, username, &json!({}))
- .unwrap_err();
- assert!(error.to_string().starts_with("CONFIG_SYNC_AUTH:"));
- }
- assert_eq!(
- connection_password(
- &state,
- Some(&config),
- "https://other.example/",
- "",
- &json!({})
- )?,
- ""
- );
- Ok(())
- }
-}
diff --git a/crates/host-core/src/config_sync/merge.rs b/crates/host-core/src/config_sync/merge.rs
index 5d4cbeafe..0230349ea 100644
--- a/crates/host-core/src/config_sync/merge.rs
+++ b/crates/host-core/src/config_sync/merge.rs
@@ -26,6 +26,10 @@ fn key(entity: &PortableEntity) -> (String, String) {
(entity.domain.clone(), entity.entity_id.clone())
}
+pub(super) fn same_version(left: &PortableEntity, right: &PortableEntity) -> bool {
+ left.deleted == right.deleted && left.digest == right.digest
+}
+
fn index(manifest: Option<&RevisionManifest>) -> BTreeMap<(String, String), PortableEntity> {
manifest
.map(|manifest| {
@@ -123,7 +127,7 @@ pub fn three_way(
(None, None, None) => Vec::new(),
(None, Some(local), None) => vec![local.clone()],
(None, None, Some(remote)) => vec![remote.clone()],
- (None, Some(local), Some(remote)) if local.digest == remote.digest => {
+ (None, Some(local), Some(remote)) if same_version(local, remote) => {
vec![local.clone()]
}
(None, Some(local), Some(remote)) => {
@@ -162,7 +166,7 @@ pub fn three_way(
vec![local_candidate, remote_candidate]
}
}
- (Some(_base), Some(local), Some(remote)) if local.digest == remote.digest => {
+ (Some(_base), Some(local), Some(remote)) if same_version(local, remote) => {
vec![local.clone()]
}
(Some(base), Some(local), Some(remote))
@@ -185,13 +189,13 @@ pub fn three_way(
vec![local_candidate, remote_candidate]
}
}
- (Some(base), Some(local), remote) if local.digest == base.digest => {
+ (Some(base), Some(local), remote) if same_version(local, base) => {
remote.cloned().into_iter().collect()
}
- (Some(base), local, Some(remote)) if remote.digest == base.digest => {
+ (Some(base), local, Some(remote)) if same_version(remote, base) => {
local.cloned().into_iter().collect()
}
- (Some(base), None, Some(remote)) if remote.digest == base.digest => {
+ (Some(base), None, Some(remote)) if same_version(remote, base) => {
vec![PortableEntity {
domain: base.domain.clone(),
entity_id: base.entity_id.clone(),
@@ -205,7 +209,7 @@ pub fn three_way(
resource_ids: Vec::new(),
}]
}
- (Some(base), Some(local), None) if local.digest == base.digest => {
+ (Some(base), Some(local), None) if same_version(local, base) => {
vec![PortableEntity {
domain: base.domain.clone(),
entity_id: base.entity_id.clone(),
@@ -290,18 +294,11 @@ pub fn snapshot_with_tombstones(
continue;
}
if selection.is_selected(&entity.domain) {
- snapshot.manifest.entities.push(PortableEntity {
- domain: entity.domain.clone(),
- entity_id: entity.entity_id.clone(),
- label: entity.label.clone(),
- deleted: true,
- requires_approval: entity.requires_approval,
- secret_bearing: entity.secret_bearing,
- mapping_required: entity.mapping_required,
- digest: entity.digest.clone(),
- payload: entity.payload.clone(),
- resource_ids: Vec::new(),
- });
+ let mut tombstone = entity.clone();
+ tombstone.deleted = true;
+ tombstone.resource_ids.clear();
+ refresh_digest(&mut tombstone);
+ snapshot.manifest.entities.push(tombstone);
} else {
// Category opt-out is a subscription policy, not a delete. Keep
// the last acknowledged value in the local merge input so remote
@@ -504,4 +501,29 @@ mod tests {
assert_eq!(merged.entities[0].payload["theme"], "dark");
assert_eq!(merged.entities[0].payload["language"], "zh-CN");
}
+
+ #[test]
+ fn remote_deletion_reaches_an_unchanged_device() {
+ let base = manifest(vec![entity("a", "0")]);
+ let mut deleted = base.entities[0].clone();
+ deleted.deleted = true;
+ let remote = manifest(vec![deleted]);
+ let merged = three_way(Some(&base), &base, Some(&remote)).expect("remote deletion");
+ assert!(merged.conflicts.is_empty());
+ assert!(merged.entities[0].deleted);
+ }
+
+ #[test]
+ fn remote_deletion_conflicts_with_an_offline_edit() {
+ let base = manifest(vec![entity("a", "0")]);
+ let local = manifest(vec![entity("a", "edited")]);
+ let mut deleted = base.entities[0].clone();
+ deleted.deleted = true;
+ let remote = manifest(vec![deleted]);
+ let merged = three_way(Some(&base), &local, Some(&remote)).expect("delete versus edit");
+ assert_eq!(merged.conflicts.len(), 1);
+ assert_eq!(merged.entities.len(), 2);
+ assert!(merged.entities.iter().any(|entity| entity.deleted));
+ assert!(merged.entities.iter().any(|entity| !entity.deleted));
+ }
}
diff --git a/crates/host-core/src/config_sync/mod.rs b/crates/host-core/src/config_sync/mod.rs
index 5c34a1f11..f099241ef 100644
--- a/crates/host-core/src/config_sync/mod.rs
+++ b/crates/host-core/src/config_sync/mod.rs
@@ -8,4 +8,4 @@ pub(crate) use crypto::{
create_vault, decrypt_object, encrypt_object, object_id, rewrap_vault, unlock_vault,
vault_key_b64, vault_key_from_b64, VaultHeader, VaultKey,
};
-pub(crate) use transport::{remote_error_is_offline, WebDavConfig, WebDavTransport};
+pub(crate) use transport::{remote_error_is_offline, S3Config, S3Transport};
diff --git a/crates/host-core/src/config_sync/progress.rs b/crates/host-core/src/config_sync/progress.rs
index 99611f4c1..977ffb7c0 100644
--- a/crates/host-core/src/config_sync/progress.rs
+++ b/crates/host-core/src/config_sync/progress.rs
@@ -2,7 +2,7 @@
//!
//! A sync is one request: it captures the local snapshot, reads the remote
//! revision, merges, uploads every resource object, publishes the head, applies
-//! the result and cleans up history. The caller hears back only at the end, and
+//! the result. The caller hears back only at the end, and
//! the upload is unbatched — one object per resource, two round trips each — so
//! a vault with a few hundred resources looks like a frozen window unless the
//! work reports itself. That is what a [`SyncProgressObserver`] is for.
@@ -29,8 +29,6 @@ pub(crate) enum SyncPhase {
Upload,
/// Writing the approved result locally.
Apply,
- /// Deleting revisions the retention window no longer keeps.
- Cleanup,
}
impl SyncPhase {
@@ -42,7 +40,6 @@ impl SyncPhase {
SyncPhase::Merge => "merge",
SyncPhase::Upload => "upload",
SyncPhase::Apply => "apply",
- SyncPhase::Cleanup => "cleanup",
}
}
}
@@ -135,7 +132,6 @@ impl ProgressNotifier {
SyncPhase::Merge => 2,
SyncPhase::Upload => 3,
SyncPhase::Apply => 4,
- SyncPhase::Cleanup => 5,
}
}
@@ -197,7 +193,6 @@ mod tests {
(SyncPhase::Merge, "merge"),
(SyncPhase::Upload, "upload"),
(SyncPhase::Apply, "apply"),
- (SyncPhase::Cleanup, "cleanup"),
];
for (phase, name) in phases {
assert_eq!(phase.as_str(), name);
diff --git a/crates/host-core/src/config_sync/signing.rs b/crates/host-core/src/config_sync/signing.rs
new file mode 100644
index 000000000..adf7dcb4a
--- /dev/null
+++ b/crates/host-core/src/config_sync/signing.rs
@@ -0,0 +1,89 @@
+//! AWS Signature Version 4 for the bounded, single-object S3 request surface.
+//! HMAC uses the maintained ring implementation already used by rustls.
+use anyhow::{anyhow, bail, Result};
+use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, HOST};
+use reqwest::{Method, Url};
+use sha2::{Digest, Sha256};
+
+pub(super) struct Credentials {
+ pub access_key_id: String,
+ pub secret_access_key: String,
+ pub session_token: Option<String>,
+}
+
+fn header(value: &str) -> Result<HeaderValue> {
+ HeaderValue::from_str(value)
+ .map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid S3 signing header"))
+}
+
+fn hmac(key: &[u8], data: &str) -> Vec<u8> {
+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key);
+ ring::hmac::sign(&key, data.as_bytes()).as_ref().to_vec()
+}
+
+/// Paths are already encoded exactly once by the transport. S3 must not
+/// normalize paths or encode the separating slashes a second time.
+pub(super) fn sign(
+ method: &Method,
+ url: &Url,
+ region: &str,
+ credentials: &Credentials,
+ body: &[u8],
+ headers: &mut HeaderMap,
+ timestamp: &str,
+) -> Result<()> {
+ if timestamp.len() != 16 || !timestamp.is_ascii() || url.query().is_some() {
+ bail!("CONFIG_SYNC_INVALID: unsupported S3 signing input");
+ }
+ let hostname = url
+ .host_str()
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: missing S3 host"))?;
+ let host = match url.port() {
+ Some(port) => format!("{hostname}:{port}"),
+ None => hostname.to_string(),
+ };
+ headers.insert(HOST, header(&host)?);
+ headers.insert("x-amz-date", header(timestamp)?);
+ let payload_hash = hex::encode(Sha256::digest(body));
+ headers.insert("x-amz-content-sha256", header(&payload_hash)?);
+ if let Some(token) = &credentials.session_token {
+ headers.insert("x-amz-security-token", header(token)?);
+ }
+ let mut names: Vec<_> = headers.keys().map(|name| name.as_str()).collect();
+ names.sort_unstable();
+ let signed_headers = names.join(";");
+ let mut canonical_headers = String::new();
+ for name in names {
+ let value = headers[name]
+ .to_str()
+ .map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid S3 signing header"))?;
+ let normalized = value.split_ascii_whitespace().collect::<Vec<_>>().join(" ");
+ canonical_headers.push_str(&format!("{name}:{normalized}\n"));
+ }
+ let canonical_request = format!(
+ "{method}\n{}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}",
+ url.path()
+ );
+ let day = &timestamp[..8];
+ let scope = format!("{day}/{region}/s3/aws4_request");
+ let string_to_sign = format!(
+ "AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{}",
+ hex::encode(Sha256::digest(canonical_request.as_bytes()))
+ );
+ let date_key = hmac(
+ format!("AWS4{}", credentials.secret_access_key).as_bytes(),
+ day,
+ );
+ let region_key = hmac(&date_key, region);
+ let service_key = hmac(&region_key, "s3");
+ let signing_key = hmac(&service_key, "aws4_request");
+ let signature = hex::encode(hmac(&signing_key, &string_to_sign));
+ let authorization = format!("AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}", credentials.access_key_id);
+ let mut value = header(&authorization)?;
+ value.set_sensitive(true);
+ headers.insert(AUTHORIZATION, value);
+ if let Some(value) = headers.get_mut("x-amz-security-token") {
+ value.set_sensitive(true);
+ }
+ Ok(())
+}
diff --git a/crates/host-core/src/config_sync/transport.rs b/crates/host-core/src/config_sync/transport.rs
index 2fbde7048..ba1f204e1 100644
--- a/crates/host-core/src/config_sync/transport.rs
+++ b/crates/host-core/src/config_sync/transport.rs
@@ -1,254 +1,244 @@
-use anyhow::{bail, Context, Result};
+use anyhow::{anyhow, bail, Result};
use reqwest::header::{HeaderMap, HeaderValue, ETAG, IF_MATCH, IF_NONE_MATCH};
use reqwest::{Client, Method, StatusCode, Url};
use std::net::IpAddr;
+use std::time::Duration;
use uuid::Uuid;
+#[path = "signing.rs"]
+mod signing;
+#[cfg(test)]
+#[path = "transport_tests.rs"]
+pub(crate) mod tests;
+
const MAX_REMOTE_OBJECT_BYTES: usize = 64 * 1024 * 1024;
-const MAX_REMOTE_LIST_ENTRIES: usize = 4096;
-#[derive(Debug, Clone)]
-pub struct WebDavConfig {
+// Deliberately not Debug: connection credentials must never enter logs.
+pub struct S3Config {
pub endpoint: String,
- pub username: String,
- pub password: String,
- pub directory: String,
- /// Whether the network policy in force allows a plaintext hop to a WebDAV
- /// endpoint. This is no longer the per-endpoint acknowledgement the sync
- /// settings used to carry: callers pass `crate::network_policy::relaxed()`,
- /// so `strict` refuses `http` outright while `relaxed` keeps it for a
- /// loopback, `.local` or private LAN host. A public `http` host is refused
- /// in either mode.
+ pub region: String,
+ pub bucket: String,
+ pub access_key_id: String,
+ pub secret_access_key: String,
+ pub session_token: Option<String>,
+ pub prefix: String,
+ pub path_style: bool,
pub allow_insecure_http: bool,
- pub missing_object_status: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct ProbeResult {
pub conditional_writes: bool,
- pub append_only: bool,
- pub missing_object_status: Option<u16>,
}
-#[derive(Debug, Clone)]
-pub struct WebDavTransport {
+pub struct S3Transport {
client: Client,
base: Url,
- username: String,
- password: String,
- directory: String,
- missing_object_status: Option<StatusCode>,
+ key_prefix: String,
+ region: String,
+ credentials: signing::Credentials,
}
-fn validate_relative_directory(value: &str) -> Result<String> {
- let trimmed = value.trim().trim_matches('/');
- if trimmed.is_empty() {
- return Ok(String::new());
+fn safe_path(value: &str, allow_empty: bool) -> Result<()> {
+ if (value.is_empty() && !allow_empty) || value.len() > 1024 {
+ bail!("CONFIG_SYNC_INVALID: invalid S3 object path length");
}
- let mut parts = Vec::new();
- for part in trimmed.split('/') {
- if part.is_empty() || part == "." || part == ".." || part.contains('\\') {
- bail!("CONFIG_SYNC_INVALID: remote directory contains an unsafe path segment");
- }
- if part.len() > 128
- || !part
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ' '))
+ if value.is_empty() {
+ return Ok(());
+ }
+ for segment in value.split('/') {
+ if segment.is_empty()
+ || matches!(segment, "." | "..")
+ || !segment
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || b"-_.~ ".contains(&c))
{
- bail!("CONFIG_SYNC_INVALID: remote directory contains an unsupported character");
+ bail!("CONFIG_SYNC_INVALID: unsafe S3 object path");
}
- parts.push(part.to_string());
}
- Ok(parts.join("/"))
+ Ok(())
}
fn is_lan_http_host(host: &str) -> bool {
let host = host
- .trim()
- .trim_start_matches('[')
- .trim_end_matches(']')
+ .trim_matches(['[', ']'])
.trim_end_matches('.')
.to_ascii_lowercase();
if matches!(host.as_str(), "localhost" | "localhost.localdomain") || host.ends_with(".local") {
return true;
}
-
match host.parse::<IpAddr>() {
- Ok(IpAddr::V4(address)) => {
- let octets = address.octets();
- address.is_loopback()
- || address.is_link_local()
- || octets[0] == 10
- || (octets[0] == 172 && (16..=31).contains(&octets[1]))
- || (octets[0] == 192 && octets[1] == 168)
- }
- Ok(IpAddr::V6(address)) => {
- let segments = address.segments();
- address.is_loopback()
- || (segments[0] & 0xfe00) == 0xfc00
- || (segments[0] & 0xffc0) == 0xfe80
+ Ok(IpAddr::V4(ip)) => ip.is_loopback() || ip.is_private() || ip.is_link_local(),
+ Ok(IpAddr::V6(ip)) => {
+ ip.is_loopback() || ip.is_unique_local() || ip.is_unicast_link_local()
}
Err(_) => false,
}
}
-/// Validate a WebDAV endpoint and return the base URL to address.
-///
-/// `allow_insecure_http` is the network policy's answer, so a plaintext `http`
-/// endpoint is refused unless the relaxed mode asked for it *and* the host is
-/// the user's own LAN. Public `http` stays refused in every mode: the request
-/// would carry the WebDAV credentials in the clear across the internet.
fn validate_endpoint(raw: &str, allow_insecure_http: bool) -> Result<Url> {
- let mut url = Url::parse(raw.trim()).context("parse WebDAV endpoint")?;
- if !matches!(url.scheme(), "https" | "http") {
- bail!("CONFIG_SYNC_INVALID: WebDAV endpoint must use HTTPS");
- }
- if url.scheme() == "http" && !allow_insecure_http {
- bail!("CONFIG_SYNC_INVALID: HTTP requires the relaxed network policy");
- }
- if url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() {
- bail!("CONFIG_SYNC_INVALID: endpoint must not contain userinfo");
+ let url =
+ Url::parse(raw.trim()).map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid S3 endpoint"))?;
+ if !matches!(url.scheme(), "https" | "http")
+ || url.host_str().is_none()
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.query().is_some()
+ || url.fragment().is_some()
+ || !matches!(url.path(), "" | "/")
+ {
+ bail!(
+ "CONFIG_SYNC_INVALID: S3 endpoint must be an HTTP(S) origin without userinfo, path, query or fragment"
+ );
}
- if url.scheme() == "http" && !is_lan_http_host(url.host_str().unwrap_or_default()) {
+ if url.scheme() == "http"
+ && (!allow_insecure_http || !is_lan_http_host(url.host_str().unwrap_or_default()))
+ {
bail!(
- "CONFIG_SYNC_INVALID: HTTP is limited to localhost, .local, or private LAN addresses"
+ "CONFIG_SYNC_INVALID: HTTP requires relaxed network policy and a private LAN endpoint"
);
}
- url.set_query(None);
- url.set_fragment(None);
- let path = url.path().trim_end_matches('/').to_string();
- url.set_path(&format!("{path}/"));
Ok(url)
}
-impl WebDavTransport {
- pub fn new(config: &WebDavConfig) -> Result<Self> {
- let base = validate_endpoint(&config.endpoint, config.allow_insecure_http)?;
- let directory = validate_relative_directory(&config.directory)?;
+impl S3Transport {
+ pub fn new(config: &S3Config) -> Result<Self> {
+ let mut base = validate_endpoint(&config.endpoint, config.allow_insecure_http)?;
+ safe_path(&config.prefix, true)?;
+ if !(3..=63).contains(&config.bucket.len())
+ || !config
+ .bucket
+ .bytes()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b".-".contains(&c))
+ || !config
+ .bucket
+ .as_bytes()
+ .first()
+ .is_some_and(u8::is_ascii_alphanumeric)
+ || !config
+ .bucket
+ .as_bytes()
+ .last()
+ .is_some_and(u8::is_ascii_alphanumeric)
+ || config.bucket.contains("..")
+ || config.bucket.contains(".-")
+ || config.bucket.contains("-.")
+ || config.bucket.parse::<IpAddr>().is_ok()
+ {
+ bail!("CONFIG_SYNC_INVALID: invalid S3 bucket name");
+ }
+ if config.region.is_empty()
+ || config.region.len() > 128
+ || !config
+ .region
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || c == b'-')
+ || config.access_key_id.is_empty()
+ || config.access_key_id.len() > 256
+ || !config
+ .access_key_id
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c))
+ || config.secret_access_key.is_empty()
+ || config.secret_access_key.len() > 4096
+ {
+ bail!("CONFIG_SYNC_INVALID: invalid S3 region or credentials");
+ }
+ if let Some(token) = &config.session_token {
+ if token.len() > 16384 || HeaderValue::from_str(token).is_err() {
+ bail!("CONFIG_SYNC_INVALID: invalid S3 session token");
+ }
+ }
+ let bucket_path = if config.path_style {
+ format!("{}/", config.bucket)
+ } else {
+ let host = base.host_str().unwrap_or_default();
+ if host.trim_matches(['[', ']']).parse::<IpAddr>().is_ok() {
+ bail!("CONFIG_SYNC_INVALID: virtual-hosted S3 requires a DNS endpoint");
+ }
+ base.set_host(Some(&format!("{}.{host}", config.bucket)))
+ .map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid virtual-hosted S3 endpoint"))?;
+ String::new()
+ };
+ let key_prefix = if config.prefix.is_empty() {
+ bucket_path
+ } else {
+ format!("{bucket_path}{}/", config.prefix)
+ };
let client = Client::builder()
.redirect(reqwest::redirect::Policy::none())
- .https_only(false)
+ .connect_timeout(Duration::from_secs(10))
+ .timeout(Duration::from_secs(60))
.build()
- .context("build WebDAV client")?;
+ .map_err(|_| anyhow!("CONFIG_SYNC_NETWORK: could not create S3 client"))?;
Ok(Self {
client,
base,
- username: config.username.trim().to_string(),
- password: config.password.clone(),
- directory,
- missing_object_status: compatible_missing_object_status(config.missing_object_status),
+ key_prefix,
+ region: config.region.clone(),
+ credentials: signing::Credentials {
+ access_key_id: config.access_key_id.clone(),
+ secret_access_key: config.secret_access_key.clone(),
+ session_token: config.session_token.clone(),
+ },
})
}
- pub fn with_probe_result(mut self, probe: &ProbeResult) -> Self {
- self.missing_object_status = compatible_missing_object_status(probe.missing_object_status);
- self
- }
-
fn url(&self, relative: &str) -> Result<Url> {
- if relative.is_empty() || relative.starts_with('/') || relative.contains("..") {
- bail!("CONFIG_SYNC_INVALID: unsafe remote object path");
- }
- let prefix = if self.directory.is_empty() {
- String::new()
- } else {
- format!("{}/", self.directory)
- };
- self.base
- .join(&format!("{prefix}{relative}"))
- .context("resolve WebDAV object URL")
- }
-
- fn authenticated(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
- if self.username.is_empty() {
- request
- } else {
- request.basic_auth(&self.username, Some(&self.password))
- }
+ safe_path(relative, false)?;
+ let path = format!("{}{relative}", self.key_prefix);
+ safe_path(&path, false)?;
+ let mut url = self.base.clone();
+ // The path alphabet is unreserved ASCII plus slash and space. Encode
+ // space as %20, never '+', and preserve slashes for S3 canonicalization.
+ url.set_path(&format!("/{}", path.replace(' ', "%20")));
+ Ok(url)
}
async fn send(
&self,
method: Method,
relative: &str,
- body: Option<Vec<u8>>,
- headers: HeaderMap,
+ body: Vec<u8>,
+ mut headers: HeaderMap,
) -> Result<reqwest::Response> {
- self.send_url(method, self.url(relative)?, body, headers)
- .await
- }
-
- async fn send_url(
- &self,
- method: Method,
- url: Url,
- body: Option<Vec<u8>>,
- headers: HeaderMap,
- ) -> Result<reqwest::Response> {
- let mut request = self.client.request(method, url).headers(headers);
- if let Some(body) = body {
- request = request.body(body);
+ if body.len() > MAX_REMOTE_OBJECT_BYTES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: S3 object is too large");
}
+ let url = self.url(relative)?;
+ signing::sign(
+ &method,
+ &url,
+ &self.region,
+ &self.credentials,
+ &body,
+ &mut headers,
+ &chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string(),
+ )?;
+ // reqwest derives Host / HTTP/2 :authority from this same URL. Keep it
+ // in the signature, but do not emit a second explicit authority field.
+ headers.remove(reqwest::header::HOST);
let response = self
- .authenticated(request)
+ .client
+ .request(method, url)
+ .headers(headers)
+ .body(body)
.send()
.await
.map_err(request_error)?;
- // A 201 often carries Location. Only a 3xx is a redirect, and the
- // client is built not to follow one.
if response.status().is_redirection() {
- bail!(
- "CONFIG_SYNC_REDIRECT: use the direct WebDAV endpoint; redirects are not followed"
- );
+ bail!("CONFIG_SYNC_REDIRECT: use the direct S3 endpoint; redirects are not followed");
}
Ok(response)
}
- /// Create every missing collection from the selected endpoint down to
- /// `relative`. A nested remote directory such as `backups/pi` otherwise
- /// fails because its parent does not exist yet. Ancestors outside the
- /// endpoint are never created.
- pub async fn ensure_collection(&self, relative: &str) -> Result<()> {
- let target = self.url(relative)?;
- let base_path = self.base.path().trim_end_matches('/');
- let suffix = target
- .path()
- .trim_end_matches('/')
- .strip_prefix(base_path)
- .ok_or_else(|| anyhow::anyhow!("CONFIG_SYNC_INVALID: collection escaped endpoint"))?;
- let mut path = base_path.to_string();
- for segment in suffix.split('/').filter(|segment| !segment.is_empty()) {
- path.push('/');
- path.push_str(segment);
- let mut url = self.base.clone();
- url.set_path(&path);
- let response = self
- .send_url(
- Method::from_bytes(b"MKCOL").expect("MKCOL is a valid method"),
- url,
- None,
- HeaderMap::new(),
- )
- .await?;
- match response.status() {
- status
- if status.is_success()
- || status == StatusCode::METHOD_NOT_ALLOWED
- || status == StatusCode::PRECONDITION_FAILED => {}
- status => return Err(status_error("collection create", status)),
- }
- }
- Ok(())
- }
-
- async fn limited_bytes(response: reqwest::Response) -> Result<Vec<u8>> {
+ async fn limited_bytes(mut response: reqwest::Response) -> Result<Vec<u8>> {
if response
.content_length()
- .is_some_and(|length| length > MAX_REMOTE_OBJECT_BYTES as u64)
+ .is_some_and(|size| size > MAX_REMOTE_OBJECT_BYTES as u64)
{
bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote object is too large");
}
- let mut response = response;
let mut result = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(request_error)? {
if result.len().saturating_add(chunk.len()) > MAX_REMOTE_OBJECT_BYTES {
@@ -261,239 +251,182 @@ impl WebDavTransport {
pub async fn get(&self, relative: &str) -> Result<Option<(Vec<u8>, Option<String>)>> {
let response = self
- .send(Method::GET, relative, None, HeaderMap::new())
+ .send(Method::GET, relative, Vec::new(), HeaderMap::new())
.await?;
- if response.status() == StatusCode::NOT_FOUND
- || self.missing_object_status == Some(response.status())
- {
+ if response.status() == StatusCode::NOT_FOUND {
return Ok(None);
}
- if !response.status().is_success() {
- return Err(status_error("GET", response.status()));
+ if response.status() != StatusCode::OK {
+ return Err(response_error("read", response).await);
}
- let etag = strong_etag(response.headers());
+ let etag = response
+ .headers()
+ .get(ETAG)
+ .and_then(|value| value.to_str().ok())
+ .filter(|value| valid_etag(value))
+ .map(str::to_string);
Ok(Some((Self::limited_bytes(response).await?, etag)))
}
- pub async fn put_unconditional(&self, relative: &str, body: Vec<u8>) -> Result<()> {
- let response = self
- .send(Method::PUT, relative, Some(body), HeaderMap::new())
- .await?;
- if !response.status().is_success() {
- return Err(status_error("unconditional write", response.status()));
- }
- Ok(())
- }
-
- /// List direct children of a WebDAV collection. Append-only compatibility
- /// mode uses this to discover per-device heads without overwriting a
- /// shared mutable head. The returned names are intentionally opaque; the
- /// caller validates them against its domain-specific identifier rules.
- pub async fn list_children(&self, relative: &str) -> Result<Vec<String>> {
- let mut headers = HeaderMap::new();
- headers.insert(
- reqwest::header::HeaderName::from_static("depth"),
- HeaderValue::from_static("1"),
- );
- headers.insert(
- reqwest::header::CONTENT_TYPE,
- HeaderValue::from_static("application/xml; charset=utf-8"),
- );
- let body = br#"<?xml version="1.0" encoding="utf-8"?>
-<D:propfind xmlns:D="DAV:"><D:prop><D:resourcetype/></D:prop></D:propfind>"#
- .to_vec();
- let response = self
- .send(
- Method::from_bytes(b"PROPFIND").expect("PROPFIND is a valid method"),
- relative,
- Some(body),
- headers,
- )
- .await?;
- if response.status().as_u16() == 405 || response.status().as_u16() == 501 {
- bail!("CONFIG_SYNC_UNSUPPORTED: WebDAV directory listing is not supported");
- }
- if response.status().as_u16() != 207 && !response.status().is_success() {
- return Err(status_error("directory listing", response.status()));
- }
- let body = Self::limited_bytes(response).await?;
- let text = String::from_utf8(body).context("decode WebDAV directory listing")?;
- let collection_url = self.url(relative)?;
- let collection_path = collection_url.path().trim_end_matches('/').to_string();
- let collection_origin = (
- collection_url.scheme().to_string(),
- collection_url.host_str().map(str::to_string),
- collection_url.port_or_known_default(),
- );
- let hrefs = regex::Regex::new(
- r"(?is)<(?:[A-Za-z_][A-Za-z0-9_.-]*:)?href[^>]*>(.*?)</(?:[A-Za-z_][A-Za-z0-9_.-]*:)?href\s*>",
- )
- .expect("static WebDAV href expression")
- .captures_iter(&text)
- .filter_map(|capture| capture.get(1).map(|value| value.as_str().trim()))
- .map(xml_unescape)
- .filter_map(|href| {
- let href = href
- .split(['?', '#'])
- .next()
- .unwrap_or(&href);
- let href_url = self.base.join(href).ok()?;
- let href_origin = (
- href_url.scheme().to_string(),
- href_url.host_str().map(str::to_string),
- href_url.port_or_known_default(),
- );
- if href_origin != collection_origin {
- return None;
- }
- let child_path = href_url.path().trim_end_matches('/');
- let prefix = format!("{collection_path}/");
- let name = child_path.strip_prefix(&prefix)?;
- (!name.is_empty() && !name.contains('/')).then(|| name.to_string())
- })
- .take(MAX_REMOTE_LIST_ENTRIES + 1)
- .collect::<Vec<_>>();
- if hrefs.len() > MAX_REMOTE_LIST_ENTRIES {
- bail!("CONFIG_SYNC_LIMIT_EXCEEDED: WebDAV directory has too many entries");
+ async fn conditional_put(
+ &self,
+ relative: &str,
+ body: Vec<u8>,
+ headers: HeaderMap,
+ ) -> Result<bool> {
+ let response = self.send(Method::PUT, relative, body, headers).await?;
+ match response.status() {
+ StatusCode::PRECONDITION_FAILED | StatusCode::CONFLICT => Ok(false),
+ status if status.is_success() => Ok(true),
+ _ => Err(response_error("write", response).await),
}
- Ok(hrefs)
}
pub async fn put_if_none(&self, relative: &str, body: Vec<u8>) -> Result<bool> {
let mut headers = HeaderMap::new();
headers.insert(IF_NONE_MATCH, HeaderValue::from_static("*"));
- let response = self
- .send(Method::PUT, relative, Some(body), headers)
- .await?;
- match response.status() {
- StatusCode::PRECONDITION_FAILED => Ok(false),
- status if status.is_success() => Ok(true),
- status => Err(status_error("create", status)),
- }
+ self.conditional_put(relative, body, headers).await
}
pub async fn put_if_match(&self, relative: &str, etag: &str, body: Vec<u8>) -> Result<bool> {
+ if !valid_etag(etag) {
+ bail!("CONFIG_SYNC_INVALID: a strong S3 ETag is required");
+ }
let mut headers = HeaderMap::new();
headers.insert(
IF_MATCH,
- HeaderValue::from_str(etag).context("invalid WebDAV ETag")?,
+ HeaderValue::from_str(etag)
+ .map_err(|_| anyhow!("CONFIG_SYNC_INVALID: invalid S3 ETag"))?,
);
- let response = self
- .send(Method::PUT, relative, Some(body), headers)
- .await?;
- match response.status() {
- StatusCode::PRECONDITION_FAILED => Ok(false),
- status if status.is_success() => Ok(true),
- status => Err(status_error("conditional write", status)),
- }
+ self.conditional_put(relative, body, headers).await
}
pub async fn delete(&self, relative: &str) -> Result<()> {
let response = self
- .send(Method::DELETE, relative, None, HeaderMap::new())
+ .send(Method::DELETE, relative, Vec::new(), HeaderMap::new())
.await?;
- if response.status() != StatusCode::NOT_FOUND && !response.status().is_success() {
- return Err(status_error("delete", response.status()));
+ if response.status().is_success() || response.status() == StatusCode::NOT_FOUND {
+ return Ok(());
}
- Ok(())
+ Err(response_error("delete", response).await)
}
+ /// Only this random key is owned by the capability probe. Never enumerate,
+ /// create a bucket, change its ACL, or remove any configured vault object.
pub async fn probe(&self) -> Result<ProbeResult> {
- self.ensure_collection(".probe").await?;
- let probe = format!(".probe/{}", Uuid::new_v4());
- let first_body = b"pi-desktop-config-sync-probe".to_vec();
- let second_body = b"pi-desktop-config-sync-probe-2".to_vec();
- let first = self.put_if_none(&probe, first_body.clone()).await?;
- if !first {
- bail!("CONFIG_SYNC_REMOTE: probe object unexpectedly existed");
+ let path = format!("probe/{}", Uuid::new_v4());
+ let first = self.put_if_none(&path, b"probe-one".to_vec()).await;
+ if matches!(first, Ok(false)) {
+ // A collision did not create an object owned by this probe.
+ return Ok(ProbeResult {
+ conditional_writes: false,
+ });
}
- let second = self.put_if_none(&probe, second_body.clone()).await?;
- let (strong_etag, readable) = self
- .get(&probe)
- .await?
- .map(|(bytes, etag)| (etag, bytes == first_body))
- .unwrap_or((None, false));
- let matched_update = if let Some(etag) = strong_etag.as_deref() {
- self.put_if_match(&probe, etag, second_body.clone())
- .await
- .unwrap_or(false)
- } else {
- false
- };
- let stale_rejected = if matched_update {
- if let Some(etag) = strong_etag.as_deref() {
- match self
- .put_if_match(&probe, etag, b"pi-desktop-config-sync-stale".to_vec())
- .await
- {
- Ok(accepted) => !accepted,
- Err(_) => false,
- }
- } else {
- false
+ let result = async {
+ first?;
+ if self
+ .put_if_none(&path, b"must-not-replace".to_vec())
+ .await?
+ {
+ return Ok(false);
}
- } else {
- false
- };
- let updated_readable = self
- .get(&probe)
- .await?
- .is_some_and(|(bytes, _)| bytes == second_body);
- let probe_name = probe.rsplit('/').next().unwrap_or_default();
- let append_only = match self.list_children(".probe").await {
- Ok(children) => children.iter().any(|child| child == probe_name),
- Err(error) if error.to_string().starts_with("CONFIG_SYNC_UNSUPPORTED") => false,
- Err(error) => return Err(error),
- };
- self.delete(&probe).await?;
- let missing_object_status = match self
- .send(Method::GET, &probe, None, HeaderMap::new())
- .await?
- .status()
- {
- StatusCode::BAD_GATEWAY => Some(StatusCode::BAD_GATEWAY.as_u16()),
- _ => None,
- };
- Ok(ProbeResult {
- conditional_writes: !second
- && readable
- && matched_update
- && stale_rejected
- && updated_readable,
- append_only,
- missing_object_status,
- })
+ let Some((first, Some(etag))) = self.get(&path).await? else {
+ return Ok(false);
+ };
+ if first != b"probe-one" {
+ return Ok(false);
+ }
+ if !self
+ .put_if_match(&path, &etag, b"probe-two".to_vec())
+ .await?
+ {
+ return Ok(false);
+ }
+ if self
+ .put_if_match(&path, &etag, b"must-not-replace".to_vec())
+ .await?
+ {
+ return Ok(false);
+ }
+ let Some((second, Some(new_etag))) = self.get(&path).await? else {
+ return Ok(false);
+ };
+ Ok(second == b"probe-two" && etag != new_etag)
+ }
+ .await;
+ let cleanup = async {
+ self.delete(&path).await?;
+ if self.get(&path).await?.is_some() {
+ bail!("CONFIG_SYNC_REMOTE: S3 probe cleanup could not be verified");
+ }
+ Ok(())
+ }
+ .await;
+ match (result, cleanup) {
+ (Ok(conditional_writes), Ok(())) => Ok(ProbeResult { conditional_writes }),
+ (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
+ (Err(error), Err(cleanup)) => {
+ Err(anyhow!("{error}; probe cleanup also failed: {cleanup}"))
+ }
+ }
}
}
-fn xml_unescape(value: &str) -> String {
- value
- .replace("&lt;", "<")
- .replace("&gt;", ">")
- .replace("&quot;", "\"")
- .replace("&apos;", "'")
- .replace("&amp;", "&")
+fn valid_etag(value: &str) -> bool {
+ value.len() >= 3
+ && value.len() <= 256
+ && value.starts_with('"')
+ && value.ends_with('"')
+ && value[1..value.len() - 1]
+ .bytes()
+ .all(|c| c.is_ascii_graphic() && c != b'"')
}
-fn strong_etag(headers: &HeaderMap) -> Option<String> {
- let value = headers.get(ETAG)?.to_str().ok()?.trim();
- if value.is_empty() || value.starts_with("W/") {
- return None;
+fn request_error(error: reqwest::Error) -> anyhow::Error {
+ if error.is_timeout() {
+ anyhow!("CONFIG_SYNC_TIMEOUT: S3 request timed out")
+ } else {
+ anyhow!("CONFIG_SYNC_NETWORK: S3 connection failed; check the network and TLS certificate")
}
- Some(value.to_string())
}
-fn compatible_missing_object_status(value: Option<u16>) -> Option<StatusCode> {
- (value == Some(StatusCode::BAD_GATEWAY.as_u16())).then_some(StatusCode::BAD_GATEWAY)
+// Only fixed service error names are returned; XML messages may echo secrets.
+fn service_error_code(bytes: &[u8]) -> Option<&'static str> {
+ const CODES: &[&str] = &[
+ "SignatureDoesNotMatch",
+ "AuthorizationHeaderMalformed",
+ "InvalidRequest",
+ "InvalidArgument",
+ "MissingContentLength",
+ "InvalidAccessKeyId",
+ "RequestTimeTooSkewed",
+ "RequestExpired",
+ "InvalidToken",
+ "ExpiredToken",
+ "AccessDenied",
+ "XAmzContentSHA256Mismatch",
+ "InvalidHostHeader",
+ ];
+ let text = std::str::from_utf8(bytes).ok()?;
+ CODES
+ .iter()
+ .copied()
+ .find(|code| text.contains(&format!("<Code>{code}</Code>")))
}
-fn request_error(error: reqwest::Error) -> anyhow::Error {
- if error.is_timeout() {
- anyhow::anyhow!("CONFIG_SYNC_TIMEOUT: WebDAV request timed out")
+async fn response_error(operation: &str, mut response: reqwest::Response) -> anyhow::Error {
+ let error = status_error(operation, response.status());
+ let mut bytes = Vec::new();
+ while let Ok(Some(chunk)) = response.chunk().await {
+ if bytes.len() + chunk.len() > 8192 {
+ break;
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ if let Some(code) = service_error_code(&bytes) {
+ anyhow!("{error} ({code})")
} else {
- anyhow::anyhow!(
- "CONFIG_SYNC_NETWORK: WebDAV connection failed; check the network and TLS certificate"
- )
+ error
}
}
@@ -502,453 +435,26 @@ fn status_error(operation: &str, status: StatusCode) -> anyhow::Error {
401 => "AUTH",
403 => "PERMISSION",
404 => "NOT_FOUND",
- 409 | 423 => "CONFLICT",
+ 409 => "CONFLICT",
413 | 507 => "QUOTA",
429 => "RATE_LIMIT",
500..=599 => "SERVER",
_ => "REMOTE",
};
- anyhow::anyhow!("CONFIG_SYNC_{code}: WebDAV {operation} returned {status}")
+ anyhow!(
+ "CONFIG_SYNC_{code}: S3 {operation} returned HTTP {}",
+ status.as_u16()
+ )
}
pub fn remote_error_is_offline(error: &anyhow::Error) -> bool {
- let text = error.to_string().to_lowercase();
+ let text = error.to_string();
[
- "config_sync_network:",
- "config_sync_timeout:",
- "config_sync_server:",
- "config_sync_rate_limit:",
+ "CONFIG_SYNC_NETWORK:",
+ "CONFIG_SYNC_TIMEOUT:",
+ "CONFIG_SYNC_SERVER:",
+ "CONFIG_SYNC_RATE_LIMIT:",
]
.iter()
.any(|prefix| text.starts_with(prefix))
- || text.contains("request failed")
- || text.contains("timed out")
- || text.contains("dns")
- || text.contains("connect")
-}
-
-#[cfg(test)]
-pub(crate) mod tests {
- use super::*;
- use std::collections::{BTreeSet, HashMap, HashSet};
- use std::sync::{Arc, Mutex};
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
- use tokio::net::{TcpListener, TcpStream};
-
- #[derive(Default)]
- struct FixtureState {
- objects: HashMap<String, Vec<u8>>,
- etags: HashMap<String, u64>,
- collections: HashSet<String>,
- next_etag: u64,
- weak_etag: bool,
- missing_status: Option<u16>,
- ignore_preconditions: bool,
- require_parent: bool,
- }
-
- async fn read_request(stream: &mut TcpStream) -> Option<(String, String, HeaderMap, Vec<u8>)> {
- let mut buffer = Vec::new();
- let header_end;
- loop {
- let mut chunk = [0u8; 4096];
- let read = stream.read(&mut chunk).await.ok()?;
- if read == 0 {
- return None;
- }
- buffer.extend_from_slice(&chunk[..read]);
- if let Some(index) = buffer.windows(4).position(|value| value == b"\r\n\r\n") {
- header_end = index + 4;
- break;
- }
- if buffer.len() > 1024 * 1024 {
- return None;
- }
- }
- let header_text = String::from_utf8_lossy(&buffer[..header_end]).into_owned();
- let mut lines = header_text.split("\r\n");
- let request = lines.next()?.split_whitespace().collect::<Vec<_>>();
- if request.len() < 2 {
- return None;
- }
- let mut headers = HeaderMap::new();
- for line in lines {
- let Some((name, value)) = line.split_once(':') else {
- continue;
- };
- let name = reqwest::header::HeaderName::from_bytes(name.trim().as_bytes()).ok()?;
- let value = HeaderValue::from_str(value.trim()).ok()?;
- headers.insert(name, value);
- }
- let content_length = headers
- .get(reqwest::header::CONTENT_LENGTH)
- .and_then(|value| value.to_str().ok())
- .and_then(|value| value.parse::<usize>().ok())
- .unwrap_or(0);
- while buffer.len() < header_end + content_length {
- let mut chunk = [0u8; 4096];
- let read = stream.read(&mut chunk).await.ok()?;
- if read == 0 {
- return None;
- }
- buffer.extend_from_slice(&chunk[..read]);
- }
- Some((
- request[0].to_string(),
- request[1].to_string(),
- headers,
- buffer[header_end..header_end + content_length].to_vec(),
- ))
- }
-
- async fn write_response(
- stream: &mut TcpStream,
- status: u16,
- headers: &[(&str, String)],
- body: &[u8],
- ) {
- let reason = match status {
- 200 => "OK",
- 201 => "Created",
- 204 => "No Content",
- 207 => "Multi-Status",
- 404 => "Not Found",
- 405 => "Method Not Allowed",
- 412 => "Precondition Failed",
- 502 => "Bad Gateway",
- _ => "Bad Request",
- };
- let mut response = format!(
- "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nConnection: close\r\n",
- body.len()
- );
- for (name, value) in headers {
- response.push_str(&format!("{name}: {value}\r\n"));
- }
- response.push_str("\r\n");
- let _ = stream.write_all(response.as_bytes()).await;
- let _ = stream.write_all(body).await;
- }
-
- async fn handle_fixture_connection(mut stream: TcpStream, state: Arc<Mutex<FixtureState>>) {
- let Some((method, target, headers, body)) = read_request(&mut stream).await else {
- return;
- };
- let path = target.split('?').next().unwrap_or(&target).to_string();
- let response = {
- let mut state = state.lock().expect("fixture state");
- match method.as_str() {
- "MKCOL" => {
- let normalized = path.trim_end_matches('/').to_string();
- if state.require_parent {
- let parent = normalized
- .rsplit_once('/')
- .map(|(parent, _)| parent)
- .unwrap_or("");
- if !parent.is_empty() && !state.collections.contains(parent) {
- (409, Vec::new(), None)
- } else if state.collections.insert(normalized) {
- (201, Vec::new(), None)
- } else {
- (405, Vec::new(), None)
- }
- } else if state.collections.insert(path) {
- (201, Vec::new(), None)
- } else {
- (405, Vec::new(), None)
- }
- }
- "GET" => {
- if let Some(value) = state.objects.get(&path) {
- let etag = state.etags.get(&path).copied().unwrap_or_default();
- let etag = if state.weak_etag {
- format!("W/\"{etag}\"")
- } else {
- format!("\"{etag}\"")
- };
- (200, value.clone(), Some(etag))
- } else if let Some(status) = state.missing_status {
- (status, Vec::new(), None)
- } else {
- (404, Vec::new(), None)
- }
- }
- "PROPFIND" => {
- let collection = path.trim_end_matches('/');
- if !state.collections.contains(collection) {
- (404, Vec::new(), None)
- } else {
- let prefix = format!("{collection}/");
- let mut entries = BTreeSet::new();
- entries.insert(format!("{collection}/"));
- for candidate in state
- .collections
- .iter()
- .map(String::as_str)
- .chain(state.objects.keys().map(String::as_str))
- {
- let Some(child) = candidate.strip_prefix(&prefix) else {
- continue;
- };
- if !child.is_empty() && !child.contains('/') {
- entries.insert(candidate.to_string());
- }
- }
- let mut xml = String::from(
- r#"<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">"#,
- );
- for entry in entries {
- xml.push_str(&format!(
- "<D:response><D:href>{entry}</D:href></D:response>"
- ));
- }
- xml.push_str("</D:multistatus>");
- (207, xml.into_bytes(), None)
- }
- }
- "PUT" => {
- let existing = state.objects.contains_key(&path);
- let none_match = headers
- .get(IF_NONE_MATCH)
- .and_then(|value| value.to_str().ok())
- .is_some_and(|value| value == "*");
- let match_ok = headers
- .get(IF_MATCH)
- .and_then(|value| value.to_str().ok())
- .and_then(|value| value.trim_matches('"').parse::<u64>().ok())
- .is_some_and(|expected| state.etags.get(&path) == Some(&expected));
- if !state.ignore_preconditions
- && ((none_match && existing)
- || (headers.contains_key(IF_MATCH) && !match_ok))
- {
- (412, Vec::new(), None)
- } else {
- state.next_etag = state.next_etag.saturating_add(1);
- let etag = state.next_etag;
- state.objects.insert(path.clone(), body);
- state.etags.insert(path, etag);
- (201, Vec::new(), None)
- }
- }
- "DELETE" => {
- state.objects.remove(&path);
- state.etags.remove(&path);
- (204, Vec::new(), None)
- }
- _ => (400, Vec::new(), None),
- }
- };
- let response_headers = response
- .2
- .into_iter()
- .map(|etag| ("ETag", etag))
- .collect::<Vec<_>>();
- write_response(&mut stream, response.0, &response_headers, &response.1).await;
- }
-
- pub(crate) struct Fixture {
- pub(crate) endpoint: String,
- pub(crate) task: tokio::task::JoinHandle<()>,
- }
-
- pub(crate) async fn fixture(weak_etag: bool) -> Fixture {
- fixture_with_options(weak_etag, None, false, false).await
- }
-
- pub(crate) async fn fixture_ignoring_preconditions() -> Fixture {
- fixture_with_options(false, None, true, false).await
- }
-
- async fn fixture_with_options(
- weak_etag: bool,
- missing_status: Option<u16>,
- ignore_preconditions: bool,
- require_parent: bool,
- ) -> Fixture {
- let listener = TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind fixture");
- let address = listener.local_addr().expect("fixture address");
- let state = Arc::new(Mutex::new(FixtureState {
- weak_etag,
- missing_status,
- ignore_preconditions,
- require_parent,
- ..FixtureState::default()
- }));
- let task = tokio::spawn(async move {
- loop {
- let Ok((stream, _)) = listener.accept().await else {
- break;
- };
- tokio::spawn(handle_fixture_connection(stream, state.clone()));
- }
- });
- Fixture {
- endpoint: format!("http://{address}/"),
- task,
- }
- }
-
- fn fixture_transport(endpoint: &str) -> WebDavTransport {
- WebDavTransport::new(&WebDavConfig {
- endpoint: endpoint.to_string(),
- username: String::new(),
- password: String::new(),
- directory: "vault".into(),
- allow_insecure_http: true,
- missing_object_status: None,
- })
- .expect("transport")
- }
-
- #[test]
- fn endpoint_requires_https_unless_explicitly_acknowledged_for_lan_hosts() {
- assert!(validate_endpoint("http://192.168.1.10/root", false).is_err());
- assert!(validate_endpoint("http://192.168.1.10/root", true).is_ok());
- assert!(validate_endpoint("http://localhost/root", true).is_ok());
- assert!(validate_endpoint("http://nas.local/root", true).is_ok());
- assert!(validate_endpoint("http://0.0.0.0/root", true).is_err());
- assert!(validate_endpoint("http://[::]/root", true).is_err());
- assert!(validate_endpoint("http://dav.example.test/root", true).is_err());
- assert!(validate_endpoint("https://dav.example.test/root", false).is_ok());
- assert!(validate_endpoint("https://user:[email protected]/root", true).is_err());
- }
-
- #[test]
- fn remote_directory_rejects_traversal_and_unsafe_names() {
- assert!(validate_relative_directory("vault/../escape").is_err());
- assert!(validate_relative_directory("vault\\escape").is_err());
- assert!(validate_relative_directory("vault/%secret").is_err());
- assert_eq!(
- validate_relative_directory("/pi-desktop/config/").expect("safe directory"),
- "pi-desktop/config"
- );
- }
-
- #[test]
- fn weak_etags_are_not_accepted_for_head_cas() {
- let mut headers = HeaderMap::new();
- headers.insert(ETAG, HeaderValue::from_static("W/\"weak\""));
- assert_eq!(strong_etag(&headers), None);
- headers.insert(ETAG, HeaderValue::from_static("\"strong\""));
- assert_eq!(strong_etag(&headers).as_deref(), Some("\"strong\""));
- }
-
- #[tokio::test]
- async fn nested_directory_creates_missing_ancestors() {
- let fixture = fixture_with_options(false, None, false, true).await;
- let transport = WebDavTransport::new(&WebDavConfig {
- endpoint: fixture.endpoint.clone(),
- username: String::new(),
- password: String::new(),
- directory: "backups/pi/settings".into(),
- allow_insecure_http: true,
- missing_object_status: None,
- })
- .expect("transport");
- transport
- .ensure_collection("vault")
- .await
- .expect("nested collections");
- }
-
- #[tokio::test]
- async fn local_fixture_proves_conditional_writes() {
- let fixture = fixture(false).await;
- let transport = fixture_transport(&fixture.endpoint);
- let probe = transport.probe().await.expect("probe");
- assert!(probe.conditional_writes);
- assert!(probe.append_only);
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn probe_rejects_servers_that_ignore_conditional_headers() {
- let fixture = fixture_with_options(false, None, true, false).await;
- let transport = fixture_transport(&fixture.endpoint);
- let probe = transport.probe().await.expect("probe");
- assert!(!probe.conditional_writes);
- assert!(probe.append_only);
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn directory_listing_excludes_the_collection_itself() {
- let fixture = fixture(false).await;
- let transport = fixture_transport(&fixture.endpoint);
- transport
- .ensure_collection("heads")
- .await
- .expect("collection");
- transport
- .put_unconditional("heads/device-a", b"head".to_vec())
- .await
- .expect("head");
- assert_eq!(
- transport.list_children("heads").await.expect("listing"),
- vec!["device-a".to_string()]
- );
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn probe_records_bad_gateway_as_the_missing_object_status() {
- let fixture = fixture_with_options(false, Some(502), false, false).await;
- let transport = fixture_transport(&fixture.endpoint);
- let probe = transport.probe().await.expect("probe");
- assert!(probe.conditional_writes);
- assert_eq!(probe.missing_object_status, Some(502));
- let transport = transport.with_probe_result(&probe);
- assert!(transport
- .get("missing")
- .await
- .expect("missing get")
- .is_none());
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn empty_vault_initialization_has_one_winner() {
- let fixture = fixture(false).await;
- let transport = fixture_transport(&fixture.endpoint);
- let first = transport.put_if_none("header", b"first".to_vec());
- let second = transport.put_if_none("header", b"second".to_vec());
- let (first, second) = tokio::join!(first, second);
- let winners = [first.expect("first"), second.expect("second")]
- .into_iter()
- .filter(|value| *value)
- .count();
- assert_eq!(winners, 1);
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn stale_cas_writer_is_rejected() {
- let fixture = fixture(false).await;
- let transport = fixture_transport(&fixture.endpoint);
- assert!(transport
- .put_if_none("head", b"first".to_vec())
- .await
- .expect("create"));
- let (_, etag) = transport.get("head").await.expect("get").expect("head");
- let etag = etag.expect("strong etag");
- assert!(transport
- .put_if_match("head", &etag, b"second".to_vec())
- .await
- .expect("matching update"));
- assert!(!transport
- .put_if_match("head", &etag, b"stale".to_vec())
- .await
- .expect("stale update"));
- fixture.task.abort();
- }
-
- #[tokio::test]
- async fn weak_etag_fixture_is_not_accepted_by_probe() {
- let fixture = fixture(true).await;
- let transport = fixture_transport(&fixture.endpoint);
- assert!(!transport.probe().await.expect("probe").conditional_writes);
- fixture.task.abort();
- }
}
diff --git a/crates/host-core/src/config_sync/transport_tests.rs b/crates/host-core/src/config_sync/transport_tests.rs
new file mode 100644
index 000000000..b34b501ac
--- /dev/null
+++ b/crates/host-core/src/config_sync/transport_tests.rs
@@ -0,0 +1,422 @@
+use super::*;
+use reqwest::header::{AUTHORIZATION, HOST};
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+
+#[derive(Default)]
+struct FixtureState {
+ objects: HashMap<String, (Vec<u8>, String)>,
+ weak_etag: bool,
+ ignore_preconditions: bool,
+ read_status: Option<u16>,
+ fail_next_read: bool,
+ fail_delete: bool,
+}
+
+pub(crate) struct Fixture {
+ pub(crate) endpoint: String,
+ pub(crate) task: tokio::task::JoinHandle<()>,
+ state: Arc<Mutex<FixtureState>>,
+}
+
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+async fn read_request(stream: &mut TcpStream) -> Option<(Method, String, HeaderMap, Vec<u8>)> {
+ let mut buffer = Vec::new();
+ let header_end;
+ loop {
+ let mut chunk = [0u8; 4096];
+ let read = stream.read(&mut chunk).await.ok()?;
+ if read == 0 {
+ return None;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ if let Some(index) = buffer.windows(4).position(|v| v == b"\r\n\r\n") {
+ header_end = index + 4;
+ break;
+ }
+ if buffer.len() > 1024 * 1024 {
+ return None;
+ }
+ }
+ let text = String::from_utf8_lossy(&buffer[..header_end]).into_owned();
+ let mut lines = text.split("\r\n");
+ let mut request = lines.next()?.split_whitespace();
+ let method = Method::from_bytes(request.next()?.as_bytes()).ok()?;
+ let path = request.next()?.to_string();
+ let mut headers = HeaderMap::new();
+ for line in lines {
+ if let Some((name, value)) = line.split_once(':') {
+ headers.insert(
+ reqwest::header::HeaderName::from_bytes(name.as_bytes()).ok()?,
+ HeaderValue::from_str(value.trim()).ok()?,
+ );
+ }
+ }
+ let length = headers
+ .get("content-length")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.parse::<usize>().ok())
+ .unwrap_or(0);
+ if length > MAX_REMOTE_OBJECT_BYTES {
+ return None;
+ }
+ while buffer.len() < header_end + length {
+ let mut chunk = [0u8; 4096];
+ let read = stream.read(&mut chunk).await.ok()?;
+ if read == 0 {
+ return None;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ }
+ Some((
+ method,
+ path,
+ headers,
+ buffer[header_end..header_end + length].to_vec(),
+ ))
+}
+
+// Verify every wire request (including conditional headers and optional token).
+// The independent official AWS vector below anchors the signer itself.
+fn authorized(method: &Method, path: &str, headers: &HeaderMap, body: &[u8]) -> Result<bool> {
+ let host = headers
+ .get(HOST)
+ .ok_or_else(|| anyhow!("missing host"))?
+ .to_str()?;
+ let url = Url::parse(&format!("http://{host}{path}"))?;
+ let timestamp = headers
+ .get("x-amz-date")
+ .ok_or_else(|| anyhow!("missing date"))?
+ .to_str()?;
+ let mut expected = HeaderMap::new();
+ for name in [IF_MATCH, IF_NONE_MATCH] {
+ if let Some(value) = headers.get(&name) {
+ expected.insert(name, value.clone());
+ }
+ }
+ let credentials = signing::Credentials {
+ access_key_id: "fixture-access".into(),
+ secret_access_key: "fixture-secret".into(),
+ session_token: headers
+ .get("x-amz-security-token")
+ .map(|_| "fixture-session".into()),
+ };
+ signing::sign(
+ method,
+ &url,
+ "us-east-1",
+ &credentials,
+ body,
+ &mut expected,
+ timestamp,
+ )?;
+ Ok(expected
+ .iter()
+ .all(|(name, value)| headers.get(name) == Some(value)))
+}
+
+async fn handle(mut stream: TcpStream, state: Arc<Mutex<FixtureState>>) {
+ let Some((method, path, headers, body)) = read_request(&mut stream).await else {
+ return;
+ };
+ let (status, response, etag) = {
+ let mut state = state.lock().unwrap();
+ if !authorized(&method, &path, &headers, &body).unwrap_or(false) {
+ (
+ 403,
+ b"fixture credential details must not escape".to_vec(),
+ None,
+ )
+ } else if method == Method::GET && state.fail_next_read {
+ state.fail_next_read = false;
+ (503, Vec::new(), None)
+ } else {
+ match method {
+ Method::GET => {
+ if let Some(status) = state.read_status {
+ (status, Vec::new(), None)
+ } else if let Some((body, etag)) = state.objects.get(&path) {
+ let tag = if state.weak_etag {
+ format!("W/{etag}")
+ } else {
+ etag.clone()
+ };
+ (200, body.clone(), Some(tag))
+ } else {
+ (404, Vec::new(), None)
+ }
+ }
+ Method::PUT => {
+ let existing = state.objects.get(&path);
+ let conflict = (headers.contains_key(IF_NONE_MATCH) && existing.is_some())
+ || headers.get(IF_MATCH).is_some_and(|value| {
+ existing.is_none_or(|(_, tag)| value != tag.as_str())
+ });
+ if conflict && !state.ignore_preconditions {
+ (412, Vec::new(), None)
+ } else {
+ let etag = format!("\"{}\"", hex::encode(Sha256::digest(&body)));
+ state.objects.insert(path, (body, etag));
+ (200, Vec::new(), None)
+ }
+ }
+ Method::DELETE if state.fail_delete => (403, Vec::new(), None),
+ Method::DELETE => {
+ state.objects.remove(&path);
+ (204, Vec::new(), None)
+ }
+ _ => (405, Vec::new(), None),
+ }
+ }
+ };
+ let mut response_headers = format!(
+ "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n",
+ response.len()
+ );
+ if let Some(etag) = etag {
+ response_headers.push_str(&format!("ETag: {etag}\r\n"));
+ }
+ if status == 307 {
+ response_headers.push_str("Location: http://127.0.0.1:1/must-not-follow\r\n");
+ }
+ response_headers.push_str("\r\n");
+ stream.write_all(response_headers.as_bytes()).await.unwrap();
+ stream.write_all(&response).await.unwrap();
+}
+
+pub(crate) async fn fixture(weak_etag: bool) -> Fixture {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let endpoint = format!("http://{}", listener.local_addr().unwrap());
+ let state = Arc::new(Mutex::new(FixtureState {
+ weak_etag,
+ ..Default::default()
+ }));
+ let serving_state = state.clone();
+ let task = tokio::spawn(async move {
+ let mut requests = tokio::task::JoinSet::new();
+ loop {
+ tokio::select! {
+ result = listener.accept() => {
+ let (stream, _) = result.unwrap();
+ requests.spawn(handle(stream, serving_state.clone()));
+ }
+ result = requests.join_next(), if !requests.is_empty() => { result.unwrap().unwrap(); }
+ }
+ }
+ });
+ Fixture {
+ endpoint,
+ task,
+ state,
+ }
+}
+
+pub(crate) async fn fixture_ignoring_preconditions() -> Fixture {
+ let fixture = fixture(false).await;
+ fixture.state.lock().unwrap().ignore_preconditions = true;
+ fixture
+}
+
+fn config(endpoint: &str) -> S3Config {
+ S3Config {
+ endpoint: endpoint.into(),
+ region: "us-east-1".into(),
+ bucket: "fixture-bucket".into(),
+ access_key_id: "fixture-access".into(),
+ secret_access_key: "fixture-secret".into(),
+ session_token: None,
+ prefix: "nested/test prefix".into(),
+ path_style: true,
+ allow_insecure_http: true,
+ }
+}
+
+#[test]
+fn aws_official_get_object_signature_vector() -> Result<()> {
+ // https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
+ let credentials = signing::Credentials {
+ access_key_id: "AKIAIOSFODNN7EXAMPLE".into(),
+ secret_access_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(),
+ session_token: None,
+ };
+ let mut headers = HeaderMap::new();
+ headers.insert("range", HeaderValue::from_static("bytes=0-9"));
+ signing::sign(
+ &Method::GET,
+ &Url::parse("https://examplebucket.s3.amazonaws.com/test.txt")?,
+ "us-east-1",
+ &credentials,
+ b"",
+ &mut headers,
+ "20130524T000000Z",
+ )?;
+ assert!(headers[AUTHORIZATION]
+ .to_str()?
+ .ends_with("Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"));
+ Ok(())
+}
+
+#[test]
+fn addressing_and_input_boundaries() -> Result<()> {
+ let mut config = config("https://s3.example.test:9443");
+ let transport = S3Transport::new(&config)?;
+ assert_eq!(
+ transport.url("head")?.as_str(),
+ "https://s3.example.test:9443/fixture-bucket/nested/test%20prefix/head"
+ );
+ config.path_style = false;
+ let virtual_host = S3Transport::new(&config)?;
+ assert_eq!(
+ virtual_host.url("head")?.as_str(),
+ "https://fixture-bucket.s3.example.test:9443/nested/test%20prefix/head"
+ );
+ for path in [
+ "",
+ "../secret",
+ "a/../b",
+ "a//b",
+ "/outside",
+ "a\\b",
+ "a%2fb",
+ "a?query",
+ "a#fragment",
+ ] {
+ assert!(transport.url(path).is_err(), "accepted {path}");
+ }
+ for endpoint in [
+ "http://public.example.test",
+ "http://0.0.0.0",
+ "http://[::]",
+ "https://user:[email protected]",
+ "https://s3.example.test/?secret=1",
+ "https://s3.example.test/#fragment",
+ "https://s3.example.test/path",
+ "file:///tmp",
+ ] {
+ assert!(validate_endpoint(endpoint, true).is_err());
+ }
+ for endpoint in [
+ "http://127.0.0.1",
+ "http://[::1]",
+ "http://192.168.1.10",
+ "http://nas.local",
+ ] {
+ assert!(validate_endpoint(endpoint, false).is_err());
+ assert!(validate_endpoint(endpoint, true).is_ok());
+ }
+ for etag in [
+ "",
+ "*",
+ "W/\"weak\"",
+ "\"\"",
+ "\"one\",\"two\"",
+ "\"line\nbreak\"",
+ ] {
+ assert!(!valid_etag(etag));
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn signed_probe_proves_cas_and_cleans_only_its_objects() -> Result<()> {
+ let fixture = fixture(false).await;
+ let mut config = config(&fixture.endpoint);
+ config.session_token = Some("fixture-session".into());
+ let transport = S3Transport::new(&config)?;
+ assert!(transport.put_if_none("existing", b"keep".to_vec()).await?);
+ assert!(transport.probe().await?.conditional_writes);
+ assert_eq!(fixture.state.lock().unwrap().objects.len(), 1);
+ assert_eq!(transport.get("existing").await?.unwrap().0, b"keep");
+ let (first, second) = tokio::join!(
+ transport.put_if_none("head", b"first".to_vec()),
+ transport.put_if_none("head", b"second".to_vec())
+ );
+ assert_ne!(first?, second?);
+ let (_, etag) = transport.get("head").await?.unwrap();
+ let etag = etag.unwrap();
+ let (first, second) = tokio::join!(
+ transport.put_if_match("head", &etag, b"third".to_vec()),
+ transport.put_if_match("head", &etag, b"fourth".to_vec())
+ );
+ assert_ne!(first?, second?);
+ Ok(())
+}
+
+#[tokio::test]
+async fn unsupported_servers_and_failed_probe_are_cleaned() -> Result<()> {
+ for weak_etag in [false, true] {
+ let fixture = fixture(weak_etag).await;
+ fixture.state.lock().unwrap().ignore_preconditions = !weak_etag;
+ assert!(
+ !S3Transport::new(&config(&fixture.endpoint))?
+ .probe()
+ .await?
+ .conditional_writes
+ );
+ assert!(fixture.state.lock().unwrap().objects.is_empty());
+ }
+ let fixture = fixture(false).await;
+ fixture.state.lock().unwrap().fail_next_read = true;
+ assert!(S3Transport::new(&config(&fixture.endpoint))?
+ .probe()
+ .await
+ .is_err());
+ assert!(fixture.state.lock().unwrap().objects.is_empty());
+ fixture.state.lock().unwrap().fail_delete = true;
+ assert!(S3Transport::new(&config(&fixture.endpoint))?
+ .probe()
+ .await
+ .is_err());
+ Ok(())
+}
+
+#[tokio::test]
+async fn errors_preserve_auth_missing_offline_and_redirect_boundaries() -> Result<()> {
+ let fixture = fixture(false).await;
+ let mut config = config(&fixture.endpoint);
+ config.secret_access_key = "invalid-secret".into();
+ let error = S3Transport::new(&config)?.get("missing").await.unwrap_err();
+ assert!(error.to_string().starts_with("CONFIG_SYNC_PERMISSION:"));
+ assert!(!error.to_string().contains("credential details"));
+ assert!(!remote_error_is_offline(&error));
+ config.secret_access_key = "fixture-secret".into();
+ let transport = S3Transport::new(&config)?;
+ for (status, prefix, offline) in [
+ (403, "CONFIG_SYNC_PERMISSION:", false),
+ (502, "CONFIG_SYNC_SERVER:", true),
+ (307, "CONFIG_SYNC_REDIRECT:", false),
+ ] {
+ fixture.state.lock().unwrap().read_status = Some(status);
+ let error = transport.get("missing").await.unwrap_err();
+ assert!(error.to_string().starts_with(prefix));
+ assert_eq!(remote_error_is_offline(&error), offline);
+ }
+ fixture.state.lock().unwrap().read_status = None;
+ assert!(transport.get("missing").await?.is_none());
+ Ok(())
+}
+
+#[test]
+fn service_error_details_never_echo_untrusted_text() {
+ assert_eq!(
+ service_error_code(b"<Error><Code>InvalidRequest</Code><Message>secret</Message></Error>"),
+ Some("InvalidRequest")
+ );
+ assert_eq!(
+ service_error_code(b"<Error><Code>reflected-secret</Code></Error>"),
+ None
+ );
+ assert_eq!(
+ service_error_code(b"<Message>InvalidRequest secret</Message>"),
+ None
+ );
+ assert_eq!(service_error_code(&[0xff]), None);
+}
diff --git a/crates/host-core/src/network_policy.rs b/crates/host-core/src/network_policy.rs
index 1e4d899c8..60db0f46a 100644
--- a/crates/host-core/src/network_policy.rs
+++ b/crates/host-core/src/network_policy.rs
@@ -3,7 +3,7 @@
//!
//! `packages/shared/src/network-policy.ts` holds the whole policy and lives in
//! the processes that judge an address. The host asks it one question: is the
-//! relaxed mode in force? That is the answer the WebDAV transport needs before
+//! relaxed mode in force? That is the answer the S3 transport needs before
//! it opens a plaintext hop to a LAN endpoint the user configured. The stored
//! settings value is mirrored here whenever the app hands the host its
//! settings, exactly as `network_proxy.rs` mirrors the proxy.
diff --git a/crates/host-core/src/user_skills.rs b/crates/host-core/src/user_skills.rs
index ae9b49296..f1b425c01 100644
--- a/crates/host-core/src/user_skills.rs
+++ b/crates/host-core/src/user_skills.rs
@@ -1216,10 +1216,8 @@ impl UserSkillRegistry {
Ok(result)
}
- /// Apply approved, bounded package resources inside the Host-owned skill
- /// directory. Existing files with different bytes are treated as an
- /// external edit instead of being overwritten blindly; omitted files are
- /// retained for the same reason.
+ /// Seed fixtures without overwriting existing resource contents.
+ #[cfg(test)]
pub fn write_package_files(
&mut self,
id: &str,
@@ -1227,66 +1225,24 @@ impl UserSkillRegistry {
project_path: Option<&str>,
files: &[(String, Vec<u8>)],
) -> Result<()> {
- if files.len() > MAX_SKILL_PACKAGE_FILES {
- bail!("SKILL_LIMIT_EXCEEDED: skill package contains too many files");
- }
- let total = files.iter().try_fold(0usize, |total, (_, bytes)| {
- total
- .checked_add(bytes.len())
- .ok_or_else(|| anyhow::anyhow!("SKILL_LIMIT_EXCEEDED: skill package is too large"))
- })?;
- if total > MAX_SKILL_PACKAGE_BYTES {
- bail!("SKILL_LIMIT_EXCEEDED: skill package is too large");
- }
- if files.is_empty() {
- return Ok(());
- }
- let Some(record) = self.find(id, Some(level), project_path)? else {
- bail!("SKILL_INVALID: skill package target was not found");
- };
- let Some(root) = package_root(&record, level, project_path)? else {
- bail!("SKILL_INVALID: package resources require a directory-shaped skill");
- };
- let root_metadata = fs::symlink_metadata(&root)?;
- if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() {
- bail!("SKILL_INVALID: skill package root is unsafe");
- }
- let mut seen = HashSet::new();
- for (relative, bytes) in files {
- let target = package_destination(&root, relative)?;
- if !seen.insert(relative.clone()) {
- bail!("SKILL_INVALID: skill package contains duplicate paths");
- }
- if bytes.len() > MAX_SKILL_RESOURCE_BYTES {
- bail!("SKILL_LIMIT_EXCEEDED: skill package resource is too large");
- }
- ensure_no_symlink_path(&root, &target)?;
- if target.exists() {
- let metadata = fs::symlink_metadata(&target)?;
- if metadata.file_type().is_symlink() || !metadata.is_file() {
- bail!("SKILL_INVALID: skill package destination is unsafe");
- }
- if fs::read(&target)? == *bytes {
- continue;
- }
+ let existing = self.package_files(id, level, project_path)?;
+ let mut desired = existing
+ .iter()
+ .cloned()
+ .collect::<std::collections::BTreeMap<_, _>>();
+ for (path, bytes) in files {
+ if desired.get(path).is_some_and(|old| old != bytes) {
bail!("CONFIG_SYNC_CONFLICT: skill package resource was edited locally");
}
- if let Some(parent) = target.parent() {
- fs::create_dir_all(parent)?;
- ensure_no_symlink_path(&root, parent)?;
- }
- let temporary = target.with_file_name(format!(
- ".{}.{}.tmp",
- target
- .file_name()
- .and_then(|value| value.to_str())
- .unwrap_or("resource"),
- Uuid::new_v4()
- ));
- fs::write(&temporary, bytes)?;
- fs::rename(&temporary, &target)?;
+ desired.insert(path.clone(), bytes.clone());
}
- Ok(())
+ self.replace_package_files(
+ id,
+ level,
+ project_path,
+ &existing,
+ &desired.into_iter().collect::<Vec<_>>(),
+ )
}
pub fn remove(
@@ -1361,6 +1317,7 @@ fn scope_for(level: CapabilityLevel, project_path: Option<&str>) -> ActivationSc
}
}
+mod package_sync;
/// Package bounds are asserted in their own module: `tests.rs` is close to the
/// rust file-size limit, and these tests share one fixture.
#[cfg(test)]
diff --git a/crates/host-core/src/user_skills/package_sync.rs b/crates/host-core/src/user_skills/package_sync.rs
new file mode 100644
index 000000000..b5183fe37
--- /dev/null
+++ b/crates/host-core/src/user_skills/package_sync.rs
@@ -0,0 +1,116 @@
+//! Compare-and-replace of approved skill resources. Validate the entire change
+//! before writing, retain unrelated files, and permit journal replay.
+use super::*;
+use std::collections::BTreeMap;
+
+fn checked_files(files: &[(String, Vec<u8>)]) -> Result<BTreeMap<&str, &[u8]>> {
+ if files.len() > MAX_SKILL_PACKAGE_FILES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package contains too many files");
+ }
+ let mut total = 0usize;
+ let mut result = BTreeMap::new();
+ for (path, bytes) in files {
+ total = total
+ .checked_add(bytes.len())
+ .ok_or_else(|| anyhow::anyhow!("SKILL_LIMIT_EXCEEDED: skill package is too large"))?;
+ if total > MAX_SKILL_PACKAGE_BYTES || bytes.len() > MAX_SKILL_RESOURCE_BYTES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package resource or total is too large");
+ }
+ if result.insert(path.as_str(), bytes.as_slice()).is_some() {
+ bail!("SKILL_INVALID: skill package contains duplicate paths");
+ }
+ }
+ Ok(result)
+}
+
+fn read_current(root: &Path, target: &Path) -> Result<Option<Vec<u8>>> {
+ ensure_no_symlink_path(root, target)?;
+ match fs::symlink_metadata(target) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(error.into()),
+ Ok(metadata) => {
+ if !metadata.is_file() || metadata.file_type().is_symlink() {
+ bail!("SKILL_INVALID: skill package destination is unsafe");
+ }
+ if metadata.len() > MAX_SKILL_RESOURCE_BYTES as u64 {
+ bail!("SKILL_LIMIT_EXCEEDED: existing skill resource is too large");
+ }
+ Ok(Some(fs::read(target)?))
+ }
+ }
+}
+
+impl UserSkillRegistry {
+ /// Update only files whose bytes still match the observed local version or
+ /// the desired version (an interrupted import replay). Unlisted files stay.
+ pub(crate) fn replace_package_files(
+ &mut self,
+ id: &str,
+ level: CapabilityLevel,
+ project_path: Option<&str>,
+ expected: &[(String, Vec<u8>)],
+ files: &[(String, Vec<u8>)],
+ ) -> Result<()> {
+ let expected = checked_files(expected)?;
+ let desired = checked_files(files)?;
+ if expected.is_empty() && desired.is_empty() {
+ return Ok(());
+ }
+ let record = self
+ .find(id, Some(level), project_path)?
+ .ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: skill package target was not found"))?;
+ let root = package_root(&record, level, project_path)?.ok_or_else(|| {
+ anyhow::anyhow!("SKILL_INVALID: package resources require a directory-shaped skill")
+ })?;
+ let metadata = fs::symlink_metadata(&root)?;
+ if metadata.file_type().is_symlink() || !metadata.is_dir() {
+ bail!("SKILL_INVALID: skill package root is unsafe");
+ }
+ let paths = expected
+ .keys()
+ .chain(desired.keys())
+ .copied()
+ .collect::<std::collections::BTreeSet<_>>();
+ let mut changes = Vec::new();
+ for path in paths {
+ let target = package_destination(&root, path)?;
+ let current = read_current(&root, &target)?;
+ let next = desired.get(path).copied();
+ if current.as_deref() == next {
+ continue;
+ }
+ if current.as_deref() != expected.get(path).copied() {
+ bail!("CONFIG_SYNC_CONFLICT: skill package resource was edited locally");
+ }
+ changes.push((target, current, next));
+ }
+ for (target, expected, next) in changes {
+ if read_current(&root, &target)? != expected {
+ bail!("CONFIG_SYNC_CONFLICT: skill package resource changed during import");
+ }
+ if let Some(bytes) = next {
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)?;
+ ensure_no_symlink_path(&root, parent)?;
+ }
+ let temporary = target.with_file_name(format!(".resource-{}.tmp", Uuid::new_v4()));
+ let result = (|| -> Result<()> {
+ fs::write(&temporary, bytes)?;
+ ensure_no_symlink_path(&root, &target)?;
+ if read_current(&root, &target)? != expected {
+ bail!("CONFIG_SYNC_CONFLICT: skill package resource changed during import");
+ }
+ fs::rename(&temporary, &target)?;
+ Ok(())
+ })();
+ if result.is_err() && temporary.exists() {
+ fs::remove_file(&temporary)?;
+ }
+ result?;
+ } else {
+ fs::remove_file(&target)?;
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/host-core/src/user_skills/package_tests.rs b/crates/host-core/src/user_skills/package_tests.rs
index ab8e690f6..f125d2f39 100644
--- a/crates/host-core/src/user_skills/package_tests.rs
+++ b/crates/host-core/src/user_skills/package_tests.rs
@@ -185,3 +185,36 @@ fn skill_document_limit_still_matches_the_prompt_sized_cap() {
let error = registry.create(payload).unwrap_err().to_string();
assert!(error.contains("document exceeds"), "error = {error}");
}
+
+#[test]
+fn approved_resource_replacement_checks_the_baseline_and_preserves_extra_files() {
+ let app = tempdir().unwrap();
+ let (mut registry, id, root) = packaged_skill(&app);
+ let project = app.path().join("project");
+ let project_path = Some(project.to_str().unwrap());
+ let before = vec![
+ ("data.txt".into(), b"old".to_vec()),
+ ("removed.txt".into(), b"remove".to_vec()),
+ ];
+ registry
+ .write_package_files(&id, CapabilityLevel::Project, project_path, &before)
+ .unwrap();
+ fs::write(root.join("unrelated.txt"), b"keep").unwrap();
+ let next = vec![("data.txt".into(), b"new".to_vec())];
+ fs::write(root.join("data.txt"), b"local edit").unwrap();
+ assert!(registry
+ .replace_package_files(&id, CapabilityLevel::Project, project_path, &before, &next)
+ .is_err());
+ assert_eq!(fs::read(root.join("data.txt")).unwrap(), b"local edit");
+ assert!(root.join("removed.txt").exists());
+ fs::write(root.join("data.txt"), b"old").unwrap();
+ registry
+ .replace_package_files(&id, CapabilityLevel::Project, project_path, &before, &next)
+ .unwrap();
+ registry
+ .replace_package_files(&id, CapabilityLevel::Project, project_path, &before, &next)
+ .unwrap();
+ assert_eq!(fs::read(root.join("data.txt")).unwrap(), b"new");
+ assert!(!root.join("removed.txt").exists());
+ assert_eq!(fs::read(root.join("unrelated.txt")).unwrap(), b"keep");
+}
diff --git a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
index aed948493..48f741a04 100644
--- a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
+++ b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
@@ -1,8 +1,13 @@
# ADR 0300: Host-owned encrypted portable configuration sync
-- Status: Accepted for implementation
+- Status: Partially superseded by [S3-only configuration backup and sync](s3-only-configuration-backup-sync.md)
- Date: 2026-09-22
+The ownership and encryption rationale below remains historical context. The
+WebDAV transport, append-only fallback, and endpoint-specific missing-status
+decisions no longer describe current behavior. See the S3 decision and current
+configuration-sync spec for the implemented contract.
+
## Context
PI-Desktop has portable preferences and user-owned capabilities spread across
diff --git a/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md
index 8a15e8ff2..d6a237ecf 100644
--- a/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md
+++ b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md
@@ -1,9 +1,13 @@
# ADR 0301: Explicit append-only WebDAV compatibility mode
-- Status: Accepted for implementation
+- Status: Superseded by [S3-only configuration backup and sync](s3-only-configuration-backup-sync.md)
- Date: 2026-09-22
- Amends: ADR 0300
+This document records the removed WebDAV compatibility design. It is not a
+current contract: S3 requires reliable conditional writes, and there is no
+append-only fallback. Existing WebDAV data is preserved without migration.
+
## Context
Some WebDAV servers accept `If-None-Match` and `If-Match` headers but ignore
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c61dcbc89..101ad914a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -20,6 +20,7 @@ Each ADR includes:
| ID | Title | Status |
|---|---|---|
+| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 |
| composer-mcp-invocations | [Composer MCP Invocations](composer-mcp-invocations.md) | Accepted |
| chronological-system-transcript | [Preserve chronological model system state](chronological-system-transcript.md) | Accepted |
| mcp-tool-approval-risk | [User MCP tools keep the normal approval path](mcp-tool-approval-risk.md) | Accepted |
@@ -336,8 +337,8 @@ Each ADR includes:
| 0297 | [Provider-hosted web search as an adapter capability](0297-provider-hosted-web-search-adapter-capability.md) | Accepted |
| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) |
| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) |
-| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Accepted for implementation |
-| 0301 | [Explicit append-only WebDAV compatibility mode](0301-explicit-append-only-webdav-compatibility-mode.md) | Accepted for implementation |
+| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Partially superseded by S3-only configuration backup/sync |
+| 0301 | [Explicit append-only WebDAV compatibility mode](0301-explicit-append-only-webdav-compatibility-mode.md) | Superseded by S3-only configuration backup/sync |
| 0302 | [A failed compaction keeps the recent window, and an oversized summary is chunked](0302-compaction-fallback-recent-window-and-chunked-summary.md) | Accepted for implementation (issue #827; amends ADR 0049 / ADR 0282) |
| 0303 | [A skill package carries resources far above the document cap](0303-skill-package-resource-limits.md) | Accepted for implementation (amends ADR 0300) |
| 0304 | [Trust the network endpoints the user enters themselves](0304-user-supplied-endpoint-trust.md) | Accepted for implementation (amends ADR 0243 / 0245 / 0247; follows ADR 0142 / 0257 / 0300) |
diff --git a/docs/adr/s3-only-configuration-backup-sync.md b/docs/adr/s3-only-configuration-backup-sync.md
new file mode 100644
index 000000000..0e1845a11
--- /dev/null
+++ b/docs/adr/s3-only-configuration-backup-sync.md
@@ -0,0 +1,83 @@
+# ADR: S3-only encrypted configuration backup and synchronization
+
+- Status: Accepted; implemented in the S3 configuration-sync change
+- Supersedes: The WebDAV transport and compatibility decisions in ADR 0300 and ADR 0301
+
+## Context
+
+A configuration vault must preserve encryption, domain allowlists, device-local
+mappings, credential opt-in, approvals, and concurrent-edit safety. The existing
+WebDAV compatibility mode required per-device heads and listing/ancestry logic
+while still lacking atomic initialization and reliable shared publication.
+The approved direction is direct private S3 storage, without a custom cloud
+service, database upload, or WebDAV fallback.
+
+Users also need a local-snapshot backup mode that does not apply remote changes.
+Shared resource reuse and offline devices make physical garbage collection
+unsafe without a separate cross-device retention protocol.
+
+## Decision
+
+Keep persistence, encryption, merge, scheduling and import ownership in Rust
+Host Core. Replace WebDAV with a bounded AWS Signature V4 S3 transport using
+maintained cryptographic primitives. Support path-style and virtual-hosted
+addressing and session tokens, but require a successful conditional-write probe
+for every service. There is no append-only or unconditional fallback.
+
+Use separate authenticated `head` and `backup-head` objects. Sync performs
+three-way merge and applies remote changes; backup publishes only local
+snapshots. Each head indexes the latest 30 revisions. Keep immutable objects
+indefinitely instead of claiming that a bounded history index bounds storage.
+
+Support only the new S3 data format, without legacy detection or migration.
+Do not delete unrelated old data. S3 uses a new `configSyncS3` key namespace
+and a fresh local state identity on connection or mode changes. Credential
+reuse is bound to the complete connection identity.
+Retain both shared and observed baselines so device-local projections and
+credential opt-out do not become false edits.
+
+Sync restore publishes a new shared revision with explicit propagation
+acknowledgment. Backup restore applies locally without changing cloud history.
+Both save a local recovery point and preserve activation review. Password
+changes rewrap the same vault key; they do not revoke previously unlocked
+devices.
+
+## Alternatives
+
+- Keep WebDAV alongside S3: rejected by the approved S3-only scope and because
+ it preserves a second publication and compatibility path.
+- Accept ignored conditional headers: rejected because concurrent publication
+ can silently lose configuration changes.
+- Store SQLite or the entire data directory: rejected because it includes
+ device state, credentials and unrelated data rather than portable entities.
+- Delete everything outside the 30-entry history index: rejected because
+ resource sharing, in-flight publication and offline devices are not proven
+ safe by one device's index.
+- Add a hosted coordination service: unnecessary for the bounded conditional
+ object protocol and outside the approved direct-storage design.
+
+## Consequences
+
+The implementation has one cloud transport and publication model, no server
+component, and unchanged process ownership. Existing WebDAV users must configure
+S3 explicitly; their old cloud backups remain untouched and cannot be restored
+through the new S3 transport. Applications sharing a vault must use the S3
+contract together.
+
+Storage can grow indefinitely. A bucket lifecycle policy that expires referenced
+objects can break synchronization or restore; the application does not claim to
+make arbitrary lifecycle deletion safe. Providers must honor strong ETags and
+conditional writes; compatibility is established by the actual endpoint probe,
+not a vendor label.
+
+The existing Host secret store uses encrypted files plus a colocated machine
+key, not OS Keychain protection. Remote encryption protects configuration
+contents but does not hide bucket identity, request timing, object sizes or
+traffic patterns. A malicious server can deny service or replay old valid state
+to a fresh device. A local import journal and per-file atomic replacement are
+not a whole-filesystem transaction.
+
+The current behavioral contract is
+[Portable configuration sync](../spec/03-runtime/22-config-sync.md), and
+executable transport, merge, application and multi-device tests remain the
+source of truth.
diff --git a/docs/spec/01-product/00-overview.md b/docs/spec/01-product/00-overview.md
index 9844fad6b..95b2c96da 100644
--- a/docs/spec/01-product/00-overview.md
+++ b/docs/spec/01-product/00-overview.md
@@ -37,7 +37,7 @@ PI-Desktop =
9. Make project sessions, imports, extensions, and scheduled prompts practical
for daily local work
10. Synchronize explicitly selected portable configuration through a
- host-owned encrypted WebDAV vault without exporting conversation history
+ host-owned encrypted S3 vault without exporting conversation history
## Non-goals (MVP)
diff --git a/docs/spec/01-product/01-product-scope.md b/docs/spec/01-product/01-product-scope.md
index bfa6413b6..397df5439 100644
--- a/docs/spec/01-product/01-product-scope.md
+++ b/docs/spec/01-product/01-product-scope.md
@@ -53,7 +53,7 @@ notifications, and run scheduled prompts manually or on a remembered cadence.
### H. Portable configuration sync
-Configure an encrypted WebDAV vault for portable preferences and user-owned
+Configure an encrypted S3 vault for portable preferences and user-owned
capabilities, review category and credential inclusion, and reconcile changes
across devices without synchronizing conversation history or source files.
@@ -78,7 +78,7 @@ across devices without synchronizing conversation history or source files.
- Extensions page: local plugins, marketplace packages, MCP, Skills, and
Subagents with activation scopes
- Scheduled task records with manual execution and cadence metadata
-- Host-owned encrypted WebDAV configuration sync with category selection,
+- Host-owned encrypted S3 configuration backup/sync with category selection,
conditional-write probing, three-way merge, and local activation review
- Rust host core skeleton for privileged operations
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 2b540c8b7..02a67c841 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2443,21 +2443,21 @@ unchanged. See [provider configuration](12-provider-config-schema.md).
The Settings → Cloud sync page uses the following renderer-to-Main channels;
all are forwarded to the Host-owned `configSync.*` RPC methods. The page is a
-development-build-only surface for now; the channels and their Host contracts
-are unchanged:
+development-build-only surface. Channel names stay stable; connection inputs
+and results use the S3-only contract in `types/config-sync.ts`:
| IPC channel | Host method | contract |
|---|---|---|
| `pi-desktop/configSync/getState` | `configSync.getState` | redacted status, category selections, preview counts, and pending approval summaries |
-| `pi-desktop/configSync/test` | `configSync.test` | WebDAV capability probe using a temporary object; no configuration is persisted |
+| `pi-desktop/configSync/test` | `configSync.test` | S3 conditional-write probe and verified cleanup; returns `{ ok: true, conditionalWrites: true }` without persisting configuration |
| `pi-desktop/configSync/configure` | `configSync.configure` | validates the endpoint, stores encrypted local sync metadata, and enables the vault |
-| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | runs one Host-owned reconciliation cycle |
+| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | runs one Host-owned two-way sync or local-snapshot backup, according to the saved mode |
| `pi-desktop/configSync/pause` | `configSync.pause` | pauses or resumes this device only |
| `pi-desktop/configSync/unlock` | `configSync.unlock` | unlocks the local vault for the current process/device |
| `pi-desktop/configSync/approve` / `reject` | `configSync.approve` / `configSync.reject` | records a digest-bound local activation decision |
| `pi-desktop/configSync/mapProject` | `configSync.mapProject` | binds one opaque project/group identity to one or more explicitly selected local folders, preserving primary-root order |
-| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | lists redacted reachable revision metadata only |
-| `pi-desktop/configSync/restore` | `configSync.restore` | creates a new propagated revision from an explicitly acknowledged historical revision and stages local approvals/recovery |
+| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | lists the saved mode's latest 30 indexed revisions; never emitted as a state-change event |
+| `pi-desktop/configSync/restore` | `configSync.restore` | sync publishes a new shared revision with propagation acknowledgment; backup restores locally without changing cloud history; both retain recovery/approvals |
| `pi-desktop/configSync/changePassword` | `configSync.changePassword` | CAS-rewraps the vault key header without returning keys or secret values |
| `pi-desktop/configSync/disconnect` | `configSync.disconnect` | removes local sync metadata and keys; it does not delete remote vault data |
@@ -2469,7 +2469,7 @@ transport/lifecycle coordinator and does not schedule, merge, encrypt, or
apply configuration.
A manual sync reports `configSync.progress` while it runs: the phase
-(`capture`, `download`, `merge`, `upload`, `apply`, or `cleanup`), the units
+(`capture`, `download`, `merge`, `upload`, or `apply`), the units
done and total for that phase, and the bytes when they are known. A long upload
of many resource objects is therefore not an interface with nothing to show.
Background polls report nothing, since only the manual path has a caller
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index e33b307c2..deb978b09 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -163,12 +163,15 @@ by path/hash.
### 1.3 Portable configuration sync
-Host-core stores sync configuration in the `configSync` key-value namespace.
-The vault key reference and WebDAV password use the existing encrypted secret
-store. `config-sync/base.bin` and `config-sync/pending.bin` are authenticated
-encrypted bundles replaced with temp-file rename; they are not renderer- or
-sidecar-readable files. Sync revisions and resources remain remote immutable
-objects and do not change the SQLite schema or transcript retention.
+Host Core stores S3 configuration at `configSyncS3/config` in the key-value
+store. Credentials and the vault key use existing encrypted secret storage.
+`config-sync/s3/<state-id>/base.bin` stores shared and observed baselines;
+`pending.bin` and local recovery points are also authenticated encrypted
+bundles replaced through temp-file rename. Connection or mode changes create
+a fresh state ID. The legacy `configSync` namespace, old credentials and old
+files are preserved, not migrated or deleted. Remote immutable objects remain
+indefinitely; only the mode-specific history index is capped at 30 revisions.
+This does not change the SQLite schema or transcript retention.
### 2.0 Message-owned review snapshots (ADR 0043)
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 94e9b3ed7..75a06c902 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1308,28 +1308,32 @@ The Host exposes the `configSync.getState`, `configSync.test`,
`configSync.mapProject`, `configSync.listHistory`, `configSync.restore`,
`configSync.changePassword`, and
`configSync.disconnect` methods through the existing Electron Host bridge.
-These methods operate on the Host-owned encrypted vault and the explicit
-portable-domain adapter registry. They do not expose raw secrets or local
-filesystem bindings to the Renderer.
-
-`configSync.test` performs a capability probe against a temporary remote
-object and reports whether reliable strong conditional writes are available.
-`configSync.syncNow` and the five-minute automatic poll serialize per vault,
-reconcile against the last acknowledged base, publish immutable encrypted
-objects followed by a conditional head update, and retain unresolved
-conflicts/security-sensitive imports as pending state. A failed head
-precondition restarts from the newly read head; it never overwrites blindly.
-
-`configSync.listHistory` returns revision IDs, creation timestamps, parent IDs,
-and counts without decrypting data in the Renderer. `configSync.restore` requires
-an explicit propagation acknowledgement, writes an encrypted local recovery
-point, publishes a new head with a CAS, and keeps executable/security-sensitive
-entities pending until local approval. `configSync.changePassword` updates the
-wrapped-key header with a strong-ETag CAS; it does not revoke copied old vault
-keys.
-
-The public result is a redacted state snapshot. `configSync.changed` is a Host
-notification carrying that same snapshot. Approval and rejection require the
-current entity digest, so a security-relevant edit cannot reuse an older local
-decision. Disconnect deletes only local credentials, vault keys, metadata and
-staging files; remote objects remain intact.
+These methods operate on the Host-owned encrypted S3 vault and explicit
+portable-domain adapters. Connection input uses `endpoint`, `region`, `bucket`,
+`prefix`, `accessKeyId`, optional `secretAccessKey` and `sessionToken`,
+`pathStyle`, and `mode: "sync" | "backup"`. The former WebDAV fields are
+rejected. Omitted credential fields mean reuse for the exact connection;
+an empty token clears it. Responses contain no secrets or vault keys.
+
+`configSync.test` proves reliable conditional writes with a random temporary
+object and verifies cleanup. It returns `{ ok: true, conditionalWrites: true }`
+or an error, never an append-only capability result. `configure` performs the
+same probe and creates or unlocks the vault without applying remote settings.
+
+`configSync.syncNow` runs the saved mode. Sync reconciles shared, observed and
+remote state before conditional publication and local application. Backup
+publishes only a local snapshot to its separate head. Publication precondition
+failures restart from the latest head, never an unconditional overwrite.
+
+`configSync.listHistory` returns at most 30 indexed entries for the saved mode.
+It returns metadata only, and is not broadcast as a `configSync.changed` state.
+Sync `restore` requires `acknowledgePropagation: true` and publishes a new
+shared revision. Backup restore is local only and leaves remote heads intact.
+Both save a local recovery point and keep sensitive activation pending.
+`changePassword` CAS-rewraps the same key; it does not revoke unlocked devices.
+
+State responses and `configSync.changed` include `mode` and S3 connection
+metadata. Approval/rejection remain digest-bound. Only the new S3 format is
+supported; there is no old-data detection or migration. Disconnect removes
+only current S3 credentials, keys and local sync metadata/staging; unrelated
+files and remote objects remain intact. See `22-config-sync.md`.
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index ac7fc80ef..a73dde68a 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -73,8 +73,8 @@ registered; reserved codes in §3.7 remain intentionally absent from
| `LIMIT_EXCEEDED` | no | a payload exceeded a fixed host bound (item count, byte size, or a 64 MiB NDJSON request line) and was refused |
| `CONFIG_SYNC_INVALID` | no | invalid sync configuration, password, path, request, or approval input |
| `CONFIG_SYNC_LOCKED` | no | the local encrypted sync vault is not unlocked |
-| `CONFIG_SYNC_UNSUPPORTED` | no | the vault format or WebDAV server capability is unsupported |
-| `CONFIG_SYNC_REMOTE` | maybe | remote WebDAV object, authentication, quota, or availability failure |
+| `CONFIG_SYNC_UNSUPPORTED` | no | the vault format or S3 conditional-write capability is unsupported |
+| `CONFIG_SYNC_REMOTE` | maybe | S3 object, authentication, quota, or availability failure |
| `CONFIG_SYNC_CONFLICT` | maybe | remote head, vault identity, or approval digest conflict |
| `CONFIG_SYNC_CRYPTO` | no | authenticated encryption, object identity, or ciphertext validation failed |
| `CONFIG_SYNC_MAPPING_REQUIRED` | no | imported project-scoped configuration needs an explicit local folder/group mapping |
diff --git a/docs/spec/03-runtime/14-secrets-storage.md b/docs/spec/03-runtime/14-secrets-storage.md
index 8d29ad36a..d9764398b 100644
--- a/docs/spec/03-runtime/14-secrets-storage.md
+++ b/docs/spec/03-runtime/14-secrets-storage.md
@@ -99,7 +99,7 @@ Renderer uses provider methods that accept optional `secretValue` on create/upda
8. Portable configuration sync exports provider API keys or MCP
environment/header values only after explicit credential opt-in. Values
remain inside host-owned encrypted staging and are restored through the
- receiving device's local secret store. WebDAV credentials, machine
+ receiving device's local secret store. S3 connection credentials, machine
encryption keys, OAuth sessions, and cookies are never portable.
## 7. Redaction policy
diff --git a/docs/spec/03-runtime/22-config-sync.md b/docs/spec/03-runtime/22-config-sync.md
index dbe0e76ed..a7e4a1db7 100644
--- a/docs/spec/03-runtime/22-config-sync.md
+++ b/docs/spec/03-runtime/22-config-sync.md
@@ -1,8 +1,8 @@
# Portable configuration sync
-Status: implemented baseline for the approved WebDAV configuration-sync slice.
+Status: implemented S3-only configuration backup and synchronization.
-Portable configuration sync is a host-owned, encrypted WebDAV workflow. It
+Portable configuration sync is a host-owned, encrypted S3 workflow. It
does not synchronize conversation history, project source files, attachments,
runtime state, or model weights. The Renderer only receives redacted status,
preview counts, conflicts, and activation summaries.
@@ -12,10 +12,10 @@ preview counts, conflicts, and activation summaries.
The process path remains:
```text
-Renderer → Preload IPC → Electron Main → host-core → WebDAV
+Renderer → Preload IPC → Electron Main → host-core → private S3-compatible bucket
```
-Host-core owns the vault key, WebDAV transport, revision state, merge base,
+Host-core owns the vault key, S3 transport, revision state, merge base,
pending approvals, local encrypted staging, and import application. Electron
Main only registers the IPC handlers and forwards `configSync.changed`.
Agent Runtime has no sync implementation.
@@ -64,7 +64,7 @@ as unsupported rather than treated as synchronized. Approved plugin installation
intent is kept in a Host-owned local overlay; it never pulls plugin bytes or
permission grants.
-## 3. Vault and WebDAV protocol
+## 3. Vault and S3 protocol
Each vault has a random data key. The backup password is processed with bounded
Argon2id parameters, and the data key is wrapped with AES-256-GCM. Every head,
@@ -74,81 +74,87 @@ fresh nonce. Resource object IDs are keyed content identifiers, so plaintext
global hashes are not required. The vault envelope version is independent from
the SQLite schema and is bumped when cryptographic derivation changes.
-The remote layout is an opaque header plus immutable revision/resource objects.
-Strict mode also has one mutable encrypted head:
+The remote layout uses one wrapped-key header, two mode-specific encrypted
+heads, and immutable authenticated revision/resource objects:
```text
-<selected-directory>/header
-<selected-directory>/vault/<opaque-vault-id>/head
-<selected-directory>/vault/<opaque-vault-id>/revisions/<revision-id>
-<selected-directory>/vault/<opaque-vault-id>/objects/<object-id>
+<bucket>/<prefix>/header
+<bucket>/<prefix>/vault/<opaque-vault-id>/head
+<bucket>/<prefix>/vault/<opaque-vault-id>/backup-head
+<bucket>/<prefix>/vault/<opaque-vault-id>/revisions/<revision-id>
+<bucket>/<prefix>/vault/<opaque-vault-id>/objects/<object-id>
```
-Strict initialization uses `If-None-Match: *`. Existing heads require a strong
-ETag and are published with `If-Match`. A failed precondition restarts
-reconciliation from the newly read head; it never overwrites blindly. The
-capability probe writes a temporary object with conditional creation twice,
-obtains a strong ETag, verifies a matching `If-Match` update, and verifies a
-stale `If-Match` is rejected before the object is removed.
+The S3 head format is `pi-desktop-config-sync-s3`, version 1. Each head indexes
+at most 30 revisions, newest first. Sync and backup have separate heads,
+history, and authentication purposes; neither mode follows an unbounded parent
+graph. Immutable objects remain stored indefinitely. This bounds history
+queries, **not storage usage**; no physical cloud garbage collection runs.
+
+AWS Signature V4 signs requests, including conditional headers and optional
+session tokens. Both path-style and virtual-hosted bucket addressing are
+supported. The input uses `endpoint`, `region`, `bucket`, `prefix`,
+`accessKeyId`, optional `secretAccessKey`, optional `sessionToken`, and
+`pathStyle`. Defaults are `us-east-1`, `pi-desktop/config`, and path style.
+The bucket must already exist and remain private; Host never creates it or
+changes ACLs. Scope credentials to this bucket/prefix. Normal operation needs
+object GET/PUT and deletion of the random probe objects; it does not list the
+bucket. A provider may also require scoped ListBucket permission to distinguish
+missing objects from access denial.
+
+Initialization uses `If-None-Match: *`; head updates require a strong ETag and
+`If-Match`. A rejected precondition restarts reconciliation, never a blind
+overwrite. The probe verifies exclusive creation, matching update, stale-write
+rejection, and readback, then deletes and verifies its own random object. A
+first-create collision is never deleted. Ignored preconditions are unsupported;
+there is no WebDAV transport, append-only mode, or unconditional fallback.
+
+Only GET 404 means absent. 403 is an authorization failure; 502 remains an
+availability failure. Conditional PUT 409/412 means a lost publication race.
+Errors retain stable `CONFIG_SYNC_*` codes without exposing credentials,
+request signatures, URLs containing keys, or server response bodies.
+
+Endpoints must be origin-only URLs: no userinfo, query, fragment, or non-root
+path. Redirects and public plaintext HTTP are rejected. LAN HTTP is allowed
+only by the Host's relaxed network policy, not by a separate sync checkbox.
+Connection timeout is 10 seconds, request timeout is 60 seconds, and streamed
+objects are capped at 64 MiB. Object paths and prefixes use bounded safe ASCII
+segments, not arbitrary S3 key strings; traversal and weak ETags are rejected.
+
+Saved credentials are reused only for the same endpoint, region, bucket,
+prefix, access key ID, and addressing style. Omitted secret/token fields mean
+reuse; an empty session token clears it. Supplying both fields replaces the
+credentials without relying on a readable old secret. Changing the connection
+or operating mode creates a new local state identity; pending imports must be
+resolved first. Re-saving preserves an existing pause.
-The settings page also offers an explicit append-only compatibility mode for a
-server that ignores conditional headers. The probe must still prove bounded
-`PROPFIND` directory listing. Compatibility mode adds an opaque per-device
-pointer collection:
-
-```text
-<selected-directory>/vault/<opaque-vault-id>/heads/<device-id>
-```
+## 4. Merge and activation
-Each device overwrites only its own encrypted pointer and verifies it by
-reading it back. A sync lists all pointers, includes a legacy strict head when
-present, walks the bounded parent graph, removes ancestor pointers, and merges
-the remaining tips against the acknowledged base. New revisions and resources
-are unique immutable objects; an existing resource is read and authenticated
-before reuse. Compatibility mode retains immutable history and does not run
-remote cleanup because the server cannot provide a safe cross-device
-acknowledgement protocol. All devices sharing a vault must use the same mode.
-This mode is never selected silently and does not claim strict CAS guarantees.
-
-Some WebDAV gateways report a missing object as `502 Bad Gateway` instead of
-`404 Not Found`. The capability probe records this behavior for the selected
-endpoint after deleting its temporary object; subsequent reads treat only that
-observed status as absence. Other non-success responses remain errors. This
-does not relax strict-mode conditional-write requirements: a server that
-ignores `If-None-Match` or `If-Match` is usable for bidirectional sync only
-after the user selects append-only compatibility mode and the directory-listing
-probe succeeds.
-
-HTTPS is required by default. The settings page may expose an explicit
-LAN-risk acknowledgement for HTTP, but Host accepts that exception only for
-localhost, `.local` names, or private/link-local IP addresses. Public HTTP
-endpoints remain rejected. The warning explains that HTTP does not protect
-WebDAV credentials in transit. Redirect responses are rejected and are not
-followed; a success response may still carry a Location header. Endpoint
-userinfo, path traversal, unsafe remote names, oversized objects, weak ETags,
-and unbounded KDF parameters are rejected. Missing collections under the
-selected endpoint, including a nested remote directory, are created in order.
-A stored WebDAV app password is reused only for the same endpoint and account.
-Saving sync settings keeps a pause that was already set. Host errors use stable
-`CONFIG_SYNC_*` codes so the settings page can show a recovery action without
-treating the server text as the only message.
+The encrypted baseline stores both the acknowledged shared revision and its
+observed local projection. Credential opt-out and device-local overlays must
+not manufacture local edits or block remote deletions. Unacknowledged local
+edits are not absorbed when another entity is approved.
-## 4. Merge and activation
+In `sync` mode, capture, remote read, three-way merge, immutable upload, CAS
+publication, and local application are serialized per vault. Scalar settings
+merge by declared entity unit; provider, MCP, skill, and automation records are
+not merged as arbitrary arrays. Tombstones carry deletion state and refreshed
+digests and remain in subsequent baselines. An unselected category is not a
+deletion.
-The local encrypted base is the last acknowledged common revision. Capture,
-remote read, three-way merge, immutable object upload, head publication, and
-local application are serialized per vault. Strict mode uses CAS head
-publication; compatibility mode publishes a per-device pointer and merges
-discovered tips. Scalar settings merge by
-declared entity unit; provider records, MCP records, skill packages, and
-automation definitions are not merged as arbitrary JSON arrays. Tombstones
-represent explicit deletion; an unselected category is not deletion.
+In `backup` mode, a run publishes a local snapshot to `backup-head`. It reads
+head metadata for CAS/history but does not download or apply remote
+configuration. Multiple devices keep independent snapshots in that history,
+not merged configurations. Unchanged snapshots do not create new revisions.
Same edits converge and disjoint edits continue. Same-unit edits and
delete-versus-edit retain both candidates as conflicts. Imported MCP, skills,
subagents, plugins, and automations require local activation approval; an
approval is bound to the entity digest. A changed command, endpoint, script,
instruction, or credential destination therefore invalidates the old approval.
+An applied conflict choice records both candidate digests. The next sync
+folds that exact unchanged pair into the chosen canonical entity and publishes
+it with CAS. Changed candidates still require a new explicit choice.
Missing provider references are retained as dependency approvals instead of
being written as unusable defaults; unrelated entities can continue applying.
The host never activates staged executable content merely because a UI flag is
@@ -164,41 +170,43 @@ steps or leaves the bundle visible for retry before the configuration is
considered converged. Existing direct local MCP creation behavior is
unchanged.
+Receiving application preferences are filtered through the portable-field
+allowlist. Credential opt-out also applies on import, including provider keys
+and MCP environment/header fields. Approved skill resource replacement checks
+expected content, paths and symlinks, retains unrelated files, and removes only
+previously synchronized files omitted by the new package. Each file is replaced
+atomically; an import journal is recovery bookkeeping, not a transaction over
+the whole filesystem.
+
## 5. Settings workflow
The destination is a development-build-only surface for now: a packaged build
omits the Settings → Cloud sync row, page, and settings-search hits, while
the Host-owned sync behavior described here is unchanged.
-Settings → Cloud sync provides WebDAV endpoint credentials, vault password,
-device label, server compatibility mode, category selection, a capability test,
-sync-now, unlock, pause, folder mapping, approval/rejection, revision
-history/restore, vault-password rewrap, and disconnect controls. Strict CAS is
-the default. Selecting append-only compatibility mode shows a persistent risk
-warning and requires confirmation before configuration is saved; its test
-success reports directory-listing support rather than conditional-write
-support. The renderer displays
+Settings → Cloud sync provides S3 connection fields, a vault password, device
+label, `sync` (default) or `backup` mode, automatic-run selection, categories,
+connection testing, manual run, unlock, pause, folder mapping, approval/rejection,
+history/restore, password rewrap, and disconnect. The renderer displays
`notConfigured`, `locked`, `upToDate`, `localChangesPending`, `syncing`,
`offline`, `unsupportedServer`, `conflict`, `awaitingActivation`, `paused`,
and `error` as distinct states. Disconnect keeps local data and does not delete
remote data.
-Reopening the page paints the last redacted host state and history from a
-short-lived renderer cache, then refreshes the host in the background. The
-connection draft (endpoint, username, remote directory, device label,
-compatibility mode, and category choices) is kept in renderer-local storage so
-an unfinished form survives navigation or reload. It is marked saved again
-when the host confirms the persisted configuration. WebDAV app passwords stay
-in the Host secret store and are reused only for the same endpoint and account;
-the renderer never stores either password, and a vault password is only needed
-when a new or locked device must open the vault.
-
-A manual sync reports what it is doing while it runs. `configSync.progress`
-carries the current phase — `capture`, `download`, `merge`, `upload`, `apply`,
-or `cleanup` — the units finished in that phase, and the bytes when they are
-known: `done`/`total` count resource objects while transferring — the device
-tips being read, in append-only mode — and entities otherwise, a `total` of 0
-means the phase cannot know its size, and a
+Reopening the page paints cached redacted state/history and a validated,
+non-sensitive draft, then refreshes in the background. The S3 draft key is
+`pi.desktop.configSyncS3Draft.v1`; old WebDAV drafts are ignored, not deleted.
+Only endpoint, region, bucket, prefix, access key ID, addressing style, mode,
+device label, automatic-run choice, and categories are persisted. Passwords,
+secret access keys, and session tokens remain transient input memory and are
+cleared after a successful save. A replacement secret with a blank token sends
+an explicit empty token; blank unchanged controls reuse Host credentials.
+Changing the saved connection or mode invalidates history and outstanding
+history reads. An unsaved mode selection does not change restore behavior.
+
+A manual run reports `capture`, `download`, `merge`, `upload`, and `apply` via
+`configSync.progress`; there is no cleanup phase. `done`/`total` count objects
+while transferring and entities otherwise. A total of 0 means unknown, and a
`bytesTotal` of 0 means the byte size is unknown, which is the normal case for a
download. Reports are throttled, a phase change is never dropped, and the state
event plus the call's return value stay the terminal signal. Background polls
@@ -206,8 +214,8 @@ report nothing: only the manual path has a caller watching.
Credentials and memory are unchecked by default. The setup preview reports
supported, excluded, secret-bearing, mapping-required, and pending-activation
-counts. Raw secret values, vault keys, and backup passwords never cross the
-renderer boundary.
+counts. Raw exported secrets and vault keys are never returned to the renderer;
+new connection secrets and backup passwords cross IPC only as transient inputs.
The host owns an immediate startup check, a 30-second local-change debounce,
and a bounded five-minute remote poll when automatic sync is enabled. Failed
@@ -218,27 +226,32 @@ the app exits.
## 6. Durability and compatibility
-Sync configuration is stored in the host `kv` namespace. The vault key and
-WebDAV password use the existing host secret store. Local base and pending
-bundles are encrypted and replaced through temp-file rename. A malformed or
-unauthenticated local bundle is an error, not an empty state. Backup format
-versioning is independent from the SQLite schema; a newer format is rejected
-without truncating the local representation.
-
-Strict remote history retains the newest 30 reachable logical revisions and
-protects the current head, merge base, pending conflict references, and
-recovery points; unreferenced objects are deleted only after a grace period and
-successful publication. Compatibility mode retains immutable history because
-there is no safe cross-device cleanup acknowledgement. Restore publishes a new
-revision after a pre-restore encrypted local recovery point is written. A
-vault-password change CAS-updates the wrapped-key header in strict mode; in
-compatibility mode it uses an unconditional write followed by authenticated
-readback. Neither mode changes the vault data key; copied old keys are not
-cryptographically revoked, so device removal is not treated as revocation.
-
-Project-group mappings accept ordered multi-root bindings and preserve the
-primary root invariant. WebDAV tests use an in-process fixture for conditional
-creation, strong-ETag updates, stale-writer rejection, empty-vault races, and
-weak-ETag rejection. The remaining availability limitation is inherent: a
-fresh device without trusted head history cannot prove that a malicious server
-returned the newest valid backup.
+S3 configuration is stored at `configSyncS3/config` in the Host `kv` store.
+The vault key and S3 secret bundle use existing encrypted Host secret storage.
+That implementation uses encrypted files and a `.machine-key` in the same data
+directory, not an OS Keychain backend; copying the entire data directory is not
+a protected cloud backup.
+
+Local state lives under `config-sync/s3/<state-id>/`. The encrypted shared/
+observed baseline, pending bundle, and recovery points use temp-file rename.
+A malformed or unauthenticated bundle is an error, not an empty state.
+Only the new S3 format is supported. Old configuration, credentials and backup
+formats are not detected, interpreted or migrated. Existing unrelated files
+and cloud objects are not deleted. No SQLite migration is needed.
+
+Restore first saves an encrypted local recovery point. Sync restore requires
+`acknowledgePropagation: true` and immediately publishes a new shared revision;
+sensitive local activation remains separately approved on each device. Backup
+restore is local only and does not move either remote head. The latest backup
+can also be restored. Neither mode silently overwrites a pending import.
+
+A password change CAS-updates and authenticates the wrapped-key header without
+changing the vault data key. Previously unlocked devices retain access; this
+is rewrapping, not device revocation. A fresh device without trusted head
+history cannot prove a malicious server returned the newest valid backup.
+Availability and freshness against such a server are not guaranteed.
+
+The protocol and connection contracts are intentionally S3-only. All devices
+sharing the S3 vault must use this implementation. The former WebDAV backend
+and its append-only compatibility mode are removed, not emulated.
+See [the S3 decision](../../adr/s3-only-configuration-backup-sync.md).
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 7bc4a8034..68c75c5d3 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -204,38 +204,40 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
### Cloud sync
-- **Connection**: WebDAV URL, username, app password, remote directory, device
- label, a separate backup/vault password, and a server compatibility mode.
- Strict CAS is the default. The test action uses only temporary remote
- objects; strict mode must prove conditional creation and readback, while
- append-only compatibility mode must prove bounded directory listing. Choosing
- compatibility mode shows a persistent warning and requires confirmation
- before save. The warning explains that all devices in the vault must use the
- same mode, history is retained, and concurrent changes may still require
- review.
+- **Connection**: S3 endpoint, region, private bucket, object prefix, access key
+ ID, secret access key, optional session token, addressing style, device label,
+ and separate backup/vault password. Choose two-way sync or backup-only mode
+ and whether runs are automatic. Connection testing uses random temporary
+ objects and requires reliable conditional writes; there is no fallback.
- **Portable configuration**: supported categories are selected by default;
credentials and project memory are explicit opt-ins. The preview reports
supported, excluded, secret-bearing, mapping-required, and pending-approval
counts.
-- **Safety**: the page never renders raw credentials or vault keys. Imported
- MCP, skills, subagents, plugins, automations, and project-scoped data remain
- pending until local activation approval and any required folder mapping are
- complete. HTTPS remains the default. For a trusted LAN endpoint, the page
- can explicitly acknowledge HTTP risk; public HTTP endpoints are rejected and
- the warning explains that WebDAV credentials are not encrypted in transit.
- Disconnect preserves local and remote data.
+- **Safety**: exported secrets and vault keys are never returned to the page.
+ Connection secrets exist only in transient password controls. Imported
+ executable/security-sensitive content keeps local approval and mapping.
+ Public HTTP and redirects are rejected; LAN HTTP follows the shared Host
+ network policy, not a page-specific checkbox. Disconnect preserves local
+ configuration and remote objects. Only the new S3 format is supported;
+ there is no legacy-data detection, migration or compatibility notice.
- **State and recovery**: show distinct configured, locked, syncing, offline,
unsupported-server, conflict, awaiting-activation, paused, and error states.
Users can sync now, unlock, pause this device, approve/reject staged items,
and disconnect. The page does not imply convergence from an old successful
run while a pending state remains.
-- **Fast revisit and drafts**: render the last redacted state and history from
- a short-lived local cache while the host refresh runs in the background. Keep
- endpoint, username, remote directory, device label, compatibility mode, and
- category choices in renderer-local storage so an unfinished form survives
- navigation or reload. WebDAV app passwords remain in Host-owned secret
- storage and are reused only for the same endpoint and account; vault
- passwords are never written to renderer storage.
+- **Fast revisit and drafts**: cache redacted status/history and typed,
+ non-sensitive connection choices. S3 uses a versioned draft key; old drafts
+ are ignored. Secret keys, session tokens and vault passwords never enter
+ renderer persistence. Blank credentials reuse Host storage only for the exact
+ same connection; an explicit token-clear checkbox and new secret replacement
+ can clear the saved session token. Connection/mode changes invalidate history,
+ including late responses from the previous connection.
+- **History and restore**: show the latest 30 revisions for the saved mode and
+ disclose indefinite object retention without automatic cloud cleanup. Sync
+ restore confirms immediate propagation; backup restore confirms local-only
+ application and permits the current backup. Unsaved mode edits do not change
+ these semantics. Both retain local recovery and approval requirements.
+ Password changes are key rewrapping, not revocation of unlocked devices.
### 全局 AI (`ai` tab)
- **Permissions** card: the global permission-mode control
diff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.md
index e4fad3928..bdfab3c3a 100644
--- a/docs/spec/05-security/01-security.md
+++ b/docs/spec/05-security/01-security.md
@@ -158,33 +158,34 @@ policy above.
## 4.3 Portable configuration sync
-WebDAV sync is a host-core network boundary. The renderer and Agent Runtime
-cannot access the endpoint, WebDAV password, backup password, vault key, or
-portable secret values. Host-core validates the selected HTTPS endpoint,
-rejects userinfo and redirects, constrains relative paths, bounds remote object
-size and KDF parameters, and requires strong conditional-write behavior before
-publishing a shared head in strict mode. An explicitly confirmed append-only
-compatibility mode may be used after a bounded `PROPFIND` directory-listing
-probe succeeds; it publishes per-device encrypted pointers and retains
-immutable history rather than pretending an unconditional `PUT` is CAS.
-
-Every remote payload is authenticated ciphertext. The WebDAV server receives
-neither the vault password nor the local machine encryption key. Credentials
-are exported only after explicit category opt-in and are never included in
-status, preview, conflict labels, or logs. Restored provider/MCP secrets are
-written through the host secret store; OAuth sessions and cookies are never
-portable.
+S3 configuration backup/sync is a Host Core network boundary. The renderer
+supplies connection secrets and the vault password only as transient IPC
+inputs, receives redacted status, and never owns the transport or vault key.
+Agent Runtime has no sync implementation. Host validates origin-only endpoints,
+rejects redirects and public plaintext HTTP, constrains paths, bounds streamed
+objects and KDF parameters, and requires strong conditional writes. LAN HTTP
+follows the shared relaxed network policy. There is no WebDAV or append-only
+fallback; only GET 404 is absence, never 403 or 502.
+
+Vault contents are authenticated ciphertext. S3 never receives the backup
+password or machine key. SigV4 uses scoped S3 credentials; bucket identity,
+request timing and object sizes remain visible. Credential export and import
+require opt-in. Raw exported secrets are absent from status, preview, conflict
+labels and logs. Provider/MCP secrets use the Host secret store; OAuth sessions
+and cookies are not portable. The local secret store uses encrypted files plus
+a colocated `.machine-key`, not an OS Keychain backend.
Imported commands, endpoints, scripts, skills, plugins, and automations are
staged behind a digest-bound local approval. Local paths and approvals are
overlays, not shared entities. A new device therefore cannot execute a
synchronized capability merely because its desired enabled flag was imported.
-The compatibility-mode warning states that all devices sharing a vault must
-use the same mode and that concurrent changes can still require review. It
-does not weaken approval, secret export, redirect, path, object-size, or
-freshness protections. The server can still deny availability or replay a
-valid old head to a fresh device that has no trusted history; sync does not
-claim availability or freshness against a malicious server.
+Both operating modes preserve approval and mapping requirements. A backup run
+does not apply remote configuration. Password rewrapping does not revoke
+previously unlocked devices. Immutable objects are retained indefinitely; a
+30-entry history index is not a cloud storage limit. A server can still deny
+service or replay an old valid head to a fresh device with no trusted history.
+Per-file atomic replacement and import journaling do not constitute a
+whole-filesystem transaction.
## 5. Command execution
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d676358fd..738fb3e94 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -9504,73 +9504,71 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
because the host has no device backend yet, so this scenario stays Draft until
audio lands.
-### E2E-CONFIG-SYNC-webdav-portable-configuration
-
-- **Preconditions:** A built task candidate, an isolated host profile, and a
- local WebDAV fixture that supports strong ETags and conditional PUT, plus a
- fixture variant that ignores conditional headers but supports `PROPFIND`
- directory listing. No real WebDAV account, provider, or production desktop.
- Developer mode starts off so the destination is exercised as developed.
-- **Steps:** 1) In a development build with developer mode off, confirm Cloud
- sync is present in the rail and returned by settings search, then open it and
- confirm neither the rail row nor the page title carries an Experimental
- badge. 2) Toggle developer mode on and off and confirm the destination stays
- reachable either way. 3) Enter the fixture URL,
- device label, directory, and backup password. 4) Run the capability test and
- confirm it uses temporary objects. 5) Select provider/MCP/skill categories
- while leaving credentials and memory off; enable credentials in a second
- preview and verify only redacted counts are shown. 6) Configure device A,
- create a user provider and MCP definition, and sync. 7) Configure device B
- against the same vault, sync, inspect pending activation/mapping, and verify
- no command or task runs before approval. 8) Approve a changed safe entity,
- reject one staged entity, edit disjoint settings on both devices, and sync
- again. 9) Exercise a concurrent head writer, wrong password, weak ETag,
- ciphertext corruption, redirect, archive traversal, and network interruption.
- 10) On the ignored-precondition fixture, select explicit compatibility mode,
- confirm the warning, and configure two devices. Verify each device publishes
- its own encrypted head under the heads collection, a concurrent update is
- merged from both tips, and compatibility mode does not delete immutable
- history. Cancel the confirmation once and verify configuration is not saved.
- 11) Use the explicit LAN HTTP acknowledgement with a loopback/private fixture,
- verify the setting survives a state refresh, and confirm a public HTTP
- endpoint is rejected even when the checkbox is selected. 12) Leave the
- Cloud sync page with an unfinished connection edit, reopen it, and confirm
- the non-sensitive draft is painted immediately while host state/history
- refreshes in the background. Confirm a configured endpoint reuses its stored
- WebDAV app password, while password fields themselves remain blank and no
- vault password is written to renderer storage.
-- **Expected:** Cloud sync is reachable in development builds without developer
- mode, is absent from a packaged build's rail, page, and settings search,
- carries no Experimental badge, and neither its availability nor its behavior
- changes when developer mode is toggled.
- Strict mode refuses
- unreliable conditional writes. The explicit
- compatibility mode accepts only a server that proves bounded directory
- listing, explains that it is not atomic CAS, and retains per-device tips for
- merge/recovery. A server that ignores conditional headers is never accepted
- without that user selection. HTTP remains opt-in and is accepted only for
- localhost, `.local`, or private/link-local addresses; public HTTP endpoints
- are rejected and the UI explains the credential exposure risk. A fixture that
- reports a missing object as 502 is accepted only after the capability probe
- observes that endpoint-specific behavior. WebDAV sees
- only authenticated ciphertext and opaque object names; raw secrets never
- appear in renderer state or logs. Identical and disjoint edits converge,
- conflicts remain reviewable, explicit deletions use tombstones, category
- opt-out is not deletion, and executable imports remain inactive until local
- approval and mapping. Reopening Settings does not block on history, and
- unfinished non-sensitive connection choices survive navigation or reload.
- Recovery never exposes a partial local apply.
-- **Specs:** `04-ux/06-settings-ia.md`, `03-runtime/22-config-sync.md`,
- `03-runtime/14-secrets-storage.md`, `05-security/01-security.md`, ADR 0300,
- ADR 0301.
-- **Acceptance:** F (persistence), Security, Quality.
-- **Milestone:** M6+.
-- **Status:** Draft; merge/crypto, in-process WebDAV conditional-write
- coverage, and the two-device host/WebDAV path are automated by
- `pnpm test:e2e:config-sync`. Cloud sync's development-build-only visibility
- and its packaged-build omission are asserted by
- `settings-developer-only-destinations.test.mjs`; full
- renderer-driven persistence and checkpoint recovery fault injection remain.
+<a id="e2e-config-sync-webdav-portable-configuration"></a>
+
+### E2E-CONFIG-SYNC-s3-portable-configuration
+
+- **Preconditions:** A built task candidate, isolated Host processes with
+ separate data, HOME and agent directories, and a local S3 fixture with strong
+ ETags and conditional PUT. No real model provider or running desktop instance.
+ A live S3 run is separately opt-in and requires explicit authorization.
+- **Steps:**
+ 1. Confirm Cloud sync remains development-build-only and has no Experimental
+ badge. Open Settings and confirm only the new S3 setup is offered;
+ old formats are not detected, migrated or deleted.
+ 2. Enter endpoint, region, private bucket, prefix, access key, secret key,
+ optional session token and addressing style. Test conditional creation,
+ readback, matching update, stale-write rejection and probe cleanup.
+ Reject ignored preconditions, weak ETags, redirects, public HTTP and 403;
+ never interpret 502 as a missing object. LAN HTTP follows network policy.
+ 3. Configure two sync devices. Publish a provider and mapped packaged skill,
+ receive them as pending where approval is required, approve, and verify
+ visible persisted configuration and resource bytes. Exercise disjoint edits,
+ same-entity conflicts and explicit choice convergence, remote deletion
+ versus offline edit, and repeated polling. Credential opt-out must not
+ manufacture local edits or prevent deletion convergence. No real executable
+ capability is run.
+ 4. Configure backup mode. Verify remote configuration is not applied, backup
+ history is separate, unchanged snapshots do not duplicate revisions, and
+ a local restore does not change either cloud head.
+ 5. Restore an older sync revision with propagation acknowledgment. Verify a
+ local recovery point, a new shared revision and propagation to the second
+ device, with sensitive activation still requiring approval. Rewrap the
+ password without claiming revocation of already unlocked devices.
+ 6. Reopen Settings with saved and unfinished drafts. Preserve typed S3 choices
+ and automatic-run preferences, but never persist secret keys, tokens or
+ passwords. Test blank credential reuse, explicit token clearing and full
+ replacement. Invalidate history on destination/mode changes and ignore
+ outstanding responses from the old connection. Unsaved mode changes must
+ not alter restore confirmation or propagation flags.
+ 7. Restart an isolated Host and verify persisted state, then disconnect without
+ deleting unrelated data. Inspect remote object bytes for known fixture
+ plaintext and verify there is no automatic immutable-object GC.
+- **Expected:** Only S3 is supported, with mandatory conditional writes and
+ encrypted vault contents. Identical/disjoint edits converge; conflicts and
+ tombstones preserve changes; excluded categories do not imply deletion.
+ Backup never downloads/applies remote configuration during normal runs.
+ History queries index at most 30 revisions; stored immutable objects are not
+ automatically deleted. Import recovery remains observable; per-file atomic
+ replacement is not asserted to be a whole-filesystem transaction.
+- **Live S3 safety:** `--live-s3 --env-file <authorized-file>` reads credentials
+ programmatically without logging/copying them. Use a new random test prefix,
+ confirm it is initially empty, run actual isolated Host processes, delete
+ only objects created under that prefix, and verify it is empty afterward.
+ Never use an existing backup prefix or production desktop profile. Record
+ tested base/candidate and distinguish this run from a standalone SDK probe.
+- **Automation:** `pnpm test:e2e:config-sync` is the multi-Host harness.
+ Rust `config_sync::` and `user_skills::` suites cover transport, merge,
+ application and resource safety. `config-sync-user-path.test.mjs` runs the
+ real settings page with a mocked external IPC boundary and no network;
+ `config-sync-ipc.test.mjs` covers Main notification shape. Visibility remains
+ covered by `settings-developer-only-destinations.test.mjs`.
+- **Specs:** `03-runtime/22-config-sync.md`, `04-ux/06-settings-ia.md`,
+ `03-runtime/14-secrets-storage.md`, `05-security/01-security.md`,
+ `docs/adr/s3-only-configuration-backup-sync.md`.
+- **Acceptance:** F (persistence), Security, Quality. **Milestone:** M6+.
+- **Status:** Candidate validation required; full checkpoint-recovery fault
+ injection is not claimed by the settings or multi-Host happy-path suites.
**E2E-CHAT-session-todo-checklist: TodoWrite to session-aware TodoDock**
@@ -9623,7 +9621,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — Desktop automations | E2E-SCHEDULED-desktop-automation-lifecycle |
-| F / Security / Quality — Portable configuration sync | E2E-CONFIG-SYNC-webdav-portable-configuration |
+| F / Security / Quality — Portable configuration sync | E2E-CONFIG-SYNC-s3-portable-configuration |
| A / C — Unicode stdio framing | E2E-RPC-unicode-separators |
| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back |
| C / D / Quality — Sidebar row states | E2E-LAYOUT-sidebar-row-states |
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index f218e7c90..c096e2c9e 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1871,26 +1871,28 @@ unchanged. See [provider configuration](12-provider-config-schema.md).
## 15. 云配置同步
-设置 → 云同步页面使用以下 Renderer-to-Main 通道;所有通道都会转发到 Host 所有的 `configSync.*` RPC 方法。该页面当前仅在开发构建可见;通道与其 Host 契约不变:
+The development-build-only page keeps its channel names. Inputs and results
+use the S3-only contract in `types/config-sync.ts` and the current source spec.
| IPC 通道 | Host 方法 | 契约 |
|---|---|---|
| `pi-desktop/configSync/getState` | `configSync.getState` | 脱敏状态、类别选择、预览计数和待审批摘要 |
-| `pi-desktop/configSync/test` | `configSync.test` | 使用临时对象进行 WebDAV 能力探测;不持久化配置 |
+| `pi-desktop/configSync/test` | `configSync.test` | S3 conditional-write probe with verified cleanup; returns `{ ok: true, conditionalWrites: true }` without persisting configuration |
| `pi-desktop/configSync/configure` | `configSync.configure` | 校验 endpoint、保存加密的本地同步元数据并启用 vault |
-| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | 执行一次由 Host 所有的协调周期 |
+| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | runs the saved sync or backup mode |
| `pi-desktop/configSync/pause` | `configSync.pause` | 仅暂停或恢复本设备 |
| `pi-desktop/configSync/unlock` | `configSync.unlock` | 为当前进程/设备解锁本地 vault |
| `pi-desktop/configSync/approve` / `reject` | `configSync.approve` / `configSync.reject` | 记录绑定 digest 的本地激活决定 |
| `pi-desktop/configSync/mapProject` | `configSync.mapProject` | 将一个不透明项目/组身份绑定到一个或多个明确选择的本地文件夹,并保留 primary-root 顺序 |
-| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | 只列出脱敏的可达 revision 元数据 |
-| `pi-desktop/configSync/restore` | `configSync.restore` | 根据明确确认的历史 revision 创建新的传播 revision,并暂存本地审批/恢复信息 |
+| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | latest 30 indexed revisions for the saved mode; never broadcast as state |
+| `pi-desktop/configSync/restore` | `configSync.restore` | sync publishes with propagation acknowledgment; backup restores locally; both retain recovery and approvals |
| `pi-desktop/configSync/changePassword` | `configSync.changePassword` | CAS 重新包裹 vault key header,不返回 key 或秘密值 |
| `pi-desktop/configSync/disconnect` | `configSync.disconnect` | 移除本地同步元数据和 key;不会删除远端 vault 数据 |
输入密码只会被传给需要它的操作。原始秘密、vault key、解密资源或远端 archive 不会返回到 Renderer。`configSync.changed` 事件携带相同的脱敏状态,并由 Host 发起的变更(包括 Host scheduler)触发。Main 只是传输/生命周期协调器,不负责调度、合并、加密或应用配置。
-手动同步会在运行期间报告 `configSync.progress`:当前阶段(`capture`、`download`、`merge`、`upload`、`apply` 或 `cleanup`)、该阶段已完成与总量,以及已知时的字节数。因此上传大量资源对象时,界面不会无内容可显示。后台轮询不报告进度,因为只有手动路径有调用方在等待。
+Manual progress uses `capture`, `download`, `merge`, `upload`, and `apply` with
+unit and byte counts. There is no cleanup phase. Background polls stay silent.
## 16. 实时语音 API
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index b6e3de64f..49365f018 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -75,8 +75,8 @@ type AppError = {
| `LIMIT_EXCEEDED` | 不 | 载荷超过了固定的主机上限(条目数、字节数)并被拒绝 |
| `CONFIG_SYNC_INVALID` | 不 | 同步配置、密码、路径、请求或审批输入无效 |
| `CONFIG_SYNC_LOCKED` | 不 | 本地加密同步 vault 尚未解锁 |
-| `CONFIG_SYNC_UNSUPPORTED` | 不 | vault 格式或 WebDAV 服务器能力不受支持 |
-| `CONFIG_SYNC_REMOTE` | 也许 | 远端 WebDAV 对象、认证、配额或可用性失败 |
+| `CONFIG_SYNC_UNSUPPORTED` | no | unsupported vault format or S3 conditional-write capability |
+| `CONFIG_SYNC_REMOTE` | maybe | S3 object, authentication, quota or availability failure |
| `CONFIG_SYNC_CONFLICT` | 也许 | 远端 head、vault 身份或审批 digest 冲突 |
| `CONFIG_SYNC_CRYPTO` | 不 | 认证加密、对象身份或密文校验失败 |
| `CONFIG_SYNC_MAPPING_REQUIRED` | 不 | 导入的项目作用域配置需要明确的本地文件夹/项目组映射 |
diff --git a/docs/zh-CN/spec/03-runtime/22-config-sync.md b/docs/zh-CN/spec/03-runtime/22-config-sync.md
index b6e0100b3..2b0399671 100644
--- a/docs/zh-CN/spec/03-runtime/22-config-sync.md
+++ b/docs/zh-CN/spec/03-runtime/22-config-sync.md
@@ -2,19 +2,22 @@
> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/22-config-sync) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。
-状态:已实现已批准 WebDAV 配置同步切片的基线。
+Status: S3-only encrypted configuration backup and synchronization.
-便携式配置同步是由 Host 所有、使用加密 WebDAV 的工作流。它不会同步对话历史、项目源文件、附件、运行时状态或模型权重。Renderer 只接收脱敏后的状态、预览计数、冲突和激活摘要。
+The current contract is [the English source](/spec/03-runtime/22-config-sync).
+Portable configuration excludes chats, project source, attachments, runtime
+state and model weights. Only redacted state is returned to the renderer.
## 1. 所有权与边界
进程路径保持不变:
```text
-Renderer → Preload IPC → Electron Main → host-core → WebDAV
+Renderer → Preload IPC → Electron Main → host-core → private S3-compatible bucket
```
-Host-core 持有 vault key、WebDAV 传输、修订状态、合并基线、待处理审批、本地加密暂存以及导入应用。Electron Main 只注册 IPC 处理器并转发 `configSync.changed`。Agent Runtime 不实现同步。
+Host Core owns S3 transport, keys, revisions, baselines, staging, approvals and
+application. Electron Main is a thin IPC bridge; Agent Runtime owns no sync.
导出路径是 `crates/host-core/src/config_sync/domains.rs` 中按域明确列出的 allowlist。它不会序列化数据库、secrets 目录或任意文件系统树。本地路径、窗口状态、就绪标记、OAuth 会话、插件二进制文件和设备审批属于本地覆盖或排除数据。
同一模块为每个受支持的域暴露适配器注册表,声明 schema 版本、便携/秘密字段、本地覆盖、身份与引用、合并粒度、激活方式以及恢复策略。
@@ -29,62 +32,97 @@ Host-core 持有 vault key、WebDAV 传输、修订状态、合并基线、待
项目和 workspace 绑定使用不透明的逻辑标识符表示。Host-core 为每个已注册的独立项目分配持久逻辑身份;项目组根目录的身份由组身份和有序根位置派生。设备映射把接收的逻辑 ID 覆盖到本地文件夹,因此不同绝对路径不会产生重复实体。
传入的项目作用域可执行内容在本地文件夹映射和审批存在前保持暂存。加密的便携实体负载中不会写入本地路径。没有受支持适配器的插件数据会报告为不支持,而不会被声称为已同步。已审批的插件安装意图保存在 Host 所有的本地覆盖中;它不会拉取插件字节或权限授予。
-## 3. Vault 与 WebDAV 协议
+## 3. Vault and S3 protocol
每个 vault 都有随机 data key。备份密码使用有界的 Argon2id 参数处理,data key 使用 AES-256-GCM 包裹。每个 head、revision manifest 和 resource object 都使用按 purpose/vault 派生的对象密钥、域隔离的关联数据和新鲜 nonce 单独认证。resource object ID 是带密钥的内容标识符,因此不需要明文全局 hash。vault envelope 版本独立于 SQLite schema;密码派生发生变化时会提升该版本。
-远端布局是不透明 header 和不可变 revision/resource object。严格模式额外使用一个可变加密 head:
+S3 uses origin-only endpoints, region, bucket, prefix, access key ID, secret
+access key, optional session token and path-style/virtual-hosted addressing.
+Defaults: `us-east-1`, `pi-desktop/config`, path style, and `sync` mode.
+The private bucket must already exist; Host does not create it or change ACLs.
```text
-<selected-directory>/header
-<selected-directory>/vault/<opaque-vault-id>/head
-<selected-directory>/vault/<opaque-vault-id>/revisions/<revision-id>
-<selected-directory>/vault/<opaque-vault-id>/objects/<object-id>
+<bucket>/<prefix>/header
+<bucket>/<prefix>/vault/<vault-id>/head
+<bucket>/<prefix>/vault/<vault-id>/backup-head
+<bucket>/<prefix>/vault/<vault-id>/revisions/<revision-id>
+<bucket>/<prefix>/vault/<vault-id>/objects/<object-id>
```
-严格模式初始化使用 `If-None-Match: *`。已有 head 必须有 strong ETag,并使用 `If-Match` 发布。前置条件失败时会从重新读取的 head 开始重新协调;绝不会盲目覆盖。能力探测会用临时对象进行两次条件创建,取得 strong ETag,验证匹配的 `If-Match` 更新,并验证旧的 `If-Match` 会被拒绝,然后删除该对象。
-
-设置页还提供一个明确选择的追加式兼容模式,用于忽略条件头的服务器。能力探测仍必须证明有界的 `PROPFIND` 目录列表能力。兼容模式增加不透明的每设备指针集合:
-
-```text
-<selected-directory>/vault/<opaque-vault-id>/heads/<device-id>
-```
-
-每台设备只覆盖自己的加密指针,并通过回读验证。同步会列出所有指针(若存在也会纳入旧的严格模式 head),遍历有界的父 revision 图,移除作为其他指针祖先的指针,并以已确认的基线合并剩余 tips。新 revision 和 resource 使用唯一不可变对象;复用已有 resource 前会先读取并认证。兼容模式保留不可变历史,不运行远端清理,因为服务器无法提供安全的跨设备确认协议。共享同一 vault 的所有设备必须使用相同模式。该模式不会被静默选择,也不宣称提供严格 CAS 保证。
-
-部分 WebDAV 网关会把不存在的对象返回为 `502 Bad Gateway`,而不是
-`404 Not Found`。能力探测会在删除临时对象后记录所选 endpoint 的这一行为;后续读取只会将该
-endpoint 已观测到的状态视为对象不存在,其他非成功响应仍然报错。这不会放宽严格模式的条件写要求:忽略 `If-None-Match` 或 `If-Match` 的服务器,只有在用户选择追加式兼容模式且目录列表探测成功后,才支持双向同步。
-
-默认要求 HTTPS。设置页可显式确认 LAN HTTP 风险,但 Host 仅接受 localhost、`.local` 或私有/链路本地 IP;公网 HTTP 仍会被拒绝。3xx 重定向会被拒绝且不会跟随;成功响应仍可以带 Location。endpoint userinfo、路径穿越、不安全远端名称、过大对象、weak ETag 和无界 KDF 参数都会被拒绝。所选端点下缺失的集合(含嵌套远程目录)会按顺序创建。已保存的 WebDAV 应用密码只对同一端点和账户复用。再次保存同步设置会保留已有的暂停状态。Host 错误使用稳定的 `CONFIG_SYNC_*` 代码,设置页据此给出恢复说明。
+SigV4 signs conditional headers and optional session tokens. The probe verifies
+exclusive creation, readback, matching update, stale-write rejection and its
+own random-object cleanup. Strong ETags and reliable `If-None-Match`/`If-Match`
+are mandatory. There is no WebDAV, append-only mode or unconditional fallback.
+Only GET 404 means absent; 403 and 502 remain errors. Redirects and public HTTP
+are rejected. LAN HTTP follows Host network policy, not a sync checkbox.
+Requests use 10-second connect and 60-second total timeouts, 64 MiB object
+bounds, and validated safe ASCII paths. Userinfo, query, fragment and non-root
+endpoint paths are rejected. Raw credentials/signatures are not logged.
+
+Credentials are reused only for the same full connection identity. Omitted
+secret/token inputs mean reuse; an empty token clears it. Supplying both fields
+permits full replacement without reading damaged old credentials. Connection
+or mode changes create fresh local state; pending imports must be resolved.
## 4. 合并与激活
-本地加密基线是最后一次确认的共同 revision。每个 vault 内的捕获、远端读取、三方合并、不可变对象上传、head 发布和本地应用会串行执行。严格模式使用 CAS head 发布;兼容模式发布每设备指针并合并发现的 tips。标量设置按声明的实体单元合并;provider 记录、MCP 记录、skill package 和 automation 定义不会作为任意 JSON 数组合并。tombstone 表示明确删除;未选择的类别不表示删除。
+Sync uses three-way merge and CAS publication. Shared and observed baselines
+separate cloud acknowledgment from local overlays and credential opt-out.
+Unacknowledged local edits stay visible. Tombstones include deletion state and
+refreshed digests; category opt-out does not delete remote entities. Backup
+publishes local snapshots to `backup-head` without applying remote settings.
+Both modes have independent 30-entry history indexes; immutable objects remain
+indefinitely, so history is bounded but cloud storage is not.
相同编辑会收敛,不相交编辑可以继续。同一单元编辑以及 delete-versus-edit 会将两个候选都保留为冲突。导入的 MCP、skills、subagents、plugins 和 automations 需要本地激活审批;审批绑定实体 digest。因此命令、endpoint、脚本、指令或凭据目的地改变后,旧审批会失效。缺失的 provider 引用会作为依赖审批保留,而不会被写成不可用的默认值;无关实体仍可继续应用。
Host 绝不会仅因为 UI flag 被设置就激活暂存的可执行内容。新导入的 automation 定义同样会被禁用,直到本设备明确取得执行所有权;已有本地任务继续使用其设备本地启用状态。
导入路径会在应用每个实体前重新检查捕获到的本地 generation。捕获之后发生的修改会保留,并在下一轮重新协调。持久化的加密 pending bundle 会记录捕获的本地 manifest 和 `applying` 标记;重启恢复会完成已审批步骤,或在认为配置已收敛前保留 bundle 供重试。现有的本地 MCP 直接创建行为不变。
+Receiving application settings use the portable allowlist; credential opt-out
+also applies on import. Skill resource updates check expected bytes and paths,
+preserve unrelated files, and delete only omitted synchronized files. Per-file
+atomic replacement and import journaling are not a filesystem-wide transaction.
+
## 5. 设置工作流
该目的地当前仅在开发构建可见:打包构建会省略「设置 → 云同步」的导轨行、页面与设置搜索命中,而本文描述的 Host 行为不变。
-设置 → 云同步提供 WebDAV endpoint 凭据、vault 密码、设备标签、服务器兼容模式、类别选择、能力测试、立即同步、解锁、暂停、文件夹映射、批准/拒绝、revision history/restore、vault 密码重新包裹以及断开连接控制。严格 CAS 是默认模式。选择追加式兼容模式会显示持续风险提示,并在保存配置前要求确认;其测试成功提示目录列表支持,而不是条件写支持。Renderer 将 `notConfigured`、`locked`、`upToDate`、`localChangesPending`、`syncing`、`offline`、`unsupportedServer`、`conflict`、`awaitingActivation`、`paused` 和 `error` 显示为不同状态。断开连接会保留本地数据,不会删除远端数据。
-
-重新打开页面时,先用短时的 Renderer 缓存绘制最近一次脱敏的 Host 状态和历史记录,随后在后台刷新 Host。连接草稿(endpoint、用户名、远程目录、设备标签、兼容模式和类别选择)保存在 Renderer 本地存储中,因此离开页面或重载后未完成的表单仍会保留;Host 确认已保存的配置后,草稿会重新标记为已保存。WebDAV 应用密码留在 Host secret store 中,且只对同一 endpoint 和账户复用;Renderer 永远不会存储任一密码,只有新设备或已锁定设备需要打开 vault 时才需要输入 vault 密码。
+Settings exposes S3 fields, vault password, device label, modes, automatic runs,
+categories, probing, manual run, pause, unlock, approvals, mappings, history,
+restore, password rewrap and disconnect. Existing distinct status codes remain.
+The S3 draft key is `pi.desktop.configSyncS3Draft.v1`; old drafts are ignored,
+not deleted. Persist only typed non-secret choices. Secrets and passwords stay
+in transient input memory and are cleared after save. A replacement secret with
+a blank token clears the old token. Saved destination/mode changes invalidate
+history and outstanding responses; unsaved mode edits do not alter restore.
-手动同步会在运行期间报告它正在做什么。`configSync.progress` 携带当前阶段(`capture`、`download`、`merge`、`upload`、`apply` 或 `cleanup`)、该阶段已完成的单位数,以及已知时的字节数:`done`/`total` 在传输时计资源对象(追加式模式下计正在读取的设备 tip)、其他阶段计实体;`total` 为 0 表示该阶段无法预知总量;`bytesTotal` 为 0 表示字节数未知,这是下载阶段的常态。报告会节流,阶段变化绝不丢弃,状态事件与调用的返回值仍是终态信号。后台轮询不报告进度:只有手动路径有调用方在等待。
-
-凭据和 memory 默认未选中。设置预览报告 supported、excluded、secret-bearing、mapping-required 和 pending-activation 计数。原始秘密值、vault key 和备份密码永远不会跨过 Renderer 边界。
+Progress phases are `capture`, `download`, `merge`, `upload`, and `apply`, with
+unit/byte totals of zero meaning unknown. No cleanup phase remains. Credentials
+and memory remain opt-in; keys and exported secrets are never returned to the
+renderer. Newly entered connection secrets/passwords are transient IPC inputs.
Host 负责自动同步启用后的启动即时检查、30 秒本地变更防抖以及有界的五分钟远端轮询。失败网络请求使用带 jitter 且有上限的指数重试;paused、locked、不兼容、认证和错误密码状态不会启动重试循环。应用退出时 worker 会随 Host 取消;退出后没有额外 daemon。
## 6. 持久性与兼容性
-同步配置存储在 Host 的 `kv` namespace 中。vault key 和 WebDAV password 使用现有 Host secret store。本地基线和 pending bundle 会加密,并通过临时文件 rename 替换。格式错误或未认证的本地 bundle 会报告错误,而不是当作空状态。备份格式版本独立于 SQLite schema;遇到更新格式时会拒绝且不截断本地表示。
-
-严格模式的远端 history 保留最新 30 个可达的逻辑 revision,并保护当前 head、merge base、待处理冲突引用和恢复点;只有在宽限期结束且发布成功后才会删除未引用对象。兼容模式保留不可变历史,因为没有安全的跨设备清理确认。restore 会先写入恢复前的本地加密恢复点,再发布新的 revision。严格模式下 vault 密码变更会 CAS 更新 wrapped-key header;兼容模式使用无条件写入后再认证回读。两种模式都不会改变 vault data key;已复制的旧 key 无法被密码变更进行密码学撤销,因此移除设备不等同于撤销访问。
-
-项目组映射接受有序的多根绑定,并保留 primary root 不变量。WebDAV 测试使用进程内 fixture 覆盖条件创建、strong-ETag 更新、旧 writer 拒绝、空 vault 竞争和 weak-ETag 拒绝。剩余的可用性限制是固有的:没有可信 head 历史的新设备无法证明恶意服务器返回的是最新有效备份。
+S3 uses `configSyncS3/config` and `config-sync/s3/<state-id>/`. Encrypted
+shared/observed baselines, pending bundles and recovery points use temp-file
+rename. Malformed or unauthenticated state is an error, never an empty state.
+The existing local secret store uses encrypted files plus a colocated
+`.machine-key`, not OS Keychain protection. SQLite schema is unchanged.
+
+Only the new S3 format is supported. Old configuration and backups are not
+detected, interpreted or migrated. Existing unrelated files and cloud objects
+are not deleted. Disconnect removes only current S3 state.
+
+An applied conflict choice records both candidate digests. The next sync
+folds only that exact unchanged pair into the chosen entity and publishes it
+with CAS. Changed candidates require another explicit choice.
+
+Restore first writes a local recovery point. Sync restore requires propagation
+acknowledgment and immediately publishes a new revision; sensitive activation
+still requires device-local approval. Backup restore is local only and may
+restore the latest backup without changing either cloud head. Password changes
+CAS-rewrap the same key and do not revoke previously unlocked devices. A fresh
+device cannot prove a malicious server returned the newest valid backup.
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index f1c01d0f3..ffb482db3 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -317,11 +317,24 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历
### 云同步
-- **连接**:提供 WebDAV URL、用户名、应用密码、远程目录、设备标签、独立的备份/vault 密码和服务器兼容模式。默认使用严格 CAS;能力测试只使用临时远端对象。选择追加式兼容模式时显示持续风险提示,并在保存前要求确认。
+- **Connection**: S3 endpoint, region, private bucket, prefix, access key ID,
+ secret key, optional token, addressing style, device label and vault password.
+ Choose sync or backup mode and automatic runs. Conditional writes are required;
+ there is no WebDAV/append-only fallback. Legacy data remains without migration.
- **可移植配置**:支持的类别默认选中;凭据和项目 memory 必须明确选择。预览显示 supported、excluded、secret-bearing、mapping-required 和 pending-approval 计数。
-- **安全**:页面不渲染原始凭据或 vault key。导入的 MCP、skills、subagents、plugins、automations 和项目作用域数据在本地激活审批及必要的文件夹映射完成前保持暂存。断开连接保留本地和远端数据。
+- **Safety**: vault keys and exported secrets are never returned to the page.
+ Connection secrets stay transient; imports keep local approval and mappings.
+ Public HTTP and redirects are rejected; LAN HTTP follows Host network policy.
+ Disconnect preserves local configuration, legacy data and remote objects.
- **状态与恢复**:显示已配置、已锁定、同步中、离线、不支持服务器、冲突、等待激活、暂停和错误等不同状态。用户可以立即同步、解锁、暂停本设备、批准/拒绝暂存项目以及断开连接。存在待处理状态时,页面不会根据旧的成功记录暗示已经收敛。
-- **快速重返和草稿**:Host 在后台刷新时,先用短时本地缓存绘制最近一次脱敏的状态和历史记录。endpoint、用户名、远程目录、设备标签、兼容模式和类别选择保存在 Renderer 本地存储中,因此离开页面或重载后未完成的表单仍会保留。WebDAV 应用密码继续保存在 Host 管理的 secret storage 中,且只对同一 endpoint 和账户复用;vault 密码永远不会写入 Renderer 存储。
+- **Drafts and recovery**: cache only typed non-secret S3 choices under a new
+ versioned key; ignore old drafts. Blank credentials reuse the exact connection,
+ while explicit clearing/replacement clears the token. Never persist secrets or
+ passwords. Invalidate old history requests when the saved destination/mode
+ changes. Display the latest 30 revisions and disclose indefinite object
+ retention. Sync restore confirms immediate publication; backup restore is
+ local only. Unsaved mode edits do not change restore semantics. Password
+ changes do not revoke unlocked devices.
### 信息
- app/host/protocol版本+开放日志
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 92098e9d3..cbe817326 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5621,7 +5621,7 @@ eleven-tool-round desktop paths are verified by
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — 桌面定时任务 | E2E-SCHEDULED-desktop-automation-lifecycle |
-| F / Security / Quality — 便携式配置同步 | E2E-CONFIG-SYNC-webdav-portable-configuration |
+| F / Security / Quality — Portable configuration sync | E2E-CONFIG-SYNC-s3-portable-configuration |
| A / C — Unicode stdio 成帧 | E2E-RPC-unicode-separators |
| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back |
| C / D / Quality — 侧边栏行状态 | E2E-LAYOUT-sidebar-row-states |
@@ -8935,15 +8935,32 @@ the latest destination. These assertions measure work counts, not device FPS.
- **状态:** `node scripts/e2e-scheduled.mjs` 自动化覆盖;按 AGENTS.md 在任务候选
版本上运行,并记录已测提交与基线。
-### E2E-CONFIG-SYNC-webdav-portable-configuration
-
-- **前提:** 已构建的任务候选版本、隔离的 Host 配置(开发者模式默认关闭,用来验证开发构建下的目的地),以及支持 strong ETag 和条件 PUT 的本地 WebDAV fixture,另有忽略条件头但支持 `PROPFIND` 目录列举的 fixture 变体。不使用真实 WebDAV 账户、provider 或生产桌面。
-- **步骤:** 1)在开发构建中、开发者模式关闭的情况下打开设置,确认“云同步”出现在导轨中且设置搜索能命中它;打开该页,确认导轨行和页面标题都不带实验性徽章。2)开关一次开发者模式,确认该目的地始终可用且可见性不变。3)填写 fixture URL、设备标签、目录和备份密码。4)运行能力测试,确认使用临时对象。5)选择 provider/MCP/skill 类别,保持凭据和 memory 未选中;在第二次预览中启用凭据,确认只显示脱敏计数。6)配置设备 A,创建 user provider 和 MCP 定义并同步。7)让设备 B 连接同一 vault,同步后检查待激活/映射,并验证审批前不会运行命令或任务。8)批准一个变更后的安全实体,拒绝一个暂存实体,在两台设备上编辑不相交设置并再次同步。9)测试并发 head writer、错误密码、weak ETag、密文损坏、redirect、归档路径穿越和网络中断。10)使用回环/私有地址的 fixture 勾选“允许在受信任的内网地址使用 HTTP”,确认刷新状态后仍保留;即使勾选,公网 HTTP 地址也必须被拒绝。
-- **预期:** 云同步在开发构建中、开发者模式关闭时即可访问,打包构建的导轨、页面和设置搜索都不含它,且导轨行与页面标题都不带实验性徽章;开关开发者模式既不改变入口可见性也不改变同步行为。测试拒绝不可靠的条件写入。HTTP 默认关闭,仅允许 localhost、`.local` 或私有/链路本地地址;公网 HTTP 地址会被拒绝,界面会提示凭据暴露风险。若 fixture 探测到该 endpoint 对不存在对象返回 502,后续只兼容该 endpoint 的这一行为;忽略条件头的服务器仍必须标记为不受支持。WebDAV 只能看到已认证的密文和不透明对象名;原始秘密不会出现在 Renderer 状态或日志中。相同和不相交的编辑会收敛,冲突保持可审查,明确删除使用 tombstone,类别退出不是删除,可执行导入在本地审批和映射前保持不激活。恢复不会暴露部分应用的本地配置。
-- **规格:** `04-ux/06-settings-ia.md`、`03-runtime/22-config-sync.md`、`03-runtime/14-secrets-storage.md`、`05-security/01-security.md`、ADR 0300。
-- **验收:** F(持久化)、Security、Quality。
-- **里程碑:** M6+。
-- **状态:** Draft;合并/密码学和进程内 WebDAV 条件写入覆盖已存在。云同步仅开发构建可见、打包构建省略该目的地由 `apps/desktop/test/settings-developer-only-destinations.test.mjs` 断言;完整双设备进程路径和逐检查点本地恢复故障注入仍待自动化。
+<a id="e2e-config-sync-webdav-portable-configuration"></a>
+
+### E2E-CONFIG-SYNC-s3-portable-configuration
+
+Follow the [current S3 acceptance scenario](/spec/06-delivery/04-e2e-test-plan#e2e-config-sync-s3-portable-configuration).
+
+- Use separate Host processes, data directories, HOME and agent directories.
+ Local S3 fixtures exercise conditional writes, authentication, merge,
+ conflict choices and repeated convergence, deletions, credential opt-out,
+ approval and skill resources.
+- Backup only uploads local snapshots; histories are mode-specific. Sync
+ restore publishes with explicit acknowledgment; backup restore stays local.
+- The real settings-page test covers secret-free drafts, saved credential reuse,
+ explicit token clearing, mode selection, restore confirmation, stale history
+ responses and disconnect. Development-build-only visibility remains unchanged.
+- Live S3 is explicitly opt-in and authorized. Read credentials without logging
+ or copying them; use a fresh random prefix, verify initial emptiness, clean
+ only test-created objects and verify final emptiness. Never use the running
+ desktop or real model providers. Record the tested candidate/base.
+- A 30-entry history index does not imply physical garbage collection. Only
+ the new S3 format is supported, without legacy detection or migration;
+ unrelated data is not deleted. Recovery is not whole-filesystem atomicity.
+- Automation: `pnpm test:e2e:config-sync`, Rust `config_sync::` and
+ `user_skills::`, `config-sync-user-path.test.mjs`, `config-sync-ipc.test.mjs`.
+ Full checkpoint-recovery fault injection is not claimed by these user paths.
+- Acceptance: F (persistence), Security, Quality. Candidate validation required.
### E2E-DIALOG-long-text-boundaries
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 629e11f88..c28652b37 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -803,9 +803,8 @@ sklm: {
},
"configSync": {
title: "Cloud sync",
- connectionTitle: "WebDAV cloud sync",
- connectionDescription:
- "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ connectionTitle: "S3-Konfigurationssicherung und Synchronisierung",
+ connectionDescription: "Portable Konfiguration verschlüsselt in einem privaten S3-Bucket speichern. Chats, Quelldateien und Laufzeitdaten bleiben lokal.",
errorTitle: "Sync needs attention",
errorDetails: "Technical details",
backupPasswordOptional: "Leave this blank to keep the current vault password.",
@@ -813,37 +812,43 @@ sklm: {
previewPending: "Pending activation: {{count}}",
previewConflicts: "Conflicts: {{count}}",
errors: {
- auth: "Check the WebDAV username and app password, then test the connection again.",
- permission: "This account cannot read and write the selected WebDAV directory.",
- notFound: "Check the WebDAV URL and directory. Use the WebDAV endpoint, not the website home page.",
+ auth: "Prüfe S3-Zugriffsschlüssel, geheimen Schlüssel, Sitzungstoken, Region und Gerätezeit.",
+ permission: "Erlaube Lesen, bedingtes Schreiben und das Löschen von Testobjekten im gewählten Bucket-Präfix.",
+ notFound: "Prüfe S3-Endpunkt, Region, Bucket und Objektpräfix.",
conflict: "Another device updated this backup. Sync again to merge, then review anything waiting for approval.",
quota: "The remote storage is full. Free space or raise the quota, then retry.",
rateLimit: "The server is rate limiting requests. Retry the sync in a moment.",
- server: "The WebDAV server is temporarily unavailable.",
+ server: "Der S3-Dienst ist vorübergehend nicht verfügbar.",
network: "Check the network, address, and certificate, then retry.",
- redirect: "The server redirected the request. Use the direct WebDAV URL.",
- unsupported: "This server does not support the required WebDAV operations. Try compatibility mode.",
+ redirect: "Verwende den direkten regionalen S3-Endpunkt. Weiterleitungen werden nicht verfolgt.",
+ unsupported: "Der S3-Dienst muss zuverlässige bedingte Schreibvorgänge unterstützen. Es gibt keinen Kompatibilitätsmodus.",
locked: "Enter the backup password to unlock sync.",
- invalid: "Check the server URL, directory, and required passwords.",
- password: "Use the backup password created for this vault, not the WebDAV password.",
+ invalid: "Prüfe die S3-Verbindungsfelder und erforderlichen Zugangsdaten.",
+ password: "Verwende das Sicherungspasswort des Tresors, nicht den geheimen S3-Schlüssel.",
limit: "The backup is larger than the supported size. Sync fewer categories and retry.",
unknown: "Sync did not finish. Check the connection and retry. Open the technical details if it keeps failing.",
},
- endpoint: "WebDAV URL",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Server-Kompatibilität",
- remoteModeHint:
- "Der strikte Modus erfordert zuverlässige bedingte Schreibvorgänge. Verwende den Kompatibilitätsmodus nur für Server, die If-Match/If-None-Match ignorieren.",
- remoteModeStrict: "Striktes CAS (empfohlen)",
- remoteModeAppendOnly: "Kompatibilitätsmodus (nur anhängen)",
- appendOnlyWarning:
- "Dieser Modus ist für WebDAV-Server gedacht, die bedingte Schreibvorgänge ignorieren. Initialisiere den Tresor zuerst auf einem Gerät, bevor weitere Geräte beitreten. Er verwendet gerätespezifische Anhängeköpfe und behält den Remote-Verlauf; alle Geräte in diesem Tresor müssen den Kompatibilitätsmodus verwenden. Gleichzeitige Änderungen müssen möglicherweise geprüft werden.",
- appendOnlyConfirm:
- "Dieser Server kann bedingte Schreibvorgänge nicht erzwingen. Der Kompatibilitätsmodus behält den Verlauf, bietet aber kein atomares Compare-and-Swap. Fortfahren?",
- username: "Username",
- appPassword: "App password",
- appPasswordSavedHint: "Sicher auf diesem Gerät gespeichert. Leer lassen, um es wiederzuverwenden.",
- directory: "Remote directory",
+ endpoint: "S3-Endpunkt",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Region",
+ bucket: "Privater Bucket",
+ prefix: "Objektpräfix",
+ accessKeyId: "Zugriffsschlüssel-ID",
+ secretAccessKey: "Geheimer Zugriffsschlüssel",
+ secretSavedHint: "Leer lassen, um den lokal gespeicherten Schlüssel für genau diese Verbindung zu verwenden.",
+ sessionToken: "Sitzungstoken (optional)",
+ sessionTokenHint: "Leer behält das gespeicherte Token, außer bei einem neuen geheimen Schlüssel. Temporäre Zugangsdaten benötigen auch ein neues Token.",
+ clearSessionToken: "Gespeichertes Sitzungstoken löschen",
+ addressing: "Bucket-Adressierung",
+ addressingHint: "Verwende den Dienstendpunkt, keine öffentliche Download-URL oder URL mit Bucket-Pfad.",
+ pathStyle: "Pfadstil",
+ virtualHosted: "Virtueller Host",
+ mode: "Betriebsmodus",
+ modeHint: "Sicherung lädt nur dieses Gerät hoch. Synchronisierung übernimmt und vereint Änderungen anderer Geräte. Jeder Modus hat einen eigenen Verlauf.",
+ modeSync: "Bidirektionale Synchronisierung",
+ modeBackup: "Nur Sicherung",
+ automaticSync: "Automatisch ausführen",
+ backupNow: "Jetzt sichern",
deviceLabel: "Device label",
defaultDevice: "This device",
backupPassword: "Backup password",
@@ -853,7 +858,7 @@ sklm: {
currentBackupPassword: "Current vault password",
newBackupPassword: "New vault password",
changePasswordTitle: "Change vault password",
- changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePasswordDescription: "Verpackt den Tresorschlüssel neu. Bereits entsperrte Geräte behalten Zugriff; ihr Zugriff wird nicht widerrufen.",
changePassword: "Change password",
passwordChanged: "Vault password changed.",
showPassword: "Show password",
@@ -862,12 +867,8 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
- testAppendOnlySuccess:
- "The server supports directory listing for append-only compatibility mode.",
- testAppendOnlyUnsupported:
- "The server did not prove directory listing for compatibility mode; sync is not enabled.",
- enable: "Enable sync",
- save: "Save and sync",
+ enable: "Sicherung / Synchronisierung aktivieren",
+ save: "Speichern und ausführen",
configured: "Cloud sync configuration saved.",
syncNow: "Sync now",
progressTitle: "Synchronisierung läuft…",
@@ -878,7 +879,6 @@ sklm: {
merge: "Änderungen werden zusammengeführt",
upload: "Änderungen werden hochgeladen",
apply: "Änderungen werden angewendet",
- cleanup: "Aufräumen",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -930,14 +930,15 @@ sklm: {
mappingsDescription: "Local folders stay device-specific and are never uploaded.",
mappingUnavailable: "Folder unavailable",
historyTitle: "History and restore",
- historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ historyDescription: "Zeigt die letzten 30 Revisionen dieses Modus. Verschlüsselte Objekte bleiben unbegrenzt erhalten; keine automatische Cloud-Bereinigung.",
+ restoreBackupConfirm: "Diese Sicherung nur auf diesem Gerät wiederherstellen? Ein lokaler Wiederherstellungspunkt wird gespeichert. Der Cloud-Verlauf bleibt unverändert; sensible Änderungen benötigen eine Freigabe.",
refreshHistory: "Refresh history",
currentRevision: "Current revision",
historyItems: "items",
historyEmpty: "No remote revisions are available yet.",
historyLocked: "Unlock the vault to read revision history.",
restore: "Restore",
- restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreConfirm: "Diese Revision wiederherstellen und sofort an andere Geräte veröffentlichen? Ein lokaler Wiederherstellungspunkt wird gespeichert. Sensible Änderungen benötigen auf jedem Gerät eine Freigabe.",
restoreStarted: "Restore staged. Review pending approvals.",
disconnectTitle: "Disconnect",
disconnectDescription:
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index af94c60bc..5749b8e38 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1085,9 +1085,8 @@ sklm: {
},
configSync: {
title: "Cloud sync",
- connectionTitle: "WebDAV cloud sync",
- connectionDescription:
- "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ connectionTitle: "S3 configuration backup and sync",
+ connectionDescription: "Encrypt portable configuration in a private S3-compatible bucket. Chats, source files, and runtime state are excluded.",
errorTitle: "Sync needs attention",
errorDetails: "Technical details",
backupPasswordOptional: "Leave this blank to keep the current vault password.",
@@ -1095,37 +1094,43 @@ sklm: {
previewPending: "Pending activation: {{count}}",
previewConflicts: "Conflicts: {{count}}",
errors: {
- auth: "Check the WebDAV username and app password, then test the connection again.",
- permission: "This account cannot read and write the selected WebDAV directory.",
- notFound: "Check the WebDAV URL and directory. Use the WebDAV endpoint, not the website home page.",
+ auth: "Check the S3 access key, secret key, session token, region, and device clock.",
+ permission: "Allow reading, conditional writing, and probe-object deletion in the selected bucket prefix.",
+ notFound: "Check the S3 endpoint, region, bucket, and object prefix.",
conflict: "Another device updated this backup. Sync again to merge, then review anything waiting for approval.",
quota: "The remote storage is full. Free space or raise the quota, then retry.",
rateLimit: "The server is rate limiting requests. Retry the sync in a moment.",
- server: "The WebDAV server is temporarily unavailable.",
+ server: "The S3 service is temporarily unavailable.",
network: "Check the network, address, and certificate, then retry.",
- redirect: "The server redirected the request. Use the direct WebDAV URL.",
- unsupported: "This server does not support the required WebDAV operations. Try compatibility mode.",
+ redirect: "Use the direct regional S3 endpoint; redirects are not followed.",
+ unsupported: "This S3 service must support reliable conditional writes. No compatibility fallback is available.",
locked: "Enter the backup password to unlock sync.",
- invalid: "Check the server URL, directory, and required passwords.",
- password: "Use the backup password created for this vault, not the WebDAV password.",
+ invalid: "Check the S3 connection fields and required credentials.",
+ password: "Use the backup password for this vault, not the S3 secret key.",
limit: "The backup is larger than the supported size. Sync fewer categories and retry.",
unknown: "Sync did not finish. Check the connection and retry. Open the technical details if it keeps failing.",
},
- endpoint: "WebDAV URL",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Server compatibility",
- remoteModeHint:
- "Strict mode requires reliable conditional writes. Use compatibility mode only for a server that ignores If-Match/If-None-Match.",
- remoteModeStrict: "Strict CAS (recommended)",
- remoteModeAppendOnly: "Compatibility mode (append-only)",
- appendOnlyWarning:
- "This mode is for WebDAV servers that ignore conditional writes. Initialize the vault on one device before joining from others. It uses per-device append-only heads and retains remote history; every device sharing this vault must use compatibility mode. Concurrent changes may still require review.",
- appendOnlyConfirm:
- "This server mode cannot enforce conditional writes. Compatibility mode retains history but cannot provide atomic compare-and-swap. Continue?",
- username: "Username",
- appPassword: "App password",
- appPasswordSavedHint: "Saved securely on this device. Leave blank to reuse it.",
- directory: "Remote directory",
+ endpoint: "S3 endpoint",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Region",
+ bucket: "Private bucket",
+ prefix: "Object prefix",
+ accessKeyId: "Access key ID",
+ secretAccessKey: "Secret access key",
+ secretSavedHint: "Leave blank to reuse the locally saved key for this exact connection.",
+ sessionToken: "Session token (optional)",
+ sessionTokenHint: "Blank keeps the saved token unless you enter a new secret key. Supply a new token together with temporary credentials.",
+ clearSessionToken: "Clear the saved session token",
+ addressing: "Bucket addressing",
+ addressingHint: "Use the service endpoint, not a public download URL or a URL containing the bucket path.",
+ pathStyle: "Path style",
+ virtualHosted: "Virtual hosted",
+ mode: "Operation mode",
+ modeHint: "Backup only uploads this device. Two-way sync merges and applies changes across devices. Each mode has separate history.",
+ modeSync: "Two-way sync",
+ modeBackup: "Backup only",
+ automaticSync: "Run automatically",
+ backupNow: "Back up now",
deviceLabel: "Device label",
defaultDevice: "This device",
backupPassword: "Backup password",
@@ -1135,8 +1140,7 @@ sklm: {
currentBackupPassword: "Current vault password",
newBackupPassword: "New vault password",
changePasswordTitle: "Change vault password",
- changePasswordDescription:
- "Rewrap the vault key without re-encrypting or exposing configuration data.",
+ changePasswordDescription: "Rewrap the vault key without exposing data. Previously unlocked devices retain access; this does not revoke them.",
changePassword: "Change password",
passwordChanged: "Vault password changed.",
showPassword: "Show password",
@@ -1145,12 +1149,8 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
- testAppendOnlySuccess:
- "The server supports directory listing for append-only compatibility mode.",
- testAppendOnlyUnsupported:
- "The server did not prove directory listing for compatibility mode; sync is not enabled.",
- enable: "Enable sync",
- save: "Save and sync",
+ enable: "Enable backup / sync",
+ save: "Save and run",
configured: "Cloud sync configuration saved.",
syncNow: "Sync now",
progressTitle: "Syncing…",
@@ -1161,7 +1161,6 @@ sklm: {
merge: "Merging changes",
upload: "Uploading changes",
apply: "Applying changes",
- cleanup: "Cleaning up",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -1213,16 +1212,15 @@ sklm: {
mappingsDescription: "Local folders stay device-specific and are never uploaded.",
mappingUnavailable: "Folder unavailable",
historyTitle: "History and restore",
- historyDescription:
- "Restore creates a new revision and propagates the selected configuration to subscribed devices.",
+ historyDescription: "Shows the latest 30 revisions for this mode. Encrypted objects are retained indefinitely; cloud storage is not automatically cleaned up.",
+ restoreBackupConfirm: "Restore this backup on this device only? A local recovery point will be saved. Remote history will not change, and sensitive changes still require approval.",
refreshHistory: "Refresh history",
currentRevision: "Current revision",
historyItems: "items",
historyEmpty: "No remote revisions are available yet.",
historyLocked: "Unlock the vault to read revision history.",
restore: "Restore",
- restoreConfirm:
- "Restore this revision? The restored configuration will be published to other subscribed devices after local approvals.",
+ restoreConfirm: "Restore and publish this revision to other devices? A local recovery point will be saved. Publication is immediate; sensitive changes require approval on each device.",
restoreStarted: "Restore staged. Review any pending local approvals.",
disconnectTitle: "Disconnect",
disconnectDescription:
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 64cfa0961..85c75f6dc 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -803,9 +803,8 @@ sklm: {
},
"configSync": {
title: "Cloud sync",
- connectionTitle: "WebDAV cloud sync",
- connectionDescription:
- "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ connectionTitle: "Copia de configuración y sincronización S3",
+ connectionDescription: "Cifra la configuración portátil en un bucket S3 privado. No incluye conversaciones, archivos fuente ni estado de ejecución.",
errorTitle: "Sync needs attention",
errorDetails: "Technical details",
backupPasswordOptional: "Leave this blank to keep the current vault password.",
@@ -813,37 +812,43 @@ sklm: {
previewPending: "Pending activation: {{count}}",
previewConflicts: "Conflicts: {{count}}",
errors: {
- auth: "Check the WebDAV username and app password, then test the connection again.",
- permission: "This account cannot read and write the selected WebDAV directory.",
- notFound: "Check the WebDAV URL and directory. Use the WebDAV endpoint, not the website home page.",
+ auth: "Revisa las claves S3, el token de sesión, la región y el reloj del dispositivo.",
+ permission: "Permite lectura, escritura condicional y eliminación de objetos de prueba en el prefijo elegido.",
+ notFound: "Revisa el endpoint S3, la región, el bucket y el prefijo.",
conflict: "Another device updated this backup. Sync again to merge, then review anything waiting for approval.",
quota: "The remote storage is full. Free space or raise the quota, then retry.",
rateLimit: "The server is rate limiting requests. Retry the sync in a moment.",
- server: "The WebDAV server is temporarily unavailable.",
+ server: "El servicio S3 no está disponible temporalmente.",
network: "Check the network, address, and certificate, then retry.",
- redirect: "The server redirected the request. Use the direct WebDAV URL.",
- unsupported: "This server does not support the required WebDAV operations. Try compatibility mode.",
+ redirect: "Usa el endpoint regional S3 directo. No se siguen redirecciones.",
+ unsupported: "El servicio S3 debe admitir escrituras condicionales fiables. No hay modo de compatibilidad.",
locked: "Enter the backup password to unlock sync.",
- invalid: "Check the server URL, directory, and required passwords.",
- password: "Use the backup password created for this vault, not the WebDAV password.",
+ invalid: "Revisa los campos de conexión S3 y las credenciales necesarias.",
+ password: "Usa la contraseña de la bóveda, no la clave secreta S3.",
limit: "The backup is larger than the supported size. Sync fewer categories and retry.",
unknown: "Sync did not finish. Check the connection and retry. Open the technical details if it keeps failing.",
},
- endpoint: "WebDAV URL",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Compatibilidad del servidor",
- remoteModeHint:
- "El modo estricto requiere escrituras condicionales fiables. Usa el modo de compatibilidad solo con servidores que ignoran If-Match/If-None-Match.",
- remoteModeStrict: "CAS estricto (recomendado)",
- remoteModeAppendOnly: "Modo de compatibilidad (solo anexar)",
- appendOnlyWarning:
- "Este modo es para servidores WebDAV que ignoran las escrituras condicionales. Inicializa la bóveda en un dispositivo antes de unir otros. Usa cabeceras de anexado por dispositivo y conserva el historial remoto; todos los dispositivos que compartan esta bóveda deben usar el modo de compatibilidad. Los cambios simultáneos pueden requerir revisión.",
- appendOnlyConfirm:
- "Este servidor no puede aplicar escrituras condicionales. El modo de compatibilidad conserva el historial, pero no ofrece un compare-and-swap atómico. ¿Continuar?",
- username: "Username",
- appPassword: "App password",
- appPasswordSavedHint: "Guardada de forma segura en este dispositivo. Déjala vacía para reutilizarla.",
- directory: "Remote directory",
+ endpoint: "Endpoint S3",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Región",
+ bucket: "Bucket privado",
+ prefix: "Prefijo de objetos",
+ accessKeyId: "ID de clave de acceso",
+ secretAccessKey: "Clave de acceso secreta",
+ secretSavedHint: "Déjala vacía para reutilizar la clave local de esta misma conexión.",
+ sessionToken: "Token de sesión (opcional)",
+ sessionTokenHint: "Vacío conserva el token guardado, salvo al introducir una nueva clave secreta. Incluye un token nuevo con credenciales temporales.",
+ clearSessionToken: "Borrar el token de sesión guardado",
+ addressing: "Direccionamiento del bucket",
+ addressingHint: "Usa el endpoint del servicio, no una URL pública ni una URL con la ruta del bucket.",
+ pathStyle: "Por ruta",
+ virtualHosted: "Host virtual",
+ mode: "Modo de operación",
+ modeHint: "La copia solo sube este dispositivo. La sincronización combina y aplica cambios entre dispositivos. Cada modo tiene su propio historial.",
+ modeSync: "Sincronización bidireccional",
+ modeBackup: "Solo copia de seguridad",
+ automaticSync: "Ejecutar automáticamente",
+ backupNow: "Crear copia ahora",
deviceLabel: "Device label",
defaultDevice: "This device",
backupPassword: "Backup password",
@@ -853,7 +858,7 @@ sklm: {
currentBackupPassword: "Current vault password",
newBackupPassword: "New vault password",
changePasswordTitle: "Change vault password",
- changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePasswordDescription: "Vuelve a envolver la clave de la bóveda. Los dispositivos ya desbloqueados conservan el acceso; no se revoca.",
changePassword: "Change password",
passwordChanged: "Vault password changed.",
showPassword: "Show password",
@@ -862,12 +867,8 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
- testAppendOnlySuccess:
- "The server supports directory listing for append-only compatibility mode.",
- testAppendOnlyUnsupported:
- "The server did not prove directory listing for compatibility mode; sync is not enabled.",
- enable: "Enable sync",
- save: "Save and sync",
+ enable: "Activar copia / sincronización",
+ save: "Guardar y ejecutar",
configured: "Cloud sync configuration saved.",
syncNow: "Sync now",
progressTitle: "Sincronizando…",
@@ -878,7 +879,6 @@ sklm: {
merge: "Combinando cambios",
upload: "Subiendo cambios",
apply: "Aplicando cambios",
- cleanup: "Limpiando",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -930,14 +930,15 @@ sklm: {
mappingsDescription: "Local folders stay device-specific and are never uploaded.",
mappingUnavailable: "Folder unavailable",
historyTitle: "History and restore",
- historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ historyDescription: "Muestra las últimas 30 revisiones de este modo. Los objetos cifrados se conservan indefinidamente; no hay limpieza automática en la nube.",
+ restoreBackupConfirm: "¿Restaurar esta copia solo en este dispositivo? Se guardará un punto de recuperación local. El historial remoto no cambiará y los cambios sensibles requieren aprobación.",
refreshHistory: "Refresh history",
currentRevision: "Current revision",
historyItems: "items",
historyEmpty: "No remote revisions are available yet.",
historyLocked: "Unlock the vault to read revision history.",
restore: "Restore",
- restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreConfirm: "¿Restaurar y publicar esta revisión inmediatamente para otros dispositivos? Se guardará un punto de recuperación local. Los cambios sensibles requieren aprobación en cada dispositivo.",
restoreStarted: "Restore staged. Review pending approvals.",
disconnectTitle: "Disconnect",
disconnectDescription:
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 308e446d4..8596c348c 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -803,9 +803,8 @@ sklm: {
},
"configSync": {
title: "Cloud sync",
- connectionTitle: "WebDAV cloud sync",
- connectionDescription:
- "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ connectionTitle: "Sauvegarde et synchronisation S3",
+ connectionDescription: "Chiffrez la configuration portable dans un compartiment S3 privé. Conversations, fichiers sources et état d’exécution sont exclus.",
errorTitle: "Sync needs attention",
errorDetails: "Technical details",
backupPasswordOptional: "Leave this blank to keep the current vault password.",
@@ -813,37 +812,43 @@ sklm: {
previewPending: "Pending activation: {{count}}",
previewConflicts: "Conflicts: {{count}}",
errors: {
- auth: "Check the WebDAV username and app password, then test the connection again.",
- permission: "This account cannot read and write the selected WebDAV directory.",
- notFound: "Check the WebDAV URL and directory. Use the WebDAV endpoint, not the website home page.",
+ auth: "Vérifiez les clés S3, le jeton de session, la région et l’horloge de l’appareil.",
+ permission: "Autorisez la lecture, l’écriture conditionnelle et la suppression des objets de test dans le préfixe choisi.",
+ notFound: "Vérifiez le point de terminaison S3, la région, le compartiment et le préfixe.",
conflict: "Another device updated this backup. Sync again to merge, then review anything waiting for approval.",
quota: "The remote storage is full. Free space or raise the quota, then retry.",
rateLimit: "The server is rate limiting requests. Retry the sync in a moment.",
- server: "The WebDAV server is temporarily unavailable.",
+ server: "Le service S3 est temporairement indisponible.",
network: "Check the network, address, and certificate, then retry.",
- redirect: "The server redirected the request. Use the direct WebDAV URL.",
- unsupported: "This server does not support the required WebDAV operations. Try compatibility mode.",
+ redirect: "Utilisez le point de terminaison régional S3 direct. Les redirections ne sont pas suivies.",
+ unsupported: "Le service S3 doit garantir les écritures conditionnelles. Aucun mode de compatibilité n’est proposé.",
locked: "Enter the backup password to unlock sync.",
- invalid: "Check the server URL, directory, and required passwords.",
- password: "Use the backup password created for this vault, not the WebDAV password.",
+ invalid: "Vérifiez les paramètres S3 et les identifiants requis.",
+ password: "Utilisez le mot de passe du coffre, pas la clé secrète S3.",
limit: "The backup is larger than the supported size. Sync fewer categories and retry.",
unknown: "Sync did not finish. Check the connection and retry. Open the technical details if it keeps failing.",
},
- endpoint: "WebDAV URL",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Compatibilité du serveur",
- remoteModeHint:
- "Le mode strict exige des écritures conditionnelles fiables. Utilisez le mode de compatibilité uniquement avec un serveur qui ignore If-Match/If-None-Match.",
- remoteModeStrict: "CAS strict (recommandé)",
- remoteModeAppendOnly: "Mode de compatibilité (ajout uniquement)",
- appendOnlyWarning:
- "Ce mode est destiné aux serveurs WebDAV qui ignorent les écritures conditionnelles. Initialisez le coffre sur un appareil avant d’en joindre d’autres. Il utilise des têtes d’ajout par appareil et conserve l’historique distant ; tous les appareils de ce coffre doivent utiliser le mode de compatibilité. Les modifications simultanées peuvent nécessiter une vérification.",
- appendOnlyConfirm:
- "Ce serveur ne peut pas appliquer les écritures conditionnelles. Le mode de compatibilité conserve l’historique, mais ne fournit pas de compare-and-swap atomique. Continuer ?",
- username: "Username",
- appPassword: "App password",
- appPasswordSavedHint: "Enregistré de façon sécurisée sur cet appareil. Laissez vide pour le réutiliser.",
- directory: "Remote directory",
+ endpoint: "Point de terminaison S3",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Région",
+ bucket: "Compartiment privé",
+ prefix: "Préfixe des objets",
+ accessKeyId: "Identifiant de clé d’accès",
+ secretAccessKey: "Clé d’accès secrète",
+ secretSavedHint: "Laissez vide pour réutiliser la clé locale de cette connexion exacte.",
+ sessionToken: "Jeton de session (facultatif)",
+ sessionTokenHint: "Vide conserve le jeton enregistré, sauf si vous saisissez une nouvelle clé secrète. Fournissez aussi un nouveau jeton avec des identifiants temporaires.",
+ clearSessionToken: "Effacer le jeton de session enregistré",
+ addressing: "Adressage du compartiment",
+ addressingHint: "Utilisez le point de terminaison du service, pas une URL publique ou contenant le chemin du compartiment.",
+ pathStyle: "Par chemin",
+ virtualHosted: "Hôte virtuel",
+ mode: "Mode de fonctionnement",
+ modeHint: "La sauvegarde envoie seulement cet appareil. La synchronisation fusionne et applique les changements entre appareils. Les historiques sont séparés.",
+ modeSync: "Synchronisation bidirectionnelle",
+ modeBackup: "Sauvegarde uniquement",
+ automaticSync: "Exécuter automatiquement",
+ backupNow: "Sauvegarder maintenant",
deviceLabel: "Device label",
defaultDevice: "This device",
backupPassword: "Backup password",
@@ -853,7 +858,7 @@ sklm: {
currentBackupPassword: "Current vault password",
newBackupPassword: "New vault password",
changePasswordTitle: "Change vault password",
- changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePasswordDescription: "Réenveloppe la clé du coffre. Les appareils déjà déverrouillés conservent leur accès ; il n’est pas révoqué.",
changePassword: "Change password",
passwordChanged: "Vault password changed.",
showPassword: "Show password",
@@ -862,12 +867,8 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
- testAppendOnlySuccess:
- "The server supports directory listing for append-only compatibility mode.",
- testAppendOnlyUnsupported:
- "The server did not prove directory listing for compatibility mode; sync is not enabled.",
- enable: "Enable sync",
- save: "Save and sync",
+ enable: "Activer la sauvegarde / synchronisation",
+ save: "Enregistrer et exécuter",
configured: "Cloud sync configuration saved.",
syncNow: "Sync now",
progressTitle: "Synchronisation…",
@@ -878,7 +879,6 @@ sklm: {
merge: "Fusion des modifications",
upload: "Envoi des modifications",
apply: "Application des modifications",
- cleanup: "Nettoyage",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -930,14 +930,15 @@ sklm: {
mappingsDescription: "Local folders stay device-specific and are never uploaded.",
mappingUnavailable: "Folder unavailable",
historyTitle: "History and restore",
- historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ historyDescription: "Affiche les 30 dernières révisions de ce mode. Les objets chiffrés restent stockés sans limite de durée ; aucun nettoyage automatique du cloud.",
+ restoreBackupConfirm: "Restaurer cette sauvegarde uniquement sur cet appareil ? Un point de récupération local sera créé. L’historique distant reste intact et les changements sensibles nécessitent une approbation.",
refreshHistory: "Refresh history",
currentRevision: "Current revision",
historyItems: "items",
historyEmpty: "No remote revisions are available yet.",
historyLocked: "Unlock the vault to read revision history.",
restore: "Restore",
- restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreConfirm: "Restaurer et publier immédiatement cette révision aux autres appareils ? Un point de récupération local sera créé. Les changements sensibles nécessitent une approbation sur chaque appareil.",
restoreStarted: "Restore staged. Review pending approvals.",
disconnectTitle: "Disconnect",
disconnectDescription:
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 813cc0846..34b7fd997 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -811,9 +811,8 @@ sklm: {
},
configSync: {
title: "Cloud sync",
- connectionTitle: "WebDAV cloud sync",
- connectionDescription:
- "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ connectionTitle: "S3 설정 백업 및 동기화",
+ connectionDescription: "이식 가능한 설정을 비공개 S3 버킷에 암호화하여 저장합니다. 대화, 소스 파일, 런타임 상태는 제외됩니다.",
errorTitle: "Sync needs attention",
errorDetails: "Technical details",
backupPasswordOptional: "Leave this blank to keep the current vault password.",
@@ -821,37 +820,43 @@ sklm: {
previewPending: "Pending activation: {{count}}",
previewConflicts: "Conflicts: {{count}}",
errors: {
- auth: "Check the WebDAV username and app password, then test the connection again.",
- permission: "This account cannot read and write the selected WebDAV directory.",
- notFound: "Check the WebDAV URL and directory. Use the WebDAV endpoint, not the website home page.",
+ auth: "S3 액세스 키, 비밀 키, 세션 토큰, 리전 및 기기 시간을 확인하세요.",
+ permission: "선택한 버킷 접두사에서 읽기, 조건부 쓰기 및 테스트 객체 삭제를 허용하세요.",
+ notFound: "S3 엔드포인트, 리전, 버킷 및 객체 접두사를 확인하세요.",
conflict: "Another device updated this backup. Sync again to merge, then review anything waiting for approval.",
quota: "The remote storage is full. Free space or raise the quota, then retry.",
rateLimit: "The server is rate limiting requests. Retry the sync in a moment.",
- server: "The WebDAV server is temporarily unavailable.",
+ server: "S3 서비스를 일시적으로 사용할 수 없습니다.",
network: "Check the network, address, and certificate, then retry.",
- redirect: "The server redirected the request. Use the direct WebDAV URL.",
- unsupported: "This server does not support the required WebDAV operations. Try compatibility mode.",
+ redirect: "리전의 직접 S3 엔드포인트를 사용하세요. 리디렉션은 따르지 않습니다.",
+ unsupported: "S3 서비스는 신뢰할 수 있는 조건부 쓰기를 지원해야 합니다. 호환 모드는 제공하지 않습니다.",
locked: "Enter the backup password to unlock sync.",
- invalid: "Check the server URL, directory, and required passwords.",
- password: "Use the backup password created for this vault, not the WebDAV password.",
+ invalid: "S3 연결 필드와 필수 자격 증명을 확인하세요.",
+ password: "S3 비밀 키가 아닌 이 볼트의 백업 비밀번호를 사용하세요.",
limit: "The backup is larger than the supported size. Sync fewer categories and retry.",
unknown: "Sync did not finish. Check the connection and retry. Open the technical details if it keeps failing.",
},
- endpoint: "WebDAV URL",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "서버 호환 모드",
- remoteModeHint:
- "엄격 모드는 신뢰할 수 있는 조건부 쓰기를 요구합니다. If-Match/If-None-Match를 무시하는 서버에서만 호환 모드를 사용하세요.",
- remoteModeStrict: "엄격한 CAS (권장)",
- remoteModeAppendOnly: "호환 모드 (추가 전용)",
- appendOnlyWarning:
- "이 모드는 조건부 쓰기를 무시하는 WebDAV 서버용입니다. 다른 장치를 참여시키기 전에 한 장치에서 볼트를 초기화하세요. 장치별 추가 전용 헤드와 원격 기록을 사용하며, 이 볼트를 공유하는 모든 장치가 호환 모드를 사용해야 합니다. 동시 변경은 검토가 필요할 수 있습니다.",
- appendOnlyConfirm:
- "이 서버는 조건부 쓰기를 적용할 수 없습니다. 호환 모드는 기록을 보존하지만 원자적 compare-and-swap을 제공하지 않습니다. 계속하시겠습니까?",
- username: "Username",
- appPassword: "App password",
- appPasswordSavedHint: "이 기기에 안전하게 저장됩니다. 재사용하려면 비워 두세요.",
- directory: "Remote directory",
+ endpoint: "S3 엔드포인트",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "리전",
+ bucket: "비공개 버킷",
+ prefix: "객체 접두사",
+ accessKeyId: "액세스 키 ID",
+ secretAccessKey: "비밀 액세스 키",
+ secretSavedHint: "비워 두면 정확히 같은 연결에 대해 로컬에 저장된 키를 재사용합니다.",
+ sessionToken: "세션 토큰 (선택 사항)",
+ sessionTokenHint: "비워 두면 저장된 토큰을 유지하지만 새 비밀 키를 입력하면 지웁니다. 임시 자격 증명과 함께 새 토큰을 입력하세요.",
+ clearSessionToken: "저장된 세션 토큰 지우기",
+ addressing: "버킷 주소 지정",
+ addressingHint: "공개 다운로드 URL이나 버킷 경로가 포함된 URL 대신 서비스 엔드포인트를 사용하세요.",
+ pathStyle: "경로 방식",
+ virtualHosted: "가상 호스트 방식",
+ mode: "작동 모드",
+ modeHint: "백업은 이 기기만 업로드합니다. 양방향 동기화는 기기 간 변경을 병합하고 적용합니다. 각 모드의 기록은 별도입니다.",
+ modeSync: "양방향 동기화",
+ modeBackup: "백업만",
+ automaticSync: "자동 실행",
+ backupNow: "지금 백업",
deviceLabel: "Device label",
defaultDevice: "This device",
backupPassword: "Backup password",
@@ -861,7 +866,7 @@ sklm: {
currentBackupPassword: "Current vault password",
newBackupPassword: "New vault password",
changePasswordTitle: "Change vault password",
- changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePasswordDescription: "볼트 키를 다시 래핑합니다. 이미 잠금 해제된 기기는 계속 접근할 수 있으며 권한이 취소되지 않습니다.",
changePassword: "Change password",
passwordChanged: "Vault password changed.",
showPassword: "Show password",
@@ -870,12 +875,8 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
- testAppendOnlySuccess:
- "The server supports directory listing for append-only compatibility mode.",
- testAppendOnlyUnsupported:
- "The server did not prove directory listing for compatibility mode; sync is not enabled.",
- enable: "Enable sync",
- save: "Save and sync",
+ enable: "백업 / 동기화 활성화",
+ save: "저장 후 실행",
configured: "Cloud sync configuration saved.",
syncNow: "Sync now",
progressTitle: "동기화 중…",
@@ -886,7 +887,6 @@ sklm: {
merge: "변경 사항 병합 중",
upload: "변경 사항 업로드 중",
apply: "변경 사항 적용 중",
- cleanup: "정리 중",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -938,14 +938,15 @@ sklm: {
mappingsDescription: "Local folders stay device-specific and are never uploaded.",
mappingUnavailable: "Folder unavailable",
historyTitle: "History and restore",
- historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ historyDescription: "현재 모드의 최근 30개 버전을 표시합니다. 암호화된 객체는 무기한 보존되며 클라우드 저장소는 자동 정리되지 않습니다.",
+ restoreBackupConfirm: "이 기기에서만 백업을 복원할까요? 로컬 복구 지점을 저장합니다. 원격 기록은 변경하지 않으며 민감한 변경은 승인이 필요합니다.",
refreshHistory: "Refresh history",
currentRevision: "Current revision",
historyItems: "items",
historyEmpty: "No remote revisions are available yet.",
historyLocked: "Unlock the vault to read revision history.",
restore: "Restore",
- restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreConfirm: "이 버전을 복원하고 즉시 다른 기기에 게시할까요? 로컬 복구 지점을 저장합니다. 민감한 변경은 각 기기에서 승인이 필요합니다.",
restoreStarted: "Restore staged. Review pending approvals.",
disconnectTitle: "Disconnect",
disconnectDescription:
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index ed63f6dd3..a206758d7 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1053,8 +1053,8 @@ export const ptBR = {
},
configSync: {
title: "Sincronização na nuvem",
- connectionTitle: "Sincronização na nuvem via WebDAV",
- connectionDescription: "Sincronize configurações portáteis através de um cofre criptografado WebDAV. O histórico de conversas, arquivos-fonte e estados de execução nunca são incluídos.",
+ connectionTitle: "Backup e sincronização de configurações via S3",
+ connectionDescription: "Criptografe configurações portáteis em um bucket S3 privado. Conversas, arquivos-fonte e estado de execução são excluídos.",
errorTitle: "A sincronização requer atenção",
errorDetails: "Detalhes técnicos",
backupPasswordOptional: "Deixe em branco para manter a senha atual do cofre.",
@@ -1062,34 +1062,43 @@ export const ptBR = {
previewPending: "Ativação pendente: {{count}}",
previewConflicts: "Conflitos: {{count}}",
errors: {
- auth: "Verifique o nome de usuário WebDAV e a senha do aplicativo, depois teste a conexão novamente.",
- permission: "Esta conta não tem permissão para ler e gravar no diretório WebDAV selecionado.",
- notFound: "Verifique a URL e o diretório do WebDAV. Use o endpoint do WebDAV, não a página inicial do site.",
+ auth: "Verifique as chaves S3, o token de sessão, a região e o relógio do dispositivo.",
+ permission: "Permita leitura, gravação condicional e exclusão de objetos de teste no prefixo escolhido.",
+ notFound: "Verifique o endpoint S3, a região, o bucket e o prefixo dos objetos.",
conflict: "Outro dispositivo atualizou este backup. Sincronize novamente para mesclar e revise o que estiver aguardando aprovação.",
- quota: "O armazenamento remoto está cheio. Libere espaço ou aumente a cota no servidor WebDAV e tente novamente.",
+ quota: "O armazenamento remoto está cheio. Libere espaço ou aumente a cota e tente novamente.",
rateLimit: "O servidor está limitando as requisições. Tente sincronizar novamente em alguns instantes.",
- server: "O servidor WebDAV está temporariamente indisponível.",
+ server: "O serviço S3 está temporariamente indisponível.",
network: "Verifique a rede, o endereço e o certificado, depois tente novamente.",
- redirect: "O servidor redirecionou a requisição. Use a URL direta do WebDAV.",
- unsupported: "Este servidor não suporta as operações WebDAV necessárias. Tente o modo de compatibilidade.",
+ redirect: "Use o endpoint regional S3 direto. Redirecionamentos não são seguidos.",
+ unsupported: "O serviço S3 deve oferecer gravações condicionais confiáveis. Não há modo de compatibilidade.",
locked: "Digite a senha do cofre para desbloquear a sincronização.",
- invalid: "Verifique a URL do servidor, o diretório e as senhas necessárias.",
- password: "Use a senha do cofre criada para este cofre, não a senha do WebDAV.",
+ invalid: "Verifique os campos da conexão S3 e as credenciais necessárias.",
+ password: "Use a senha deste cofre, não a chave secreta S3.",
limit: "O backup é maior do que o tamanho suportado. Sincronize menos categorias e tente novamente.",
unknown: "A sincronização não foi concluída. Verifique a conexão e tente novamente. Abra os detalhes técnicos se o problema persistir.",
},
- endpoint: "URL do WebDAV",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Modo de sincronização remota",
- remoteModeHint: "O modo estrito exige suporte confiável a gravações condicionais. Use o modo de compatibilidade somente com servidores que ignoram If-Match/If-None-Match.",
- remoteModeStrict: "CAS estrito (recomendado)",
- remoteModeAppendOnly: "Modo de compatibilidade (somente anexação)",
- appendOnlyWarning: "Este modo é para servidores WebDAV que ignoram gravações condicionais. Inicialize o cofre em um dispositivo antes de conectar outros. Usa cabeçalhos de anexação por dispositivo e preserva o histórico remoto; todos os dispositivos que compartilham este cofre devem usar o modo de compatibilidade. Alterações concorrentes podem exigir revisão.",
- appendOnlyConfirm: "Este modo de servidor não consegue impor gravações condicionais. O modo de compatibilidade preserva o histórico, mas não fornece compare-and-swap atômico. Continuar?",
- username: "Nome de usuário",
- appPassword: "Senha do aplicativo",
- appPasswordSavedHint: "Salva com segurança neste dispositivo. Deixe em branco para reutilizá-la.",
- directory: "Diretório remoto",
+ endpoint: "Endpoint S3",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Região",
+ bucket: "Bucket privado",
+ prefix: "Prefixo dos objetos",
+ accessKeyId: "ID da chave de acesso",
+ secretAccessKey: "Chave de acesso secreta",
+ secretSavedHint: "Deixe em branco para reutilizar a chave local desta mesma conexão.",
+ sessionToken: "Token de sessão (opcional)",
+ sessionTokenHint: "Em branco mantém o token salvo, exceto ao inserir uma nova chave secreta. Informe também um novo token com credenciais temporárias.",
+ clearSessionToken: "Limpar o token de sessão salvo",
+ addressing: "Endereçamento do bucket",
+ addressingHint: "Use o endpoint do serviço, não uma URL pública ou uma URL com o caminho do bucket.",
+ pathStyle: "Por caminho",
+ virtualHosted: "Host virtual",
+ mode: "Modo de operação",
+ modeHint: "O backup apenas envia este dispositivo. A sincronização mescla e aplica mudanças entre dispositivos. Cada modo tem seu próprio histórico.",
+ modeSync: "Sincronização bidirecional",
+ modeBackup: "Somente backup",
+ automaticSync: "Executar automaticamente",
+ backupNow: "Fazer backup agora",
deviceLabel: "Identificação do dispositivo",
defaultDevice: "Este dispositivo",
backupPassword: "Senha do cofre",
@@ -1098,7 +1107,7 @@ export const ptBR = {
currentBackupPassword: "Senha atual do cofre",
newBackupPassword: "Nova senha do cofre",
changePasswordTitle: "Alterar senha do cofre",
- changePasswordDescription: "Reenvelopa a chave do cofre sem recriptografar nem expor dados de configuração.",
+ changePasswordDescription: "Reenvelopa a chave do cofre. Dispositivos já desbloqueados mantêm o acesso; ele não é revogado.",
changePassword: "Alterar senha",
passwordChanged: "Senha do cofre alterada.",
showPassword: "Exibir senha",
@@ -1106,10 +1115,8 @@ export const ptBR = {
test: "Testar servidor",
testSuccess: "O servidor suporta as gravações condicionais necessárias.",
testUnsupported: "O servidor não comprovou suporte a gravações condicionais confiáveis; a sincronização não foi habilitada.",
- testAppendOnlySuccess: "O servidor suporta listagem de diretórios para o modo de compatibilidade somente anexação.",
- testAppendOnlyUnsupported: "O servidor não comprovou suporte à listagem de diretórios para o modo de compatibilidade; a sincronização não foi habilitada.",
- enable: "Habilitar sincronização",
- save: "Salvar e sincronizar",
+ enable: "Habilitar backup / sincronização",
+ save: "Salvar e executar",
configured: "Configuração de sincronização na nuvem salva.",
syncNow: "Sincronizar agora",
progressTitle: "Sincronizando…",
@@ -1120,7 +1127,6 @@ export const ptBR = {
merge: "Mesclando alterações",
upload: "Enviando alterações",
apply: "Aplicando alterações",
- cleanup: "Limpando",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}"
@@ -1169,14 +1175,15 @@ export const ptBR = {
mappingsDescription: "Pastas locais permanecem específicas deste dispositivo e nunca são enviadas.",
mappingUnavailable: "Pasta indisponível",
historyTitle: "Histórico e restauração",
- historyDescription: "A restauração cria uma nova revisão e propaga a configuração selecionada para os dispositivos inscritos.",
+ historyDescription: "Mostra as últimas 30 revisões deste modo. Objetos criptografados são mantidos indefinidamente; não há limpeza automática da nuvem.",
+ restoreBackupConfirm: "Restaurar este backup somente neste dispositivo? Um ponto de recuperação local será salvo. O histórico remoto não muda e alterações sensíveis exigem aprovação.",
refreshHistory: "Atualizar histórico",
currentRevision: "Revisão atual",
historyItems: "itens",
historyEmpty: "Nenhuma revisão remota disponível ainda.",
historyLocked: "Desbloqueie o cofre para visualizar o histórico de revisões.",
restore: "Restaurar",
- restoreConfirm: "Restaurar esta revisão? A configuração restaurada será publicada para outros dispositivos inscritos após aprovação local.",
+ restoreConfirm: "Restaurar e publicar esta revisão imediatamente para outros dispositivos? Um ponto de recuperação local será salvo. Alterações sensíveis exigem aprovação em cada dispositivo.",
restoreStarted: "Restauração preparada. Revise as aprovações pendentes.",
disconnectTitle: "Desconectar",
disconnectDescription: "Preserva os dados locais e mantém o cofre remoto intacto.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 7691dbffe..002d66649 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -811,8 +811,8 @@ sklm: {
},
configSync: {
title: "Bulut senkronizasyonu",
- connectionTitle: "WebDAV bulut senkronizasyonu",
- connectionDescription: "Şifreli bir WebDAV kasası üzerinden taşınabilir yapılandırmayı senkronize edin.",
+ connectionTitle: "S3 yapılandırma yedekleme ve senkronizasyonu",
+ connectionDescription: "Taşınabilir yapılandırmayı özel bir S3 kovasında şifreleyin. Sohbetler, kaynak dosyaları ve çalışma zamanı durumu dahil edilmez.",
errorTitle: "Senkronizasyon dikkat gerektiriyor",
errorDetails: "Teknik ayrıntılar",
backupPasswordOptional: "Geçerli kasa parolasını korumak için bunu boş bırakın.",
@@ -820,37 +820,43 @@ sklm: {
previewPending: "Etkinleştirme bekleniyor: {{count}}",
previewConflicts: "Çakışmalar: {{count}}",
errors: {
- auth: "WebDAV kullanıcı adını ve uygulama parolasını kontrol edip bağlantıyı yeniden test edin.",
- permission: "Bu hesap seçilen WebDAV dizinini okuyup yazamıyor.",
- notFound: "WebDAV URL'sini ve dizini kontrol edin. Web sitesinin ana sayfası yerine WebDAV uç noktasını kullanın.",
+ auth: "S3 erişim anahtarını, gizli anahtarı, oturum belirtecini, bölgeyi ve cihaz saatini kontrol edin.",
+ permission: "Seçilen kova önekinde okuma, koşullu yazma ve test nesnesi silme izinlerini verin.",
+ notFound: "S3 uç noktasını, bölgeyi, kovayı ve nesne önekini kontrol edin.",
conflict: "Başka bir cihaz bu yedeği güncelledi. Birleştirmek için yeniden senkronize edin, ardından onay bekleyenleri inceleyin.",
quota: "Uzak depolama alanı dolu. Yer açın veya kotayı artırın, ardından yeniden deneyin.",
rateLimit: "Sunucu istekleri hız sınırlıyor. Senkronizasyonu biraz sonra yeniden deneyin.",
- server: "WebDAV sunucusu geçici olarak kullanılamıyor.",
+ server: "S3 hizmeti geçici olarak kullanılamıyor.",
network: "Ağı, adresi ve sertifikayı kontrol edip yeniden deneyin.",
- redirect: "Sunucu isteği yeniden yönlendirdi. Doğrudan WebDAV URL'sini kullanın.",
- unsupported: "Bu sunucu gerekli WebDAV işlemlerini desteklemiyor. Uyumluluk modunu deneyin.",
+ redirect: "Doğrudan bölgesel S3 uç noktasını kullanın. Yönlendirmeler izlenmez.",
+ unsupported: "S3 hizmeti güvenilir koşullu yazmayı desteklemelidir. Uyumluluk modu yoktur.",
locked: "Senkronizasyonun kilidini açmak için yedekleme parolasını girin.",
- invalid: "Sunucu URL'sini, dizini ve gerekli parolaları kontrol edin.",
- password: "WebDAV parolası yerine bu kasa için oluşturulan yedekleme parolasını kullanın.",
+ invalid: "S3 bağlantı alanlarını ve gerekli kimlik bilgilerini kontrol edin.",
+ password: "S3 gizli anahtarı yerine bu kasanın yedekleme parolasını kullanın.",
limit: "Yedek, desteklenen boyuttan büyük. Daha az kategoriyi senkronize edip yeniden deneyin.",
unknown: "Senkronizasyon tamamlanmadı. Bağlantıyı kontrol edip yeniden deneyin. Sorun sürerse teknik ayrıntıları açın.",
},
- endpoint: "WebDAV URL'si",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "Sunucu uyumluluğu",
- remoteModeHint:
- "Katı mod güvenilir koşullu yazma işlemleri gerektirir. Uyumluluk modunu yalnızca If-Match/If-None-Match'i yok sayan sunucularda kullanın.",
- remoteModeStrict: "Katı CAS (önerilen)",
- remoteModeAppendOnly: "Uyumluluk modu (yalnızca ekleme)",
- appendOnlyWarning:
- "Bu mod, koşullu yazmaları yok sayan WebDAV sunucuları içindir. Diğer cihazları katmadan önce kasayı bir cihazda başlatın. Cihaz başına ekleme amaçlı başlıklar kullanır ve uzak geçmişi korur; bu kasayı paylaşan tüm cihazlar uyumluluk modunu kullanmalıdır. Eşzamanlı değişiklikler incelenmeyi gerektirebilir.",
- appendOnlyConfirm:
- "Bu sunucu koşullu yazmaları uygulayamıyor. Uyumluluk modu geçmişi korur ancak atomik compare-and-swap sağlayamaz. Devam edilsin mi?",
- username: "Kullanıcı adı",
- appPassword: "Uygulama parolası",
- appPasswordSavedHint: "Bu cihazda güvenle saklanır. Yeniden kullanmak için boş bırakın.",
- directory: "Uzak dizin",
+ endpoint: "S3 uç noktası",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "Bölge",
+ bucket: "Özel kova",
+ prefix: "Nesne öneki",
+ accessKeyId: "Erişim anahtarı kimliği",
+ secretAccessKey: "Gizli erişim anahtarı",
+ secretSavedHint: "Aynı bağlantı için yerel olarak kaydedilen anahtarı kullanmak üzere boş bırakın.",
+ sessionToken: "Oturum belirteci (isteğe bağlı)",
+ sessionTokenHint: "Yeni gizli anahtar girilmedikçe boş alan kayıtlı belirteci korur. Geçici kimlik bilgileriyle yeni belirteci de girin.",
+ clearSessionToken: "Kayıtlı oturum belirtecini temizle",
+ addressing: "Kova adresleme",
+ addressingHint: "Genel indirme URL'si veya kova yolu içeren URL yerine hizmet uç noktasını kullanın.",
+ pathStyle: "Yol biçimi",
+ virtualHosted: "Sanal ana bilgisayar",
+ mode: "Çalışma modu",
+ modeHint: "Yedekleme yalnızca bu cihazı yükler. Çift yönlü senkronizasyon cihazlar arası değişiklikleri birleştirip uygular. Geçmişler ayrıdır.",
+ modeSync: "Çift yönlü senkronizasyon",
+ modeBackup: "Yalnızca yedekleme",
+ automaticSync: "Otomatik çalıştır",
+ backupNow: "Şimdi yedekle",
deviceLabel: "Cihaz etiketi",
defaultDevice: "Bu cihaz",
backupPassword: "Yedekleme parolası",
@@ -859,7 +865,7 @@ sklm: {
currentBackupPassword: "Mevcut kasa parolası",
newBackupPassword: "Yeni kasa parolası",
changePasswordTitle: "Kasa parolasını değiştir",
- changePasswordDescription: "Yapılandırma verilerini açığa çıkarmadan kasa anahtarını yeniden sarar.",
+ changePasswordDescription: "Kasa anahtarını yeniden sarar. Daha önce kilidi açılmış cihazların erişimi korunur; iptal edilmez.",
changePassword: "Parolayı değiştir",
passwordChanged: "Kasa parolası değiştirildi.",
showPassword: "Parolayı göster",
@@ -867,10 +873,8 @@ sklm: {
test: "Sunucuyu test et",
testSuccess: "Sunucu gerekli koşullu yazma işlemlerini destekliyor.",
testUnsupported: "Sunucu güvenilir koşullu yazmayı kanıtlayamadı; senkronizasyon etkinleştirilmedi.",
- testAppendOnlySuccess: "Sunucu, ekleme amaçlı uyumluluk modu için dizin listelemeyi destekliyor.",
- testAppendOnlyUnsupported: "Sunucu, uyumluluk modu için dizin listelemeyi kanıtlayamadı; senkronizasyon etkinleştirilmedi.",
- enable: "Senkronizasyonu etkinleştir",
- save: "Kaydet ve senkronize et",
+ enable: "Yedekleme / senkronizasyonu etkinleştir",
+ save: "Kaydet ve çalıştır",
configured: "Bulut senkronizasyonu yapılandırması kaydedildi.",
syncNow: "Şimdi senkronize et",
progressTitle: "Senkronize ediliyor…",
@@ -881,7 +885,6 @@ sklm: {
merge: "Değişiklikler birleştiriliyor",
upload: "Değişiklikler yükleniyor",
apply: "Değişiklikler uygulanıyor",
- cleanup: "Temizleniyor",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -930,14 +933,15 @@ sklm: {
mappingsDescription: "Yerel klasörler cihaza özeldir ve asla yüklenmez.",
mappingUnavailable: "Klasör kullanılamıyor",
historyTitle: "Geçmiş ve geri yükleme",
- historyDescription: "Geri yükleme yeni bir sürüm oluşturur ve yerel onaylardan sonra yayar.",
+ historyDescription: "Bu modun son 30 sürümünü gösterir. Şifreli nesneler süresiz saklanır; bulut depolaması otomatik temizlenmez.",
+ restoreBackupConfirm: "Bu yedek yalnızca bu cihazda geri yüklensin mi? Yerel kurtarma noktası kaydedilir. Uzak geçmiş değişmez ve hassas değişiklikler onay gerektirir.",
refreshHistory: "Geçmişi yenile",
currentRevision: "Geçerli sürüm",
historyItems: "öğe",
historyEmpty: "Henüz uzak sürüm yok.",
historyLocked: "Sürüm geçmişini okumak için kasanın kilidini açın.",
restore: "Geri yükle",
- restoreConfirm: "Bu sürüm geri yüklensin ve abone cihazlara yayınlansın mı?",
+ restoreConfirm: "Bu sürüm geri yüklenip hemen diğer cihazlara yayınlansın mı? Yerel kurtarma noktası kaydedilir. Hassas değişiklikler her cihazda onay gerektirir.",
restoreStarted: "Geri yükleme hazırlandı. Bekleyen onayları inceleyin.",
disconnectTitle: "Bağlantıyı kes",
disconnectDescription: "Yerel verileri koruyun ve uzak kasaya dokunmayın.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index a3f575865..caef26ec0 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -802,8 +802,8 @@ sklm: {
},
configSync: {
title: "云同步",
- connectionTitle: "WebDAV 云同步",
- connectionDescription: "通过加密的 WebDAV 保管库同步可移植配置。不会包含对话历史、源文件或运行时状态。",
+ connectionTitle: "S3 配置备份与同步",
+ connectionDescription: "将可移植配置加密保存到私有 S3 兼容存储桶,不包含聊天记录、源文件和运行时状态。",
errorTitle: "同步需要处理",
errorDetails: "技术详情",
backupPasswordOptional: "留空则保留当前保管库密码。",
@@ -811,34 +811,43 @@ sklm: {
previewPending: "等待启用:{{count}}",
previewConflicts: "冲突:{{count}}",
errors: {
- auth: "请检查 WebDAV 用户名和应用密码,然后重新测试连接。",
- permission: "请确认这个账户对所选目录有读写权限。",
- notFound: "请检查 WebDAV 地址和目录。应填写 WebDAV 接口地址,而不是网站首页。",
+ auth: "请检查 S3 访问密钥、秘密密钥、临时令牌、区域和设备时间。",
+ permission: "请允许读取、条件写入所选存储桶前缀,并允许删除连接测试对象。",
+ notFound: "请检查 S3 服务地址、区域、存储桶和对象前缀。",
conflict: "另一台设备更新了这份备份。请重新同步合并,并查看等待审批的项目。",
quota: "远程存储空间不足。请释放空间或提高配额后再试。",
rateLimit: "服务器限制了请求频率。请稍后再同步。",
- server: "WebDAV 服务暂时不可用。",
+ server: "S3 服务暂时不可用。",
network: "请检查网络、地址和证书,确认能访问后再试。",
- redirect: "服务器重定向了请求。请改用直接的 WebDAV 地址。",
- unsupported: "服务器不支持所需的 WebDAV 操作。可以试试兼容模式。",
+ redirect: "请使用对应区域的直接 S3 服务地址,不支持重定向。",
+ unsupported: "S3 服务必须可靠支持条件写入,不提供降级兼容模式。",
locked: "请输入备份密码以解锁同步。",
- invalid: "请检查服务器地址、目录和必填密码。",
- password: "请使用创建这份备份时的保管库密码,而不是 WebDAV 密码。",
+ invalid: "请检查 S3 连接字段和必填凭据。",
+ password: "请使用此保管库的备份密码,而不是 S3 秘密密钥。",
limit: "备份超过支持的大小。请减少同步类别后再试。",
unknown: "同步没有完成。请检查连接后再试;如果反复失败,展开技术详情排查。",
},
- endpoint: "WebDAV 地址",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "服务器兼容模式",
- remoteModeHint: "严格模式要求服务器可靠支持条件写入。仅当服务器忽略 If-Match/If-None-Match 时使用兼容模式。",
- remoteModeStrict: "严格 CAS(推荐)",
- remoteModeAppendOnly: "兼容模式(仅追加头)",
- appendOnlyWarning: "此模式用于忽略条件写入的 WebDAV 服务器。请先在一台设备上初始化保管库,再让其他设备加入。它为每台设备使用独立的追加式头并保留远程历史;共享此保管库的所有设备都必须使用兼容模式,并发修改仍可能需要处理冲突。",
- appendOnlyConfirm: "此服务器无法执行条件写入。兼容模式会保留历史,但无法提供原子比较并交换。要继续吗?",
- username: "用户名",
- appPassword: "应用密码",
- appPasswordSavedHint: "已安全保存在本设备。留空即可复用。",
- directory: "远程目录",
+ endpoint: "S3 服务地址",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "区域",
+ bucket: "私有存储桶",
+ prefix: "对象前缀",
+ accessKeyId: "访问密钥 ID",
+ secretAccessKey: "秘密访问密钥",
+ secretSavedHint: "留空可复用本机保存的密钥,仅限连接信息完全相同的情况。",
+ sessionToken: "临时会话令牌(可选)",
+ sessionTokenHint: "留空保留已存令牌;输入新秘密密钥时则清空旧令牌。使用临时凭据时请同时填写新令牌。",
+ clearSessionToken: "清除已保存的临时令牌",
+ addressing: "存储桶寻址方式",
+ addressingHint: "填写服务端点,不要填写公开下载地址或包含存储桶路径的地址。",
+ pathStyle: "路径式",
+ virtualHosted: "虚拟主机式",
+ mode: "运行模式",
+ modeHint: "仅备份只上传本机配置;双向同步会合并并应用其他设备的改动。两种模式使用独立历史。",
+ modeSync: "双向同步",
+ modeBackup: "仅备份",
+ automaticSync: "自动运行",
+ backupNow: "立即备份",
deviceLabel: "设备名称",
defaultDevice: "此设备",
backupPassword: "备份密码",
@@ -847,7 +856,7 @@ sklm: {
currentBackupPassword: "当前保管库密码",
newBackupPassword: "新的保管库密码",
changePasswordTitle: "更改保管库密码",
- changePasswordDescription: "仅重新包装保管库密钥,不会暴露配置数据。",
+ changePasswordDescription: "仅重新包装保管库密钥,不暴露数据。已解锁设备仍可访问,更改密码不会撤销其权限。",
changePassword: "更改密码",
passwordChanged: "保管库密码已更改。",
showPassword: "显示密码",
@@ -855,10 +864,8 @@ sklm: {
test: "测试服务器",
testSuccess: "服务器支持所需的条件写入。",
testUnsupported: "服务器未能证明支持可靠的条件写入,未启用同步。",
- testAppendOnlySuccess: "服务器支持兼容模式所需的目录列表。",
- testAppendOnlyUnsupported: "服务器未能证明支持兼容模式所需的目录列表,未启用同步。",
- enable: "启用同步",
- save: "保存并同步",
+ enable: "启用备份 / 同步",
+ save: "保存并运行",
configured: "云同步配置已保存。",
syncNow: "立即同步",
progressTitle: "正在同步…",
@@ -869,7 +876,6 @@ sklm: {
merge: "正在合并改动",
upload: "正在上传改动",
apply: "正在应用改动",
- cleanup: "正在清理",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -918,14 +924,15 @@ sklm: {
mappingsDescription: "本地文件夹仅保留在设备上,不会上传。",
mappingUnavailable: "文件夹不可用",
historyTitle: "历史与恢复",
- historyDescription: "恢复会创建新版本,并在本地审批后同步到已订阅设备。",
+ historyDescription: "显示当前模式最近 30 个版本。加密对象长期保留,不会自动清理云端存储。",
+ restoreBackupConfirm: "仅在本机恢复此备份?操作前会保存本地恢复点,不改动云端历史,敏感变更仍需审批。",
refreshHistory: "刷新历史",
currentRevision: "当前版本",
historyItems: "项",
historyEmpty: "暂时没有可用的远程版本。",
historyLocked: "解锁保管库后才能读取版本历史。",
restore: "恢复",
- restoreConfirm: "恢复此版本,并将其发布到已订阅设备吗?",
+ restoreConfirm: "恢复并立即将此版本发布给其他设备?操作前会保存本地恢复点,各设备仍需审批敏感变更。",
restoreStarted: "恢复已暂存,请检查待处理的本地审批。",
disconnectTitle: "断开连接",
disconnectDescription: "保留本地数据,不修改远程保管库。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index ee2adf54e..972bfb793 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -802,8 +802,8 @@ sklm: {
},
configSync: {
title: "雲端同步",
- connectionTitle: "WebDAV 雲端同步",
- connectionDescription: "透過加密的 WebDAV 保管庫同步可攜式設定。不會包含對話記錄、原始碼或執行階段狀態。",
+ connectionTitle: "S3 設定備份與同步",
+ connectionDescription: "將可攜式設定加密儲存到私有 S3 相容儲存桶,不包含聊天記錄、原始碼和執行階段狀態。",
errorTitle: "同步需要處理",
errorDetails: "技術詳情",
backupPasswordOptional: "留空則保留目前的保管庫密碼。",
@@ -811,34 +811,43 @@ sklm: {
previewPending: "等待啟用:{{count}}",
previewConflicts: "衝突:{{count}}",
errors: {
- auth: "請檢查 WebDAV 使用者名稱和應用程式密碼,然後重新測試連線。",
- permission: "請確認這個帳戶對所選目錄有讀寫權限。",
- notFound: "請檢查 WebDAV 網址和目錄。應填寫 WebDAV 介面網址,而不是網站首頁。",
+ auth: "請檢查 S3 存取金鑰、秘密金鑰、暫時權杖、區域和裝置時間。",
+ permission: "請允許讀取、條件寫入所選儲存桶前綴,並允許刪除連線測試物件。",
+ notFound: "請檢查 S3 服務網址、區域、儲存桶和物件前綴。",
conflict: "另一台裝置更新了這份備份。請重新同步合併,並查看等待核准的項目。",
quota: "遠端儲存空間不足。請釋放空間或提高配額後再試。",
rateLimit: "伺服器限制了請求頻率。請稍後再同步。",
- server: "WebDAV 服務暫時無法使用。",
+ server: "S3 服務暫時無法使用。",
network: "請檢查網路、網址和憑證,確認能連線後再試。",
- redirect: "伺服器重新導向了請求。請改用直接的 WebDAV 網址。",
- unsupported: "伺服器不支援所需的 WebDAV 操作。可以試試相容模式。",
+ redirect: "請使用對應區域的直接 S3 服務網址,不支援重新導向。",
+ unsupported: "S3 服務必須可靠支援條件寫入,不提供降級相容模式。",
locked: "請輸入備份密碼以解除鎖定同步。",
- invalid: "請檢查伺服器網址、目錄和必填密碼。",
- password: "請使用建立這份備份時的保管庫密碼,而不是 WebDAV 密碼。",
+ invalid: "請檢查 S3 連線欄位和必填憑據。",
+ password: "請使用此保管庫的備份密碼,而不是 S3 秘密金鑰。",
limit: "備份超過支援的大小。請減少同步類別後再試。",
unknown: "同步沒有完成。請檢查連線後再試;如果反覆失敗,展開技術詳情排查。",
},
- endpoint: "WebDAV 網址",
- endpointPlaceholder: "https://dav.example.com/",
- remoteMode: "伺服器相容模式",
- remoteModeHint: "嚴格模式要求伺服器可靠支援條件寫入。僅在伺服器忽略 If-Match/If-None-Match 時使用相容模式。",
- remoteModeStrict: "嚴格 CAS(推薦)",
- remoteModeAppendOnly: "相容模式(僅追加標頭)",
- appendOnlyWarning: "此模式適用於忽略條件寫入的 WebDAV 伺服器。請先在一部裝置上初始化保管庫,再讓其他裝置加入。它會為每部裝置使用獨立的追加式標頭並保留遠端歷史;共用此保管庫的所有裝置都必須使用相容模式,並行修改仍可能需要處理衝突。",
- appendOnlyConfirm: "此伺服器無法執行條件寫入。相容模式會保留歷史,但無法提供原子比較並交換。要繼續嗎?",
- username: "使用者名稱",
- appPassword: "應用程式密碼",
- appPasswordSavedHint: "已安全儲存在此裝置。留白即可重複使用。",
- directory: "遠端目錄",
+ endpoint: "S3 服務網址",
+ endpointPlaceholder: "https://s3.example.com",
+ region: "區域",
+ bucket: "私有儲存桶",
+ prefix: "物件前綴",
+ accessKeyId: "存取金鑰 ID",
+ secretAccessKey: "秘密存取金鑰",
+ secretSavedHint: "留空可重用本機儲存的金鑰,僅限連線資訊完全相同的情況。",
+ sessionToken: "暫時工作階段權杖(選填)",
+ sessionTokenHint: "留空保留已存權杖;輸入新秘密金鑰時則清空舊權杖。使用暫時憑據時請同時填寫新權杖。",
+ clearSessionToken: "清除已儲存的暫時權杖",
+ addressing: "儲存桶定址方式",
+ addressingHint: "填寫服務端點,不要填寫公開下載網址或包含儲存桶路徑的網址。",
+ pathStyle: "路徑式",
+ virtualHosted: "虛擬主機式",
+ mode: "執行模式",
+ modeHint: "僅備份只上傳本機設定;雙向同步會合併並套用其他裝置的變更。兩種模式使用獨立歷史。",
+ modeSync: "雙向同步",
+ modeBackup: "僅備份",
+ automaticSync: "自動執行",
+ backupNow: "立即備份",
deviceLabel: "裝置名稱",
defaultDevice: "此裝置",
backupPassword: "備份密碼",
@@ -847,7 +856,7 @@ sklm: {
currentBackupPassword: "目前保管庫密碼",
newBackupPassword: "新的保管庫密碼",
changePasswordTitle: "變更保管庫密碼",
- changePasswordDescription: "只重新包裝保管庫金鑰,不會暴露設定資料。",
+ changePasswordDescription: "只重新包裝保管庫金鑰,不暴露資料。已解鎖裝置仍可存取,更改密碼不會撤銷其權限。",
changePassword: "變更密碼",
passwordChanged: "保管庫密碼已變更。",
showPassword: "顯示密碼",
@@ -855,10 +864,8 @@ sklm: {
test: "測試伺服器",
testSuccess: "伺服器支援必要的條件寫入。",
testUnsupported: "伺服器未能證明支援可靠的條件寫入,因此未啟用同步。",
- testAppendOnlySuccess: "伺服器支援相容模式所需的目錄列表。",
- testAppendOnlyUnsupported: "伺服器未能證明支援相容模式所需的目錄列表,因此未啟用同步。",
- enable: "啟用同步",
- save: "儲存並同步",
+ enable: "啟用備份 / 同步",
+ save: "儲存並執行",
configured: "雲端同步設定已儲存。",
syncNow: "立即同步",
progressTitle: "正在同步…",
@@ -869,7 +876,6 @@ sklm: {
merge: "正在合併變更",
upload: "正在上傳變更",
apply: "正在套用變更",
- cleanup: "正在清理",
},
objects: "{{done}} / {{total}}",
bytes: "{{done}} / {{total}}",
@@ -918,14 +924,15 @@ sklm: {
mappingsDescription: "本機資料夾只保留在裝置上,不會上傳。",
mappingUnavailable: "資料夾無法使用",
historyTitle: "歷史與還原",
- historyDescription: "還原會建立新版本,並在本機核准後同步到已訂閱裝置。",
+ historyDescription: "顯示目前模式最近 30 個版本。加密物件長期保留,不會自動清理雲端儲存。",
+ restoreBackupConfirm: "僅在本機還原此備份?操作前會儲存本機還原點,不更動雲端歷史,敏感變更仍需核准。",
refreshHistory: "重新整理歷史",
currentRevision: "目前版本",
historyItems: "項",
historyEmpty: "目前沒有可用的遠端版本。",
historyLocked: "解鎖保管庫後才能讀取版本歷史。",
restore: "還原",
- restoreConfirm: "要還原此版本並發布到已訂閱裝置嗎?",
+ restoreConfirm: "還原並立即將此版本發布給其他裝置?操作前會儲存本機還原點,各裝置仍需核准敏感變更。",
restoreStarted: "還原已暫存,請檢查待處理的本機核准。",
disconnectTitle: "中斷連線",
disconnectDescription: "保留本機資料,不修改遠端保管庫。",
diff --git a/packages/shared/src/types/config-sync.ts b/packages/shared/src/types/config-sync.ts
index dbc01d550..b57652010 100644
--- a/packages/shared/src/types/config-sync.ts
+++ b/packages/shared/src/types/config-sync.ts
@@ -1,9 +1,9 @@
/**
* Public contracts for the Host-owned portable configuration synchronizer.
*
- * These types intentionally contain status and redacted summaries only. Raw
- * WebDAV credentials, vault keys, backup passwords, and portable secret values
- * never cross the Host/Preload boundary.
+ * Responses contain redacted status only. S3 secrets and backup passwords are
+ * accepted as transient inputs; vault keys and portable secret values are
+ * never returned to the renderer.
*/
export const CONFIG_SYNC_CATEGORIES = [
@@ -35,33 +35,31 @@ export type ConfigSyncStatus =
| "paused"
| "error";
-export type ConfigSyncRemoteMode = "strict" | "appendOnly";
+export type ConfigSyncMode = "sync" | "backup";
export type ConfigSyncCategorySelection = Record<ConfigSyncCategory, boolean>;
/**
* The step a run is in. `capture` collects the local snapshot, `download` reads
* the remote revision's resources, `merge` reconciles both, `upload` writes the
- * merged revision's resources, `apply` writes the result locally, and `cleanup`
- * deletes revisions the retention window no longer keeps.
+ * merged revision's resources, and `apply` writes the result locally.
+ * Immutable remote objects are retained; there is no physical cleanup phase.
*/
export type ConfigSyncPhase =
| "capture"
| "download"
| "merge"
| "upload"
- | "apply"
- | "cleanup";
+ | "apply";
/**
* What a running sync is doing, reported while it runs.
*
* The sync is a single request, so without these the interface has nothing to
* show between the click and the answer. `done`/`total` are that phase's units
- * — objects for `download`/`upload` (the device tips being read, in append-only
- * mode) and entities for `capture`/`merge`/`apply`, while `cleanup` reports the
- * phase without counting it — and `total === 0` means the size of the phase is
- * not known in advance. `bytesDone`/`bytesTotal` are a byte pair that only
+ * — objects for `download`/`upload` and entities for `capture`/`merge`/`apply`.
+ * `total === 0` means the size of the phase is not known in advance.
+ * `bytesDone`/`bytesTotal` are a byte pair that only
* `upload` reports in full — `download` reports `bytesDone` alone, because a
* remote manifest names resources by id rather than by length — and
* `bytesTotal === 0` means the byte count is not known.
@@ -73,12 +71,18 @@ export type ConfigSyncProgress = {
bytesDone: number;
bytesTotal: number;
};
-export type ConfigSyncPreferences = {
+export type ConfigSyncConnection = {
endpoint: string;
- username: string;
- directory: string;
+ region: string;
+ bucket: string;
+ prefix: string;
+ accessKeyId: string;
+ pathStyle: boolean;
+};
+
+export type ConfigSyncPreferences = ConfigSyncConnection & {
deviceLabel: string;
- remoteMode?: ConfigSyncRemoteMode;
+ mode: ConfigSyncMode;
categories: ConfigSyncCategorySelection;
includeSecrets: boolean;
includeMemory: boolean;
@@ -134,10 +138,13 @@ export type ConfigSyncState = {
locked: boolean;
status: ConfigSyncStatus;
endpoint?: string;
- username?: string;
- directory?: string;
+ region?: string;
+ bucket?: string;
+ prefix?: string;
+ accessKeyId?: string;
+ pathStyle: boolean;
deviceLabel?: string;
- remoteMode: ConfigSyncRemoteMode;
+ mode: ConfigSyncMode;
categories: ConfigSyncCategorySelection;
includeSecrets: boolean;
includeMemory: boolean;
@@ -153,20 +160,28 @@ export type ConfigSyncState = {
export type ConfigSyncConfigureInput = {
endpoint: string;
- username: string;
- /** Supplied only when changing the WebDAV credential. */
- appPassword?: string;
- directory: string;
+ region: string;
+ bucket: string;
+ prefix: string;
+ accessKeyId: string;
+ /** Omitted fields reuse saved credentials only for the same connection. */
+ secretAccessKey?: string;
+ /** Empty string explicitly clears a saved session token. */
+ sessionToken?: string;
+ pathStyle?: boolean;
deviceLabel: string;
/** Required when creating or unlocking the encrypted vault. */
backupPassword: string;
- remoteMode?: ConfigSyncRemoteMode;
+ mode?: ConfigSyncMode;
categories?: Partial<ConfigSyncCategorySelection>;
includeSecrets?: boolean;
includeMemory?: boolean;
automaticSync?: boolean;
};
+export type ConfigSyncTestInput = Omit<ConfigSyncConfigureInput, "backupPassword">;
+export type ConfigSyncTestResult = { ok: true; conditionalWrites: true };
+
export type ConfigSyncApprovalInput = {
approvalId: string;
digest: string;
diff --git a/scripts/README.md b/scripts/README.md
index 959845f07..0ae5da379 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -60,11 +60,35 @@ The scenarios are specified in
| `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior |
| `e2e-transcript-render.mjs` | `pnpm test:e2e:transcript` | Production transcript render boundaries, runtime status geometry, and deterministic smooth-text cadence |
| `e2e-renderer-responsiveness.mjs` | `pnpm test:e2e:renderer-responsiveness` | Native Electron click, typing, session switching, disclosure, and scroll while an isolated child process streams large transcript deltas |
-| `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Two isolated host-core devices against an ephemeral local WebDAV fixture; covers encrypted sync, new-device approval, cross-device edits, conditional requests, and ciphertext-only remote storage |
+| `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Four isolated host-core processes against a SigV4-validating local S3 fixture; covers credential opt-out, approvals, concurrent edits/conflict resolution, mapped skill resources, deletion, sync/backup restore, restart, password rewrap, encrypted storage and cleanup |
| `e2e-supervision.mjs` | `pnpm test:e2e:supervision` | Process supervision and restart behavior |
| `e2e-subagents.mjs` | `pnpm test:e2e:subagents` | Subagent registry over RPC, then through the real loader (D202) |
| `e2e-agent-live.mjs` | `node scripts/e2e-agent-live.mjs` | Live streaming chat through agent-runtime + host-core. Requires `PI_DESKTOP_TEST_API_KEY`, `PI_DESKTOP_TEST_BASE_URL`, and `PI_DESKTOP_TEST_MODEL` (no defaults), so it has no `pnpm` alias |
+### Configuration-sync live S3 opt-in
+
+Build the task's Host binary and shared package first, reusing the existing
+development toolchain. Set `PI_DESKTOP_HOST_BIN` if the binary is outside the
+worktree. The default command uses only local S3 and temporary Host profiles.
+With explicit authorization, run:
+
+```bash
+node scripts/e2e-config-sync-multidevice.mjs --live-s3 --env-file /authorized/path/.env
+```
+
+Live administration needs an existing Python 3 + boto3 environment. The file
+must provide `S3_HOST`, `S3_REGION`, `S3_BUCKET`, `S3_ACCESS_KEY`,
+`S3_SECRET_KEY`, `S3_DOMAIN_MODE` (`false` = path-style), and optionally
+`S3_SESSION_TOKEN`. Credentials stay in memory/stdin, never arguments or logs.
+The harness creates its own UUID prefix under `pi-desktop-tests/`, checks
+initial emptiness, then runs the same actual Host journey. It needs scoped
+list/get/put/delete and bucket-versioning read permission; versioned buckets
+also need version listing/deletion. It stops every Host before deleting only
+the exact test-prefix inventory, including versions/delete markers, and checks
+final emptiness. Failed preflight never grants cleanup ownership. No production
+Desktop profile, model call or executable capability is used. Output records
+the candidate/base and Host binary hash; uncommitted task changes are explicit.
+
## Continuous integration
`.github/workflows/ci.yml` runs two jobs on pushes to `main`, on pull requests,
diff --git a/scripts/e2e-config-sync-multidevice.mjs b/scripts/e2e-config-sync-multidevice.mjs
index 5f8b40277..5b385b637 100644
--- a/scripts/e2e-config-sync-multidevice.mjs
+++ b/scripts/e2e-config-sync-multidevice.mjs
@@ -1,323 +1,86 @@
#!/usr/bin/env node
-/**
- * Two-device configuration-sync E2E against an ephemeral local WebDAV server.
- *
- * The fixture is intentionally in this script instead of using a real account:
- * it proves conditional writes, encrypted remote objects, and the approval
- * boundary without network credentials or production data. Each Host process
- * has its own data directory, while both point at the same WebDAV collection.
- */
+/** Actual isolated Host processes; local S3 by default, authorized live S3 by opt-in. */
import assert from "node:assert/strict";
-import { createServer } from "node:http";
-import { mkdtemp, rm } from "node:fs/promises";
+import { randomUUID, createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
-
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
import { Host, resolveHostBinary } from "./e2e/host.mjs";
-
-const PASSWORD = "portable-backup-password";
-const WEBDAV_USERNAME = "alice";
-const WEBDAV_PASSWORD = "webdav-fixture-password";
-
-function xmlEscape(value) {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;")
- .replaceAll('"', "&quot;")
- .replaceAll("'", "&apos;");
-}
-
-async function readBody(request) {
- const chunks = [];
- for await (const chunk of request) chunks.push(chunk);
- return Buffer.concat(chunks);
-}
-
-function normalizePath(rawPath) {
- return decodeURIComponent(rawPath).replace(/^\/+|\/+$/g, "");
-}
-
-async function startWebDavFixture() {
- const state = {
- collections: new Set(["dav"]),
- objects: new Map(),
- nextEtag: 0,
- requests: [],
- };
-
- const server = createServer(async (request, response) => {
- const path = normalizePath(
- new URL(request.url ?? "/", "http://127.0.0.1").pathname,
- );
- const method = request.method ?? "GET";
- const body = method === "PUT" ? await readBody(request) : Buffer.alloc(0);
- state.requests.push({ method, path });
-
- const send = (status, payload = Buffer.alloc(0), headers = {}) => {
- response.writeHead(status, {
- "Content-Length": payload.length,
- Connection: "close",
- ...headers,
- });
- response.end(payload);
- };
-
- const expectedAuthorization = `Basic ${Buffer.from(
- `${WEBDAV_USERNAME}:${WEBDAV_PASSWORD}`,
- ).toString("base64")}`;
- if (request.headers.authorization !== expectedAuthorization) {
- return send(401, Buffer.alloc(0), { "WWW-Authenticate": 'Basic realm="fixture"' });
- }
-
- if (method === "MKCOL") {
- const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
- if (parent && !state.collections.has(parent)) return send(409);
- if (state.collections.has(path)) return send(405);
- state.collections.add(path);
- return send(201);
- }
-
- if (method === "GET") {
- const value = state.objects.get(path);
- if (!value) return send(404);
- return send(200, value.body, { ETag: `"${value.etag}"` });
- }
-
- if (method === "PROPFIND") {
- if (!state.collections.has(path)) return send(404);
- const prefix = `${path}/`;
- const entries = new Set([`${path}/`]);
- for (const candidate of [...state.collections, ...state.objects.keys()]) {
- if (
- candidate.startsWith(prefix) &&
- !candidate.slice(prefix.length).includes("/")
- ) {
- entries.add(candidate);
- }
- }
- const xml = [
- '<?xml version="1.0" encoding="utf-8"?>',
- '<D:multistatus xmlns:D="DAV:">',
- ...[...entries].map(
- (entry) => `<D:response><D:href>/${xmlEscape(entry)}</D:href></D:response>`,
- ),
- "</D:multistatus>",
- ].join("");
- return send(207, Buffer.from(xml), { "Content-Type": "application/xml" });
- }
-
- if (method === "PUT") {
- const existing = state.objects.get(path);
- const ifNoneMatch = request.headers["if-none-match"];
- const ifMatch = request.headers["if-match"];
- if (
- (ifNoneMatch === "*" && existing) ||
- (ifMatch && (!existing || ifMatch !== `"${existing.etag}"`))
- ) {
- return send(412);
- }
- const etag = ++state.nextEtag;
- state.objects.set(path, { body, etag });
- return send(201, Buffer.alloc(0), { ETag: `"${etag}"` });
- }
-
- if (method === "DELETE") {
- state.objects.delete(path);
- return send(204);
- }
-
- return send(405);
- });
-
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- const address = server.address();
- assert.equal(typeof address, "object");
- return {
- endpoint: `http://127.0.0.1:${address.port}/dav/`,
- state,
- close: () =>
- new Promise((resolve, reject) =>
- server.close((error) => (error ? reject(error) : resolve())),
- ),
- };
-}
-
-function syncConfig(endpoint, deviceLabel, appPassword, backupPassword = PASSWORD) {
- const config = {
- endpoint,
- username: WEBDAV_USERNAME,
- directory: "pi-desktop",
- deviceLabel,
- backupPassword,
- categories: {
- application: true,
- providers: true,
- credentials: false,
- mcp: true,
- skills: true,
- subagents: true,
- instructions: true,
- projects: true,
- plugins: true,
- automation: true,
- memory: false,
- },
- includeSecrets: false,
- includeMemory: false,
- automaticSync: false,
- remoteMode: "strict",
- };
- if (appPassword !== undefined) config.appPassword = appPassword;
- return config;
-}
-
-async function approveAll(host, state) {
- let next = state;
- for (let attempt = 0; next.pendingApprovals.length > 0; attempt += 1) {
- assert.ok(attempt < 64, "approval queue did not converge");
- const item = next.pendingApprovals[0];
- next = await host.call(
- "configSync.approve",
- { approvalId: item.id, digest: item.digest },
- 120_000,
- );
- }
- return next;
-}
-
-const fixture = await startWebDavFixture();
-const dataRoot = await mkdtemp(join(tmpdir(), "pi-config-sync-multidevice-"));
-const hostBinary = resolveHostBinary();
-const hostA = new Host(hostBinary, join(dataRoot, "device-a"));
-const hostB = new Host(hostBinary, join(dataRoot, "device-b"));
-const previousAgentsDir = process.env.PI_DESKTOP_AGENTS_DIR;
-process.env.PI_DESKTOP_AGENTS_DIR = join(dataRoot, "agents");
-
+import { startS3Fixture } from "./e2e/config-sync-s3-fixture.mjs";
+import { MARKERS, PASSWORD, rpc, runSyncJourney, runBackupJourney } from "./e2e/config-sync-journey.mjs";
+
+const { values } = parseArgs({ options: { "live-s3": { type: "boolean" }, "env-file": { type: "string" } } });
+if (Boolean(values["live-s3"]) !== Boolean(values["env-file"])) throw new Error("Live tests require both --live-s3 and --env-file");
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+const prefix = `pi-desktop-tests/s3-config-sync-${randomUUID()}`;
+const binary = resolveHostBinary();
+const revision = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim();
+const base = execFileSync("git", ["rev-parse", "origin/main"], { cwd: root, encoding: "utf8" }).trim();
+execFileSync("git", ["merge-base", "--is-ancestor", "origin/main", "HEAD"], { cwd: root });
+const binarySha256 = createHash("sha256").update(await readFile(binary)).digest("hex");
+const dataRoot = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "pi-config-sync-e2e-"));
+const hosts = [];
+const errors = [];
+let store;
+let report;
+let cleanup;
+let currentStep = "setup";
+const step = (name) => { currentStep = name; console.log(`CONFIG_SYNC_STEP ${name}`); };
try {
- await Promise.all([hostA.start(), hostB.start()]);
- // The fixture intentionally uses loopback HTTP. Set the same explicit
- // relaxed LAN policy a user would choose before entering a plaintext URL.
- await Promise.all([
- hostA.call("settings.set", { networkPolicy: { mode: "relaxed" } }),
- hostB.call("settings.set", { networkPolicy: { mode: "relaxed" } }),
- ]);
-
- const configuredA = await hostA.call(
- "configSync.configure",
- syncConfig(fixture.endpoint, "Device A", WEBDAV_PASSWORD),
- 120_000,
- );
- assert.equal(configuredA.configured, true);
- assert.equal(configuredA.remoteMode, "strict");
-
- // Re-saving with the same endpoint/account and no appPassword must reuse
- // the Host-owned WebDAV secret instead of asking the renderer for it again.
- const reusedPasswordA = await hostA.call(
- "configSync.configure",
- syncConfig(fixture.endpoint, "Device A", undefined, ""),
- 120_000,
- );
- assert.equal(reusedPasswordA.configured, true);
-
- await hostA.call("configSync.syncNow", {}, 120_000);
- const { provider: sharedProvider } = await hostA.call("providers.create", {
- name: "Shared provider",
- vendorKey: "webdav-fixture",
- type: "openai_compatible",
- protocol: "openai_compatible",
- authKind: "api_key_and_base_url",
- secretValue: "fixture-provider-secret",
- baseUrl: "http://127.0.0.1:9/v1",
- apiStyle: "chat_completions",
- defaultModelId: "shared-model",
- models: [{
- id: "shared-model",
- contextWindow: 128_000,
- maxTokens: 8_192,
- thinkingLevels: ["off"],
- defaultThinkingLevel: "off",
- }],
- });
- await hostA.call("configSync.syncNow", {}, 120_000);
-
- const configuredB = await hostB.call(
- "configSync.configure",
- syncConfig(fixture.endpoint, "Device B", WEBDAV_PASSWORD),
- 120_000,
- );
- assert.equal(configuredB.configured, true);
- assert.equal(configuredB.endpoint, fixture.endpoint);
-
- const reusedPasswordB = await hostB.call(
- "configSync.configure",
- syncConfig(fixture.endpoint, "Device B", undefined, ""),
- 120_000,
- );
- assert.equal(reusedPasswordB.configured, true);
-
- let stateB = await hostB.call("configSync.syncNow", {}, 120_000);
- assert.ok(
- stateB.pendingApprovals.some((item) => item.entityId.includes(sharedProvider.id)),
- `device B should stage device A's provider for local approval (provider=${sharedProvider.id}, pending=${JSON.stringify(
- stateB.pendingApprovals.map((item) => ({
- entityId: item.entityId,
- label: item.label,
- reason: item.reason,
- })),
- )})`,
- );
- stateB = await approveAll(hostB, stateB);
- assert.equal(stateB.pendingApprovals.length, 0);
-
- const providersB = await hostB.call("providers.list", { includeDisabled: true });
- assert.ok(
- providersB.providers.some((provider) => provider.name === "Shared provider"),
- "approved provider should be available on device B",
- );
-
- await hostB.call("settings.set", { theme: "light" });
- const stateAfterLocalEdit = await hostB.call("configSync.syncNow", {}, 120_000);
- assert.ok(["upToDate", "localChangesPending"].includes(stateAfterLocalEdit.status));
- const stateA = await hostA.call("configSync.syncNow", {}, 120_000);
- assert.notEqual(stateA.status, "error");
-
- const immutableFiles = [...fixture.state.objects.keys()].filter(
- (path) => path.includes("/revisions/") || path.includes("/objects/"),
- );
- assert.ok(
- immutableFiles.length > 0,
- "WebDAV should contain encrypted immutable files",
- );
- const remotePayloads = [...fixture.state.objects.values()].map(({ body }) => body.toString("utf8"));
- assert.ok(
- remotePayloads.every((payload) => !payload.includes("Shared provider")),
- "WebDAV payloads must not expose provider labels in plaintext",
- );
- assert.ok(
- remotePayloads.every((payload) => !payload.includes("fixture-provider-secret")),
- "WebDAV payloads must not expose provider secrets in plaintext",
- );
- assert.ok(
- fixture.state.requests.some(({ method }) => method === "PROPFIND"),
- "fixture should observe WebDAV capability/listing requests",
- );
- console.log(
- "CONFIG_SYNC_MULTIDEVICE " +
- JSON.stringify({
- endpoint: fixture.endpoint,
- devices: 2,
- providerId: sharedProvider.id,
- remoteObjects: immutableFiles.length,
- requests: fixture.state.requests.length,
- statusA: stateA.status,
- statusB: stateAfterLocalEdit.status,
- }),
- );
+ store = values["live-s3"]
+ ? await (await import("./e2e/config-sync-live-s3.mjs")).openLiveS3(values["env-file"], prefix)
+ : await startS3Fixture(prefix);
+ assert.equal((await store.inventory()).length, 0, "new test namespace must be empty");
+ console.log(`CONFIG_SYNC_NAMESPACE ${prefix}`);
+ for (const name of ["a", "b", "c", "d"]) {
+ const home = join(dataRoot, name, "home");
+ await mkdir(home, { recursive: true });
+ hosts.push(new Host(binary, join(dataRoot, name, "data"), {
+ env: { HOME: home, USERPROFILE: home, PI_DESKTOP_AGENTS_DIR: join(home, "agents"), XDG_CONFIG_HOME: join(home, ".config"), DEBUG_HOST: "" },
+ quiet: Boolean(values["live-s3"]),
+ }));
+ }
+ await Promise.all(hosts.map((host) => host.start()));
+ await Promise.all(hosts.map((host) => rpc(host, "settings.set", { networkPolicy: { mode: "relaxed" } })));
+ const [a, b, c, d] = hosts;
+ const context = { a, b, c, d, connection: store.connection, store, step };
+ await runSyncJourney(context);
+ await runBackupJourney(context);
+ step("ciphertext-retention-and-disconnect");
+ const inventory = await store.inventory();
+ assert.ok(inventory.some((key) => key.includes("/revisions/")));
+ assert.ok(inventory.some((key) => key.includes("/objects/")));
+ const inspected = await store.inspect([...MARKERS, PASSWORD, store.connection.secretAccessKey, store.connection.sessionToken].filter(Boolean));
+ for (const host of hosts) assert.equal((await rpc(host, "configSync.disconnect")).configured, false);
+ assert.deepEqual(await store.inventory(), inventory, "disconnect must not delete remote data");
+ report = { mode: values["live-s3"] ? "live-s3" : "local-s3", devices: hosts.length, prefix, candidate: revision, base, workingDiff: true, binarySha256, ...inspected };
+} catch (error) {
+ errors.push(error);
} finally {
- await Promise.all([hostA.stop(), hostB.stop()]).catch(() => undefined);
- await fixture.close().catch(() => undefined);
- await rm(dataRoot, { recursive: true, force: true });
- if (previousAgentsDir === undefined) delete process.env.PI_DESKTOP_AGENTS_DIR;
- else process.env.PI_DESKTOP_AGENTS_DIR = previousAgentsDir;
+ const stopped = await Promise.allSettled(hosts.map((host) => host.stop()));
+ for (const result of stopped) if (result.status === "rejected") errors.push(result.reason);
+ if (store) {
+ try {
+ assert.ok(stopped.every((result) => result.status === "fulfilled"), "refusing cloud cleanup while a Host may still publish");
+ cleanup = await store.cleanup();
+ assert.equal(cleanup.remaining, 0);
+ assert.equal(cleanup.versions, 0);
+ } catch (error) { errors.push(error); }
+ try { await store.close(); } catch (error) { errors.push(error); }
+ }
+ // Retain isolated data if a process could still be using it.
+ if (stopped.every((result) => result.status === "fulfilled")) {
+ try { await rm(dataRoot, { recursive: true, force: true }); } catch (error) { errors.push(error); }
+ }
+}
+if (errors.length) {
+ // Never print raw live RPC/SDK errors, which may contain endpoint or credential data.
+ console.error("CONFIG_SYNC_FAILED " + JSON.stringify({ step: currentStep, prefix, cleanup, binarySha256, failures: errors.length, codes: errors.map((error) => ({ code: /^CONFIG_SYNC_[A-Z_]+$/.test(error.errorCode ?? "") ? error.errorCode : undefined, status: error.safeStatus, actual: ["boolean", "number"].includes(typeof error.actual) ? error.actual : undefined, expected: ["boolean", "number"].includes(typeof error.expected) ? error.expected : undefined, diagnostics: error.message?.match(/CONFIG_SYNC_[A-Z_]+|HTTP \d{3}|probe cleanup could not be verified|SignatureDoesNotMatch|AuthorizationHeaderMalformed|InvalidRequest|InvalidArgument|MissingContentLength|InvalidAccessKeyId|RequestTimeTooSkewed|RequestExpired|InvalidToken|ExpiredToken|AccessDenied|XAmzContentSHA256Mismatch|InvalidHostHeader/g), location: error.stack?.split("\n").find((line) => line.includes("config-sync-journey.mjs:"))?.match(/config-sync-journey\.mjs:\d+:\d+/)?.[0] })) }));
+ if (!values["live-s3"]) for (const error of errors) console.error(error);
+ process.exitCode = 1;
+} else {
+ console.log("CONFIG_SYNC_MULTIDEVICE " + JSON.stringify({ ...report, cleanup, result: "passed" }));
}
diff --git a/scripts/e2e/config-sync-journey.mjs b/scripts/e2e/config-sync-journey.mjs
new file mode 100644
index 000000000..176d5f516
--- /dev/null
+++ b/scripts/e2e/config-sync-journey.mjs
@@ -0,0 +1,233 @@
+import assert from "node:assert/strict";
+import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+export const PASSWORD = "portable-backup-password";
+export const MARKERS = ["S3 shared provider", "fixture-provider-secret", "S3 fixture instructions", "resource-first", "resource-updated", "fixture-mcp-secret"];
+const categories = Object.fromEntries(["application", "providers", "credentials", "mcp", "skills", "subagents", "instructions", "projects", "plugins", "automation"].map((name) => [name, true]));
+export const rpc = (host, method, params = {}) => host.call(method, params, 120_000);
+const sync = (host) => rpc(host, "configSync.syncNow");
+const settings = (host) => rpc(host, "settings.get");
+const provider = async (host, id) => (await rpc(host, "providers.get", { id })).provider;
+
+export function config(connection, deviceLabel, extra = {}) {
+ return { ...connection, deviceLabel, backupPassword: PASSWORD, categories: { ...categories, memory: false }, includeSecrets: true, includeMemory: false, automaticSync: false, mode: "sync", ...extra };
+}
+
+export async function approveAll(host, state, projectPath) {
+ let next = state;
+ for (let n = 0; next.pendingApprovals.length; n += 1) {
+ assert.ok(n < 64, "approvals must converge");
+ const item = next.pendingApprovals[0];
+ assert.notEqual(item.reason, "conflict", "conflicts require an explicit choice");
+ if (item.mappingKey) {
+ assert.ok(projectPath, "mapped capability requires a local path");
+ await rpc(host, "configSync.mapProject", { logicalId: item.mappingKey, paths: [projectPath] });
+ }
+ next = await rpc(host, "configSync.approve", { approvalId: item.id, digest: item.digest });
+ }
+ return next;
+}
+
+async function choose(host, state, suffix) {
+ const item = state.pendingApprovals.find((value) => value.reason === "conflict" && value.entityId.endsWith(suffix));
+ assert.ok(item, `missing explicit ${suffix} conflict candidate`);
+ return rpc(host, "configSync.approve", { approvalId: item.id, digest: item.digest });
+}
+
+export async function runSyncJourney({ a, b, connection, store, step }) {
+ const configA = config(connection, "Device A");
+ const configB = config(connection, "Device B", { includeSecrets: false });
+ step("configure-and-credential-reuse");
+ assert.deepEqual(await rpc(a, "configSync.test", configA), { ok: true, conditionalWrites: true });
+ assert.equal((await rpc(a, "configSync.configure", configA)).mode, "sync");
+ const { secretAccessKey: _secret, sessionToken: _token, ...reuse } = configA;
+ assert.equal((await rpc(a, "configSync.configure", { ...reuse, backupPassword: "" })).configured, true);
+ await rpc(a, "settings.set", { theme: "light", language: "en", networkPolicy: { mode: "strict" } });
+ // Strict mode is device-local. Local HTTP is tested under relaxed policy only.
+ if (connection.endpoint.startsWith("http:")) await rpc(a, "settings.set", { networkPolicy: { mode: "relaxed" } });
+ await sync(a);
+ const { provider: shared } = await rpc(a, "providers.create", {
+ name: MARKERS[0], vendorKey: "s3-fixture", type: "openai_compatible", protocol: "openai_compatible",
+ authKind: "api_key_and_base_url", secretValue: MARKERS[1], baseUrl: "http://127.0.0.1:9/v1", models: [],
+ });
+ await rpc(b, "settings.set", { theme: "light", language: "en" });
+ await sync(a);
+ await rpc(b, "configSync.configure", configB);
+ step("new-device-approval-and-credential-opt-out");
+ let state = await sync(b);
+ assert.ok(state.pendingApprovals.some((item) => item.entityId.includes(shared.id)));
+ assert.equal(await provider(b, shared.id), null, "provider must not appear before approval");
+ state = await approveAll(b, state);
+ assert.equal((await provider(b, shared.id)).hasSecret, false);
+ assert.equal((await provider(b, shared.id)).enabled, false);
+ assert.equal((await provider(a, shared.id)).hasSecret, true);
+ assert.equal((await settings(b)).theme, "light");
+ assert.equal((await settings(b)).networkPolicy.mode, "relaxed", "local policy is not synchronized");
+ step("mcp-approval-and-credential-opt-out");
+ await rpc(a, "mcp.upsert", { id: "s3-mcp", label: "S3 fixture MCP", level: "global", transport: "stdio", command: "never-execute-this-fixture", env: { API_KEY: MARKERS[5] }, enabled: false });
+ await sync(a);
+ state = await sync(b);
+ assert.ok(state.pendingApprovals.some((item) => item.domain === "mcp"));
+ assert.equal((await rpc(b, "mcp.list", { level: "global" })).servers.length, 0);
+ await approveAll(b, state);
+ const importedMcp = (await rpc(b, "mcp.list", { level: "global" })).servers.find((item) => item.id === "s3-mcp");
+ assert.ok(importedMcp);
+ assert.deepEqual(importedMcp.env ?? {}, {});
+ assert.deepEqual(importedMcp.headers ?? {}, {});
+ assert.equal(importedMcp.enabled, false);
+ await rpc(a, "mcp.remove", { id: "s3-mcp", level: "global" });
+ await sync(a);
+ await approveAll(b, await sync(b));
+ await sync(b);
+ await sync(a);
+ assert.equal((await rpc(b, "mcp.list", { level: "global" })).servers.length, 0);
+
+
+ step("concurrent-disjoint-edits");
+ await rpc(a, "settings.set", { theme: "dark" });
+ await rpc(b, "settings.set", { language: "de" });
+ await Promise.all([sync(a), sync(b)]);
+ await sync(a);
+ await sync(b);
+ for (const host of [a, b]) {
+ const value = await settings(host);
+ assert.equal(value.theme, "dark");
+ assert.equal(value.language, "de");
+ assert.equal((await rpc(host, "configSync.getState")).pendingApprovals.length, 0);
+ }
+
+ step("same-entity-conflict-explicit-choice");
+ await rpc(a, "settings.set", { theme: "light" });
+ await rpc(b, "settings.set", { theme: "system" });
+ await sync(a);
+ state = await sync(b);
+ assert.equal(state.status, "conflict");
+ assert.equal((await settings(b)).theme, "system", "unapproved conflict must not overwrite local settings");
+ await choose(b, state, ":remote");
+ assert.equal((await settings(b)).theme, "light");
+ await sync(b);
+ await sync(a);
+
+ step("remote-deletion-versus-offline-edit");
+ await rpc(b, "providers.update", { id: shared.id, name: "Offline provider edit" });
+ await rpc(a, "providers.delete", { id: shared.id });
+ await sync(a);
+ state = await sync(b);
+ assert.equal(state.status, "conflict");
+ assert.equal((await provider(b, shared.id)).name, "Offline provider edit");
+ await choose(b, state, ":local");
+ assert.equal((await provider(b, shared.id)).name, "Offline provider edit");
+ await sync(b);
+ await approveAll(a, await sync(a));
+ assert.equal((await provider(a, shared.id)).name, "Offline provider edit");
+ await rpc(a, "providers.delete", { id: shared.id });
+ await sync(a);
+ await approveAll(b, await sync(b));
+ await sync(b);
+ await sync(a);
+ assert.equal(await provider(b, shared.id), null, "unchanged opted-out receiver must accept deletion");
+
+ step("mapped-skill-approval-resource-update-and-deletion");
+ const projectA = join(a.dataDir, "project-a");
+ const projectB = join(b.dataDir, "project-b");
+ await Promise.all([mkdir(projectA), mkdir(projectB)]);
+ await rpc(a, "projects.create", { path: projectA });
+ const { skill } = await rpc(a, "skills.create", {
+ id: "s3-resource-skill", name: "S3 resource skill", level: "project", projectPath: projectA,
+ body: MARKERS[2], shape: "dir",
+ });
+ const source = join(dirname(skill.path), "data.txt");
+ await writeFile(source, MARKERS[3]);
+ await sync(a);
+ state = await sync(b);
+ assert.ok(state.pendingApprovals.some((item) => item.mappingKey));
+ assert.equal((await rpc(b, "skills.list", { level: "project", projectPath: projectB })).skills.length, 0);
+ await approveAll(b, state, projectB);
+ const imported = (await rpc(b, "skills.list", { level: "project", projectPath: projectB })).skills.find((item) => item.id === skill.id);
+ assert.ok(imported);
+ assert.ok(imported.path.startsWith(projectB), "source machine path must not become destination");
+ const destination = join(dirname(imported.path), "data.txt");
+ assert.equal(await readFile(destination, "utf8"), MARKERS[3]);
+ await writeFile(source, MARKERS[4]);
+ await sync(a);
+ await approveAll(b, await sync(b), projectB);
+ assert.equal(await readFile(destination, "utf8"), MARKERS[4]);
+ await rpc(a, "skills.remove", { id: skill.id, level: "project", projectPath: projectA });
+ await sync(a);
+ await approveAll(b, await sync(b), projectB);
+ assert.equal((await rpc(b, "skills.list", { level: "project", projectPath: projectB })).skills.length, 0);
+ await sync(b);
+ await sync(a);
+
+ await approveAll(a, await sync(a), projectA);
+ await approveAll(b, await sync(b), projectB);
+ step("sync-restore-publishes-and-survives-restart");
+ await rpc(a, "settings.set", { theme: "dark" });
+ const oldRevision = (await sync(a)).lastRevisionId;
+ await sync(b);
+ await rpc(a, "settings.set", { theme: "light" });
+ await sync(a);
+ await sync(b);
+ await assert.rejects(rpc(a, "configSync.restore", { revisionId: oldRevision }), /CONFIG_SYNC_INVALID/);
+ const restored = await rpc(a, "configSync.restore", { revisionId: oldRevision, acknowledgePropagation: true });
+ assert.notEqual(restored.lastRevisionId, oldRevision);
+ await approveAll(a, restored, projectA);
+ assert.equal((await settings(a)).theme, "dark");
+ await approveAll(b, await sync(b), projectB);
+ assert.equal((await settings(b)).theme, "dark");
+ const files = await readdir(join(a.dataDir, "config-sync"), { recursive: true });
+ assert.ok(files.some((name) => name.includes("recovery")), "restore must create local recovery data");
+ await b.restart();
+ const restartedState = await rpc(b, "configSync.getState");
+ assert.equal(restartedState.configured, true, "Host restart must preserve S3 configuration");
+ assert.equal((await settings(b)).theme, "dark");
+ await sync(b);
+ if (store.failWith) {
+ step("temporary-outage-and-retry");
+ store.failWith(502);
+ await assert.rejects(sync(b), /CONFIG_SYNC_SERVER/);
+ assert.equal((await rpc(b, "configSync.getState")).status, "offline");
+ store.failWith(null);
+ await sync(b);
+ assert.equal((await settings(b)).theme, "dark");
+ }
+ return { projectA, projectB };
+}
+
+export async function runBackupJourney({ a, b, c, d, connection, step }) {
+ step("backup-isolation-and-local-only-restore");
+ const backupConfig = config(connection, "Backup C", { mode: "backup" });
+ await rpc(c, "configSync.configure", backupConfig);
+ await rpc(c, "settings.set", { theme: "system" });
+ const syncHead = (await rpc(a, "configSync.listHistory"))[0].revisionId;
+ const first = (await sync(c)).lastRevisionId;
+ assert.equal((await settings(c)).theme, "system");
+ assert.equal((await rpc(c, "providers.list")).providers.length, 0);
+ assert.equal((await sync(c)).lastRevisionId, first, "unchanged backup must not duplicate revisions");
+ await rpc(d, "configSync.configure", config(connection, "Backup D", { mode: "backup" }));
+ await rpc(d, "settings.set", { theme: "light" });
+ const second = (await sync(d)).lastRevisionId;
+ assert.notEqual(second, first);
+ assert.equal((await settings(d)).theme, "light");
+ assert.equal((await sync(c)).lastRevisionId, first, "another device's backup is not merged");
+ assert.equal((await settings(c)).theme, "system");
+ const history = await rpc(c, "configSync.listHistory");
+ assert.equal(history[0].revisionId, second);
+ assert.ok(history.some((entry) => entry.revisionId === first));
+ await rpc(c, "settings.set", { theme: "dark" });
+ await rpc(c, "configSync.restore", { revisionId: first });
+ assert.equal((await settings(c)).theme, "system");
+ assert.equal((await rpc(c, "configSync.listHistory"))[0].revisionId, second);
+ assert.equal((await rpc(a, "configSync.listHistory"))[0].revisionId, syncHead);
+ assert.equal((await settings(a)).theme, "dark");
+
+ step("password-rewrap-new-device-and-existing-device");
+ const nextPassword = "replacement-backup-password";
+ await rpc(a, "configSync.changePassword", { currentPassword: PASSWORD, newPassword: nextPassword });
+ await sync(b); // An unlocked peer retains the data key: rewrap is not revocation.
+ await rpc(d, "configSync.disconnect");
+ await assert.rejects(rpc(d, "configSync.configure", config(connection, "Fresh D")), /CONFIG_SYNC_CRYPTO/);
+ await rpc(d, "configSync.configure", config(connection, "Fresh D", { backupPassword: nextPassword, mode: "backup" }));
+ assert.equal((await rpc(d, "configSync.getState")).configured, true);
+}
diff --git a/scripts/e2e/config-sync-live-s3.mjs b/scripts/e2e/config-sync-live-s3.mjs
new file mode 100644
index 000000000..fad566bb4
--- /dev/null
+++ b/scripts/e2e/config-sync-live-s3.mjs
@@ -0,0 +1,48 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { parseEnv } from "node:util";
+
+const helper = fileURLToPath(new URL("./config-sync-s3-admin.py", import.meta.url));
+
+export async function openLiveS3(envFile, prefix) {
+ const fields = parseEnv(await readFile(envFile, "utf8"));
+ for (const name of ["S3_HOST", "S3_REGION", "S3_BUCKET", "S3_ACCESS_KEY", "S3_SECRET_KEY", "S3_DOMAIN_MODE"]) {
+ if (!fields[name]) throw new Error(`Missing required ${name}`);
+ }
+ if (!["true", "false"].includes(fields.S3_DOMAIN_MODE)) throw new Error("S3_DOMAIN_MODE must be true or false");
+ const endpoint = new URL(fields.S3_HOST.includes("://") ? fields.S3_HOST : `https://${fields.S3_HOST}`);
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.pathname !== "/") {
+ throw new Error("Live S3 requires an HTTPS origin without userinfo, query or path");
+ }
+ const connection = {
+ endpoint: endpoint.origin, region: fields.S3_REGION, bucket: fields.S3_BUCKET, prefix,
+ accessKeyId: fields.S3_ACCESS_KEY, secretAccessKey: fields.S3_SECRET_KEY,
+ sessionToken: fields.S3_SESSION_TOKEN || "", pathStyle: fields.S3_DOMAIN_MODE === "false",
+ };
+ const admin = (operation, extra = {}) => new Promise((resolve, reject) => {
+ const child = execFile("python3", [helper], { timeout: 300_000, maxBuffer: 1024 * 1024, windowsHide: true }, (error, stdout) => {
+ let value;
+ try { value = JSON.parse(stdout); } catch { reject(new Error("S3 admin failed without a safe result")); return; }
+ if (error || value.ok !== true) {
+ const failure = new Error("S3 test administration failed");
+ failure.safeStatus = Number.isInteger(value.status) ? value.status : undefined;
+ reject(failure);
+ } else resolve(value.result);
+ });
+ child.stdin.on("error", () => reject(new Error("S3 admin input channel failed")));
+ child.stdin.end(JSON.stringify({ operation, connection, ...extra }));
+ });
+ // Must succeed BEFORE any Host receives the destination. Failed preflight
+ // never grants cleanup ownership of a possibly existing namespace.
+ const prepared = await admin("prepare");
+ assert.equal(prepared.empty, true);
+ return {
+ connection,
+ async inventory() { return (await admin("inventory")).keys; },
+ async inspect(markers) { return admin("inspect", { markers }); },
+ async cleanup() { return admin("cleanup", { ownedEmptyNamespace: true }); },
+ async close() {},
+ };
+}
diff --git a/scripts/e2e/config-sync-s3-admin.py b/scripts/e2e/config-sync-s3-admin.py
new file mode 100644
index 000000000..3379c5c2f
--- /dev/null
+++ b/scripts/e2e/config-sync-s3-admin.py
@@ -0,0 +1,103 @@
+"""Bounded S3 test administration. Credentials arrive only via stdin JSON."""
+import json
+import re
+import sys
+
+import boto3
+from botocore.config import Config
+from botocore.exceptions import ClientError
+
+
+def run(data):
+ connection = data["connection"]
+ prefix = connection["prefix"]
+ if not re.fullmatch(r"pi-desktop-tests/s3-config-sync-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}", prefix):
+ raise ValueError("unsafe test prefix")
+ prefix += "/"
+ client = boto3.client(
+ "s3", endpoint_url=connection["endpoint"], region_name=connection["region"],
+ aws_access_key_id=connection["accessKeyId"],
+ aws_secret_access_key=connection["secretAccessKey"],
+ aws_session_token=connection.get("sessionToken") or None,
+ config=Config(signature_version="s3v4", connect_timeout=10, read_timeout=30,
+ retries={"max_attempts": 1},
+ s3={"addressing_style": "path" if connection["pathStyle"] else "virtual"}),
+ )
+ bucket = connection["bucket"]
+ versioned = client.get_bucket_versioning(Bucket=bucket).get("Status") in ("Enabled", "Suspended")
+
+ def safe_key(key):
+ if not key.startswith(prefix):
+ raise ValueError("out-of-scope object")
+ relative = key[len(prefix):]
+ if not re.fullmatch(r"header|probe/[0-9a-f-]{36}|vault/[0-9a-f-]{36}/(?:head|backup-head|(?:revisions|objects)/[a-zA-Z0-9_.:-]{1,128})", relative):
+ raise ValueError("unexpected object in test namespace")
+ return key
+
+ def inventory():
+ keys = []
+ for page in client.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
+ keys.extend(safe_key(item["Key"]) for item in page.get("Contents", []))
+ if len(keys) > 2000:
+ raise ValueError("test inventory limit exceeded")
+ return sorted(keys)
+
+ def versions():
+ if not versioned:
+ return []
+ entries = []
+ for page in client.get_paginator("list_object_versions").paginate(Bucket=bucket, Prefix=prefix):
+ for item in page.get("Versions", []) + page.get("DeleteMarkers", []):
+ entries.append({"Key": safe_key(item["Key"]), "VersionId": item["VersionId"]})
+ if len(entries) > 10000:
+ raise ValueError("test version limit exceeded")
+ return entries
+
+ operation = data["operation"]
+ if operation == "prepare":
+ if inventory() or versions():
+ raise ValueError("test namespace is not empty")
+ return {"empty": True, "versioned": versioned}
+ if operation == "inventory":
+ return {"keys": inventory()}
+ if operation == "inspect":
+ keys = inventory()
+ if not keys:
+ raise ValueError("expected encrypted objects")
+ total = 0
+ markers = [value.encode() for value in data["markers"] if value]
+ for key in keys:
+ response = client.get_object(Bucket=bucket, Key=key)
+ with response["Body"] as stream:
+ body = stream.read(64 * 1024 * 1024 + 1)
+ total += len(body)
+ if len(body) > 64 * 1024 * 1024 or total > 256 * 1024 * 1024:
+ raise ValueError("inspection limit exceeded")
+ if any(marker in body for marker in markers):
+ raise ValueError("remote plaintext leaked")
+ return {"objects": len(keys), "ciphertext": True, "versioned": versioned}
+ if operation == "cleanup":
+ if data.get("ownedEmptyNamespace") is not True:
+ raise ValueError("cleanup requires initial empty namespace verification")
+ # Hosts have stopped. Capture one exact inventory, then delete only it.
+ entries = versions() if versioned else [{"Key": key} for key in inventory()]
+ for entry in entries:
+ client.delete_object(Bucket=bucket, **entry)
+ remaining = len(inventory())
+ remaining_versions = len(versions())
+ if remaining or remaining_versions:
+ raise ValueError("test cleanup incomplete")
+ return {"deleted": len(entries), "remaining": remaining, "versions": remaining_versions}
+ raise ValueError("unsupported administration operation")
+
+
+if __name__ == "__main__":
+ try:
+ print(json.dumps({"ok": True, "result": run(json.load(sys.stdin))}))
+ except ClientError as error:
+ # Never serialize messages, URLs, headers, request parameters or credentials.
+ print(json.dumps({"ok": False, "kind": "S3Request", "status": error.response.get("ResponseMetadata", {}).get("HTTPStatusCode")}))
+ sys.exit(1)
+ except Exception as error:
+ print(json.dumps({"ok": False, "kind": type(error).__name__}))
+ sys.exit(1)
diff --git a/scripts/e2e/config-sync-s3-fixture.mjs b/scripts/e2e/config-sync-s3-fixture.mjs
new file mode 100644
index 000000000..4c54186f8
--- /dev/null
+++ b/scripts/e2e/config-sync-s3-fixture.mjs
@@ -0,0 +1,125 @@
+import assert from "node:assert/strict";
+import { createHash, createHmac, timingSafeEqual } from "node:crypto";
+import { createServer } from "node:http";
+
+const sha256 = (value) => createHash("sha256").update(value).digest("hex");
+const hmac = (key, value) => createHmac("sha256", key).update(value).digest();
+const credentials = {
+ accessKeyId: "fixture-access-key",
+ secretAccessKey: "fixture-secret-key",
+ sessionToken: "fixture-session-token",
+ region: "us-east-1",
+ bucket: "config-sync-fixture",
+ pathStyle: true,
+};
+
+// Independent verifier: no production signer is imported by this server.
+function verifySignature(request, body) {
+ const match = /^AWS4-HMAC-SHA256 Credential=([^/]+)\/(\d{8})\/([^/]+)\/s3\/aws4_request, SignedHeaders=([^,]+), Signature=([a-f0-9]{64})$/.exec(request.headers.authorization ?? "");
+ if (!match) return false;
+ const [, accessKey, day, region, signedHeaders, signature] = match;
+ const names = signedHeaders.split(";");
+ const timestamp = request.headers["x-amz-date"];
+ if (accessKey !== credentials.accessKeyId || region !== credentials.region ||
+ !timestamp?.startsWith(day) || !/^\d{8}T\d{6}Z$/.test(timestamp) ||
+ request.headers["x-amz-content-sha256"] !== sha256(body) ||
+ request.headers["x-amz-security-token"] !== credentials.sessionToken ||
+ [...names].sort().join(";") !== signedHeaders || new Set(names).size !== names.length) return false;
+ const required = ["host", "x-amz-date", "x-amz-content-sha256", "x-amz-security-token"];
+ for (const name of ["if-match", "if-none-match"]) {
+ if (request.headers[name]) required.push(name);
+ }
+ if (required.some((name) => !names.includes(name))) return false;
+ const canonicalHeaders = names.map((name) => {
+ const value = request.headers[name];
+ return typeof value === "string" ? `${name}:${value.trim().replace(/\s+/g, " ")}\n` : "";
+ }).join("");
+ const canonical = [request.method, request.url, "", canonicalHeaders, signedHeaders, sha256(body)].join("\n");
+ const scope = `${day}/${region}/s3/aws4_request`;
+ const toSign = `AWS4-HMAC-SHA256\n${timestamp}\n${scope}\n${sha256(canonical)}`;
+ const key = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, day), region), "s3"), "aws4_request");
+ return timingSafeEqual(hmac(key, toSign), Buffer.from(signature, "hex"));
+}
+
+export async function startS3Fixture(prefix) {
+ const objects = new Map();
+ const requests = [];
+ let failureStatus = null;
+ let rejectedSignatures = 0;
+ const errors = [];
+ const server = createServer((request, response) => {
+ const send = (status, body = Buffer.alloc(0), headers = {}) => {
+ response.writeHead(status, { "Content-Length": body.length, ...headers });
+ response.end(body);
+ };
+ void (async () => {
+ const chunks = [];
+ let length = 0;
+ for await (const chunk of request) {
+ length += chunk.length;
+ if (length > 64 * 1024 * 1024) return send(413);
+ chunks.push(chunk);
+ }
+ const body = Buffer.concat(chunks);
+ if (!verifySignature(request, body)) {
+ rejectedSignatures += 1;
+ return send(403);
+ }
+ const path = decodeURIComponent(request.url.slice(1));
+ if (!path.startsWith(`${credentials.bucket}/${prefix}/`)) return send(403);
+ const key = path.slice(credentials.bucket.length + 1);
+ requests.push({ method: request.method, key });
+ if (failureStatus) return send(failureStatus);
+ const existing = objects.get(key);
+ switch (request.method) {
+ case "GET":
+ return existing ? send(200, existing.body, { ETag: existing.etag }) : send(404);
+ case "PUT": {
+ const none = request.headers["if-none-match"];
+ const match = request.headers["if-match"];
+ if ((!none && !match) || (none && match)) return send(400);
+ if ((none === "*" && existing) || (match && existing?.etag !== match)) return send(412);
+ const etag = `"${sha256(body)}"`;
+ objects.set(key, { body, etag });
+ return send(200, Buffer.alloc(0), { ETag: etag });
+ }
+ case "DELETE":
+ objects.delete(key);
+ return send(204);
+ default:
+ return send(405);
+ }
+ })().catch((error) => {
+ errors.push(error);
+ if (!response.headersSent) send(500);
+ else response.destroy();
+ });
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ return {
+ connection: { ...credentials, endpoint: `http://127.0.0.1:${server.address().port}`, prefix },
+ failWith(status) { failureStatus = status; },
+ async inventory() { return [...objects.keys()].sort(); },
+ async inspect(markers) {
+ assert.ok(objects.size > 0, "encrypted objects must exist");
+ for (const { body } of objects.values()) {
+ assert.ok(markers.every((marker) => !body.includes(Buffer.from(marker))), "remote plaintext leaked");
+ }
+ assert.equal(rejectedSignatures, 0, "all Host requests must have valid SigV4 signatures");
+ assert.ok(requests.some(({ method }) => method === "DELETE"), "probe must clean up");
+ assert.ok(requests.filter(({ method }) => method === "DELETE").every(({ key }) => key.startsWith(`${prefix}/probe/`)), "normal runs must not collect cloud objects");
+ return { objects: objects.size, requests: requests.length, ciphertext: true, signatures: true };
+ },
+ async cleanup() {
+ objects.clear();
+ return { remaining: objects.size, versions: 0 };
+ },
+ async close() {
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
+ if (errors.length) throw new AggregateError(errors, "S3 fixture failed");
+ },
+ };
+}
diff --git a/scripts/e2e/host.mjs b/scripts/e2e/host.mjs
index 70ba92e68..842052bc5 100644
--- a/scripts/e2e/host.mjs
+++ b/scripts/e2e/host.mjs
@@ -61,9 +61,11 @@ function failPending(pending, error) {
}
export class Host {
- constructor(binary, dataDir) {
+ constructor(binary, dataDir, { env = {}, quiet = false } = {}) {
this.binary = binary;
this.dataDir = dataDir;
+ this.env = { ...env };
+ this.quiet = quiet;
this.child = null;
this.stdoutReader = null;
this.pending = new Map();
@@ -82,13 +84,13 @@ export class Host {
const child = spawn(this.binary, [], {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
- env: { ...process.env, PI_DESKTOP_DATA_DIR: this.dataDir },
+ env: { ...process.env, ...this.env, PI_DESKTOP_DATA_DIR: this.dataDir },
});
this.child = child;
this.exitPromise = new Promise((resolveExit) => {
child.once("exit", (code, signal) => {
this.exited = true;
- const suffix = this.stderr.trim()
+ const suffix = !this.quiet && this.stderr.trim()
? " stderr=" + this.stderr.trim().slice(-500)
: "";
failPending(
@@ -105,14 +107,14 @@ export class Host {
});
child.stderr.on("data", (chunk) => {
this.stderr += String(chunk);
- if (process.env.DEBUG_HOST) process.stderr.write(chunk);
+ if (!this.quiet && process.env.DEBUG_HOST) process.stderr.write(chunk);
});
this.stdoutReader = readNdjsonLines(child.stdout, (line) => {
let message;
try {
message = JSON.parse(line);
} catch {
- if (process.env.DEBUG_HOST) console.error("host non-JSON stdout: " + line);
+ if (!this.quiet && process.env.DEBUG_HOST) console.error("host non-JSON stdout: " + line);
return;
}
if (message.id !== undefined && message.id !== null) {