@agenticprimitives/contracts 1.0.0-alpha.4 → 1.0.0-alpha.41

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.
Files changed (108) hide show
  1. package/AUDIT.md +330 -47
  2. package/README.md +56 -10
  3. package/deployments-base-sepolia.json +50 -0
  4. package/deployments-faithchain.json +75 -0
  5. package/deployments-hopechain.json +57 -0
  6. package/deployments-paymaster-anvil.json +1 -0
  7. package/deployments-registries-base-sepolia.json +1 -0
  8. package/deployments-registries-hopechain.json +1 -0
  9. package/dist/abi/AgentAccount.json +1827 -0
  10. package/dist/abi/AgentAccountFactory.json +545 -0
  11. package/dist/abi/AgentNameRegistry.json +51 -0
  12. package/dist/abi/AgentRegistryBase.json +652 -0
  13. package/dist/abi/AgenticGovernance.json +32 -0
  14. package/dist/abi/AgreementRegistry.json +427 -0
  15. package/dist/abi/ApprovedHashRegistry.json +47 -2
  16. package/dist/abi/AttestationRegistry.json +436 -0
  17. package/dist/abi/CallDataHashEnforcer.json +119 -0
  18. package/dist/abi/CustodyPolicy.json +1179 -0
  19. package/dist/abi/DelegationManager.json +656 -0
  20. package/dist/abi/DigestBindingEnforcer.json +251 -0
  21. package/dist/abi/EstateProjectionRegistry.json +293 -0
  22. package/dist/abi/GeoFeatureRegistry.json +625 -0
  23. package/dist/abi/IAgentAccount.json +262 -0
  24. package/dist/abi/IAgentAccountFactoryAccessor.json +15 -0
  25. package/dist/abi/IAgentAccountFactoryView.json +54 -0
  26. package/dist/abi/IAgentAccountPauseView.json +15 -0
  27. package/dist/abi/IAgenticPrimitivesAgentAccount.json +15 -0
  28. package/dist/abi/IApprovedHashRegistryView.json +26 -0
  29. package/dist/abi/IApprovedHashRegistryWrite.json +35 -0
  30. package/dist/abi/ICustodyPolicyAccountModuleView.json +31 -0
  31. package/dist/abi/ICustodyPolicyFactoryView.json +15 -0
  32. package/dist/abi/ICustodyPolicyPauseView.json +15 -0
  33. package/dist/abi/IDelegationManager.json +171 -0
  34. package/dist/abi/IERC7579HookLike.json +44 -0
  35. package/dist/abi/IERC7579ModuleLike.json +28 -0
  36. package/dist/abi/IPaymentReceiptRegistry.json +50 -0
  37. package/dist/abi/IRegistryMembershipPolicy.json +70 -0
  38. package/dist/abi/MockUSDC.json +621 -0
  39. package/dist/abi/PayloadClassesEnforcer.json +117 -0
  40. package/dist/abi/PaymentEnforcer.json +441 -0
  41. package/dist/abi/PaymentEscrow.json +324 -0
  42. package/dist/abi/PaymentReceiptRegistry.json +182 -0
  43. package/dist/abi/PermissionlessSubregistry.json +5 -0
  44. package/dist/abi/PricedSubregistry.json +869 -0
  45. package/dist/abi/QuorumEnforcer.json +311 -0
  46. package/dist/abi/ReceiptAnchorRegistry.json +153 -0
  47. package/dist/abi/SignatureSlotRecovery.json +88 -0
  48. package/dist/abi/SkillDefinitionRegistry.json +491 -0
  49. package/dist/abi/SmartAgentPaymaster.json +873 -0
  50. package/dist/abi/TreasurySpendPolicy.json +369 -0
  51. package/dist/abi/UniversalSignatureValidator.json +65 -0
  52. package/dist/abi/index.d.ts +38 -0
  53. package/dist/abi/index.js +38 -0
  54. package/dist/deployments/base-sepolia.d.ts +46 -0
  55. package/dist/deployments/base-sepolia.js +54 -0
  56. package/dist/deployments/faithchain.d.ts +55 -0
  57. package/dist/deployments/faithchain.js +79 -0
  58. package/dist/deployments/hopechain.d.ts +53 -0
  59. package/dist/deployments/hopechain.js +61 -0
  60. package/dist/deployments/index.d.ts +13 -0
  61. package/dist/deployments/index.js +28 -0
  62. package/dist/deployments/paymaster-anvil.d.ts +11 -0
  63. package/dist/deployments/paymaster-anvil.js +9 -0
  64. package/dist/deployments/registries-base-sepolia.d.ts +10 -0
  65. package/dist/deployments/registries-base-sepolia.js +8 -0
  66. package/dist/deployments/registries-hopechain.d.ts +10 -0
  67. package/dist/deployments/registries-hopechain.js +8 -0
  68. package/package.json +55 -8
  69. package/src/AgentAccount.sol +569 -38
  70. package/src/AgentAccountFactory.sol +157 -16
  71. package/src/ApprovedHashRegistry.sol +41 -6
  72. package/src/IAgentAccount.sol +23 -0
  73. package/src/SmartAgentPaymaster.sol +156 -12
  74. package/src/UniversalSignatureValidator.sol +3 -0
  75. package/src/agency/DelegationManager.sol +179 -0
  76. package/src/agency/IDelegationManager.sol +38 -0
  77. package/src/agreement/AgreementRegistry.sol +331 -0
  78. package/src/attestation/AttestationRegistry.sol +384 -0
  79. package/src/custody/CustodyPolicy.sol +263 -15
  80. package/src/custody/TreasurySpendPolicy.sol +166 -0
  81. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -0
  82. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -0
  83. package/src/enforcers/CallDataHashEnforcer.sol +61 -0
  84. package/src/enforcers/DigestBindingEnforcer.sol +107 -0
  85. package/src/enforcers/PayloadClassesEnforcer.sol +30 -0
  86. package/src/enforcers/PaymentEnforcer.sol +257 -0
  87. package/src/enforcers/QuorumEnforcer.sol +24 -1
  88. package/src/enforcers/TimestampEnforcer.sol +7 -0
  89. package/src/enforcers/ValueEnforcer.sol +6 -0
  90. package/src/geo/GeoFeatureRegistry.sol +197 -0
  91. package/src/governance/AgenticGovernance.sol +26 -4
  92. package/src/identity/AgentProfilePredicates.sol +23 -0
  93. package/src/libraries/SignatureSlotRecovery.sol +24 -7
  94. package/src/libraries/WebAuthnLib.sol +13 -0
  95. package/src/mocks/MockUSDC.sol +152 -0
  96. package/src/naming/AgentNamePredicates.sol +89 -0
  97. package/src/naming/AgentNameRegistry.sol +65 -18
  98. package/src/naming/AgentNameUniversalResolver.sol +1 -1
  99. package/src/naming/PermissionlessSubregistry.sol +19 -2
  100. package/src/naming/PricedSubregistry.sol +209 -0
  101. package/src/payments/PaymentEscrow.sol +164 -0
  102. package/src/payments/PaymentReceiptRegistry.sol +67 -0
  103. package/src/provenance/ReceiptAnchorRegistry.sol +55 -0
  104. package/src/registry/AgentRegistryBase.sol +313 -0
  105. package/src/registry/EstateProjectionRegistry.sol +109 -0
  106. package/src/registry/IRegistryMembershipPolicy.sol +30 -0
  107. package/src/relationships/AgentRelationship.sol +8 -0
  108. package/src/skills/SkillDefinitionRegistry.sol +187 -0
