@atbash/sdk 0.7.2-dev.0 → 0.8.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -281,6 +281,16 @@ interface AtbashOptions {
281
281
  * per-call `verifyPubKey` still overrides it.
282
282
  */
283
283
  verifyPubKey?: string;
284
+ /**
285
+ * Org's encryption public key (33-byte compressed secp256k1, hex). When set,
286
+ * tool calls are sealed to it and signed as `log_encrypted_tool_call` instead
287
+ * of `log_tool_call`, so the action never reaches the block in clear.
288
+ *
289
+ * Required for any org that has registered a key — the contract refuses
290
+ * plaintext for those. Omitted, behaviour is unchanged. A per-call
291
+ * `orgEncryptionPubKey` overrides this, same as `verifyPubKey`.
292
+ */
293
+ orgEncryptionPubKey?: string;
284
294
  /** When true (default), `auditToolCall` denies on any error. */
285
295
  failClosed?: boolean;
286
296
  logger?: AtbashLogger;
@@ -332,6 +342,8 @@ interface JudgeOptions {
332
342
  provider?: string;
333
343
  model?: string;
334
344
  verifyPubKey?: string;
345
+ /** Per-call override of {@link AtbashOptions.orgEncryptionPubKey}. */
346
+ orgEncryptionPubKey?: string;
335
347
  /**
336
348
  * Org name — when set, the SDK resolves which chain the agent lives
337
349
  * on via the off-chain `org_networks` map (authoritative) before
@@ -360,6 +372,8 @@ interface LogToolCallOptions {
360
372
  toolArgsJson?: string;
361
373
  /** Per-call chain override — same semantics as `JudgeOptions.chainOpts`. */
362
374
  chainOpts?: ChainOpts;
375
+ /** Per-call override of {@link AtbashOptions.orgEncryptionPubKey}. */
376
+ orgEncryptionPubKey?: string;
363
377
  }
364
378
 
365
379
  interface ChainConfig {
@@ -377,6 +391,8 @@ declare class Atbash {
377
391
  readonly orgName?: string;
378
392
  /** Default judge response-signing pubkey, if configured (see fromConfig). */
379
393
  readonly verifyPubKey?: string;
394
+ /** Default org encryption key — see {@link AtbashOptions.orgEncryptionPubKey}. */
395
+ readonly orgEncryptionPubKey?: string;
380
396
  /** When true (default), `auditToolCall` denies on any error. */
381
397
  readonly failClosed: boolean;
382
398
  private readonly logger;
@@ -1051,11 +1067,150 @@ declare function flushTelemetry(): Promise<void>;
1051
1067
  */
1052
1068
  declare function shutdownTelemetry(): Promise<void>;
1053
1069
 
1070
+ /**
1071
+ * Signs `log_encrypted_tool_call` — the ciphertext-only counterpart of
1072
+ * `log_tool_call`.
1073
+ *
1074
+ * Why this is not in the Rust core like the other signing helpers: the operation
1075
+ * takes a `byte_array` argument, and the only consumer today is the dashboard,
1076
+ * which loads the browser bundle where Rust is unreachable by construction. This
1077
+ * module is plain TypeScript so the node and browser builds share one
1078
+ * implementation and cannot drift. The Rust core gets the same operation when the
1079
+ * native/Python/Go callers need it — the wire format is pinned by `crypto/ecies.ts`.
1080
+ *
1081
+ * The contract refuses plaintext once an org registers an encryption key
1082
+ * (`log_tool_call` → "Organization requires encrypted payloads"), so for those
1083
+ * orgs this is the only way to log a tool call at all.
1084
+ */
1085
+ /** Plaintext fields of a tool call, sealed into a single ECIES payload. */
1086
+ interface ToolCallPlaintext {
1087
+ tool_name: string;
1088
+ action: string;
1089
+ context: string;
1090
+ tool_args_json: string;
1091
+ }
1092
+ /**
1093
+ * Canonical form of an action for the retry-cache hash.
1094
+ *
1095
+ * Must stay identical to `normalizeActionForHash` in the dashboard
1096
+ * (`src/lib/api/judge/on-chain.ts`): both write the same
1097
+ * `tool_call_log.normalized_action_hash` column, and `get_resolved_hold_by_action_hash`
1098
+ * matches a YELLOW hold retry against it. Diverging here silently breaks
1099
+ * hold resolution rather than failing loudly.
1100
+ */
1101
+ declare function normalizeActionForHash(action: string): string;
1102
+ /**
1103
+ * Sign a `log_encrypted_tool_call` operation.
1104
+ *
1105
+ * Everything the agent did — action, context, tool name and args — goes into a
1106
+ * single ECIES payload readable only with the org's private key. Nothing
1107
+ * identifying the action is left in the operation arguments, which are permanent
1108
+ * block data.
1109
+ *
1110
+ * `actionHash` is the one exception, and it is deliberate: it is a SHA-256 over
1111
+ * the normalized action, so the chain can match a held action against its retry
1112
+ * without being able to read it.
1113
+ *
1114
+ * @returns hex-encoded signed transaction, ready to POST as `signed_log_tool_call`.
1115
+ */
1116
+ declare function signEncryptedToolCall(toolCallId: string, action: string, context: string, toolName: string, toolArgsJson: string, orgEncryptionPubKey: string, privkeyHex: string, blockchainRidHex: string): string;
1117
+
1118
+ /**
1119
+ * ECIES over secp256k1 — encrypts on-chain payloads to an organization's public key.
1120
+ *
1121
+ * Only the holder of the org's private key can decrypt. Everyone else — including
1122
+ * anyone querying the Chromia node directly, and Atbash itself — sees ciphertext.
1123
+ * The recipient key is a dedicated encryption keypair the org generates in the
1124
+ * dashboard and registers via `org_set_encryption_key`; it is read back with the
1125
+ * `get_org_encryption_pubkey` query.
1126
+ *
1127
+ * ─── WIRE FORMAT (normative) ────────────────────────────────────────────────
1128
+ * This exact layout is mirrored in the Atbash dashboard
1129
+ * (`src/lib/chromia/ecies.ts`) and must stay byte-for-byte identical: the SDK
1130
+ * encrypts tool calls, the dashboard decrypts them.
1131
+ *
1132
+ * version 1 byte = 0x01
1133
+ * ephemeral_pubkey 33 bytes compressed secp256k1 point
1134
+ * nonce 12 bytes random, per message
1135
+ * ciphertext+tag N bytes AES-256-GCM output (16-byte tag appended)
1136
+ *
1137
+ * Version 0x01 is FROZEN, not provisional. Records encrypted under it already
1138
+ * exist on the deployed chains, and the ledger is immutable — redefining 0x01
1139
+ * would make them permanently unreadable, not merely stale. Evolving the format
1140
+ * means emitting a NEW version byte and keeping a 0x01 decrypt path, in both
1141
+ * repos, forever.
1142
+ *
1143
+ * Raw bytes, not base64: the on-chain columns are `byte_array`, so encoding to
1144
+ * text would add ~33% to what are the largest columns in the schema.
1145
+ *
1146
+ * Key agreement, per message:
1147
+ * shared_x = ECDH(ephemeral_privkey, org_pubkey).x // 32 bytes
1148
+ * key = HKDF-SHA256(ikm=shared_x, salt=ephemeral_pubkey, info=domain, len=32)
1149
+ * aad = "<domain>|<record_id>"
1150
+ *
1151
+ * A fresh ephemeral keypair is generated for every message and its private half is
1152
+ * discarded immediately. This is what makes the scheme forward-secret with respect
1153
+ * to the *sender*: leaking an agent's long-term signing key later does not expose
1154
+ * anything it encrypted in the past. (Deriving the shared secret from the agent's
1155
+ * static key instead would let anyone recompute every past shared secret, since the
1156
+ * org's public key is public by definition.)
1157
+ *
1158
+ * Three separate bindings, each closing a different substitution:
1159
+ * salt = ephemeral pubkey — ties the key to this exact handshake
1160
+ * info = domain — a verdict payload cannot be read as a tool call
1161
+ * aad = domain|record_id — a payload cannot be lifted onto another row
1162
+ */
1163
+ /**
1164
+ * Cryptographic domain per payload kind. Fed to HKDF `info`, so each kind derives
1165
+ * a different key from the same handshake — a verdict payload handed to the
1166
+ * tool-call reader fails authentication rather than decoding to an empty struct.
1167
+ *
1168
+ * Must match `EciesDomain` in the dashboard's src/lib/chromia/ecies.ts exactly:
1169
+ * the string is an input to key derivation, so any difference makes the two sides
1170
+ * mutually unreadable.
1171
+ */
1172
+ declare const EciesDomain: {
1173
+ readonly toolCall: "atbash:chain-encryption:v1:toolcall";
1174
+ readonly verdict: "atbash:chain-encryption:v1:verdict";
1175
+ readonly note: "atbash:chain-encryption:v1:note";
1176
+ readonly policy: "atbash:chain-encryption:v1:policy";
1177
+ readonly raw: "atbash:chain-encryption:v1:raw";
1178
+ };
1179
+ type EciesDomain = (typeof EciesDomain)[keyof typeof EciesDomain];
1180
+ /**
1181
+ * Encrypt `plaintext` so that only the holder of `orgPubKeyHex` can read it.
1182
+ *
1183
+ * @param plaintext UTF-8 text to protect.
1184
+ * @param orgPubKeyHex Org's compressed secp256k1 public key (33 bytes hex).
1185
+ * @param aad Context bound to the ciphertext — pass the record's id.
1186
+ * @returns raw payload for a Rell `byte_array` column.
1187
+ */
1188
+ declare function encryptForOrg(plaintext: string, orgPubKeyHex: string, aad: string, domain?: EciesDomain): Uint8Array;
1189
+ /**
1190
+ * Decrypt a payload produced by {@link encryptForOrg}.
1191
+ *
1192
+ * Throws if the key is wrong, the `aad` does not match the one used at encrypt
1193
+ * time, or the ciphertext was tampered with — GCM authentication makes all three
1194
+ * indistinguishable by design.
1195
+ *
1196
+ * @param payload Value read from the on-chain `byte_array` column.
1197
+ * @param orgPrivKeyHex Org's secp256k1 private key (32 bytes hex).
1198
+ * @param aad Must equal the `aad` used when encrypting.
1199
+ */
1200
+ declare function decryptForOrg(payload: Uint8Array, orgPrivKeyHex: string, aad: string, domain?: EciesDomain): string;
1201
+ /**
1202
+ * Size in bytes of the encrypted payload for a given plaintext length. Lets
1203
+ * callers check against the on-chain column cap (MAX_CONTENT_CIPHER_SIZE)
1204
+ * before submitting a transaction the contract would reject.
1205
+ */
1206
+ declare function encryptedLength(plaintextByteLength: number): number;
1207
+
1054
1208
  declare function isValidPrivateKey(hex: string): boolean;
1055
1209
  declare function derivePublicKey(privkey: string): string;
1056
1210
  declare function generateKeypair(): KeyPair;
1057
1211
  declare function loadAgent(privkey: string): AgentAuth;
1058
1212
  declare function signLogToolCall(toolCallId: string, action: string, context: string, toolName: string, toolArgsJson: string, privkey: string, blockchainRid: string): string;
1213
+
1059
1214
  declare function signJudgeAction(judgmentId: string, action: string, context: string, extra: string, privkey: string, blockchainRid: string): string;
1060
1215
  declare function verifySignature(body: Buffer, signatureHex: string, pubkeyHex: string): boolean;
1061
1216
  declare function normalizeForMatching(text: string): string;
@@ -1065,4 +1220,4 @@ declare function containsSecret(text: string): boolean;
1065
1220
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
1066
1221
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
1067
1222
 
1068
- export { type ActionType, type AgentAuth, type AgentMemoryEntry, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, type ChainOpts, type ClassifierToolContext, type ClassifierToolEvent, type ClassifyMemoryReadOptions, type ClassifyMemoryWriteOptions, type ClientSource, type CommitMemoryOptions, DEFAULT_BLOCKCHAIN_RID, DEFAULT_CHROMIA_NODE_URLS, DEFAULT_ENDPOINT, DEFAULT_MEMORY_PATH_PATTERNS, DEFAULT_MEMORY_READ_TOOL_NAMES, DEFAULT_MEMORY_WRITE_TOOL_NAMES, type Decision, type DecisionVerdict, type EncryptedMemory, type FromConfigOptions, type GuardLogger, type GuardMemoryDecision, type GuardMemoryWriteInput, type GuardMemoryWriteResult, type HeldAction, type HeldActionReview, type HookDecision, type JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, MemoryGuardManager, type MemoryGuardManagerOptions, MemoryIntegrityError, type MemoryPointer, type MemoryRollbackEvent, type MemoryScanOptions, type MemoryScanResult, type MemoryScanVerdict, type MemorySnapshot, type ModifiedEntry, type Network, type OrgSubscription, PointerStore, type Provider, type PubkeyValue, type RedactResult, type RollbackMemoryOptions, type SecretKind, type SecretMatch, SignatureVerificationError, type Subscription, type SyncMemoryOptions, type SyncMemoryResult, type TelemetryConfig, type TierInfo, type ToolCallFull, type ToolCallInput, type ToolCallRecord, type ValidatedEndpoint, type Verdict, type WrappedLogger, classifyMemoryRead, classifyMemoryWrite, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptMemoryContent, flushTelemetry, generateKeypair, getActiveMemory, getActiveMemoryId, getAllAgentMemory, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRollbackHistory, guardMemoryWrite, isValidPrivateKey, loadAgent, loadAgentFromFile, loadUserConfig, normalizeForMatching, normalizeStatus, normalizeVerdict, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };
1223
+ export { type ActionType, type AgentAuth, type AgentMemoryEntry, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, type ChainOpts, type ClassifierToolContext, type ClassifierToolEvent, type ClassifyMemoryReadOptions, type ClassifyMemoryWriteOptions, type ClientSource, type CommitMemoryOptions, DEFAULT_BLOCKCHAIN_RID, DEFAULT_CHROMIA_NODE_URLS, DEFAULT_ENDPOINT, DEFAULT_MEMORY_PATH_PATTERNS, DEFAULT_MEMORY_READ_TOOL_NAMES, DEFAULT_MEMORY_WRITE_TOOL_NAMES, type Decision, type DecisionVerdict, EciesDomain, type EncryptedMemory, type FromConfigOptions, type GuardLogger, type GuardMemoryDecision, type GuardMemoryWriteInput, type GuardMemoryWriteResult, type HeldAction, type HeldActionReview, type HookDecision, type JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, MemoryGuardManager, type MemoryGuardManagerOptions, MemoryIntegrityError, type MemoryPointer, type MemoryRollbackEvent, type MemoryScanOptions, type MemoryScanResult, type MemoryScanVerdict, type MemorySnapshot, type ModifiedEntry, type Network, type OrgSubscription, PointerStore, type Provider, type PubkeyValue, type RedactResult, type RollbackMemoryOptions, type SecretKind, type SecretMatch, SignatureVerificationError, type Subscription, type SyncMemoryOptions, type SyncMemoryResult, type TelemetryConfig, type TierInfo, type ToolCallFull, type ToolCallInput, type ToolCallPlaintext, type ToolCallRecord, type ValidatedEndpoint, type Verdict, type WrappedLogger, classifyMemoryRead, classifyMemoryWrite, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, flushTelemetry, generateKeypair, getActiveMemory, getActiveMemoryId, getAllAgentMemory, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRollbackHistory, guardMemoryWrite, isValidPrivateKey, loadAgent, loadAgentFromFile, loadUserConfig, normalizeActionForHash, normalizeForMatching, normalizeStatus, normalizeVerdict, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signEncryptedToolCall, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };