Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion web/src/limits/SpendingLimitsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
Expand Down
33 changes: 28 additions & 5 deletions web/src/limits/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down Expand Up @@ -153,6 +153,23 @@ 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. When
* the list cannot be read it is empty, so pausing never waits on it.
*/
async earlierIntiKeys(accountId: string): Promise<string[]> {
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);
}

private intiKeyAction(accountId: string) {
return actions.addFunctionCallAccessKey(
PublicKey.fromString(this.config.intiPublicKey),
Expand Down Expand Up @@ -222,7 +239,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({
Expand All @@ -234,7 +251,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;
}
Expand Down Expand Up @@ -286,17 +307,19 @@ export class LimitsClient {
}

async disconnectInti(accountId: string, signer: Signer): Promise<string> {
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<string> {
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;
}
Expand Down
26 changes: 20 additions & 6 deletions web/src/limits/ownerActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 | string[] {
const { token } = config;
if (action.deployContract) {
if (isEmptyContract(action.deployContract.code)) {
Expand Down Expand Up @@ -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.`);
}
Expand Down Expand Up @@ -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<string> = 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));
Expand Down
101 changes: 101 additions & 0 deletions web/src/limits/ownerSigner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) {
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();
Expand Down Expand Up @@ -142,6 +153,78 @@ 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);
});

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);
});

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"] } })],
["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)]]],
Expand Down Expand Up @@ -528,6 +611,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);
Expand Down
33 changes: 29 additions & 4 deletions web/src/limits/ownerSigner.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -38,6 +38,31 @@ 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<Set<string>> {
const current = this.config.intiPublicKey;
// 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<string>();
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<PublicKey> {
return this.inner.getPublicKey();
}
Expand All @@ -51,15 +76,15 @@ 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<void> {
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.");
this.approved = each;
}

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]);
Expand Down
Loading