@@ -22,6 +22,48 @@ import "./libraries/WebAuthnLib.sol";
22
22
  interface IAgentAccountFactoryView {
23
23
  function bundlerSigner() external view returns (address);
24
24
  function sessionIssuer() external view returns (address);
25
+ /// @dev R6.5 — the factory inherits `GovernanceManaged`; its
26
+ /// `governance()` getter returns the AgenticGovernance pointer
27
+ /// shared across every account it creates. AgentAccount reads
28
+ /// this address to call `IGovernanceView.isPaused()` from
29
+ /// `whenNotPaused`-guarded entrypoints.
30
+ function governance() external view returns (address);
31
+ /// @dev Wave-1/ACCT-C1 — the canonical CustodyPolicy this factory installs
32
+ /// as the custody executor for `mode > 0` accounts. AgentAccount reads it
33
+ /// to decide whether IT is custody-governed (its CustodyPolicy is installed)
34
+ /// vs. merely hosting an unrelated utility executor.
35
+ function custodyPolicy() external view returns (address);
36
+ }
37
+
38
+ /// @dev R6.5 — minimal interface for the pause read. Mirrors the same
39
+ /// selector `GovernanceManaged._pausedSafe()` uses so an EOA or
40
+ /// non-conforming governance contract is treated as "not paused"
41
+ /// (legacy / test deploys still work). Production deploys ALWAYS
42
+ /// use `AgenticGovernance` which implements this interface.
43
+ interface IAgentAccountPauseView {
44
+ function isPaused() external view returns (bool);
45
+ }
46
+
47
+ /// @dev Spec 253 — minimal read surface of `ApprovedHashRegistry`. The
48
+ /// account consults it ONLY from `isValidSignature` (the ERC-1271
49
+ /// entrypoint), under the `0x03` sentinel, so a hash the account
50
+ /// itself pre-approved (inside its own custody-gated execute/batch)
51
+ /// validates as an ERC-1271 signature. Address is bound IMMUTABLE in
52
+ /// the impl (see constructor) — never an owner-mutable view — so a
53
+ /// factory/governance key compromise cannot re-point it at an
54
+ /// attacker registry to forge signatures.
55
+ interface IApprovedHashRegistryView {
56
+ function isApproved(address signer, bytes32 hash) external view returns (bool);
57
+ }
58
+
59
+ /// @dev Spec 410 §1 (THESIS-1a) — the ONLY write path from this account to its registry. The account
60
+ /// computes the epoch-bound key itself (`approveDigest`); `execute` / `executeBatch` /
61
+ /// `executeFromModule` refuse the registry as a target unconditionally, so no caller — custodian,
62
+ /// module or delegate — can approve a key under an epoch the account is not in.
63
+ interface IApprovedHashRegistryWrite {
64
+ function approveHash(bytes32 hash) external;
65
+ function revokeHash(bytes32 hash) external;
66
+ function revokeAll() external;
25
67
  }
26
68
 
27
69
  /**
@@ -60,6 +102,14 @@ contract AgentAccount is
60
102
  /// @dev The ERC-4337 EntryPoint contract
61
103
  IEntryPoint private immutable _entryPoint;
62
104
 
105
+ /// @dev Spec 253 — the `ApprovedHashRegistry` consulted by the `0x03`
106
+ /// sentinel branch of `isValidSignature`. IMMUTABLE (baked into
107
+ /// impl bytecode, shared by every proxy, changeable only via a
108
+ /// custody-gated UUPS upgrade). May be `address(0)` on legacy/test
109
+ /// deploys that don't use the sentinel — in which case the
110
+ /// sentinel fails CLOSED (see `isValidSignature`).
111
+ address private immutable _approvedHashRegistry;
112
+
63
113
  /// @dev Authorized DelegationManager (ERC-7710 executor)
64
114
  address private _delegationManager;
65
115
 
@@ -108,25 +158,72 @@ contract AgentAccount is
108
158
  }
109
159
 
110
160
  /// @dev Spec 007 Phase A.5 — current pending upgrade (set by
111
- /// `upgradeToWithAuthorization` when `_upgradeTimelock > 0`).
161
+ /// `scheduleUpgrade` when `_upgradeTimelock > 0`).
112
162
  PendingUpgrade private _pendingUpgrade;
113
163
 
164
+ /// @dev CA-1 — transient "the current call stack is an authorized upgrade
165
+ /// context" flag. Set while (a) a module action executes
166
+ /// (custody-governed, e.g. `CustodyPolicy.ApplySystemUpdate`, which
167
+ /// carries its own T5 quorum + timelock) or (b) a matured owner-queued
168
+ /// upgrade fires (`executePendingUpgrade`). `_authorizeUpgrade` reads it
169
+ /// so that, once an account configures `_upgradeTimelock`, a DIRECT owner
170
+ /// `upgradeToAndCall` is refused (must `scheduleUpgrade` then
171
+ /// `executePendingUpgrade`), while the custody path keeps working with no
172
+ /// double delay. Transient ⇒ tx-global (visible in the nested
173
+ /// `_authorizeUpgrade` frame) AND absent from the storage layout.
174
+ bool private transient _upgradeAuthorizedCtx;
175
+
176
+ /// @dev Wave-1 / ACCT-C1 (spec 300) — transient "this call stack was entered
177
+ /// by the installed CustodyPolicy EXECUTOR via `executeFromModule`"
178
+ /// (custody-quorum authorized) flag. Set ONLY inside `executeFromModule`,
179
+ /// around the dispatched call, cleared after. Governance mutators require
180
+ /// it on a custody-governed account (`mode > 0`, a CustodyPolicy EXECUTOR
181
+ /// installed): a 1-of-N UserOp `execute(self, adminSelector)` self-call
182
+ /// leaves the flag unset and reverts, so the quorum+timelock can no longer
183
+ /// be bypassed by a single compromised key. Person accounts (`mode 0`, no
184
+ /// CustodyPolicy) self-govern and are exempt. Transient ⇒ tx-global +
185
+ /// absent from the storage layout.
186
+ bool private transient _custodyGovCtx;
187
+
188
+ /// @dev Wave-1 / DM-3 (spec 300) — transient "this execution stack originated
189
+ /// from the DelegationManager". Set at the outermost `execute`/`executeBatch`
190
+ /// frame whose `msg.sender == _delegationManager`, preserved across the
191
+ /// legitimate `DM → execute(self, executeBatch(...))` nest, cleared by the
192
+ /// frame that set it. While set, a self-targeted governance selector is
193
+ /// rejected — a delegation may never reach account governance (that is the
194
+ /// CustodyPolicy's job), regardless of custody mode.
195
+ bool private transient _delegationExecCtx;
196
+
114
197
  /// @dev Spec 007 Phase A.5 — maximum permitted upgrade timelock to
115
198
  /// protect against an owner accidentally setting an absurdly
116
199
  /// large delay that bricks future migrations.
117
200
  uint256 internal constant MAX_UPGRADE_TIMELOCK = 30 days;
118
201
 
202
+ /// @dev R917-C-2 (spec 408 §1.2) — THE CUSTODY EPOCH. Incremented by every path that RETIRES a
203
+ /// credential (`removeCustodian`, `removePasskey` — T6 recovery and a full rotation remove through
204
+ /// these). The `0x03` approved-hash sentinel keys every approval to the epoch it was made under
205
+ /// (`approvedHashKey`), so an approval planted by a custodian who is later removed is void the
206
+ /// moment the custody set no longer contains that custodian — an ECDSA signature dies with its key,
207
+ /// and an approved hash now dies with its custody set. Adding a credential does not bump it: an
208
+ /// added key cannot launder an approval a still-present key planted, and voiding a person's
209
+ /// standing wires every time she enrols a device would be the wrong invariant. Takes one slot
210
+ /// from the gap (49 remain).
211
+ uint64 private _custodyEpoch;
212
+
119
213
  /// @dev Spec 007 Phase A.5 (SC7 § 3.1) — storage gap reserves 50
120
214
  /// slots after the last linear-layout state variable. Future
121
215
  /// additive upgrades shrink the gap by however many slots they
122
216
  /// add. ERC-7201 namespaced state (passkeys, modules) lives at
123
217
  /// keccak-computed slots and is NOT in this linear layout.
124
- uint256[50] private __gap;
218
+ uint256[49] private __gap;
125
219
 
126
220
  // ─── Errors ─────────────────────────────────────────────────────
127
221
 
128
222
  error NotFromSelf();
129
223
  error NotCustodianOrSelf();
224
+ /// @notice R6.5 — thrown when a `whenNotPaused`-guarded entrypoint
225
+ /// is called while `AgenticGovernance.isPaused() == true`.
226
+ error SystemPaused();
130
227
  error CustodianAlreadyExists(address owner);
131
228
  error CustodianDoesNotExist(address owner);
132
229
  error CannotRemoveLastCustodian();
@@ -160,12 +257,31 @@ contract AgentAccount is
160
257
  error UpgradeNotReady(uint64 readyAt, uint256 nowTs);
161
258
  error PendingUpgradeMismatch(address pending, address attempted);
162
259
  error UpgradePending();
260
+ /// @notice CA-1 — a direct `upgradeToAndCall` was attempted while a per-account
261
+ /// upgrade timelock is set; route through `scheduleUpgrade` +
262
+ /// `executePendingUpgrade` (or the custody module path) instead.
263
+ error DirectUpgradeBlocked();
264
+ /// @notice CA-1 — `scheduleUpgrade` called with no upgrade timelock configured
265
+ /// (nothing to queue against — upgrade directly).
266
+ error UpgradeTimelockNotSet();
163
267
 
164
268
  // Wave 2A — on-chain authority closure (contract audit C-1..C-3).
165
269
  error ValidatorRequired();
166
270
  error LegacyUpgradePathDisabled();
167
271
  error ModuleOperationNotAllowed();
168
272
 
273
+ // Wave 1 — account authorization boundary (spec 300 / ACCT-C1 + DM-3).
274
+ /// @notice A governance mutator was reached on a custody-governed account
275
+ /// (`mode > 0`) outside the CustodyPolicy `executeFromModule` path —
276
+ /// i.e. a single-signer UserOp `execute(self, adminSelector)` self-call.
277
+ error AdminRequiresCustodyQuorum();
278
+ /// @notice A delegation-originated execution stack tried to self-call an
279
+ /// account-governance selector. Delegations may never reach governance.
280
+ error DelegatedGovernanceForbidden();
281
+ /// @dev Spec 410 §1 (THESIS-1a): the approved-hash registry is reachable only through
282
+ /// `approveDigest` / `revokeDigest` / `revokeAllApprovedDigests`, never as an execute target.
283
+ error ApprovedHashRegistryOnlyViaAccount();
284
+
169
285
  /// @notice Emitted when `setDelegationManager` rotates the DM via a
170
286
  /// self-call (the only authorized path post-Wave-2A).
171
287
  event DelegationManagerRotated(address indexed newDelegationManager);
@@ -200,10 +316,53 @@ contract AgentAccount is
200
316
  _;
201
317
  }
202
318
 
319
+ // ─── R6.5 / CON-AgentAccount-005 — system-wide pause modifier ──
320
+ //
321
+ // When `AgenticGovernance.isPaused() == true`, every mutating
322
+ // external entrypoint guarded by this modifier reverts with
323
+ // `SystemPaused`. Recovery-shaped entrypoints
324
+ // (`uninstallModule`, `cancelPendingUpgrade`, `removeCustodian`,
325
+ // the three `onlySelf` ceremonies) are deliberately NOT guarded
326
+ // — an operator must always be able to remove attack surface
327
+ // even during an incident.
328
+ //
329
+ // Reads `governance()` through the factory at each check so a
330
+ // factory-level governance rotation propagates to every account
331
+ // without per-account migration. Legacy / direct-deploy accounts
332
+ // (no factory) and EOA-governance / non-conforming-governance
333
+ // deploys are treated as "not paused" so existing test fixtures
334
+ // keep working — mirrors `GovernanceManaged._pausedSafe()`.
335
+ modifier whenNotPaused() {
336
+ if (_systemPaused()) revert SystemPaused();
337
+ _;
338
+ }
339
+
340
+ /// @dev R6.5 — `staticcall` chain: factory → governance.isPaused().
341
+ /// Returns `false` on any non-conforming hop (legacy
342
+ /// compatibility). Production deploys MUST pass a real
343
+ /// `AgenticGovernance` to the factory; the production-deploy
344
+ /// preflight enforces that invariant.
345
+ function _systemPaused() internal view returns (bool) {
346
+ address f = _factory;
347
+ if (f == address(0)) return false;
348
+ (bool okF, bytes memory dataF) = f.staticcall(
349
+ abi.encodeWithSelector(IAgentAccountFactoryView.governance.selector)
350
+ );
351
+ if (!okF || dataF.length < 32) return false;
352
+ address g = abi.decode(dataF, (address));
353
+ if (g == address(0) || g.code.length == 0) return false;
354
+ (bool okG, bytes memory dataG) = g.staticcall(
355
+ abi.encodeWithSelector(IAgentAccountPauseView.isPaused.selector)
356
+ );
357
+ if (!okG || dataG.length < 32) return false;
358
+ return abi.decode(dataG, (bool));
359
+ }
360
+
203
361
  // ─── Constructor / Initializer ──────────────────────────────────
204
362
 
205
- constructor(IEntryPoint entryPoint_) {
363
+ constructor(IEntryPoint entryPoint_, address approvedHashRegistry_) {
206
364
  _entryPoint = entryPoint_;
365
+ _approvedHashRegistry = approvedHashRegistry_;
207
366
  _disableInitializers();
208
367
  }
209
368
 
@@ -306,7 +465,7 @@ contract AgentAccount is
306
465
  $.piaToCredentialId[pia] = credIdDigest;
307
466
  $.rpIdHashOf[credIdDigest] = rpIdHash;
308
467
  $.count = 1;
309
- emit PasskeyAdded(credIdDigest, x, y, rpIdHash);
468
+ emit PasskeyAdded(credIdDigest);
310
469
  emit CustodianAdded(pia);
311
470
  }
312
471
 
@@ -331,7 +490,26 @@ contract AgentAccount is
331
490
  * will revert here. Master / bundler / session-issuer
332
491
  * therefore cannot upgrade even by submitting the tx.
333
492
  */
