Vendor OpenClaw source as Adolf fork baseline
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled

Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
This commit is contained in:
2026-07-05 09:36:54 +00:00
parent 3216769225
commit bedb527145
21108 changed files with 6010766 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
// Phone Control tests cover doctor contract api plugin behavior.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
createPluginStateKeyedStoreForTests,
resetPluginStateStoreForTests,
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
import type {
OpenKeyedStoreOptions,
PluginDoctorStateMigrationContext,
} from "openclaw/plugin-sdk/runtime-doctor";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { stateMigrations } from "./doctor-contract-api.js";
function createDoctorContext(env: NodeJS.ProcessEnv): PluginDoctorStateMigrationContext {
return {
openPluginStateKeyedStore<T>(options: OpenKeyedStoreOptions) {
return createPluginStateKeyedStoreForTests<T>("phone-control", {
...options,
env: options.env ?? env,
});
},
};
}
describe("phone-control doctor state migration", () => {
let stateDir = "";
let env: NodeJS.ProcessEnv;
beforeEach(async () => {
resetPluginStateStoreForTests();
stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-phone-control-doctor-"));
env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
});
afterEach(async () => {
await fs.rm(stateDir, { recursive: true, force: true });
});
it("imports legacy armed state into plugin state", async () => {
const sourcePath = path.join(stateDir, "plugins", "phone-control", "armed.json");
const legacyState = {
version: 2,
armedAtMs: 100,
expiresAtMs: 200,
group: "writes",
armedCommands: ["sms.send"],
addedToAllow: ["sms.send"],
removedFromDeny: [],
};
await fs.mkdir(path.dirname(sourcePath), { recursive: true });
await fs.writeFile(sourcePath, JSON.stringify(legacyState));
const migration = stateMigrations[0];
await expect(
migration.detectLegacyState({
config: {},
env,
stateDir,
oauthDir: path.join(stateDir, "oauth"),
context: createDoctorContext(env),
}),
).resolves.toMatchObject({
preview: [expect.stringContaining("Phone Control armed state")],
});
const result = await migration.migrateLegacyState({
config: {},
env,
stateDir,
oauthDir: path.join(stateDir, "oauth"),
context: createDoctorContext(env),
});
expect(result.warnings).toEqual([]);
expect(result.changes).toEqual([
"Migrated Phone Control armed state -> plugin state",
expect.stringContaining("Archived Phone Control armed-state legacy source"),
]);
await expect(fs.access(sourcePath)).rejects.toThrow();
await expect(fs.access(`${sourcePath}.migrated`)).resolves.toBeUndefined();
await expect(
createDoctorContext(env)
.openPluginStateKeyedStore({
namespace: "armed",
maxEntries: 1,
})
.lookup("current"),
).resolves.toEqual(legacyState);
});
});

View File

@@ -0,0 +1,140 @@
// Phone Control API module exposes the plugin public contract.
import fs from "node:fs/promises";
import path from "node:path";
import {
archiveLegacyStateSource,
type PluginDoctorStateMigration,
} from "openclaw/plugin-sdk/runtime-doctor";
type ArmGroup = "camera" | "screen" | "writes" | "all";
type ArmStateFileV1 = {
version: 1;
armedAtMs: number;
expiresAtMs: number | null;
removedFromDeny: string[];
};
type ArmStateFileV2 = {
version: 2;
armedAtMs: number;
expiresAtMs: number | null;
group: ArmGroup;
armedCommands: string[];
addedToAllow: string[];
removedFromDeny: string[];
};
type ArmStateFile = ArmStateFileV1 | ArmStateFileV2;
const ARM_STATE_NAMESPACE = "armed";
const ARM_STATE_KEY = "current";
function resolveArmStatePath(stateDir: string): string {
return path.join(stateDir, "plugins", "phone-control", "armed.json");
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
function parseArmState(value: unknown): ArmStateFile | null {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
const parsed = value as Record<string, unknown>;
if (parsed.version !== 1 && parsed.version !== 2) {
return null;
}
if (typeof parsed.armedAtMs !== "number") {
return null;
}
if (!(parsed.expiresAtMs === null || typeof parsed.expiresAtMs === "number")) {
return null;
}
if (parsed.version === 1) {
if (!isStringArray(parsed.removedFromDeny)) {
return null;
}
return {
version: 1,
armedAtMs: parsed.armedAtMs,
expiresAtMs: parsed.expiresAtMs,
removedFromDeny: parsed.removedFromDeny,
};
}
const group = typeof parsed.group === "string" ? parsed.group : "";
if (group !== "camera" && group !== "screen" && group !== "writes" && group !== "all") {
return null;
}
if (
!isStringArray(parsed.armedCommands) ||
!isStringArray(parsed.addedToAllow) ||
!isStringArray(parsed.removedFromDeny)
) {
return null;
}
return {
version: 2,
armedAtMs: parsed.armedAtMs,
expiresAtMs: parsed.expiresAtMs,
group,
armedCommands: parsed.armedCommands,
addedToAllow: parsed.addedToAllow,
removedFromDeny: parsed.removedFromDeny,
};
}
async function readLegacyArmState(filePath: string): Promise<ArmStateFile | null> {
try {
return parseArmState(JSON.parse(await fs.readFile(filePath, "utf8")) as unknown);
} catch {
return null;
}
}
export const stateMigrations: PluginDoctorStateMigration[] = [
{
id: "phone-control-armed-json-to-plugin-state",
label: "Phone Control armed state",
async detectLegacyState(params) {
const filePath = resolveArmStatePath(params.stateDir);
const state = await readLegacyArmState(filePath);
if (!state) {
return null;
}
return {
preview: [
`- Phone Control armed state: ${filePath} -> plugin state (${ARM_STATE_NAMESPACE})`,
],
};
},
async migrateLegacyState(params) {
const changes: string[] = [];
const warnings: string[] = [];
const filePath = resolveArmStatePath(params.stateDir);
const state = await readLegacyArmState(filePath);
if (!state) {
return { changes, warnings };
}
const store = params.context.openPluginStateKeyedStore<ArmStateFile>({
namespace: ARM_STATE_NAMESPACE,
maxEntries: 1,
});
const existing = await store.lookup(ARM_STATE_KEY);
if (existing) {
warnings.push("Left Phone Control armed-state source in place because plugin state exists");
return { changes, warnings };
}
await store.register(ARM_STATE_KEY, state);
changes.push("Migrated Phone Control armed state -> plugin state");
await archiveLegacyStateSource({
filePath,
label: "Phone Control armed-state",
changes,
warnings,
});
return { changes, warnings };
},
},
];

View File

@@ -0,0 +1,480 @@
// Phone Control tests cover index plugin behavior.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
OpenKeyedStoreOptions,
PluginStateKeyedStore,
} from "openclaw/plugin-sdk/plugin-state-runtime";
import {
createPluginStateKeyedStoreForTests,
resetPluginStateStoreForTests,
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
import { beforeEach, describe, expect, it, vi } from "vitest";
import registerPhoneControl from "./index.js";
import type {
OpenClawPluginApi,
OpenClawPluginCommandDefinition,
OpenClawPluginService,
PluginCommandContext,
} from "./runtime-api.js";
const PHONE_CONTROL_STATE_PREFIX = "openclaw-phone-control-test-";
const WRITE_COMMANDS = ["calendar.add", "contacts.add", "reminders.add", "sms.send"] as const;
function createApi(params: {
stateDir: string;
getConfig: () => Record<string, unknown>;
writeConfig: (next: Record<string, unknown>) => Promise<void>;
registerCommand: (command: OpenClawPluginCommandDefinition) => void;
registerService?: (service: OpenClawPluginService) => void;
openKeyedStore?: OpenClawPluginApi["runtime"]["state"]["openKeyedStore"];
}): OpenClawPluginApi {
return createTestPluginApi({
id: "phone-control",
name: "phone-control",
source: "test",
config: {},
pluginConfig: {},
runtime: {
state: {
resolveStateDir: () => params.stateDir,
openKeyedStore:
params.openKeyedStore ??
((options: OpenKeyedStoreOptions) =>
createPluginStateKeyedStoreForTests("phone-control", {
...options,
env: { ...process.env, OPENCLAW_STATE_DIR: params.stateDir },
})),
},
config: {
current: () => params.getConfig(),
mutateConfigFile: async ({
mutate,
}: {
mutate: (draft: Record<string, unknown>) => void;
}) => {
const nextConfig = structuredClone(params.getConfig());
mutate(nextConfig);
await params.writeConfig(nextConfig);
return {
path: "/tmp/openclaw.json",
previousHash: null,
persistedHash: null,
snapshot: {},
nextConfig,
afterWrite: { mode: "auto" },
followUp: { mode: "auto", requiresRestart: false },
result: undefined,
};
},
replaceConfigFile: ({ nextConfig }: { nextConfig: unknown }) =>
params.writeConfig(nextConfig as Record<string, unknown>),
},
} as unknown as OpenClawPluginApi["runtime"],
registerCommand: params.registerCommand,
...(params.registerService ? { registerService: params.registerService } : {}),
});
}
function createCommandContext(args: string): PluginCommandContext {
return {
channel: "test",
isAuthorizedSender: true,
commandBody: `/phone ${args}`,
args,
config: {},
requestConversationBinding: async () => ({
status: "error",
message: "unsupported",
}),
detachConversationBinding: async () => ({ removed: false }),
getCurrentConversationBinding: async () => null,
};
}
function createPhoneControlConfig(): Record<string, unknown> {
return {
gateway: {
nodes: {
allowCommands: [],
denyCommands: [...WRITE_COMMANDS],
},
},
};
}
function createMockOpenKeyedStore(params: {
lookup: ReturnType<typeof vi.fn>;
delete?: ReturnType<typeof vi.fn>;
}): OpenClawPluginApi["runtime"]["state"]["openKeyedStore"] {
return <T>() => {
const store: PluginStateKeyedStore<T> = {
register: vi.fn(async () => {}),
registerIfAbsent: vi.fn(async () => true),
update: vi.fn(async () => true),
lookup: params.lookup as (key: string) => Promise<T | undefined>,
consume: vi.fn(async () => undefined),
delete: (params.delete ?? vi.fn(async () => true)) as (key: string) => Promise<boolean>,
entries: vi.fn(async () => []),
clear: vi.fn(async () => {}),
};
return store;
};
}
async function withRegisteredPhoneControl(
run: (params: {
command: OpenClawPluginCommandDefinition;
writeConfigFile: ReturnType<typeof vi.fn>;
getConfig: () => Record<string, unknown>;
}) => Promise<void>,
) {
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), PHONE_CONTROL_STATE_PREFIX));
try {
let config = createPhoneControlConfig();
const writeConfigFile = vi.fn(async (next: Record<string, unknown>) => {
config = next;
});
let command: OpenClawPluginCommandDefinition | undefined;
registerPhoneControl.register(
createApi({
stateDir,
getConfig: () => config,
writeConfig: writeConfigFile,
registerCommand: (nextCommand) => {
command = nextCommand;
},
}),
);
if (!command) {
throw new Error("phone-control plugin did not register its command");
}
await run({
command,
writeConfigFile,
getConfig: () => config,
});
} finally {
await fs.rm(stateDir, { recursive: true, force: true });
}
}
describe("phone-control plugin", () => {
beforeEach(() => {
resetPluginStateStoreForTests();
});
it("arms sms.send as part of the writes group", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile, getConfig }) => {
expect(command.name).toBe("phone");
expect(command.requiredScopes).toBeUndefined();
expect(command.exposeSenderIsOwner).toBe(true);
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
const text = res?.text ?? "";
const nodes = (
getConfig().gateway as { nodes?: { allowCommands?: string[]; denyCommands?: string[] } }
).nodes;
if (!nodes) {
throw new Error("phone-control command did not persist gateway node config");
}
expect(writeConfigFile).toHaveBeenCalledTimes(1);
expect(nodes.allowCommands).toEqual([...WRITE_COMMANDS]);
expect(nodes.denyCommands).toStrictEqual([]);
expect(text).toContain("sms.send");
});
});
it("blocks internal operator.write callers from mutating phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "webchat",
gatewayClientScopes: ["operator.write"],
});
expect(res?.text ?? "").toContain("requires operator.admin");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("blocks external non-owner callers without operator.admin from mutating phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "telegram",
senderIsOwner: false,
});
expect(res?.text ?? "").toContain("requires operator.admin");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("blocks external non-owner callers without operator.admin from disarming phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("disarm"),
channel: "telegram",
senderIsOwner: false,
});
expect(res?.text ?? "").toContain("requires operator.admin");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("allows external non-owner callers without operator.admin to read phone control status", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("status"),
channel: "telegram",
senderIsOwner: false,
});
expect(res?.text ?? "").toContain("Phone control: disarmed.");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("allows external non-owner callers without operator.admin to read phone control help", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("help"),
channel: "telegram",
senderIsOwner: false,
});
expect(res?.text ?? "").toContain("/phone status");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("regression: blocks non-webchat gateway callers with operator.write from arm/disarm", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const armRes = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "telegram",
gatewayClientScopes: ["operator.write"],
});
expect(armRes?.text ?? "").toContain("requires operator.admin");
expect(writeConfigFile).not.toHaveBeenCalled();
const disarmRes = await command.handler({
...createCommandContext("disarm"),
channel: "telegram",
gatewayClientScopes: ["operator.write"],
});
expect(disarmRes?.text ?? "").toContain("requires operator.admin");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("allows internal operator.admin callers to mutate phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
expect(res?.text ?? "").toContain("sms.send");
expect(writeConfigFile).toHaveBeenCalledTimes(1);
});
});
it("rejects invalid arm durations without mutating phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const typoRes = await command.handler({
...createCommandContext("arm writes forever"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
const overflowRes = await command.handler({
...createCommandContext("arm writes 9007199254740993d"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
expect(typoRes?.text ?? "").toContain("Invalid duration");
expect(overflowRes?.text ?? "").toContain("Invalid duration");
expect(writeConfigFile).not.toHaveBeenCalled();
});
});
it("rejects arm requests when the expiry would exceed a valid Date", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(8_640_000_000_000_000));
try {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
expect(res?.text ?? "").toContain("Invalid duration");
expect(writeConfigFile).not.toHaveBeenCalled();
});
} finally {
vi.useRealTimers();
}
});
it("allows external owner callers without gateway scopes to mutate phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
const res = await command.handler({
...createCommandContext("arm writes 30s"),
channel: "telegram",
senderIsOwner: true,
});
expect(res?.text ?? "").toContain("Phone control: armed");
expect(writeConfigFile).toHaveBeenCalledTimes(1);
});
});
it("allows external channel callers with operator.admin to disarm phone control", async () => {
await withRegisteredPhoneControl(async ({ command, writeConfigFile }) => {
await command.handler({
...createCommandContext("arm writes 30s"),
channel: "webchat",
gatewayClientScopes: ["operator.admin"],
});
const res = await command.handler({
...createCommandContext("disarm"),
channel: "telegram",
gatewayClientScopes: ["operator.admin"],
});
expect(res?.text ?? "").toContain("disarmed");
expect(writeConfigFile).toHaveBeenCalledTimes(2);
});
});
it("does not block service startup on the initial expiry check", async () => {
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), PHONE_CONTROL_STATE_PREFIX));
try {
const lookup = vi.fn(async () => undefined);
let service: OpenClawPluginService | undefined;
registerPhoneControl.register(
createApi({
stateDir,
getConfig: createPhoneControlConfig,
writeConfig: async () => {},
registerCommand: () => {},
registerService: (registeredService) => {
service = registeredService;
},
openKeyedStore: createMockOpenKeyedStore({ lookup }),
}),
);
if (!service) {
throw new Error("phone-control plugin did not register its service");
}
await service.start({
config: createPhoneControlConfig(),
stateDir,
logger: { info() {}, warn() {}, error() {}, debug() {} },
});
expect(lookup).not.toHaveBeenCalled();
await new Promise<void>((resolve) => {
setImmediate(resolve);
});
expect(lookup).toHaveBeenCalledWith("current");
await service.stop?.({
config: createPhoneControlConfig(),
stateDir,
logger: { info() {}, warn() {}, error() {}, debug() {} },
});
} finally {
await fs.rm(stateDir, { recursive: true, force: true });
}
});
it("clears expired active allows before service startup completes", async () => {
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), PHONE_CONTROL_STATE_PREFIX));
try {
let config: Record<string, unknown> = {
gateway: {
nodes: {
allowCommands: [...WRITE_COMMANDS],
denyCommands: [],
},
},
};
const writeConfigFile = vi.fn(async (next: Record<string, unknown>) => {
config = next;
});
const lookup = vi.fn(async () => ({
version: 2,
armedAtMs: Date.now() - 120_000,
expiresAtMs: Date.now() - 60_000,
group: "writes",
armedCommands: [...WRITE_COMMANDS],
addedToAllow: [...WRITE_COMMANDS],
removedFromDeny: [...WRITE_COMMANDS],
}));
const removeState = vi.fn(async () => true);
let service: OpenClawPluginService | undefined;
registerPhoneControl.register(
createApi({
stateDir,
getConfig: () => config,
writeConfig: writeConfigFile,
registerCommand: () => {},
registerService: (registeredService) => {
service = registeredService;
},
openKeyedStore: createMockOpenKeyedStore({ lookup, delete: removeState }),
}),
);
if (!service) {
throw new Error("phone-control plugin did not register its service");
}
await service.start({
config,
stateDir,
logger: { info() {}, warn() {}, error() {}, debug() {} },
});
expect(writeConfigFile).toHaveBeenCalledTimes(1);
expect(removeState).toHaveBeenCalledWith("current");
expect(
(config.gateway as { nodes?: { allowCommands?: string[]; denyCommands?: string[] } }).nodes,
).toEqual({
allowCommands: [],
denyCommands: [...WRITE_COMMANDS],
});
await service.stop?.({
config,
stateDir,
logger: { info() {}, warn() {}, error() {}, debug() {} },
});
} finally {
await fs.rm(stateDir, { recursive: true, force: true });
}
});
});

