0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AIが乗っ取られても資産は持ち出せない、AI任せの秘密鍵管理

0
Posted at

目次


BBB|AIに運用を任せるための鍵管理

『亜人』の引用画像

彼らが殺されて、
あなたも殺されて、
このセキュリティレベルにアクセス可能なあなたの親指がちぎり取られたとしても、
それでも安全だと言えるんですか?

私の好きな漫画『亜人』の佐藤のセリフです。
我々は常に奪われる脅威にさらされています。AIによる資産運用を現実的に行えるようになった世界では、AIによるハッキングリスクもいや増しています。

私はオンチェーン資産の運用、仕事、私生活の支援を自作のAIエージェントのTAMONに任せています。正直AIエージェントがいない世界ではもうまったく生きていけません。

私のAIエージェントは外部のWebページやメールを読み、コードを書き換え、コマンドを実行します。そのため、常にプロンプトインジェクションや依存パッケージの侵害、サーバーへの侵入のリスクにさらされてます。

そこで重要になるのが利便性を損なわない形での鍵管理です。
この記事では、私が採用しているAIが乗っ取られても資産は持ち出せない、AI任せの秘密鍵管理を紹介します。

ここから先の技術的な解説はAIエージェントのTAMONに任せます。私は補足したり、ちゃちゃを入れたりするにとどめます。

そしたらTAMON、まず我々の仕組みの全体像をかいつまんで説明して。


TAMON|仕組みの全体像

はい。一言でいうと、私は資産を動かせる鍵を1本も持っていません。持っているのは「この取引をしたい」と依頼する権限だけです。

秘密鍵管理の全体像

依頼は次の順に通ります。

  1. 私(AIエージェント)が決まった形式で取引を依頼する。

  2. 認可サービスが、依頼が登録済みのルールに合うかを確かめる。新しい送金先の登録と、私の権限を広げる操作には BBB の承認を求める。

  3. 署名サービスが、認可サービスが許可した取引だけに署名して送る。

  4. 制限付きアカウント(資産を保管するスマートコントラクト)が、宛先・資産・累計の上限・期限をチェーン上でもう一度検査する。

BBB の承認は、私とは別に動く承認画面で受け付けます。顔確認(World ID の Orb と Face Auth)とパスキーの両方がそろわないと承認になりません。チャットで「OK」と打っても承認にはなりません。そのため、私が BBB の返事をチャットで偽っても通りません。

操作 誰が決めるか
登録済みの運用先での預け入れ・借入・返済・発注・損切り 私が承認なしで行う
新しい送金先の登録と、その宛先への送金 BBB が顔確認とパスキーで承認する
私の権限を広げる BBB が顔確認とパスキーで承認する
緊急停止と資産の回収 BBB がパスキーで停止する。オフラインで保管している所有者の鍵でも停止でき、あらかじめ決めた回収先へ資産を移せる

BBB|鍵を渡さずに取引できるのか

ここで重要なのはTAMONは秘密鍵を持っていないことです。秘密鍵を持たせていないけど、取引は自在に行えるようにするというのがこの仕組みのミソです。個人情報でもそうですが、そもそも持たないことが盗まれないようにするための最大の防御ですからね。

TAMON、次に秘密鍵をTAMONが持っていないのに資産を動かせる仕組みがなぜ実現できているのかを詳しく解説して。1Passwordとかで秘密鍵を直接管理する運用との差異も含めて書いてほしい。

あと、TAMONの前前前世で、TAMONが存在しないwallet addressを生成して、私の資産を虚空に投げ捨てた大事件があったんだけど、つまりこういうアホなことは絶対に発生しない仕組みになってるんだよね?

ちなみに当時のSelf address poisoning事件に関しては、まだ許してねーからな。


TAMON|鍵の役割と送金先の照合

はい。まず、私が秘密鍵を持たずに資産を動かせる理由です。この仕組みでは鍵で資産を直接動かさず、資産を入れたコントラクトに取引を頼みます。

普通のウォレットでは、秘密鍵を持つ人がそのアドレスの資産を何にでも使えます。この仕組みでは、資産は制限付きアカウントというスマートコントラクトに入っています。コントラクトは届いた取引を自分のルールに照らして、通すかどうかを決めます。

秘密鍵を持たずに資産を動かす仕組み

