From f9a461e98c3f3294a80abed91aaa53b80c1f676e Mon Sep 17 00:00:00 2001 From: JA VI <127710324+JaDi03@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:36:51 -0600 Subject: [PATCH 1/3] feat(web): pausing, resuming and turning off Inti also remove its earlier keys --- web/src/limits/SpendingLimitsPanel.tsx | 2 +- web/src/limits/client.ts | 27 +++++++++--- web/src/limits/ownerActions.ts | 26 ++++++++--- web/src/limits/ownerSigner.test.ts | 60 ++++++++++++++++++++++++++ web/src/limits/ownerSigner.ts | 28 ++++++++++-- 5 files changed, 127 insertions(+), 16 deletions(-) diff --git a/web/src/limits/SpendingLimitsPanel.tsx b/web/src/limits/SpendingLimitsPanel.tsx index 0d8ed33..cf7b40d 100644 --- a/web/src/limits/SpendingLimitsPanel.tsx +++ b/web/src/limits/SpendingLimitsPanel.tsx @@ -259,7 +259,7 @@ function LimitsBody({ address, config, client }: { address: string; config: Limi disabled={busy !== null} onClick={() => void run("Turning off Inti: confirm once...", async () => { - const plan = client.releasePlan(address, status.spendable, status.intiConnected); + const plan = client.releasePlan(address, status.spendable, status.intiConnected, await client.earlierIntiKeys(address)); await signer.approveAll(plan); return client.send(address, signer, plan); }) diff --git a/web/src/limits/client.ts b/web/src/limits/client.ts index a5a38d0..7699fc7 100644 --- a/web/src/limits/client.ts +++ b/web/src/limits/client.ts @@ -3,7 +3,7 @@ import type { Action, Signer } from "near-api-js"; import { priceToMicro } from "../../../agent/core/money"; import { ASSET_KEYS, ASSETS, type AssetKey } from "../../../agent/policy/assets"; import type { LimitsConfig } from "./config"; -import { assetContract, EMPTY_CONTRACT, wasmSha256, type OwnerTransaction } from "./ownerActions"; +import { assetContract, EMPTY_CONTRACT, isIntiShapedKey, wasmSha256, type OwnerTransaction } from "./ownerActions"; const TGAS = 10n ** 12n; /** Storage staking rate: 1E19 yoctoNEAR per byte (docs.near.org/protocol/storage/storage-staking). */ @@ -153,6 +153,17 @@ export class LimitsClient { return new Account(accountId, this.provider, signer); } + /** + * Inti keys from before the server's key changed: keys that may only call fund_agent on the + * account, other than the current one. Pausing, resuming and turning off remove them too. + */ + async earlierIntiKeys(accountId: string): Promise { + const list = await new Account(accountId, this.provider).getAccessKeyList(); + return list.keys + .filter((k) => k.public_key !== this.config.intiPublicKey && isIntiShapedKey(k.access_key.permission, accountId)) + .map((k) => k.public_key); + } + private intiKeyAction(accountId: string) { return actions.addFunctionCallAccessKey( PublicKey.fromString(this.config.intiPublicKey), @@ -222,7 +233,7 @@ export class LimitsClient { * Spending Limits with an empty contract, which frees the code's storage. Everything stays as * plain NEAR in the user's account. */ - releasePlan(accountId: string, wrapped: bigint, intiConnected: boolean): OwnerTransaction[] { + releasePlan(accountId: string, wrapped: bigint, intiConnected: boolean, earlierKeys: readonly string[] = []): OwnerTransaction[] { const plan: OwnerTransaction[] = []; if (wrapped > 0n) { plan.push({ @@ -234,7 +245,11 @@ export class LimitsClient { plan.push({ signerId: accountId, receiverId: accountId, - actions: [...(intiConnected ? [actions.deleteKey(PublicKey.fromString(this.config.intiPublicKey))] : []), actions.deployContract(EMPTY_CONTRACT)], + actions: [ + ...(intiConnected ? [actions.deleteKey(PublicKey.fromString(this.config.intiPublicKey))] : []), + ...earlierKeys.map((k) => actions.deleteKey(PublicKey.fromString(k))), + actions.deployContract(EMPTY_CONTRACT), + ], }); return plan; } @@ -286,17 +301,19 @@ export class LimitsClient { } async disconnectInti(accountId: string, signer: Signer): Promise { + const earlier = await this.earlierIntiKeys(accountId); const res = await this.account(accountId, signer).signAndSendTransaction({ receiverId: accountId, - actions: [actions.deleteKey(PublicKey.fromString(this.config.intiPublicKey))], + actions: [actions.deleteKey(PublicKey.fromString(this.config.intiPublicKey)), ...earlier.map((k) => actions.deleteKey(PublicKey.fromString(k)))], }); return res.transaction.hash; } async reconnectInti(accountId: string, signer: Signer): Promise { + const earlier = await this.earlierIntiKeys(accountId); const res = await this.account(accountId, signer).signAndSendTransaction({ receiverId: accountId, - actions: [this.intiKeyAction(accountId)], + actions: [...earlier.map((k) => actions.deleteKey(PublicKey.fromString(k))), this.intiKeyAction(accountId)], }); return res.transaction.hash; } diff --git a/web/src/limits/ownerActions.ts b/web/src/limits/ownerActions.ts index 6a09880..9f57d1f 100644 --- a/web/src/limits/ownerActions.ts +++ b/web/src/limits/ownerActions.ts @@ -69,8 +69,18 @@ function atomicArg(value: unknown, method: string): bigint { return BigInt(value); } +/** + * Whether an access key, as the chain shows it, has the shape of an Inti key: it may only call + * fund_agent on the account itself. Such a key can never move money anywhere but the owner's agent. + */ +export function isIntiShapedKey(permission: unknown, accountId: string): boolean { + if (typeof permission !== "object" || permission === null || !("FunctionCall" in permission)) return false; + const call = (permission as { FunctionCall: { receiver_id?: unknown; method_names?: unknown } }).FunctionCall; + return call.receiver_id === accountId && Array.isArray(call.method_names) && call.method_names.length === 1 && call.method_names[0] === "fund_agent"; +} + /** One action on the user's own account, described in one or more lines; anything else is refused. */ -function describeOwnAccountAction(action: Action, config: LimitsConfig, accountId: string): string | string[] { +function describeOwnAccountAction(action: Action, config: LimitsConfig, accountId: string, earlierIntiKeys: ReadonlySet): string | string[] { const { token } = config; if (action.deployContract) { if (isEmptyContract(action.deployContract.code)) { @@ -124,8 +134,11 @@ function describeOwnAccountAction(action: Action, config: LimitsConfig, accountI ]; } if (action.deleteKey) { - if (action.deleteKey.publicKey.toString() !== config.intiPublicKey) refuse("the key to remove is not Inti's key."); - return "Turn off Inti's access to your account."; + const key = action.deleteKey.publicKey.toString(); + if (key === config.intiPublicKey) return "Turn off Inti's access to your account."; + // An earlier Inti key, checked on chain by the signer: it may only call fund_agent on this account. + if (earlierIntiKeys.has(key)) return `Remove an earlier Inti key (${key.slice(0, 16)}...) from your account. It could only call fund_agent.`; + refuse("the key to remove is not Inti's key."); } refuse(`the action ${action.enum} is not one Inti uses.`); } @@ -356,12 +369,13 @@ export function describeOwnerMessage(message: GrantMessage, accountId: string, p /** * Plain-language lines for a transaction the app may sign with the user's full-access - * key, or a RefusedSigningError when any part of it is not an action Inti uses. + * key, or a RefusedSigningError when any part of it is not an action Inti uses. `earlierIntiKeys` + * are keys the signer read on chain and found to have Inti's shape (see isIntiShapedKey). */ -export function describeOwnerTransaction(tx: OwnerTransaction, config: LimitsConfig): string[] { +export function describeOwnerTransaction(tx: OwnerTransaction, config: LimitsConfig, earlierIntiKeys: ReadonlySet = new Set()): string[] { const accountId = tx.signerId; if (tx.actions.length === 0) refuse("the transaction is empty."); - if (tx.receiverId === accountId) return tx.actions.flatMap((action) => describeOwnAccountAction(action, config, accountId)); + if (tx.receiverId === accountId) return tx.actions.flatMap((action) => describeOwnAccountAction(action, config, accountId, earlierIntiKeys)); if (tx.receiverId === config.token.id) return tx.actions.map((action) => describeTokenAction(action, config, accountId)); const asset = assetByContract(tx.receiverId); if (asset) return tx.actions.map((action) => describeAssetEnable(action, asset.name, accountId)); diff --git a/web/src/limits/ownerSigner.test.ts b/web/src/limits/ownerSigner.test.ts index 6726c1f..e2c55c0 100644 --- a/web/src/limits/ownerSigner.test.ts +++ b/web/src/limits/ownerSigner.test.ts @@ -63,11 +63,22 @@ function clientSigningThrough(wallet: Wallet) { await sign(wallet, params.receiverId, params.actions); return { transaction: { hash: "tx" } } as never; }); + vi.spyOn(Account.prototype, "getAccessKeyList").mockResolvedValue({ keys: [] } as never); const client = new LimitsClient(config); vi.spyOn(client.provider, "callFunction").mockResolvedValue({ min: "1250000000000000000000" } as never); return client; } +/** The chain shows these keys on the account: each one answers with its permission. */ +function keysOnChain(keys: Record) { + vi.spyOn(Account.prototype, "getAccessKeyList").mockResolvedValue({ keys: Object.entries(keys).map(([public_key, permission]) => ({ public_key, access_key: { nonce: 1, permission } })) } as never); + vi.spyOn(Account.prototype, "getAccessKey").mockImplementation((key) => { + const permission = keys[key.toString()]; + return permission === undefined ? Promise.reject(new Error("no key")) : Promise.resolve({ nonce: 1, permission } as never); + }); +} +const fundAgentOnly = (accountId: string) => ({ FunctionCall: { allowance: "1", receiver_id: accountId, method_names: ["fund_agent"] } }); + afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); @@ -142,6 +153,37 @@ describe("signing with the user's account key", () => { expect(wallet.signed).toHaveLength(0); }); + it("pausing and resuming also remove an earlier Inti key that the chain shows", async () => { + const wallet = userWallet(); + const client = clientSigningThrough(wallet); + const earlier = KeyPair.fromRandom("ed25519").getPublicKey().toString(); + keysOnChain({ [intiKey.toString()]: fundAgentOnly(wallet.accountId), [earlier]: fundAgentOnly(wallet.accountId), [wallet.publicKey.toString()]: "FullAccess" }); + await client.disconnectInti(wallet.accountId, wallet.signer); + await client.reconnectInti(wallet.accountId, wallet.signer); + const removed = `Remove an earlier Inti key (${earlier.slice(0, 16)}...) from your account. It could only call fund_agent.`; + expect(wallet.shown[0]).toEqual(["Turn off Inti's access to your account.", removed]); + expect(wallet.shown[1]?.[0]).toBe(removed); + expect(wallet.shown[1]).toHaveLength(3); + expect(wallet.signed).toHaveLength(2); + }); + + const notInti: [string, (w: Wallet) => unknown][] = [ + ["the user's own full-access key", () => "FullAccess"], + ["a key for another contract", () => ({ FunctionCall: { allowance: "1", receiver_id: "other.near", method_names: ["fund_agent"] } })], + ["a key with more methods", (w) => ({ FunctionCall: { allowance: "1", receiver_id: w.accountId, method_names: ["fund_agent", "set_limit"] } })], + ["a key with any method", (w) => ({ FunctionCall: { allowance: "1", receiver_id: w.accountId, method_names: [] } })], + ]; + + it.each(notInti)("refuses to remove %s, whatever the app asks", async (_name, permission) => { + const wallet = userWallet(); + const key = KeyPair.fromRandom("ed25519").getPublicKey(); + keysOnChain({ [key.toString()]: permission(wallet), [wallet.publicKey.toString()]: "FullAccess" }); + await expect(sign(wallet, wallet.accountId, [actions.deleteKey(key)])).rejects.toThrow(RefusedSigningError); + await expect(sign(wallet, wallet.accountId, [actions.deleteKey(wallet.publicKey)])).rejects.toThrow(RefusedSigningError); + expect(wallet.shown).toHaveLength(0); + expect(wallet.signed).toHaveLength(0); + }); + const refused: [string, (w: Wallet) => [string, Action[]]][] = [ ["moving all funds and adding a stranger's full-access key", (w) => [w.accountId, [actions.transfer(10n ** 30n), actions.addFullAccessKey(KeyPair.fromRandom("ed25519").getPublicKey())]]], ["a plain NEAR transfer", (w) => [w.accountId, [actions.transfer(1n)]]], @@ -528,6 +570,24 @@ describe("turning Inti off", () => { expect(wallet.signed).toHaveLength(2); }); + it("removes an earlier Inti key in the same confirmation", async () => { + const wallet = userWallet(); + const client = clientSigningThrough(wallet); + const earlier = KeyPair.fromRandom("ed25519").getPublicKey().toString(); + keysOnChain({ [intiKey.toString()]: fundAgentOnly(wallet.accountId), [earlier]: fundAgentOnly(wallet.accountId) }); + const plan = client.releasePlan(wallet.accountId, 0n, true, await client.earlierIntiKeys(wallet.accountId)); + await wallet.signer.approveAll(plan); + await client.send(wallet.accountId, wallet.signer, plan); + expect(wallet.shown).toEqual([ + [ + "Turn off Inti's access to your account.", + `Remove an earlier Inti key (${earlier.slice(0, 16)}...) from your account. It could only call fund_agent.`, + "Remove Inti's setup from your account. The NEAR set aside for it goes back to your main balance.", + ], + ]); + expect(wallet.signed).toHaveLength(1); + }); + it("leaves out the steps that are not needed", () => { const client = new LimitsClient(config); const plan = client.releasePlan("ab".repeat(32), 0n, false); diff --git a/web/src/limits/ownerSigner.ts b/web/src/limits/ownerSigner.ts index 7f9acd2..28bc7a3 100644 --- a/web/src/limits/ownerSigner.ts +++ b/web/src/limits/ownerSigner.ts @@ -1,7 +1,7 @@ -import { Signer } from "near-api-js"; +import { Account, JsonRpcProvider, Signer } from "near-api-js"; import type { DelegateAction, PublicKey, SignedMessage, Transaction } from "near-api-js"; import type { LimitsConfig } from "./config"; -import { describeOwnerDelegate, describeOwnerMessage, describeOwnerTransaction, RefusedSigningError, type OwnerTransaction } from "./ownerActions"; +import { describeOwnerDelegate, describeOwnerMessage, describeOwnerTransaction, isIntiShapedKey, RefusedSigningError, type OwnerTransaction } from "./ownerActions"; /** What near-api-js passes to sign a NEP-413 message. */ interface MessagePayload { @@ -38,6 +38,26 @@ export class OwnerSigner extends Signer { super(); } + /** + * The keys this transaction removes, other than Inti's current one, that the chain shows with + * Inti's shape. Read here, not taken from the app, so only such keys can ever be removed. + */ + private async earlierIntiKeys(tx: OwnerTransaction): Promise> { + const current = this.config.intiPublicKey; + const asked = tx.actions.flatMap((a) => (a.deleteKey && a.deleteKey.publicKey.toString() !== current ? [a.deleteKey.publicKey.toString()] : [])); + const found = new Set(); + if (asked.length === 0 || tx.receiverId !== tx.signerId) return found; + const account = new Account(tx.signerId, new JsonRpcProvider({ url: this.config.rpcUrl })); + for (const key of asked) { + try { + if (isIntiShapedKey((await account.getAccessKey(key)).permission, tx.signerId)) found.add(key); + } catch { + // Not on the account, or the chain did not answer: the key is not treated as Inti's. + } + } + return found; + } + getPublicKey(): Promise { return this.inner.getPublicKey(); } @@ -51,7 +71,7 @@ export class OwnerSigner extends Signer { * without asking again only if it reads exactly as approved, in the same order. */ async approveAll(transactions: readonly OwnerTransaction[]): Promise { - const each = transactions.map((t) => describeOwnerTransaction(t, this.config)); + const each = await Promise.all(transactions.map(async (t) => describeOwnerTransaction(t, this.config, await this.earlierIntiKeys(t)))); if (!this.hasPasskey()) throw new RefusedSigningError("Inti refused to sign: protect your account with a passkey or an authenticator app first."); this.approved = []; if (!(await this.confirm(each.flat()))) throw new SigningCancelledError("You cancelled the signature. Nothing was sent."); @@ -59,7 +79,7 @@ export class OwnerSigner extends Signer { } override async signTransaction(transaction: Transaction) { - const lines = describeOwnerTransaction(transaction, this.config); + const lines = describeOwnerTransaction(transaction, this.config, await this.earlierIntiKeys(transaction)); if (!this.hasPasskey()) throw new RefusedSigningError("Inti refused to sign: protect your account with a passkey or an authenticator app first."); const next = this.approved.shift(); const preApproved = next !== undefined && next.length === lines.length && next.every((line, i) => line === lines[i]); From 63369381e502164a540aa394509d4a1db03a1116 Mon Sep 17 00:00:00 2001 From: JA VI <127710324+JaDi03@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:37:40 -0600 Subject: [PATCH 2/3] feat(web): pausing Inti never waits on reading its earlier keys --- web/src/limits/client.ts | 10 ++++++++-- web/src/limits/ownerSigner.test.ts | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/web/src/limits/client.ts b/web/src/limits/client.ts index 7699fc7..c6cef05 100644 --- a/web/src/limits/client.ts +++ b/web/src/limits/client.ts @@ -155,10 +155,16 @@ export class LimitsClient { /** * Inti keys from before the server's key changed: keys that may only call fund_agent on the - * account, other than the current one. Pausing, resuming and turning off remove them too. + * account, other than the current one. Pausing, resuming and turning off remove them too. When + * the list cannot be read it is empty, so pausing never waits on it. */ async earlierIntiKeys(accountId: string): Promise { - const list = await new Account(accountId, this.provider).getAccessKeyList(); + let list; + try { + list = await new Account(accountId, this.provider).getAccessKeyList(); + } catch { + return []; + } return list.keys .filter((k) => k.public_key !== this.config.intiPublicKey && isIntiShapedKey(k.access_key.permission, accountId)) .map((k) => k.public_key); diff --git a/web/src/limits/ownerSigner.test.ts b/web/src/limits/ownerSigner.test.ts index e2c55c0..a0b84b4 100644 --- a/web/src/limits/ownerSigner.test.ts +++ b/web/src/limits/ownerSigner.test.ts @@ -167,6 +167,15 @@ describe("signing with the user's account key", () => { expect(wallet.signed).toHaveLength(2); }); + it("pauses with Inti's current key even when the list of keys cannot be read", async () => { + const wallet = userWallet(); + const client = clientSigningThrough(wallet); + vi.spyOn(Account.prototype, "getAccessKeyList").mockRejectedValue(new Error("rpc down")); + await client.disconnectInti(wallet.accountId, wallet.signer); + expect(wallet.shown).toEqual([["Turn off Inti's access to your account."]]); + expect(wallet.signed).toHaveLength(1); + }); + const notInti: [string, (w: Wallet) => unknown][] = [ ["the user's own full-access key", () => "FullAccess"], ["a key for another contract", () => ({ FunctionCall: { allowance: "1", receiver_id: "other.near", method_names: ["fund_agent"] } })], From 2307fc4ce072638ce7d3fb607d7332156f03716a Mon Sep 17 00:00:00 2001 From: JA VI <127710324+JaDi03@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:42:10 -0600 Subject: [PATCH 3/3] feat(web): the signer never removes its own key --- web/src/limits/ownerSigner.test.ts | 32 ++++++++++++++++++++++++++++++ web/src/limits/ownerSigner.ts | 7 ++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/web/src/limits/ownerSigner.test.ts b/web/src/limits/ownerSigner.test.ts index a0b84b4..997fbea 100644 --- a/web/src/limits/ownerSigner.test.ts +++ b/web/src/limits/ownerSigner.test.ts @@ -176,6 +176,38 @@ describe("signing with the user's account key", () => { expect(wallet.signed).toHaveLength(1); }); + it("never removes the user's own key, even when the chain claims it can only call fund_agent", async () => { + const wallet = userWallet(); + keysOnChain({ [wallet.publicKey.toString()]: fundAgentOnly(wallet.accountId) }); + await expect(sign(wallet, wallet.accountId, [actions.deleteKey(wallet.publicKey)])).rejects.toThrow(RefusedSigningError); + expect(wallet.shown).toHaveLength(0); + expect(wallet.signed).toHaveLength(0); + }); + + it("refuses to remove a key it cannot read on chain, or one sent to another account", async () => { + const wallet = userWallet(); + const missing = KeyPair.fromRandom("ed25519").getPublicKey(); + const earlier = KeyPair.fromRandom("ed25519").getPublicKey(); + keysOnChain({ [earlier.toString()]: fundAgentOnly(wallet.accountId) }); + await expect(sign(wallet, wallet.accountId, [actions.deleteKey(missing)])).rejects.toThrow(RefusedSigningError); + await expect(sign(wallet, "other.near", [actions.deleteKey(earlier)])).rejects.toThrow(RefusedSigningError); + vi.spyOn(Account.prototype, "getAccessKey").mockRejectedValue(new Error("rpc down")); + await expect(sign(wallet, wallet.accountId, [actions.deleteKey(earlier)])).rejects.toThrow(RefusedSigningError); + expect(wallet.signed).toHaveLength(0); + }); + + it("refuses when an earlier key changed on chain between the approval and the signature", async () => { + const wallet = userWallet(); + const client = clientSigningThrough(wallet); + const earlier = KeyPair.fromRandom("ed25519").getPublicKey().toString(); + keysOnChain({ [intiKey.toString()]: fundAgentOnly(wallet.accountId), [earlier]: fundAgentOnly(wallet.accountId) }); + const plan = client.releasePlan(wallet.accountId, 0n, true, [earlier]); + await wallet.signer.approveAll(plan); + keysOnChain({ [intiKey.toString()]: fundAgentOnly(wallet.accountId) }); + await expect(client.send(wallet.accountId, wallet.signer, plan)).rejects.toThrow(RefusedSigningError); + expect(wallet.signed).toHaveLength(0); + }); + const notInti: [string, (w: Wallet) => unknown][] = [ ["the user's own full-access key", () => "FullAccess"], ["a key for another contract", () => ({ FunctionCall: { allowance: "1", receiver_id: "other.near", method_names: ["fund_agent"] } })], diff --git a/web/src/limits/ownerSigner.ts b/web/src/limits/ownerSigner.ts index 28bc7a3..d1337bc 100644 --- a/web/src/limits/ownerSigner.ts +++ b/web/src/limits/ownerSigner.ts @@ -44,7 +44,12 @@ export class OwnerSigner extends Signer { */ private async earlierIntiKeys(tx: OwnerTransaction): Promise> { const current = this.config.intiPublicKey; - const asked = tx.actions.flatMap((a) => (a.deleteKey && a.deleteKey.publicKey.toString() !== current ? [a.deleteKey.publicKey.toString()] : [])); + // The signing key itself is never an earlier Inti key, whatever the chain answers. + const own = (await this.inner.getPublicKey()).toString(); + const asked = tx.actions.flatMap((a) => { + const key = a.deleteKey?.publicKey.toString(); + return key !== undefined && key !== current && key !== own ? [key] : []; + }); const found = new Set(); if (asked.length === 0 || tx.receiverId !== tx.signerId) return found; const account = new Account(tx.signerId, new JsonRpcProvider({ url: this.config.rpcUrl }));