Node.js SDK
対応モード: Hosted Hybrid Local 利用可能なプラン: Free Solo Teams
英語の原文 -- 翻訳は技術レビュー待ちです
The Control Zero Node.js SDK provides deterministic policy enforcement for AI agents running in JavaScript and TypeScript environments. A deny stops the guarded call before it executes. Hosted policies arrive as signed bundles that are verified before use, and the SDK fails closed by default when it cannot establish coverage.
変更できないアプリケーションにはゲートウェイプロキシを、開発者向けの AI ツールにはコーディングフックを使用します。JavaScript または TypeScript のアプリケーションコードを自分で管理できる場合に、この SDK を使用します。
インストール
@controlzero パッケージは npmjs.org ではなく、Control Zero レジストリ(https://npm.controlzero.ai)から提供されます。.npmrc(プロジェクトレベルまたはユーザーレベル)で、スコープをこのレジストリに一度だけ向けてください。
@controlzero:registry=https://npm.controlzero.ai
そのうえで、インストールします。
npm install @controlzero/sdk
これにより、このページに記載されている機能セットに対応する現行の 1.13.x 系がインストールされます。@controlzero スコープ以外の依存関係は、引き続き npmjs.org から解決されます。
要件:
- Node.js 18 以降
- TypeScript 5.0+(任意。型チェック付きで使用する場合)
クイックスタート
デプロイモードを選択します。
Python SDK とは異なり、Node.js の new Client({apiKey}) コンストラクタは、ローカルポリシーなしで apiKey が指定されるとエラーを投げます。Hosted モードでは非同期ファクトリを使用してください。
// Hosted mode -- MUST use async factory
const cz = await Client.create({ apiKey: 'cz_live_your_api_key_here' });
// Local mode only -- synchronous constructor works
const cz = new Client({ policyFile: 'controlzero.yaml' });
- Hosted
- Hybrid
- Local
Hosted ポリシーはダッシュボードから取得されます。
英語の原文 -- 翻訳は技術レビュー待ちです
Audit in cloud.
ほとんどのチームに推奨します。
import { Client } from '@controlzero/sdk';
// MUST use async factory for hosted mode
const client = await Client.create({ apiKey: 'cz_live_your_api_key_here' });
// Or use env var: export CONTROLZERO_API_KEY="cz_live_..."
英語の原文 -- 翻訳は技術レビュー待ちです
The SDK pulls the signed policy bundle from the dashboard at first call, verifies its signature, decrypts locally, and enforces every call against the dashboard policy. Audit ships to the remote trail automatically.
Hybrid ポリシーファイルは利用者が管理します。
英語の原文 -- 翻訳は技術レビュー待ちです
API key enables remote audit only.
import { Client } from '@controlzero/sdk';
const client = await Client.create({
apiKey: 'cz_live_your_api_key_here',
policyFile: './controlzero.yaml',
});
適用は controlzero.yaml が制御します。
英語の原文 -- 翻訳は技術レビュー待ちです
The API key sends audit to your dashboard.
Local API キー不要。
英語の原文 -- 翻訳は技術レビュー待ちです
No network calls.
完全オフライ ン。エアギャップ環境に対応します。
import { Client } from '@controlzero/sdk';
// From a file -- synchronous constructor works for local mode
const client = new Client({ policyFile: './controlzero.yaml' });
// Or inline policy
const client = new Client({
policy: {
rules: [
{ allow: 'database:query', reason: 'Reads are permitted' },
{ deny: 'database:execute', reason: 'Writes are blocked' },
],
},
});
英語の原文 -- 翻訳は技術レビュー待ちです
Every decision and its event-level coverage is written to ./controlzero.log, so “did not run” remains distinguishable from “ran and found nothing.”
設定
Hosted Hosted モード(推奨)
非同期の Client.create ファクトリを使い、プロジェクトの API キーだけを渡します。
英語の原文 -- 翻訳は技術レビュー待ちです
The SDK pulls the signed policy bundle from the dashboard at first call, verifies its signature, decrypts locally, and enforces every call against the dashboard policy. Audit ships to the remote trail automatically.
import { Client } from '@controlzero/sdk';
const client = await Client.create({ apiKey: 'cz_live_your_api_key_here' });
new Client({ apiKey })(同期)は、API キーだけでは構築を拒否し、Client.create() を使うよう案内します。Hosted のブートストラップは I/O 呼び出しであり、await できる必要があるためです。
Local ローカルポリシーファイルを使う
import { Client } from '@controlzero/sdk';
const client = new Client({ policyFile: './controlzero.yaml' });
インラインポリシー
import { Client } from '@controlzero/sdk';
const client = new Client({
policy: {
rules: [
{ allow: 'database:query', reason: 'Reads are permitted' },
{ deny: 'database:*', reason: 'All other database operations are blocked' },
],
},
});
database:query、database:execute、database:delete は従来のアクション名で、正式な database:read、database:write、database:admin クラスと同じ呼び出しに一致します。新しいポリシーでは正式な名前を使うことを推奨しますが、従来の名前を使った既存のルールも変更なしで引き続き動作します。
ワイルドカードによるリソースの一致
resources: ['*'] を指定したルールは、呼び出し側が context.resource を渡したかどうかにかかわらず、すべての呼び出しに一致します。ルールを一律に適用したく、呼び出しごとのリソースを持たない(または渡したくない)場合に使用します。
// Policy rule with universal resource matching
// { effect: 'allow', actions: ['database:read'], resources: ['*'] }
// This call matches even though context.resource is not set:
cz.guard('database', { method: 'query', args: { sql: 'SELECT 1' } });
ワイルドカードでないリソースパターン(例: resources: ['table/orders'])では、ルールが働くために、呼び出し側が一致する context.resource を渡す必要があります。
環境変数
引数を直接渡す代わりに、環境変数で SDK を設定できます。
export CONTROLZERO_POLICY_FILE="./controlzero.yaml"
import { Client } from '@controlzero/sdk';
// Reads CONTROLZERO_POLICY_FILE from environment, or auto-discovers
// controlzero.yaml, controlzero.yml, or controlzero.json in cwd
const client = new Client();
設定オプション
| オプション | 環境変数 | 型 | デフォルト | 説明 |
|---|---|---|---|---|
apiKey | CONTROLZERO_API_KEY | string | - | Project API key. Use Client.create({ apiKey }) to enable hosted mode (auto-pulls the signed policy bundle from the dashboard; remote audit). |
policy | - | object | - | ルールを含むインラインのポリシーオブジェクト。 |
policyFile | CONTROLZERO_POLICY_FILE | string | - | YAML または JSON のポリシーファイルへのパス。 |
strictHosted | - | bool | false | Hybrid(API キー + ローカルポリシー)の場合に、警告する代わりに例外を発生させます。 |
logPath | - | string | ./controlzero.log | ローカルの監査ログファイルのパス。 |
logRotation | - | string | daily | 監査ログのローテーション間隔。 |
logRetention | - | string | 30 days | How long to keep rotated logs. |
logCompression | - | string | null | ローテーション済みログを圧縮します(例: gz)。 |
logFormat | - | string | json | 監査ログの形式(json または pretty)。 |
refreshIntervalSeconds | - | number | 300 | Hosted モード: ダッシュボードに新しいポリシーバンドルがないか確認する間隔。 |
agentName | CZ_AGENT_NAME | string | - | 帰属を示すために監査イベントに記録されるラベル。 |
Node SDK の refreshIntervalSeconds のデフォルトは 300(5 分)です。Python SDK の refresh_interval_seconds のデフォルトは 60 です。2 つのポーリング間隔をそろえるには、refreshIntervalSeconds: 60 を設定します。
ポリシーの解決順序: policy オプション、policyFile オプション、環境変数 CONTROLZERO_POLICY_FILE、次に cwd で自動検出された最初のファイル(controlzero.yaml、次に controlzero.yml、次に controlzero.json -- 最初に存在したものが優先されます)、最後に 1 回だけ警告を出して何もせず通過させる動作になります。ポリシーファイルは YAML でも JSON でもよく、どちらも同一のスキーマを使用します。
基本的な使い方
ツール呼び出しの評価
主要なメソッドは guard() で、読み込まれたポリシーに対してツール呼び出しを評価します。
import { Client } from '@controlzero/sdk';
const client = new Client({ policyFile: './controlzero.yaml' });
const decision = client.guard('database', {
method: 'query',
args: { sql: 'SELECT * FROM orders' },
});
console.log(decision.effect); // "allow" or "deny"
console.log(decision.reason); // human-readable reason
console.log(decision.policyId); // matching policy ID
拒否されたアクションの処理
ポリシーがアクションを拒否した場合は、判定の effect を確認するか、PolicyDeniedError を捕捉します。
import { Client, PolicyDeniedError } from '@controlzero/sdk';
const client = new Client({ policyFile: './controlzero.yaml' });
const decision = client.guard('filesystem', {
method: 'write_file',
args: { path: '/data/output.csv', content: '...' },
});
if (decision.effect === 'deny') {
console.log(`Blocked: ${decision.reason}`);
console.log(`Policy: ${decision.policyId}`);
}
または、raiseOnDeny を使って、拒否時に例外を投げることもできます。
try {
client.guard('filesystem', {
method: 'write_file',
args: { path: '/data/output.csv' },
raiseOnDeny: true,
});
} catch (error) {
if (error instanceof PolicyDeniedError) {
console.log(`Blocked: ${error.message}`);
}
}
API リファレンス
Client
メインのクライアントクラスです。guard() は同期です。ローカルポリシー、Hybrid、およびポリシーなしのパススルーのクライアントでは、構築は同期です。API キーのみの Hosted ブートストラップだけが、非同期ファクトリを必要とします。
new Client(options?)
新しい Control Zero クライアントを作成します。利用可能なパラメータについては、設定オプションを参照してください。initialize() の呼び出しは不要です。コンストラクタがローカルポリシーを即座に読み込みます。ポリシーがまったく設定されていない場合、クライアントは 1 回だけ警告を出し、呼び出しをそのまま通過させます。
ローカルポリシーなしで apiKey を渡すと、HostedModeNotImplemented が投げられます。Hosted モードには Client.create() を使用してください。
static Client.create(options?): Promise<Client>
英語の原文 -- 翻訳は技術レビュー待ちです
Async factory. Required for hosted mode: it fetches the signed policy bundle, verifies its signature and decrypts it before returning the client.
guard(tool, opts?): PolicyDecision
読み込まれたポリシーに対してツール呼び出しを評価します。
パラメータ:
| 名前 | 型 | 必須 | 説明 |
|---|---|---|---|
tool | string | はい | ツール名(例: "database")。 |
opts | GuardOptions | いいえ | method、args、raiseOnDeny、context を持つオプションオブジェクト。 |
GuardOptions:
| フィールド | 型 | デフォルト | 説明 |
|---|---|---|---|
method | string | "*" | メソッド名。ツールと組み合わせて "tool:method" というアクションになります。 |
args | object | {} | DLP スキャンと条件評価に使う引数。 |
raiseOnDeny | boolean | false | true の場合、拒否のときに PolicyDeniedError を投げます。 |
context | object | - | 一致判定に使う、resource と tags を持つ任意のコンテキスト。 |
戻り値: effect、reason、policyId、dlpFindings を持つ PolicyDecision。
close(): Promise<void>
バッファリングされた監査ログをフラッシュし、リソースを解放します。
PolicyDecision
guard() が返します。
| 属性 | 型 | 説明 |
|---|---|---|
effect | string | "allow" または "deny"。 |
policyId | string or null | 一致したポリシー(ある場合)。 |
reason | string | 人が読める説明。 |
denied | boolean | 便利なプロパティ: effect が "deny" のとき true。 |
dlpFindings | array | 引数内で見つかった DLP の一致のリスト。 |
PolicyDeniedError
raiseOnDeny が true でポリシーがアクションを拒否した場合に、guard() が投げます。
class PolicyDeniedError extends Error {
readonly decision: PolicyDecision;
}
MCP での使用
Control Zero は Model Context Protocol と自然に統合できます。次は、MCP のツール呼び出しをポリシーの適用でラップする例です。
import { Client, PolicyDeniedError } from '@controlzero/sdk';
const cz = new Client({ policyFile: './controlzero.yaml' });
function callMCPToolGoverned(server: string, tool: string, args: Record<string, unknown>): unknown {
// Evaluate the policy before calling the tool
cz.guard(server, {
method: tool,
args,
raiseOnDeny: true,
});
// Policy check passed. Call the tool
return mcpClient.callTool(server, tool, args);
}