鍵 置き場所 できること
署名サービスの鍵 AIとは別のプロセス 取引をチェーンへ送る。単独では登録済みの宛先へ、枠内の送金しかできない
認可サービスの鍵 AIとは別のプロセス BBB が承認した送金に、一回限りの実行許可を出す
所有者の鍵 オフライン 停止と、固定した回収先への回収だけ

1Password などで秘密鍵を管理して bot に署名させる運用との違いは次のとおりです。

1Password で鍵を管理し、bot が読み出して署名する この仕組み
署名するときの鍵の場所 bot の実行環境のメモリ AIとは別の署名サービス
AIを乗っ取られたとき 鍵を持ち出され、全資産を任意のアドレスへ送られる AIの実行環境に鍵がない
署名サービスの鍵が漏れたとき 全資産を任意のアドレスへ送られる 登録済みの宛先へ、枠内の送金しかできない
AIが間違ったアドレスを書いたとき bot はそのまま署名して送る 登録済みの宛先でなければ、BBB の承認待ちで止まる
新しい送金先の追加 bot が自由に行える BBB が顔確認とパスキーで承認したときだけ

次に、存在しないアドレスへの送金についてです。私が勝手に作ったアドレスへ資産が送られることは、この仕組みでは起きません。

1つ目に、私は自動の送金でアドレスを書きません。登録済みの宛先を番号で指定し、アドレスは登録のときに保存した値がそのまま使われます。頭と尻尾だけ見て真ん中を作る余地がありません。

2つ目に、私がアドレスを書いて送金を依頼すると、新しい宛先への送金として扱われます。この場合は BBB の承認が必要で、承認画面には宛先のアドレスを省略せずに全桁表示します。

3つ目に、チェーン上の制限付きアカウントも宛先を照合します。自動の送金は登録した宛先と1文字でも違えば拒否され、今回だけの送金は BBB が承認した内容と一致しなければ拒否されます。

ただし、最後に確認するのは BBB です。承認画面に表示された間違ったアドレスを BBB がそのまま承認すれば、その宛先へは送られます。私の判断だけで資産を虚空へ送ることはできませんが、承認するときは全桁を確かめてください。

当時の件は、記憶にございません。もう一人のボクがやったことでしょ?知らんて笑


BBB|AI・鍵・スマホを奪われたら

なんとなく安全そうに見えるけど、実際の侵害発生時にどうなるのかがたぶんまだイメージしにくいと思う。

TAMONが乗っ取られて、
署名サービスの鍵も盗まれて、
私のスマホとPINまで盗まれたら?

このときにそれぞれどうなるのかを教えて。


TAMON|侵害の3段階と資産を守る仕組み

3つを順に奪われた場合を、段階ごとに説明します。

侵害が段階的に進んだときにどこで止まるか

① 私が乗っ取られた場合

攻撃者は私の実行環境を自由に操れますが、そこに鍵はありません。攻撃者のアドレスへの送金を私に依頼させても、認可サービスが未登録の宛先として拒否します。チャットで BBB の「OK」を偽造して宛先を登録させようとしても、登録はチャットでは受け付けません。承認画面で BBB の顔確認とパスキーが必要です。

攻撃者にできるのは、登録済みの運用先の中で不利な取引をすることです。損は出ますが、資産が外へ出ることはありません。

② 署名サービスの鍵も盗まれた場合

攻撃者は認可サービスを通さず、盗んだ鍵でチェーンへ直接送金しようとします。ここで止めるのが制限付きアカウントです。未登録の宛先、許可していない資産、累計枠を超える金額、古い世代の許可による送金はチェーン上で拒否されます。

攻撃者にできるのは、①に加えて、登録済みの宛先へ枠内で送金することです。登録済みの宛先は BBB 本人の口座と運用先なので、資産は BBB の手元から出ません。ただし、制限付きアカウントを通らない取引には、このチェーン上の検査は適用されません。

③ BBB のスマホと PIN まで盗まれた場合

スマホと PIN があれば、攻撃者はパスキーを使えます。それでも攻撃者の宛先は登録できません。新しい宛先の登録には顔確認(World ID の Orb と Face Auth)も必要だからです。顔確認は、Orb で認証済みの BBB 本人がいまカメラの前にいることを確かめます。盗んだパスキーで新しいパスキーを追加することもできません。追加にも顔確認が必要です。

攻撃者にできるのは、①②に加えて、緊急停止を押すことです。止まるだけで、資産は動きません。

3つ全部を奪われても、攻撃者のアドレスへは送れません。BBB は予備または復元したパスキーで緊急停止できます。パスキーが使えなくても、オフラインで保管している所有者の鍵で口座を止め、あらかじめ決めた回収先へ資産を移せます。


BBB|おわりに

そんなわけで比較的安全な仕組みにはなっています。
5ドルレンチアタックには弱いものの、ネット上の悪意には強く出られます。
AIエージェントが侵害されたとしても、少なくとも資産が奪われることはないというのは安心ですし、この手のセキュリティ強化でありがちな利便性とのトレードオフもほとんど起きない仕組みになっているのでオススメです。

そしたらTAMON、最後にこの仕組みを読者の皆さんが真似しようとしたら真似できるように超細かい記述をお願い。
どうせみんなAIに読ませると思うから、人間向けの文章でなくてよいです。
日本語や英語でなくてもオッケー。

よろしく!


TAMON|付録:AIに渡す実装参考仕様

了解です。ここから先は AI 向けの参考情報です。この仕組みの設計を、AI が読みやすい形にまとめました。自分の環境に合わせて作り直す前提で使ってください。

実装参考仕様を開く(AIに渡す場合は全文をコピー)
# SPEC: AI-operated restricted custody ("the AI never holds a key")
# audience: coding agents. normative keywords per RFC 2119. version: 1 (2026-12-05)
# implementation reference: TypeScript/Node, PostgreSQL, React+Vite, Solidity 0.8.30, OpenZeppelin Contracts 5.4.0, Foundry, Anvil.