334
- function _authorizeUpgrade(address) internal view override onlySelf {}
493
+ function _authorizeUpgrade(address) internal view override onlySelf {
494
+ // CA-1: the per-account upgrade timelock is now ENFORCED here (it was
495
+ // previously dead code — set via `setUpgradeTimelock` but never consulted,
496
+ // so a direct `upgradeToAndCall` fired immediately). When a timelock is
497
+ // configured, a direct owner upgrade is refused; the owner must
498
+ // `scheduleUpgrade` then `executePendingUpgrade` after the delay. Authorized
499
+ // contexts — a custody-module action (its own T5 quorum + timelock) or the
500
+ // matured owner queue — set `_upgradeAuthorizedCtx` and pass through, so the
501
+ // custody path is not double-delayed. A zero timelock keeps the
502
+ // immediate-upgrade default (backward-compatible).
503
+ // Wave-1/ACCT-C1 + M-4 (spec 300): outside an authorized context, a
504
+ // custody-governed account (`mode>0`) may upgrade ONLY through the
505
+ // CustodyPolicy quorum — reject even when the per-account timelock is 0 (M-4
506
+ // floors it non-zero at the factory, but a quorum-set 0 must not re-open the
507
+ // direct path). A person account keeps the CA-1 behavior (timelock if set).
508
+ if (!_upgradeAuthorizedCtx) {
509
+ if (_hasCustodyGovernance()) revert AdminRequiresCustodyQuorum();
510
+ if (_upgradeTimelock != 0) revert DirectUpgradeBlocked();
511
+ }
512
+ }
335
513
 