View File

@@ -0,0 +1,482 @@
// Phone Control plugin entrypoint registers its OpenClaw integration.
import {
asDateTimestampMs,
resolveExpiresAtMsFromDurationMs,
} from "openclaw/plugin-sdk/number-runtime";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalLowercaseString,
normalizeStringEntries,
sortUniqueStrings,
} from "openclaw/plugin-sdk/string-coerce-runtime";
import {
definePluginEntry,
type OpenClawPluginApi,
type OpenClawPluginService,
} from "./runtime-api.js";
type ArmGroup = "camera" | "screen" | "writes" | "all";
type ArmStateFileV1 = {
version: 1;
armedAtMs: number;
expiresAtMs: number | null;
removedFromDeny: string[];
};
type ArmStateFileV2 = {
version: 2;
armedAtMs: number;
expiresAtMs: number | null;
group: ArmGroup;
armedCommands: string[];
addedToAllow: string[];
removedFromDeny: string[];
};
type ArmStateFile = ArmStateFileV1 | ArmStateFileV2;
type PhoneControlConfigView = {
readonly gateway?: {
readonly nodes?: {
readonly allowCommands?: readonly string[];
readonly denyCommands?: readonly string[];
};
};
};
const STATE_VERSION = 2;
const ARM_STATE_NAMESPACE = "armed";
const ARM_STATE_KEY = "current";
const PHONE_ADMIN_SCOPE = "operator.admin";
const GROUP_COMMANDS: Record<Exclude<ArmGroup, "all">, string[]> = {
camera: ["camera.snap", "camera.clip"],
screen: ["screen.record"],
writes: ["calendar.add", "contacts.add", "reminders.add", "sms.send"],
};
const PHONE_CONTROL_COMMANDS = Object.values(GROUP_COMMANDS).flat();
function uniqSorted(values: string[]): string[] {
return sortUniqueStrings(normalizeStringEntries(values));
}
function resolveCommandsForGroup(group: ArmGroup): string[] {
if (group === "all") {
return uniqSorted(Object.values(GROUP_COMMANDS).flat());
}
return uniqSorted(GROUP_COMMANDS[group]);
}
function formatGroupList(): string {
return ["camera", "screen", "writes", "all"].join(", ");
}
function parseDurationMs(input: string | undefined): number | null {
const raw = normalizeOptionalLowercaseString(input);
if (!raw) {
return null;
}
const m = raw.match(/^(\d+)(s|m|h|d)$/);
if (!m) {
return null;
}
const n = Number.parseInt(m[1] ?? "", 10);
if (!Number.isFinite(n) || n <= 0) {
return null;
}
const unit = m[2];
const mult = unit === "s" ? 1000 : unit === "m" ? 60_000 : unit === "h" ? 3_600_000 : 86_400_000;
const durationMs = n * mult;
return Number.isSafeInteger(durationMs) ? durationMs : null;
}
function formatDuration(ms: number): string {
const s = Math.max(0, Math.floor(ms / 1000));
if (s < 60) {
return `${s}s`;
}
const m = Math.floor(s / 60);
if (m < 60) {
return `${m}m`;
}
const h = Math.floor(m / 60);
if (h < 48) {
return `${h}h`;
}
const d = Math.floor(h / 24);
return `${d}d`;
}
function openArmStateStore(api: OpenClawPluginApi) {
return api.runtime.state.openKeyedStore<ArmStateFile>({
namespace: ARM_STATE_NAMESPACE,
maxEntries: 1,
});
}
async function readArmState(api: OpenClawPluginApi): Promise<ArmStateFile | null> {
return (await openArmStateStore(api).lookup(ARM_STATE_KEY)) ?? null;
}
async function writeArmState(api: OpenClawPluginApi, state: ArmStateFile | null): Promise<void> {
const store = openArmStateStore(api);
if (!state) {
await store.delete(ARM_STATE_KEY);
return;
}
await store.register(ARM_STATE_KEY, state);
}
function normalizeDenyList(cfg: PhoneControlConfigView): string[] {
return uniqSorted([...(cfg.gateway?.nodes?.denyCommands ?? [])]);
}
function normalizeAllowList(cfg: PhoneControlConfigView): string[] {
return uniqSorted([...(cfg.gateway?.nodes?.allowCommands ?? [])]);
}
function hasPhoneControlAllowOverride(cfg: PhoneControlConfigView): boolean {
const allow = new Set(normalizeAllowList(cfg));
return PHONE_CONTROL_COMMANDS.some((cmd) => allow.has(cmd));
}
function patchConfigNodeLists(
cfg: OpenClawPluginApi["config"],
next: { allowCommands: string[]; denyCommands: string[] },
): OpenClawPluginApi["config"] {
return {
...cfg,
gateway: {
...cfg.gateway,
nodes: {
...cfg.gateway?.nodes,
allowCommands: next.allowCommands,
denyCommands: next.denyCommands,
},
},
};
}
async function disarmNow(params: {
api: OpenClawPluginApi;
reason: string;
}): Promise<{ changed: boolean; restored: string[]; removed: string[] }> {
const { api, reason } = params;
const state = await readArmState(api);
if (!state) {
return { changed: false, restored: [], removed: [] };
}
const cfg = api.runtime.config.current();
const allow = new Set(normalizeAllowList(cfg));
const deny = new Set(normalizeDenyList(cfg));
const removed: string[] = [];
const restored: string[] = [];
if (state.version === 1) {
for (const cmd of state.removedFromDeny) {
if (!deny.has(cmd)) {
deny.add(cmd);
restored.push(cmd);
}
}
} else {
for (const cmd of state.addedToAllow) {
if (allow.delete(cmd)) {
removed.push(cmd);
}
}
for (const cmd of state.removedFromDeny) {
if (!deny.has(cmd)) {
deny.add(cmd);
restored.push(cmd);
}
}
}
if (removed.length > 0 || restored.length > 0) {
await api.runtime.config.mutateConfigFile({
afterWrite: { mode: "auto" },
mutate: (draft) => {
const next = patchConfigNodeLists(draft, {
allowCommands: uniqSorted([...allow]),
denyCommands: uniqSorted([...deny]),
});
Object.assign(draft, next);
},
});
}
await writeArmState(api, null);
api.logger.info(`phone-control: disarmed (${reason})`);
return {
changed: removed.length > 0 || restored.length > 0,
removed: uniqSorted(removed),
restored: uniqSorted(restored),
};
}
function formatHelp(): string {
return [
"Phone control commands:",
"",
"/phone status",
"/phone arm <group> [duration]",
"/phone disarm",
"",
"Groups:",
`- ${formatGroupList()}`,
"",
"Duration format: 30s | 10m | 2h | 1d (default: 10m).",
"",
"Notes:",
"- This only toggles what the gateway is allowed to invoke on phone nodes.",
"- iOS will still ask for permissions (camera, photos, contacts, etc.) on first use.",
].join("\n");
}
function parseGroup(raw: string | undefined): ArmGroup | null {
const value = normalizeOptionalLowercaseString(raw) ?? "";
if (!value) {
return null;
}
if (value === "camera" || value === "screen" || value === "writes" || value === "all") {
return value;
}
return null;
}
function lacksAdminToMutatePhoneControl(params: {
senderIsOwner?: boolean;
gatewayClientScopes?: readonly string[];
}): boolean {
const { senderIsOwner, gatewayClientScopes } = params;
if (Array.isArray(gatewayClientScopes)) {
return !gatewayClientScopes.includes(PHONE_ADMIN_SCOPE);
}
return senderIsOwner !== true;
}
function resolveArmExpiryStatus(state: ArmStateFile, nowRaw = Date.now()): string {
if (state.expiresAtMs == null) {
return "manual disarm required";
}
const now = asDateTimestampMs(nowRaw);
if (now === undefined) {
return "expiry unavailable";
}
const expiresAt = asDateTimestampMs(state.expiresAtMs);
if (expiresAt === undefined || expiresAt <= now) {
return "expired";
}
return `expires in ${formatDuration(expiresAt - now)}`;
}
function isArmStateExpired(state: ArmStateFile, nowRaw = Date.now()): boolean {
if (state.expiresAtMs == null) {
return false;
}
const now = asDateTimestampMs(nowRaw);
if (now === undefined) {
return false;
}
const expiresAt = asDateTimestampMs(state.expiresAtMs);
return expiresAt === undefined || expiresAt <= now;
}
function formatStatus(state: ArmStateFile | null): string {
if (!state) {
return "Phone control: disarmed.";
}
const until = resolveArmExpiryStatus(state);
const cmds = uniqSorted(
state.version === 1
? state.removedFromDeny
: state.armedCommands.length > 0
? state.armedCommands
: [...state.addedToAllow, ...state.removedFromDeny],
);
const cmdLabel = cmds.length > 0 ? cmds.join(", ") : "none";
return `Phone control: armed (${until}).\nTemporarily allowed: ${cmdLabel}`;
}
export default definePluginEntry({
id: "phone-control",
name: "Phone Control",
description: "Temporary allowlist control for phone automation commands",
register(api: OpenClawPluginApi) {
let expiryInterval: ReturnType<typeof setInterval> | null = null;
let initialExpiryTick: ReturnType<typeof setImmediate> | null = null;
const timerService: OpenClawPluginService = {
id: "phone-control-expiry",
start: async (ctx) => {
const tick = async () => {
const state = await readArmState(api);
if (!state || state.expiresAtMs == null) {
return;
}
if (!isArmStateExpired(state)) {
return;
}
await disarmNow({
api,
reason: "expired",
});
};
expiryInterval = setInterval(() => {
tick().catch(() => {});
}, 15_000);
expiryInterval.unref?.();
if (hasPhoneControlAllowOverride(ctx.config)) {
// Active dangerous command allows must be reconciled before gateway
// readiness; otherwise an expired phone-control window can survive.
await tick().catch(() => {});
} else {
// With no active phone-control allowlist, startup can avoid opening
// plugin state before readiness; cleanup still runs before the interval.
initialExpiryTick = setImmediate(() => {
initialExpiryTick = null;
tick().catch(() => {});
});
initialExpiryTick.unref?.();
}
},
stop: async () => {
if (initialExpiryTick) {
clearImmediate(initialExpiryTick);
initialExpiryTick = null;
}
if (expiryInterval) {
clearInterval(expiryInterval);
expiryInterval = null;
}
},
};
api.registerService(timerService);
api.registerCommand({
name: "phone",
description: "Arm/disarm high-risk phone node commands (camera/screen/writes).",
acceptsArgs: true,
exposeSenderIsOwner: true,
handler: async (ctx) => {
const args = ctx.args?.trim() ?? "";
const tokens = args.split(/\s+/).filter(Boolean);
const action = normalizeLowercaseStringOrEmpty(tokens[0]);
if (!action || action === "help") {
const state = await readArmState(api);
return { text: `${formatStatus(state)}\n\n${formatHelp()}` };
}
if (action === "status") {
const state = await readArmState(api);
return { text: formatStatus(state) };
}
if (action === "disarm") {
if (
lacksAdminToMutatePhoneControl({
senderIsOwner: ctx.senderIsOwner,
gatewayClientScopes: ctx.gatewayClientScopes,
})
) {
return {
text: "⚠️ /phone disarm requires operator.admin.",
};
}
const res = await disarmNow({
api,
reason: "manual",
});
if (!res.changed) {
return { text: "Phone control: disarmed." };
}
const restoredLabel = res.restored.length > 0 ? res.restored.join(", ") : "none";
const removedLabel = res.removed.length > 0 ? res.removed.join(", ") : "none";
return {
text: `Phone control: disarmed.\nRemoved allowlist: ${removedLabel}\nRestored denylist: ${restoredLabel}`,
};
}
if (action === "arm") {
if (
lacksAdminToMutatePhoneControl({
senderIsOwner: ctx.senderIsOwner,
gatewayClientScopes: ctx.gatewayClientScopes,
})
) {
return {
text: "⚠️ /phone arm requires operator.admin.",
};
}
const group = parseGroup(tokens[1]);
if (!group) {
return { text: `Usage: /phone arm <group> [duration]\nGroups: ${formatGroupList()}` };
}
const durationMs = tokens[2] === undefined ? 10 * 60_000 : parseDurationMs(tokens[2]);
if (durationMs === null) {
return { text: "Invalid duration. Use values like 30s, 10m, 2h, or 1d." };
}
const armedAtMs = asDateTimestampMs(Date.now());
const expiresAtMs =
armedAtMs === undefined
? undefined
: resolveExpiresAtMsFromDurationMs(durationMs, { nowMs: armedAtMs });
if (armedAtMs === undefined || expiresAtMs === undefined) {
return { text: "Invalid duration. Use values like 30s, 10m, 2h, or 1d." };
}
const commands = resolveCommandsForGroup(group);
const cfg = api.runtime.config.current();
const allowSet = new Set(normalizeAllowList(cfg));
const denySet = new Set(normalizeDenyList(cfg));
const addedToAllow: string[] = [];
const removedFromDeny: string[] = [];
for (const cmd of commands) {
if (!allowSet.has(cmd)) {
allowSet.add(cmd);
addedToAllow.push(cmd);
}
if (denySet.delete(cmd)) {
removedFromDeny.push(cmd);
}
}
await api.runtime.config.mutateConfigFile({
afterWrite: { mode: "auto" },
mutate: (draft) => {
const next = patchConfigNodeLists(draft, {
allowCommands: uniqSorted([...allowSet]),
denyCommands: uniqSorted([...denySet]),
});
Object.assign(draft, next);
},
});
await writeArmState(api, {
version: STATE_VERSION,
armedAtMs,
expiresAtMs,
group,
armedCommands: uniqSorted(commands),
addedToAllow: uniqSorted(addedToAllow),
removedFromDeny: uniqSorted(removedFromDeny),
});
const allowedLabel = uniqSorted(commands).join(", ");
return {
text:
`Phone control: armed for ${formatDuration(durationMs)}.\n` +
`Temporarily allowed: ${allowedLabel}\n` +
`To disarm early: /phone disarm`,
};
}
return { text: formatHelp() };
},
});
},
});

View File

@@ -0,0 +1,20 @@
{
"id": "phone-control",
"activation": {
"onStartup": true
},
"enabledByDefault": true,
"name": "Phone Control",
"description": "Arm/disarm high-risk phone node commands (camera/screen/writes) with an optional auto-expiry.",
"commandAliases": [
{
"name": "phone",
"kind": "runtime-slash"
}
],
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {}
}
}

View File

@@ -0,0 +1,8 @@
// Phone Control API module exposes the plugin public contract.
export { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
export type {
OpenClawPluginApi,
OpenClawPluginCommandDefinition,
PluginCommandContext,
OpenClawPluginService,
} from "openclaw/plugin-sdk/plugin-entry";