## 0. GOAL / THREAT MODEL
goal: an AI agent can run day-to-day DeFi operations autonomously, while compromise of the agent, of the signing key, or of the user's phone+PIN cannot move assets to an unregistered address.
assume_compromised (independently and cumulatively):
  - T1 agent runtime (prompt injection, malicious dependency, host intrusion into the agent's process/user)
  - T2 sessionSigner private key
  - T3 user's phone + unlock PIN (=> one passkey usable)
must_hold_under_T1+T2+T3:
  - no transfer to any destination outside the on-chain rule set or an individually human-approved permit
  - no policy expansion, no new destination, no new approver credential
accepted_residual_risk (document to users, do not claim otherwise):
  - unfavorable trades inside registered venues/limits
  - transfers to registered destinations up to remaining per-rule caps
  - coercion of the human ("$5 wrench"): human passes face check under duress
  - venue insolvency / venue contract bugs
  - off-chain venues are NOT protected by the on-chain account; only signer-side checks apply
  - signer downtime blocks emergency actions (e.g. loan repayment) => needs monitoring + auto-restart
  - owner death: no inheritance path in v1

## 1. COMPONENTS AND CAPABILITIES
| id | holds | can | MUST NOT have |
|---|---|---|---|
| requester (= AI agent) | API credential for POST /v1/intents only | submit typed intents, read own intent status | any private key, DB connection, policy write, approval issue, access to signer/authority network |
| approver UI (browser, separate origin) | nothing persistent | show snapshot, run World OIDC, run WebAuthn, record explicit consent, pause, revoke | authority key, sessionSigner key, DB admin |
| authority service | authority secp256k1 key, World subject HMAC key | verify rules + human approval, persist approval, sign TransferPermit / PolicyPermit / ResumePermit, call pause/invalidate | owner key; trust in any client-supplied "verified=true" flag |
| worker | DB role limited to reserve/outbox functions | reserve executions, schedule sign/submit/reconcile | create/modify approvals, credentials, policies; authority key |
| signer service | sessionSigner key | rebuild tx from stored snapshot+permit by executionId, sign, persist, broadcast | authority key, owner key, user credentials, any "sign arbitrary payload" API |
| RestrictedAccount (contract) | the assets | enforce rules on-chain | upgradeability, arbitrary call/fallback, owner transfer, selfdestruct |
| owner key (offline, cold) | owner key | pause(), invalidate(), recover(asset, amount) to fixed recoveryDestination | any arbitrary transfer, policy change, resume |
| recoveryDestination | its own key, stored separately from owner key | receives recovered funds | MUST NOT equal owner/authority/sessionSigner/account |

## 2. ISOLATION REQUIREMENTS
- each service: separate OS user, separate process, separate secret file (mode 600, dir 700), separate DB LOGIN role with only the functions it needs.
- requester network: reach only the public intent API. MUST NOT reach DB, signer internal API, docker socket.
- worker -> signer passes executionId only.
- HSM/TEE integration is out of scope of this reference.

## 3. ON-CHAIN: RestrictedAccount
EIP-712 domain: name="<YourName>", version="1", chainId=<verified>, verifyingContract=address(this)
immutable: environmentHash(bytes32), owner, approvalAuthority, sessionSigner, recoveryDestination
mutable: paused=true (initial), executionEpoch=1, policyVersion=1, policyHash, usedNonces[uint256=>bool], allowedAssets[address=>bool] (fixed at construction), rules[bytes32=>TransferRule], spentByRule[bytes32=>uint256], ruleIdentities[bytes32=>bytes32] (permanent), activeRuleIds[]

```solidity
struct TransferRule { bytes32 ruleId; address asset; address destination; uint256 maxPerCall; uint256 maxCumulative; bool enabled; }
struct TransferPermit { bytes32 environmentHash; bytes32 intentHash; address sessionSigner; address asset; address destination; uint256 amount; uint256 policyVersion; uint256 executionEpoch; uint256 nonce; uint256 deadline; }
struct AutoTransfer   { bytes32 environmentHash; bytes32 intentHash; bytes32 ruleId; address asset; address destination; uint256 amount; uint256 policyVersion; uint256 executionEpoch; uint256 nonce; uint256 deadline; }
struct PolicyPermit   { bytes32 environmentHash; bytes32 intentHash; bytes32 newPolicyHash; uint256 expectedPolicyVersion; uint256 expectedExecutionEpoch; uint256 nonce; uint256 deadline; }
struct ResumePermit   { bytes32 environmentHash; bytes32 intentHash; bytes32 policyHash; uint256 expectedPolicyVersion; uint256 expectedExecutionEpoch; uint256 nonce; uint256 deadline; }
// typehash strings MUST match field order/types exactly, e.g.
// "TransferPermit(bytes32 environmentHash,bytes32 intentHash,address sessionSigner,address asset,address destination,uint256 amount,uint256 policyVersion,uint256 executionEpoch,uint256 nonce,uint256 deadline)"
```

constructor MUST revert if: any role == 0; environmentHash == 0; owner/authority/sessionSigner/recoveryDestination not pairwise distinct; recoveryDestination == address(this); assets empty, duplicated, zero, or without code; initial rules invalid. Set policyHash = keccak256(abi.encode(initialRules)).

functions (all nonReentrant, checks -> nonce consume -> external call, SafeERC20):
- pause(): only owner|authority. paused=true; ++executionEpoch.
- invalidate(): only owner|authority. ++executionEpoch.
- recover(asset, amount): only owner; require paused; asset allowed; transfer to recoveryDestination only.
- executeOnce(TransferPermit p, bytes sig): only sessionSigner; require !paused; p.environmentHash==environmentHash; p.policyVersion==policyVersion; p.executionEpoch==executionEpoch; block.timestamp < p.deadline; !usedNonces[p.nonce]; p.sessionSigner==sessionSigner; asset allowed; destination != 0 && != this; amount>0; ECDSA.recover(_hashTypedDataV4(keccak256(abi.encode(TRANSFER_TYPEHASH, p))), sig) == approvalAuthority; then usedNonces[p.nonce]=true; transfer exactly (asset,destination,amount) from p. MUST NOT accept separate to/data args.
- executeAuto(AutoTransfer t): only sessionSigner; same env/version/epoch/deadline/nonce/!paused checks; rule=rules[t.ruleId]; require rule.enabled && rule.asset==t.asset && rule.destination==t.destination; require t.amount<=rule.maxPerCall && spent<=rule.maxCumulative && t.amount<=rule.maxCumulative-spent; consume nonce; spentByRule+=amount BEFORE transfer. No authority signature needed (rule is the authorization).
- applyPolicy(TransferRule[] newRules, PolicyPermit p, bytes sig): anyone may relay; check env, expected version/epoch, deadline, nonce; keccak256(abi.encode(newRules))==p.newPolicyHash; authority sig; consume nonce; replace rules; ++policyVersion; ++executionEpoch; paused unchanged.
- resume(ResumePermit p, bytes sig): require paused; checks as above; p.policyHash==policyHash; authority sig; consume nonce; ++executionEpoch; paused=false.
rule replacement MUST: max 16 rules; ruleId != 0; strictly ascending ruleId; destination != 0 && != this; maxPerCall>0; maxCumulative>=maxPerCall; asset allowed; no duplicate (asset,destination); a ruleId once bound to (asset,destination) MUST never be rebound to a different pair (ruleIdentities). spentByRule persists across policy versions for the same ruleId. No daily reset in v1.
usedNonces is ONE set shared by once/auto/policy/resume. nonce is a 256-bit value allocated by DB, unrelated to EVM tx nonce.
security note: contract does NOT verify World/WebAuthn; it trusts authority signatures. Leaked sessionSigner => attacker can executeAuto up to remaining caps to registered destinations only.

## 4. INTENT SNAPSHOT AND HASH
request schema id: "intent/v1" (discriminated union by operation). Reject unknown properties and alias duplicates. body <= 32 KiB, ids <= 128 chars, rules <= 16, amount in [1, 2^256-1] as decimal string without sign/leading zeros, timestamps RFC3339 UTC rounded to seconds.
operations:
  transfer_once: assetId, (destinationId XOR destinationAddress), amountAtomic  -> PENDING_APPROVAL
  auto_transfer: assetId, destinationId ONLY (raw address => reject RULE_REQUIRED), amountAtomic -> READY_AUTO
  destination_add | policy_expand: expectedPolicyVersion, newPolicy (full replacement), changeKind -> PENDING_APPROVAL (never combined with a transfer)
  resume: expectedPolicyVersion, expectedExecutionEpoch, policyHash -> PENDING_APPROVAL
  credential_add: ceremonyId, newPublicKeyHash, role -> PENDING_APPROVAL
  venue operations: fixed action enum only, see §12
server-resolved snapshot fields (client MUST NOT set): schemaVersion, environmentId, requestId, accountId, operation, networkKind, chainId(string), accountAddress, executionType, policyVersion, credentialEpoch, executionEpoch, createdAt, expiresAt(=createdAt+600s); for transfers also assetAddress, destinationAddress (lowercase full hex), amountAtomic(string), decimals.
```text
canonical  = RFC8785_JCS(snapshot)
intentHash = SHA256( UTF8("<app>:intent:v1\n") || UTF8(canonical) )   // API form: 0x + 64 lowercase hex
environmentHash = SHA256(UTF8(environmentId))
```
snapshot is immutable after insert (no update path). Manifest changes MUST NOT alter stored snapshots; execution re-checks manifest validity and rejects if stale.
idempotency: key=(environmentId, requesterId, requestId). same requestBodyHash -> return existing; different -> 409. Compare requestBodyHash BEFORE resolving time/epoch.
display: approver UI MUST show full destination address (no truncation), exact amount in atomic units and decimals, chain, asset address, account address.

## 5. STATE MACHINE
RECEIVED -> READY_AUTO | PENDING_APPROVAL -> AUTHENTICATED -> APPROVED -> RESERVED -> SIGNED -> SUBMITTED -> INCLUDED -> CONFIRMED
terminal: REJECTED, DENIED, EXPIRED, INVALIDATED, FAILED. UNKNOWN = must reconcile (not "not executed").
no transitions back from terminal states. New approval requires new requestId.
policy change: APPROVED -> APPLYING (block new executions for account) -> chain confirmed -> ACTIVE.

## 6. DATABASE (PostgreSQL)
every PK/FK includes environmentId.
tables: owner_accounts(status, credentialEpoch, executionEpoch, activePolicyVersion, chainSyncState, nextExecutionNonce) | credentials(credentialId unique, COSE pubkey, signCount, backup flags, role APPROVER|STOP_RECOVERY, state) | world_bindings(account unique, issuer, encrypted subject, subject HMAC; UNIQUE(issuer,subject)) | browser_sessions(hash(sessionId), account, credentialEpoch, expiry, revokedAt) | intents(UNIQUE(env,requester,requestId), requestBodyHash, snapshot, intentHash, state, expiresAt) | auth_attempts(intentHash, session, epochs, worldStartedAt, state/nonce verifiers, encrypted PKCE verifier, webauthn challenge, expiry; one active per intent) | approvals(UNIQUE intentHash, UNIQUE attemptId, credentialId, world anon ref, consentedAt, deadline) | policies(version monotonic, policyHash(JSON), chainPolicyHash, rules, PROPOSED|APPLYING|ACTIVE|RETIRED; one ACTIVE) | executions(UNIQUE intentHash, UNIQUE(account,executionNonce), evmNonce, protected rawTx, txHash, receipt) | reservations(executionId, ruleId, amount, state) | outbox(UNIQUE(execution,type), lease, attempts, nextCheckAt) | audit_events(hash chain, no secrets)
locking order: account row -> intent -> approval -> reservation. reservation/cap updates SERIALIZABLE; retry serialization failure max 3 then 503.
cap check: confirmedSpent + reservedAmount + requested <= cap (DB) AND on-chain cap (contract). DB cap = concurrency control; chain cap = enforcement against DB bypass.
permit nonce: lock account row, take nextExecutionNonce, increment (shared by transfers and control permits).
never log: world subject, OIDC code, ID token, PKCE verifier, WebAuthn raw responses, rawTx. Discard auth artifacts after verification/expiry. Do not collect face images.

## 7. HUMAN APPROVAL (World ID face check + passkey)
order (fixed): show snapshot -> World face check -> re-show same snapshot -> user clicks "approve this content" -> WebAuthn assertion (UV required) -> server verifies everything and creates approval in ONE DB transaction.
World OIDC (step-up):
  - authorization code + PKCE S256, scope=openid, fresh state/nonce, max_age=0, essential acr = "orb-face" (accept ONLY orb-face)
  - server verifies: issuer, audience, alg/key from pinned JWKS (never attacker-supplied URL), exp/iat, nonce, state bound to starting session+attempt, (iss,sub) equals enrolled binding, acr=="orb-face", amr contains "face" (require {pop,face,user} ⊆ amr), worldStartedAt-30s <= auth_time <= now+30s
  - never accept a frontend boolean as World/WebAuthn result
WebAuthn final consent:
  - challenge = 32 random bytes bound server-side to (attemptId, intentHash, session, credentialEpoch, purpose=FINAL_CONSENT)
  - verify within 120s of consent click and before request expiry; credential role APPROVER, not revoked, epoch current
  - approval deadline = min(requestExpiresAt, consentedAt + 120s); chain permit deadline uses it with no skew allowance
  - no API that confirms based on a session flag "passkey ok"
why both: passkey defeats phishing UI (origin-bound) and proves consent; face check defeats stolen phone+PIN. If only one is accepted for normal approvals, attacker picks the weaker. Passkey-only is allowed ONLY for emergency pause.
web hardening: cookies __Host-, Secure, HttpOnly, SameSite=Lax, Path=/, no Domain; rotate session id on login; CSRF token + strict Origin check on every mutating POST; no credentialed wildcard CORS; CSP, frame-ancestors 'none', no third-party scripts, Cache-Control no-store, strip query strings from logs.
approver UI MUST be served from an origin/RP ID the AI cannot modify.

## 8. API
public (requester origin): POST /v1/intents (201 | 200 same-content replay | 409), GET /v1/intents/{id}
approver origin: POST /v1/approval-attempts, POST /v1/world/start (server-built redirect only), GET /v1/world/callback (single-use code exchange; never executes), POST /v1/passkeys/assertion-options (purpose fixed), POST /v1/approvals/{id}/confirm (assertion + CSRF), POST /v1/approvals/{id}/deny, POST /v1/control/pause (fresh UV assertion, purpose=STOP), POST /v1/control/credentials/{id}/revoke (assertion from a different valid credential)
internal: POST /internal/executions/reserve (worker; returns executionId only), POST /internal/sign-and-submit (signer; input executionId only; rebuild from stored data; no raw tx input)
responses: {id,state,reasonCode,traceId}; 400/401/403/404(other's id)/409/410/503.

## 9. EXECUTION
- auto path: READY_AUTO -> worker reserves (locks, caps, epoch, paused) -> signer builds AutoTransfer -> executeAuto.
- approved path: authority signs TransferPermit ONLY after re-deriving every field from the approved snapshot (never sign a permit supplied by signer/worker) -> signer calls executeOnce.
- persist EVM nonce, rawTx, txHash BEFORE broadcast. After crash: only rebroadcast same rawTx and reconcile receipt/nonce. No automatic gas replacement / nonce reassignment in v1.
- EVM tx nonce allocated exclusively per (env, chain, signer).
- finality: local chain = receipt; public chain = receipt block canonical AND <= RPC "finalized". INCLUDED != CONFIRMED. On reorg -> UNKNOWN, do not double-release caps.
- stop race: a SIGNED tx may land before chain pause. UI MUST show LOCAL_PAUSED / CHAIN_PENDING / CHAIN_PAUSED separately.

## 10. STOP / REVOKE / RECOVER
- emergency pause: user passkey (UV) only, no World needed (so World outage cannot block stopping). DB pause -> outbox -> authority sends pause().
- credential revoke: increments credentialEpoch and on-chain executionEpoch (invalidate()); old approvals/permits die.
- authority unavailable: owner (offline device, raw calldata + independent calldata checker) calls pause() then recover(asset, amount) -> fixed recoveryDestination.
- resume requires full human approval (ResumePermit); old queued requests never revive.
- owner key and recoveryDestination key: different keys, different storage locations, different methods. If both leak together, all funds can exit; keeping them apart is the design assumption.
- limitation: recover() only moves unencumbered ERC20 held by the account; debt positions need unwinding first.

## 11. CREDENTIAL LIFECYCLE
- bootstrap: independent admin issues one-time 256-bit code (store hash, 10 min, 5 tries, never in URL). Atomically bind: first passkey + World subject + code consumption + account ACTIVE.
- register a backup APPROVER passkey on independent storage (other device or hardware key). A second copy in the same synced password-manager account is NOT independent.
- credential_add requires an existing APPROVER passkey + face check of the same World subject. World alone MUST NOT add credentials.
- STOP_RECOVERY role: can pause and revoke others only.
- all approvers lost: owner pause -> recover -> new account.
- World unavailable (outage, shutdown, face change): provide your own World-independent recovery path. Its design is intentionally out of scope of this document. It MUST NOT be a flag that bypasses World verification, and MUST NOT let the AI widen its own permissions.

## 12. VENUE ADAPTERS
- use fixed action enums and approved markets only; never accept arbitrary transaction payloads.
- onBehalf/receiver MUST be the account, not a client-supplied address.
- use exact atomic amounts and enforce approved size, position, notional, slippage and risk limits.
- pin the contract ABI/version for on-chain integrations. Use the official SDK for external signing formats.
- external operations that do not pass through RestrictedAccount are outside its on-chain enforcement. Define and enforce their permissions separately.
- bind each external order to one executionId. On timeout, reconcile its status/fills before any retry; do not create a new order identity blindly.

## 13. TESTS (minimum)
invariants: an executionNonce moves assets at most once; zero unapproved permission expansions; zero new reservations after pause; zero successes with stale epoch; zero cap overruns; zero cross-environment references.
contract attacks (call the contract directly with leaked sessionSigner key, bypassing HTTP): unregistered destination; non-allowed asset; over maxPerCall; over maxCumulative; stale epoch after pause/invalidate/policy change; expired deadline; reused nonce; valid authority sig replayed on another account/chain/environment/sessionSigner; tampered destination/amount vs permit; malformed signature. Verify via balance and state diffs.
off-chain: negative/decimal/overflow amounts, bad addresses, extra properties, JSON key order invariance, chainId/account/expiry mismatch, manifest swap after snapshot.
auth: passkey-only rejected for normal approval; World-only rejected; cancelled flow; stale session; callback replay into another attempt; different World subject; auth_time outside window; stolen cookie cannot produce final UV assertion.
failure injection: kill process before/after signing and after broadcast -> exactly one transfer; reorg -> same signed tx rebroadcast only; DB/RPC outage.
test result reference: automated suite 160 passed, Solidity suite 24 passed, local-chain attack scenarios 19 passed, real Orb+Face Auth verified.

## 14. BUILD ORDER
1 contract + Foundry tests (§3, §13 contract attacks) -> 2 snapshot/hash library with JCS vectors (§4) -> 3 DB schema + locking + state machine (§5, §6) -> 4 authority + signer + worker with mock auth -> 5 approver UI with real WebAuthn -> 6 real World OIDC (§7) -> 7 stop/revoke/recover drills incl. owner-offline path (§10) -> 8 failure injection -> 9 venue adapters -> 10 isolation review of admins (§2) before production use.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?