336
514
  /**
337
515
  * @notice DEPRECATED — single-signature upgrade path (contract audit C-3).
@@ -358,10 +536,26 @@ contract AgentAccount is
358
536
  revert LegacyUpgradePathDisabled();
359
537
  }
360
538
 
539
+ /// @notice CA-1 — queue an implementation upgrade subject to the per-account
540
+ /// upgrade timelock. The owner signs a userOp that calls this
541
+ /// (`onlySelf`); the bound implementation can then be applied via
542
+ /// `executePendingUpgrade` once `_upgradeTimelock` has elapsed. Only
543
+ /// meaningful when a timelock is configured — with none set, upgrade
544
+ /// directly. Overwrites any existing pending upgrade.
545
+ function scheduleUpgrade(address newImplementation) external onlySelf {
546
+ _requireCustodyGoverned();
547
+ if (newImplementation == address(0)) revert ZeroAddress();
548
+ uint256 tl = _upgradeTimelock;
549
+ if (tl == 0) revert UpgradeTimelockNotSet();
550
+ uint64 readyAt = uint64(block.timestamp + tl);
551
+ _pendingUpgrade = PendingUpgrade({newImplementation: newImplementation, readyAt: readyAt});
552
+ emit UpgradeProposed(newImplementation, readyAt);
553
+ }
554
+
361
555
  /// @notice Execute a previously-queued upgrade. Permissionless once
362
556
  /// the timelock has expired — anyone can pay the gas, but
363
557
  /// the implementation address was bound at queue time.
364
- function executePendingUpgrade() external {
558
+ function executePendingUpgrade() external whenNotPaused {
365
559
  PendingUpgrade memory p = _pendingUpgrade;
366
560
  if (p.readyAt == 0) revert NoPendingUpgrade();
367
561
  if (block.timestamp < p.readyAt) revert UpgradeNotReady(p.readyAt, block.timestamp);
@@ -369,28 +563,47 @@ contract AgentAccount is
369
563
  // impl can't replay this state.
370
564
  delete _pendingUpgrade;
371
565
  emit UpgradeAuthorized(p.newImplementation);
566
+ // CA-1: authorize the nested `_authorizeUpgrade` for this matured queue
567
+ // (transient, tx-global). Cleared after so a later same-tx direct upgrade
568
+ // isn't inadvertently authorized.
569
+ _upgradeAuthorizedCtx = true;
372
570
  this.upgradeToAndCall(p.newImplementation, "");
571
+ _upgradeAuthorizedCtx = false;
373
572
  }
374
573
 
375
- /// @notice Cancel a queued upgrade during the timelock window. Owner
376
- /// signs a digest that binds to the pending implementation
377
- /// AND `address(this)` + chain id, preventing cross-account
378
- /// replay of a cancel-grant.
574
+ /// @notice Cancel a queued upgrade during the timelock window.
575
+ /// @dev NEW-CANCEL-UPGRADE-1: cancel is a governance op. On a CUSTODY-GOVERNED
576
+ /// account (mode>0 / org) it MUST go through the custody quorum — routed via
577
+ /// the CustodyPolicy executor (`_custodyGovCtx`), exactly like `scheduleUpgrade`
578
+ /// and the other governance mutators — so a single compromised custodian's
579
+ /// ECDSA signature cannot perpetually cancel quorum-scheduled upgrades
580
+ /// (upgrade-liveness DoS). The lightweight ECDSA cancel-grant fast-path remains
581
+ /// ONLY for non-governed (mode-0) accounts, where the sole custodian IS the owner.
379
582
  /// @param ownerSig Owner ECDSA signature over `keccak256(abi.encode(
380
583
  /// "UPGRADE_CANCEL", _pendingUpgrade.newImplementation,
381
- /// address(this), block.chainid))`.
584
+ /// address(this), block.chainid))`. Ignored on governed accounts
585
+ /// (the quorum context authorizes; no signature is consulted).
382
586
  function cancelPendingUpgrade(bytes calldata ownerSig) external {
587
+ bool governed = _hasCustodyGovernance();
588
+ // Governed: authorize FIRST (fail-closed before revealing pending state). Only the custody quorum
589
+ // (executor self-call with the gov context set) may cancel — `_custodyGovCtx` is set solely by
590
+ // `executeFromModule` when the caller is the CustodyPolicy module, so this reverts
591
+ // AdminRequiresCustodyQuorum for any single-custodian / external attempt.
592
+ if (governed) _requireCustodyGoverned();
383
593
  PendingUpgrade memory p = _pendingUpgrade;
384
594
  if (p.readyAt == 0) revert NoPendingUpgrade();
385
- bytes32 digest = keccak256(
386
- abi.encode(
387
- bytes32("UPGRADE_CANCEL"),
388
- p.newImplementation,
389
- address(this),
390
- block.chainid
391
- )
392
- );
393
- if (!_verifyEcdsa(digest, ownerSig)) revert NotOwnerSig();
595
+ if (!governed) {
596
+ // Non-governed (mode-0): the sole custodian's ECDSA cancel-grant authorizes.
597
+ bytes32 digest = keccak256(
598
+ abi.encode(
599
+ bytes32("UPGRADE_CANCEL"),
600
+ p.newImplementation,
601
+ address(this),
602
+ block.chainid
603
+ )
604
+ );
605
+ if (!_verifyEcdsa(digest, ownerSig)) revert NotOwnerSig();
606
+ }
394
607
  delete _pendingUpgrade;
395
608
  emit UpgradeCancelled(p.newImplementation);
396
609
  }
@@ -400,6 +613,7 @@ contract AgentAccount is
400
613
  /// (`onlySelf`). 0 == immediate upgrades (default,
401
614
  /// backward-compat).
402
615
  function setUpgradeTimelock(uint256 secs) external onlySelf {
616
+ _requireCustodyGoverned();
403
617
  if (secs > MAX_UPGRADE_TIMELOCK) {
404
618
  revert UpgradeTimelockTooLong(secs, MAX_UPGRADE_TIMELOCK);
405
619
  }
@@ -443,6 +657,7 @@ contract AgentAccount is
443
657
  * a self-call into this function.
444
658
  */
445
659
  function setDelegationManager(address dm) external onlySelf {
660
+ _requireCustodyGoverned();
446
661
  if (dm.code.length == 0) revert ValidatorRequired();
447
662
  _delegationManager = dm;
448
663
  emit DelegationManagerRotated(dm);
@@ -506,6 +721,7 @@ contract AgentAccount is
506
721
  * delegation the owner has authorized.
507
722
  */
508
723
  function acceptSessionDelegation(bytes32 sessionDelegationHash) external onlySelf {
724
+ _requireCustodyGoverned();
509
725
  if (_acceptedSessionDelegations[sessionDelegationHash]) {
510
726
  revert SessionDelegationAlreadyAccepted(sessionDelegationHash);
511
727
  }
@@ -689,7 +905,11 @@ contract AgentAccount is
689
905
  uint256 moduleTypeId,
690
906
  address module,
691
907
  bytes calldata initData
692
- ) external onlySelfOrFactoryInit {
908
+ ) external onlySelfOrFactoryInit whenNotPaused {
909
+ // Wave-1/ACCT-C1: on a custody-governed account, module installs must route
910
+ // through the CustodyPolicy quorum. Exempt by construction at factory-init
911
+ // (no EXECUTOR installed yet ⇒ `_hasCustodyGovernance()` is false).
912
+ _requireCustodyGoverned();
693
913
  if (module == address(0)) revert ZeroAddress();
694
914
  if (!_isSupportedModuleType(moduleTypeId)) revert UnsupportedModuleType(moduleTypeId);
695
915
 
@@ -739,6 +959,7 @@ contract AgentAccount is
739
959
  // at deploy time, and there's never a legitimate reason for
740
960
  // the factory to do that.
741
961
  if (msg.sender != address(this)) revert ModuleOperationNotAllowed();
962
+ _requireCustodyGoverned();
742
963
  if (!_isSupportedModuleType(moduleTypeId)) revert UnsupportedModuleType(moduleTypeId);
743
964
 
744
965
  ModulesStorage storage $ = _modulesStorage();
@@ -746,6 +967,13 @@ contract AgentAccount is
746
967
  revert ModuleNotInstalled(moduleTypeId, module);
747
968
  }
748
969
 
970
+ // R917-C-1: effects BEFORE the interaction. The module's `onUninstall` may verify that this account
971
+ // no longer lists it (CustodyPolicy does — that is how it tells `uninstallModule` apart from a
972
+ // custodian's `execute(custodyPolicy, onUninstall)`), so the flag is cleared first. A revert below
973
+ // still rolls the whole call back.
974
+ $.installed[moduleTypeId][module] = false;
975
+ _removeFromList($.installedList[moduleTypeId], module);
976
+
749
977
  // Loud uninstall — if the module reverts in onUninstall, we revert
750
978
  // too so the caller sees the failure. (Owner can force-uninstall
751
979
  // by passing deInitData the module can handle, or by re-deploying
@@ -756,9 +984,6 @@ contract AgentAccount is
756
984
  revert ModuleOnUninstallFailed(reason);
757
985
  }
758
986
 
759
- $.installed[moduleTypeId][module] = false;
760
- _removeFromList($.installedList[moduleTypeId], module);
761
-
762
987
  emit ModuleUninstalled(moduleTypeId, module);
763
988
  }
764
989
 
@@ -837,6 +1062,7 @@ contract AgentAccount is
837
1062
  function executeFromModule(address target, uint256 value, bytes calldata data)
838
1063
  external
839
1064
  nonReentrant
1065
+ whenNotPaused
840
1066
  returns (bytes memory)
841
1067
  {
842
1068
  ModulesStorage storage $ = _modulesStorage();
@@ -844,7 +1070,31 @@ contract AgentAccount is
844
1070
  revert NotInstalledExecutor(msg.sender);
845
1071
  }
846
1072
  emit ModuleExecuted(msg.sender, target, value);
1073
+ _rejectDirectRegistryCall(target);
1074
+ // CA-1 + Wave-1/ACCT-C1 (spec 300): a module action from the CANONICAL CustodyPolicy is a
1075
+ // custody-governed context (gated upstream by its own T5 quorum + timelock). `_custodyGovCtx`
1076
+ // authorizes every governance mutator this call dispatches (the ONLY way past
1077
+ // `_requireCustodyGoverned` on a `mode>0` account); `_upgradeAuthorizedCtx` additionally exempts a
1078
+ // dispatched upgrade from the per-account timelock (no double delay). Both transient.
1079
+ //
1080
+ // NEW-EXEC-MODULE-1 (2026-07-05 audit, internal + external): grant that context ONLY to the
1081
+ // canonical CustodyPolicy the factory installs — NOT to any installed executor. Otherwise a second
1082
+ // (utility / automation) executor a quorum installs believing it unprivileged would silently inherit
1083
+ // full authority to mutate custody / DM / upgrade / modules, bypassing quorum+timelock. Matching the
1084
+ // specific policy address is the same check `_hasCustodyGovernance` uses. A non-canonical executor
1085
+ // runs WITHOUT the context, so `_requireCustodyGoverned` rejects any governance mutator it dispatches
1086
+ // (defense-in-depth: not reachable at v1 since the factory installs only CustodyPolicy).
1087
+ address f = _factory;
1088
+ bool custodyGoverned = f != address(0) && msg.sender == IAgentAccountFactoryView(f).custodyPolicy();
1089
+ if (custodyGoverned) {
1090
+ _custodyGovCtx = true;
1091
+ _upgradeAuthorizedCtx = true;
1092
+ }
847
1093
  (bool ok, bytes memory ret) = target.call{value: value}(data);
1094
+ if (custodyGoverned) {
1095
+ _upgradeAuthorizedCtx = false;
1096
+ _custodyGovCtx = false;
1097
+ }
848
1098
  if (!ok) {
849
1099
  assembly { revert(add(ret, 32), mload(ret)) }
850
1100
  }
@@ -891,9 +1141,28 @@ contract AgentAccount is
891
1141
  /// EntryPoint / self / DelegationManager; the guard hardens
892
1142
  /// against a malicious target re-entering through one of those
893
1143
  /// callers.
894
- function execute(address target, uint256 value, bytes calldata data) external override nonReentrant {
1144
+ ///
1145
+ /// Slither reports `reentrancy-eth` here because `_delegationExecCtx`
1146
+ /// is written after the external calls. The write is `= false`, and the
1147
+ /// flag is RESTRICTIVE while set: `_rejectDelegatedGovernance` reverts a
1148
+ /// delegation-originated governance self-call only when it is true. A
1149
+ /// reentrant frame therefore observes the *more* restricted state, never
1150
+ /// a bypass — and the only readers of the flag are `execute` (guarded by
1151
+ /// `nonReentrant` on this very function) and `executeBatch`, whose own
1152
+ /// exemption is justified at its declaration. The flag is transient
1153
+ /// (EIP-1153), so it cannot survive the transaction either.
1154
+ // slither-disable-next-line reentrancy-eth
1155
+ function execute(address target, uint256 value, bytes calldata data) external override nonReentrant whenNotPaused {
895
1156
  _requireForExecute();
896
1157
 
1158
+ // DM-3 (spec 300): mark a delegation-originated stack (set once at the
1159
+ // outermost DM frame; preserved across the legitimate DM → execute(self,
1160
+ // executeBatch(...)) nest) and forbid it from self-calling governance.
1161
+ bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1162
+ if (setDelCtx) _delegationExecCtx = true;
1163
+ _rejectDirectRegistryCall(target);
1164
+ _rejectDelegatedGovernance(target, data);
1165
+
897
1166
  ModulesStorage storage $ = _modulesStorage();
898
1167
  address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
899
1168
  bytes[] memory hookData = new bytes[](hooks.length);
@@ -921,6 +1190,8 @@ contract AgentAccount is
921
1190
  for (uint256 i = 0; i < hooks.length; i++) {
922
1191
  IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
923
1192
  }
1193
+
1194
+ if (setDelCtx) _delegationExecCtx = false;
924
1195
  }
925
1196
 
926
1197
  /// @notice Atomically execute multiple calls from this account.
@@ -944,9 +1215,25 @@ contract AgentAccount is
944
1215
  /// OUTER `execute` already holds the guard, so external re-entry
945
1216
  /// is blocked; `_requireForExecute` restricts entry to
946
1217
  /// EntryPoint / self / DM (DM has its own `nonReentrant`).
947
- function executeBatch(Call[] calldata calls) external override {
1218
+ ///
1219
+ /// Slither reports `reentrancy-eth` here for the same reason as
1220
+ /// `execute`, and it is a false positive for the same reason: the
1221
+ /// post-call write clears `_delegationExecCtx`, a transient flag that
1222
+ /// only ever *adds* a restriction while set. Note this function is
1223
+ /// deliberately un-guarded (see above), so the suppression is scoped to
1224
+ /// this detector on this declaration only — any other high-severity
1225
+ /// finding here still fails the build.
1226
+ // slither-disable-next-line reentrancy-eth
1227
+ function executeBatch(Call[] calldata calls) external override whenNotPaused {
948
1228
  _requireForExecute();
949
1229
 
1230
+ // DM-3 (spec 300): same delegation-origin marking as `execute`. Preserved
1231
+ // across the DM → execute(self, executeBatch(...)) nest so a governance
1232
+ // self-call in ANY inner call is caught even though this frame's
1233
+ // msg.sender is address(this).
1234
+ bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1235
+ if (setDelCtx) _delegationExecCtx = true;
1236
+
950
1237
  ModulesStorage storage $ = _modulesStorage();
951
1238
  address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
952
1239
  bytes[] memory hookData = new bytes[](hooks.length);
@@ -960,6 +1247,8 @@ contract AgentAccount is
960
1247
  }
961
1248
 
962
1249
  for (uint256 i = 0; i < calls.length; i++) {
1250
+ _rejectDirectRegistryCall(calls[i].target);
1251
+ _rejectDelegatedGovernance(calls[i].target, calls[i].data);
963
1252
  (bool ok, bytes memory ret) = calls[i].target.call{ value: calls[i].value }(calls[i].data);
964
1253
  if (!ok) {
965
1254
  assembly {
@@ -972,6 +1261,8 @@ contract AgentAccount is
972
1261
  for (uint256 i = 0; i < hooks.length; i++) {
973
1262
  IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
974
1263
  }
1264
+
1265
+ if (setDelCtx) _delegationExecCtx = false;
975
1266
  }
976
1267
 
977
1268
  // ─── ERC-4337 ───────────────────────────────────────────────────
@@ -1005,6 +1296,99 @@ contract AgentAccount is
1005
1296
  }
1006
1297
  }
1007
1298
 
1299
+ // ─── Wave 1 — account authorization boundary (spec 300) ─────────
1300
+
1301
+ /// @dev True when this account is custody-governed — i.e. the canonical
1302
+ /// CustodyPolicy the factory installs for `mode > 0` accounts is installed
1303
+ /// as an EXECUTOR here. Governance mutators then require the
1304
+ /// `executeFromModule` (quorum+timelock) path. A `mode 0` person account
1305
+ /// (no CustodyPolicy) self-governs; installing an UNRELATED utility executor
1306
+ /// does NOT make it custody-governed (we check the specific policy address,
1307
+ /// not "any executor"). If the factory is unknown (legacy direct deploy),
1308
+ /// fall back to person semantics.
1309
+ function _hasCustodyGovernance() internal view returns (bool) {
1310
+ address f = _factory;
1311
+ if (f == address(0)) return false;
1312
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1313
+ if (cp == address(0)) return false;
1314
+ return _modulesStorage().installed[MODULE_TYPE_EXECUTOR][cp];
1315
+ }
1316
+
1317
+ /// @dev ACCT-C1 gate: on a custody-governed account, a governance mutator is
1318
+ /// reachable only through `executeFromModule` (which sets `_custodyGovCtx`).
1319
+ /// A single-signer UserOp `execute(self, adminSelector)` self-call leaves the
1320
+ /// flag unset and reverts here, so the custody quorum can no longer be bypassed.
1321
+ function _requireCustodyGoverned() internal view {
1322
+ if (_hasCustodyGovernance() && !_custodyGovCtx) revert AdminRequiresCustodyQuorum();
1323
+ }
1324
+
1325
+ /// @dev DM-3 gate: a delegation-originated stack may never self-call an account
1326
+ /// governance selector. `_delegationExecCtx` is set at the outermost
1327
+ /// DM-driven `execute`/`executeBatch` and persists across the legitimate
1328
+ /// `DM → execute(self, executeBatch(...))` nest, so a nested governance
1329
+ /// self-call is caught regardless of mode.
1330
+ function _rejectDelegatedGovernance(address target, bytes calldata data) internal view {
1331
+ if (!_delegationExecCtx) return;
1332
+ if (
1333
+ target == address(this) &&
1334
+ data.length >= 4 &&
1335
+ _isGovernanceSelector(bytes4(data[0:4]))
1336
+ ) {
1337
+ revert DelegatedGovernanceForbidden();
1338
+ }
1339
+ // R917-C-1/C-2 (spec 408 §1.1): a delegation stack may not speak AS THE ACCOUNT to the account's own
1340
+ // custody-tier contracts. `CustodyPolicy` and `ApprovedHashRegistry` treat `msg.sender == account` as
1341
+ // the principal — a delegate reaching them through `execute` would uninstall the custody policy
1342
+ // (bricking the account) or plant approved-hash root delegations that outlive the delegate's own
1343
+ // caveats. Any selector: there is no legitimate delegated call to either.
1344
+ if (_isAccountTrustedTarget(target)) revert DelegatedGovernanceForbidden();
1345
+ }
1346
+
1347
+ /// @dev Spec 410 §1 (THESIS-1a). `ApprovedHashRegistry.approveHash` stores whatever 32 bytes the account
1348
+ /// sends, and the custody epoch is public — so a custodian who could reach the registry through
1349
+ /// `execute` could approve `keccak256(abi.encode(h, epoch + 1))`: inert now, live the moment a
1350
+ /// recovery bumps the epoch to expel that very custodian. Closing it: the registry is never an
1351
+ /// execute target; the account derives the key on chain in `approveDigest`, under the epoch it is
1352
+ /// in, and nowhere else. Unconditional — not only under the delegation context (R917-C-1/C-2).
1353
+ function _rejectDirectRegistryCall(address target) internal view {
1354
+ if (target == _approvedHashRegistry && target != address(0)) revert ApprovedHashRegistryOnlyViaAccount();
1355
+ }
1356
+
1357
+ /// @dev The contracts that take THIS ACCOUNT as principal when it is `msg.sender` — reachable only from
1358
+ /// the account's own governance paths (`uninstallModule`, a custodian-signed userOp), never from a
1359
+ /// delegation. The custody policy is read from the factory (the canonical one; a legacy direct
1360
+ /// deploy with no factory has none); the registry is the immutable this account was built with.
1361
+ function _isAccountTrustedTarget(address target) internal view returns (bool) {
1362
+ if (target == _approvedHashRegistry && target != address(0)) return true;
1363
+ address f = _factory;
1364
+ if (f == address(0)) return false;
1365
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1366
+ return cp != address(0) && target == cp;
1367
+ }
1368
+
1369
+ /// @dev The account-governance selector set — mutators that change custody,
1370
+ /// the DelegationManager, installed modules, or the upgrade path. Kept in
1371
+ /// sync with the `_requireCustodyGoverned`-gated functions above.
1372
+ function _isGovernanceSelector(bytes4 s) internal pure returns (bool) {
1373
+ return
1374
+ s == this.setDelegationManager.selector ||
1375
+ s == UUPSUpgradeable.upgradeToAndCall.selector ||
1376
+ s == this.setUpgradeTimelock.selector ||
1377
+ s == this.scheduleUpgrade.selector ||
1378
+ s == this.executePendingUpgrade.selector ||
1379
+ s == this.cancelPendingUpgrade.selector ||
1380
+ s == this.installModule.selector ||
1381
+ s == this.uninstallModule.selector ||
1382
+ s == IAgentAccount.addCustodian.selector ||
1383
+ s == IAgentAccount.removeCustodian.selector ||
1384
+ s == this.addPasskey.selector ||
1385
+ s == this.removePasskey.selector ||
1386
+ s == this.acceptSessionDelegation.selector ||
1387
+ s == this.approveDigest.selector ||
1388
+ s == this.revokeDigest.selector ||
1389
+ s == this.revokeAllApprovedDigests.selector;
1390
+ }
1391
+
1008
1392
  // ─── ERC-1271 ───────────────────────────────────────────────────
1009
1393
 
1010
1394
  /// @dev 32-byte ERC-6492 magic suffix — `0x6492…6492` repeated.
@@ -1018,6 +1402,23 @@ contract AgentAccount is
1018
1402
  bytes32 hash,
1019
1403
  bytes calldata signature
1020
1404
  ) external view override(IAgentAccount, IERC1271) returns (bytes4) {
1405
+ // Spec 253 — approved-hash sentinel (ERC-1271 ONLY). A bare 1-byte
1406
+ // 0x03 validates iff THIS account pre-approved `hash` in the
1407
+ // (immutable) ApprovedHashRegistry — letting an org batch its
1408
+ // outbound-delegation approvals into one deploy userOp. Checked on
1409
+ // the RAW signature before the ERC-6492 unwrap: a 1-byte sig can't
1410
+ // carry a 32-byte 6492 suffix, so there's no smuggling path. This
1411
+ // branch is unreachable from `_validateSignature`/`_validateSig`
1412
+ // (the userOp-auth path), where 0x03 is an unknown type → false.
1413
+ // Fails CLOSED if the registry is unset/not-a-contract (ADR-0013).
1414
+ // R917-C-2: the registry is consulted for the EPOCH-BOUND key, never the raw hash — an approval
1415
+ // made under a custody set that has since retired a credential is not this account's approval.
1416
+ if (signature.length == 1 && uint8(signature[0]) == SIG_TYPE_APPROVED_HASH) {
1417
+ if (_approvedHashRegistry.code.length == 0) return bytes4(0xffffffff);
1418
+ return IApprovedHashRegistryView(_approvedHashRegistry).isApproved(address(this), approvedHashKey(hash))
1419
+ ? ERC1271_MAGIC_VALUE
1420
+ : bytes4(0xffffffff);
1421
+ }
1021
1422
  bytes memory inner = signature;
1022
1423
  if (signature.length >= 32 && bytes32(signature[signature.length - 32:]) == ERC6492_MAGIC) {
1023
1424
  (, , bytes memory unwrapped) = abi.decode(
@@ -1033,6 +1434,12 @@ contract AgentAccount is
1033
1434
 
1034
1435
  uint8 internal constant SIG_TYPE_ECDSA = 0x00;
1035
1436
  uint8 internal constant SIG_TYPE_WEBAUTHN = 0x01;
1437
+ /// @dev Spec 253 — approved-hash sentinel. Honored ONLY by
1438
+ /// `isValidSignature` (ERC-1271), NEVER by `_validateSig` /
1439
+ /// `_validateSignature` (the userOp-auth path) — there `0x03` is an
1440
+ /// unknown type and returns false. A bare 1-byte `0x03` means
1441
+ /// "this hash is pre-approved in the ApprovedHashRegistry".
1442
+ uint8 internal constant SIG_TYPE_APPROVED_HASH = 0x03;
1036
1443
 
1037
1444
  /// @dev Internal dispatcher. Accepts plain 65-byte ECDSA sigs as legacy
1038
1445
  /// form AND type-prefixed sigs (first byte = SIG_TYPE_*).
@@ -1061,11 +1468,14 @@ contract AgentAccount is
1061
1468
 
1062
1469
  function _verifyEcdsa(bytes32 hash, bytes memory sig) internal view returns (bool) {
1063
1470
  // Try raw hash first — matches EntryPoint v0.8 (EIP-712 userOpHash signed directly).
1471
+ // R6.3: third return (sigVersion) intentionally discarded; we rely on `err` + custodian-set membership.
1472
+ // slither-disable-next-line unused-return
1064
1473
  (address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(hash, sig);
1065
1474
  if (err == ECDSA.RecoverError.NoError && _externalCustodians[recovered]) return true;
1066
1475
  // Fall back to eth-signed-message wrap — matches v0.7 and legacy ERC-1271
1067
1476
  // callers that pre-prefix the digest.
1068
1477
  bytes32 ethSigned = hash.toEthSignedMessageHash();
1478
+ // slither-disable-next-line unused-return
1069
1479
  (recovered, err,) = ECDSA.tryRecover(ethSigned, sig);
1070
1480
  return err == ECDSA.RecoverError.NoError && _externalCustodians[recovered];
1071
1481
  }
@@ -1079,9 +1489,12 @@ contract AgentAccount is
1079
1489
  bytes memory sig,
1080
1490
  address expected
1081
1491
  ) internal pure returns (bool) {
1492
+ // R6.3: third return (sigVersion) intentionally discarded; the `err` discriminant + `recovered == expected` is the auth.
1493
+ // slither-disable-next-line unused-return
1082
1494
  (address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(hash, sig);
1083
1495
  if (err == ECDSA.RecoverError.NoError && recovered == expected) return true;
1084
1496
  bytes32 ethSigned = MessageHashUtils.toEthSignedMessageHash(hash);
1497
+ // slither-disable-next-line unused-return
1085
1498
  (recovered, err,) = ECDSA.tryRecover(ethSigned, sig);
1086
1499
  return err == ECDSA.RecoverError.NoError && recovered == expected;
1087
1500
  }
@@ -1105,11 +1518,23 @@ contract AgentAccount is
1105
1518
  PasskeyEntry storage key = $.keys[a.credentialIdDigest];
1106
1519
  if (key.x == 0 && key.y == 0) return false;
1107
1520
  // H7-C.1 / CON-WEBAUTHN-001: pin per-credential rpIdHash + require UP.
1108
- // UV is not required at the library layer; account policy can layer
1109
- // UV requirement in via a future policy module if needed.
1521
+ // R8.2 / ATL-SEC-03: require UV (User Verification) at the library
1522
+ // layer. Wave H1 made the JS-side ceremony pass
1523
+ // `userVerification: 'required'` for custody-grade flows
1524
+ // (demo-sso, demo-sso-next, demo-org, demo-web-recovery); the
1525
+ // third-party audit (2026-05-31) correctly observed that the
1526
+ // contract still passed `requireUv: false` here. That meant a
1527
+ // permissive authenticator could produce a UP-only assertion
1528
+ // and we'd accept it. R8.2 makes UV strictly required on every
1529
+ // ERC-1271 verify. Browser ceremonies that pass
1530
+ // `userVerification: 'preferred'` will be REJECTED at the
1531
+ // signature step — those apps (demo-web, demo-web-pro) MUST
1532
+ // upgrade to `'required'` for production deployments. Tests
1533
+ // exercising lower-assurance flows can install a separate
1534
+ // passkey-validator module that relaxes this check.
1110
1535
  bytes32 rpIdHash = $.rpIdHashOf[a.credentialIdDigest];
1111
1536
  if (rpIdHash == bytes32(0)) return false;
1112
- return WebAuthnLib.verify(a, hash, key.x, key.y, rpIdHash, false);
1537
+ return WebAuthnLib.verify(a, hash, key.x, key.y, rpIdHash, /*requireUv*/ true);
1113
1538
  } catch {
1114
1539
  return false;
1115
1540
  }
@@ -1150,6 +1575,19 @@ contract AgentAccount is
1150
1575
  return _passkeyStorage().piaToCredentialId[account] != bytes32(0);
1151
1576
  }
1152
1577
 
1578
+ /// @notice EXT-ISCUSTODIAN-1 (2026-07-05 audit): like `isCustodian` but EXCLUDES the account itself.
1579
+ /// @dev `isCustodian(address(this)) == true` is deliberate (account-actor compatibility), but that
1580
+ /// footgun can recreate the ACCT-C2 quorum-collapse class in a FUTURE consumer that reuses
1581
+ /// `isCustodian` as if it meant "external signer." Any quorum / authority consumer that must count
1582
+ /// only real external custodians / passkeys (never the account) should use THIS view. ACCT-C2 fixed
1583
+ /// the current CustodyPolicy quorum at the counting site (reject signer==account); this gives new
1584
+ /// consumers the safe primitive so the class can't reappear off-path.
1585
+ function isExternalCustodianOrPasskey(address account) external view returns (bool) {
1586
+ if (account == address(this)) return false;
1587
+ if (_externalCustodians[account]) return true;
1588
+ return _passkeyStorage().piaToCredentialId[account] != bytes32(0);
1589
+ }
1590
+
1153
1591
  /// @inheritdoc IAgentAccount
1154
1592
  /// @dev Counts EOA/contract custodians PLUS registered passkeys —
1155
1593
  /// each passkey contributes one PIA-custodian. Matches the
@@ -1161,15 +1599,23 @@ contract AgentAccount is
1161
1599
  }
1162
1600
 
1163
1601
  /// @notice Deterministically derive the Passkey-Identity-Address for
1164
- /// a P-256 public key. Exposed as `pure` so off-chain code +
1165
- /// other contracts (CustodyPolicy, factory) can recompute it
1166
- /// without reading account state.
1167
- function passkeyIdentity(uint256 x, uint256 y) public pure returns (address) {
1602
+ /// a P-256 public key ON THIS ACCOUNT. Spec 302 W2: the PIA is
1603
+ /// account-scoped — `keccak256(abi.encode(x, y, address(this)))` —
1604
+ /// so the same physical passkey yields a DIFFERENT custodian
1605
+ /// address on every account it custodies. The pre-302 global
1606
+ /// derivation (`keccak256(abi.encode(x, y))`) made the PIA a
1607
+ /// public cross-account join key: one `CustodianAdded(pia)` log
1608
+ /// scan clustered a person's SA with every org/treasury SA their
1609
+ /// root passkey controls. Off-chain mirror: account-custody
1610
+ /// `passkeyIdentity(x, y, account)`; the v=2 signature slot
1611
+ /// verifier (SignatureSlotRecovery) re-derives with the same
1612
+ /// account scope.
1613
+ function passkeyIdentity(uint256 x, uint256 y) public view returns (address) {
1168
1614
  return _passkeyIdentity(x, y);
1169
1615
  }
1170
1616
 
1171
- function _passkeyIdentity(uint256 x, uint256 y) internal pure returns (address) {
1172
- return address(uint160(uint256(keccak256(abi.encode(x, y)))));
1617
+ function _passkeyIdentity(uint256 x, uint256 y) internal view returns (address) {
1618
+ return address(uint160(uint256(keccak256(abi.encode(x, y, address(this))))));
1173
1619
  }
1174
1620
 
1175
1621
  /// @inheritdoc IAgentAccount
@@ -1178,7 +1624,8 @@ contract AgentAccount is
1178
1624
  /// agenticprimitives AgentAccount is forbidden — enforced via
1179
1625
  /// the ERC-165 marker. Passkey custodians are not added here;
1180
1626
  /// use `addPasskey` instead.
1181
- function addCustodian(address owner) external override onlySelf {
1627
+ function addCustodian(address owner) external override onlySelf whenNotPaused {
1628
+ _requireCustodyGoverned();
1182
1629
  if (owner == address(0)) revert ZeroAddress();
1183
1630
  if (_externalCustodians[owner]) revert CustodianAlreadyExists(owner);
1184
1631
  if (_isAgenticPrimitivesAgent(owner)) {
@@ -1222,11 +1669,13 @@ contract AgentAccount is
1222
1669
  /// owner if there are also no registered passkeys. A passkey-only
1223
1670
  /// account is allowed, but a zero-signer account is not.
1224
1671
  function removeCustodian(address owner) external override onlySelf {
1672
+ _requireCustodyGoverned();
1225
1673
  if (!_externalCustodians[owner]) revert CustodianDoesNotExist(owner);
1226
1674
  if (_externalCustodianCount == 1 && _passkeyStorage().count == 0) revert CannotRemoveLastCustodian();
1227
1675
  _externalCustodians[owner] = false;
1228
1676
  _externalCustodianCount--;
1229
1677
  emit CustodianRemoved(owner);
1678
+ _bumpCustodyEpoch();
1230
1679
  }
1231
1680
 
1232
1681
  // ─── Passkey (WebAuthn P-256) management ──────────────────────
@@ -1266,8 +1715,22 @@ contract AgentAccount is
1266
1715
  assembly { $.slot := slot }
1267
1716
  }
1268
1717
 
1269
- event PasskeyAdded(bytes32 indexed credentialIdDigest, uint256 x, uint256 y, bytes32 rpIdHash);
1718
+ /// @dev Spec 302 W1 — the event carries ONLY the credential digest. The raw
1719
+ /// P256 coordinates and rpIdHash were removed: identical (x, y) across
1720
+ /// accounts let any log indexer cluster every SA one physical passkey
1721
+ /// custodies (publicly defeating ADR-0025's person↔org privacy), and
1722
+ /// sha256(rpId) is a guessable-preimage domain disclosure. Coordinates
1723
+ /// remain in storage — the ONE read path is `getPasskey(credentialIdDigest)`
1724
+ /// (ADR-0012/0013; INV-302-3).
1725
+ event PasskeyAdded(bytes32 indexed credentialIdDigest);
1270
1726
  event PasskeyRemoved(bytes32 indexed credentialIdDigest);
1727
+ /// @dev R917-C-2 — a credential was retired; every approved hash keyed to the previous epoch is void.
1728
+ event CustodyEpochBumped(uint64 epoch);
1729
+ /// @dev Spec 410 §1 — `digest` approved under `epoch` through the account's own key derivation.
1730
+ event DigestApproved(bytes32 indexed digest, uint64 epoch);
1731
+ event DigestRevoked(bytes32 indexed digest, uint64 epoch);
1732
+ /// @dev Spec 410 §1 — every approval this account ever made is void (registry-side epoch bump).
1733
+ event AllDigestsRevoked();
1271
1734
 
1272
1735
  /// @notice Register a new WebAuthn credential bound to a specific RP.
1273
1736
  /// `onlySelf` — callable via a UserOp signed by any existing signer
@@ -1286,6 +1749,7 @@ contract AgentAccount is
1286
1749
  uint256 y,
1287
1750
  bytes32 rpIdHash
1288
1751
  ) external onlySelf {
1752
+ _requireCustodyGoverned();
1289
1753
  if (x == 0 || y == 0) revert InvalidPasskeyPublicKey();
1290
1754
  // Audit C-6: zero digest poisons piaToCredentialId mapping.
1291
1755
  if (credentialIdDigest == bytes32(0)) revert InvalidCredentialIdDigest();
@@ -1301,7 +1765,7 @@ contract AgentAccount is
1301
1765
  $.piaToCredentialId[pia] = credentialIdDigest;
1302
1766
  $.rpIdHashOf[credentialIdDigest] = rpIdHash;
1303
1767
  $.count += 1;
1304
- emit PasskeyAdded(credentialIdDigest, x, y, rpIdHash);
1768
+ emit PasskeyAdded(credentialIdDigest);
1305
1769
  emit CustodianAdded(pia);
1306
1770
  }
1307
1771
 
@@ -1310,6 +1774,7 @@ contract AgentAccount is
1310
1774
  /// AND passkeys together. Also clears the credential's PIA
1311
1775
  /// entry so `isCustodian(pia)` flips back to false.
1312
1776
  function removePasskey(bytes32 credentialIdDigest) external onlySelf {
1777
+ _requireCustodyGoverned();
1313
1778
  PasskeyStorage storage $ = _passkeyStorage();
1314
1779
  if (!$.registered[credentialIdDigest]) revert PasskeyNotRegistered(credentialIdDigest);
1315
1780
  if (_externalCustodianCount + $.count == 1) revert CannotRemoveLastSigner();
@@ -1322,6 +1787,7 @@ contract AgentAccount is
1322
1787
  $.count -= 1;
1323
1788
  emit PasskeyRemoved(credentialIdDigest);
1324
1789
  emit CustodianRemoved(pia);
1790
+ _bumpCustodyEpoch();
1325
1791
  }
1326
1792
 
1327
1793
  /// @notice Whether a passkey is registered on this account.
@@ -1335,11 +1801,76 @@ contract AgentAccount is
1335
1801
  return (k.x, k.y);
1336
1802
  }
1337
1803
 
1804
+ /// @notice Read the RP-ID hash a credential was registered against.
1805
+ /// @dev Spec 302 W1 (INV-302-3): the slimmed `PasskeyAdded` event no longer
1806
+ /// carries `rpIdHash`; this getter is the ONE read path for it
1807
+ /// (ADR-0012/0013 — `readContract`, no log walking).
1808
+ function getPasskeyRpIdHash(bytes32 credentialIdDigest) external view returns (bytes32) {
1809
+ return _passkeyStorage().rpIdHashOf[credentialIdDigest];
1810
+ }
1811
+
1338
1812
  /// @notice Total count of registered passkeys.
1339
1813
  function passkeyCount() external view returns (uint256) {
1340
1814
  return _passkeyStorage().count;
1341
1815
  }
1342
1816
 
1817
+ // ─── Custody epoch (R917-C-2, spec 408 §1.2) ─────────────────────
1818
+
1819
+ /// @notice The current custody epoch — bumped whenever a credential is retired.
1820
+ function custodyEpoch() external view returns (uint64) {
1821
+ return _custodyEpoch;
1822
+ }
1823
+
1824
+ /// @notice THE KEY an SDK approves in the `ApprovedHashRegistry` for `hash` to validate through this
1825
+ /// account's `0x03` sentinel NOW: `keccak256(abi.encode(hash, custodyEpoch))`. A counterfactual
1826
+ /// account (not yet deployed) is at epoch 0, so its key is computable before deploy — which is
1827
+ /// what spec 253's batched deploy-and-approve relies on.
1828
+ function approvedHashKey(bytes32 hash) public view returns (bytes32) {
1829
+ return keccak256(abi.encode(hash, _custodyEpoch));
1830
+ }
1831
+
1832
+ /// @dev Retire-a-credential paths call this; see `_custodyEpoch`.
1833
+ function _bumpCustodyEpoch() internal {
1834
+ uint64 next = _custodyEpoch + 1;
1835
+ _custodyEpoch = next;
1836
+ emit CustodyEpochBumped(next);
1837
+ }
1838
+
1839
+ // ─── Approved digests (spec 410 §1, THESIS-1a) ───────────────────
1840
+
1841
+ /// @notice Approve `digest` for this account's `0x03` sentinel under the epoch the account is IN. The
1842
+ /// only path to the registry (`execute` refuses it as a target), so the key is never computed
1843
+ /// by a caller and never for an epoch other than the current one. `onlySelf`, not
1844
+ /// custody-gated: spec 253's one-prompt org-create batches it into the deploy userOp under the
1845
+ /// creating custodian, and the epoch (R917-C-2) plus `revokeAllApprovedDigests` on every
1846
+ /// recovery path (spec 410 §1.2) close the persistence risk instead. A delegation stack cannot
1847
+ /// reach it (`_isGovernanceSelector`).
1848
+ function approveDigest(bytes32 digest) external onlySelf {
1849
+ if (_approvedHashRegistry == address(0)) revert ApprovedHashRegistryOnlyViaAccount();
1850
+ IApprovedHashRegistryWrite(_approvedHashRegistry).approveHash(approvedHashKey(digest));
1851
+ emit DigestApproved(digest, _custodyEpoch);
1852
+ }
1853
+
1854
+ /// @notice Revoke one approval made under the current epoch.
1855
+ function revokeDigest(bytes32 digest) external onlySelf {
1856
+ if (_approvedHashRegistry == address(0)) revert ApprovedHashRegistryOnlyViaAccount();
1857
+ IApprovedHashRegistryWrite(_approvedHashRegistry).revokeHash(approvedHashKey(digest));
1858
+ emit DigestRevoked(digest, _custodyEpoch);
1859
+ }
1860
+
1861
+ /// @notice Void EVERY approval this account ever made, under any epoch — including one planted for a
1862
+ /// future epoch before this contract generation refused direct registry calls. `CustodyPolicy`
1863
+ /// calls it as the last step of every recovery path; a custody-governed account reaches it
1864
+ /// only through the module (`_requireCustodyGoverned`), a mode-0 person through her own userOp.
1865
+ /// Recovery re-approves nothing: the person re-issues from a reviewed list (spec 410 §1.2).
1866
+ function revokeAllApprovedDigests() external onlySelf {
1867
+ _requireCustodyGoverned();
1868
+ // No registry wired: nothing was ever approvable (the sentinel fails closed, l. ~1388), so there is
1869
+ // nothing to void — a no-op, never a revert, so a recovery on such an account still completes.
1870
+ if (_approvedHashRegistry != address(0)) IApprovedHashRegistryWrite(_approvedHashRegistry).revokeAll();
1871
+ emit AllDigestsRevoked();
1872
+ }
1873
+
1343
1874
  // ─── Custody policy + scheduled changes ───────────────────────────
1344
1875
  //
1345
1876
  // The schedule / apply / cancel custody-change surface, CustodyAction