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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ A NEAR contract that records an agent's request to act and an approver's decisio
- Contract: [`contracts/approval`](contracts/approval/README.md)
- Operations: [`scripts/near`](scripts/near/README.md)
- Approver page: [`ui/approvals`](ui/approvals/README.md)
- Spec review page: [`ui/spec-approvals`](ui/spec-approvals/README.md)
- Spec review, one signature per requirement (R1–R6, D1–D17): [`ui/spec-approvals`](ui/spec-approvals/README.md)
- Spec review, full packet: [`ui/spec-approvals-full`](ui/spec-approvals-full/README.md)

The testnet demonstration is [`approvals.difflabai.testnet`](https://testnet.nearblocks.io/address/approvals.difflabai.testnet), owned by `difflabai.testnet`. It can still be redeployed. Set `NEAR_ACCOUNT_ID` to point the scripts at it, or at your own account. `APPROVAL_CONTRACT_ID` defaults to `approvals.<NEAR_ACCOUNT_ID>`.

Expand Down
4 changes: 2 additions & 2 deletions scripts/near/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ seconds).
| `request-action.sh <agent> <action>` | Signs `request_action` with the agent's stored key, else `APPROVAL_AGENT_*` from `.env` when it names this account (or `--key-file PATH`), after checking the key may call `request_action` and is registered; prints the request id. `--action-file PATH` (`-` for stdin) reads the action byte for byte; an action starting with `-` goes after `--`. |
| `approve.sh <approver> <request_id> <action>` | Signs `approve` with the approver's stored key, else `APPROVAL_APPROVER_*` from `.env` (or `--key-file PATH`); prints the proof. Checks first that the key may call `approve` and is registered, that the request is pending, that the action matches exactly, and that the agent isn't the approver's own account (`--skip-checks` sends anyway). The action can come from `--action-file PATH`, or, after reviewing it, from `--action-from-request`. |
| `reject.sh <approver> <request_id>` | Signs `reject` with the stored key, else `APPROVAL_APPROVER_*` from `.env` (or `--key-file PATH`); prints the rejection. Refuses before sending when the key may not call `reject` (e.g. an approve-only key). |
| `submit-spec-packet.sh [--packet PATH] [--item ID]... [--setup-agent] [--dry-run] [--yes]` | Files each item of a spec review packet (default `ui/spec-approvals/packets/near-approval.json`) as one request for review in [`ui/spec-approvals/`](../../ui/spec-approvals/README.md). Each action names the item and the SHA-256 of its text (`spec_packet.py`). Idempotent: items that already have a pending, approved or rejected request are skipped, and only items with void requests are filed again. The agent (`--agent`, else `APPROVAL_AGENT_ACCOUNT_ID`, else `spec-agent`) signs as `request-action.sh` does: `--key-file`, its stored key, or `APPROVAL_AGENT_*` from `.env`. `--setup-agent` creates and registers the stored key with `new-principal.sh` if it is missing. |
| `submit-spec-packet.sh [--packet PATH] [--item ID]... [--setup-agent] [--dry-run] [--yes]` | Files each item of a spec review packet (default `ui/spec-approvals-full/packets/near-approval.json`) as one request for review in [`ui/spec-approvals-full/`](../../ui/spec-approvals-full/README.md). Pass `--packet ui/spec-approvals/packets/requirements.json` to file one request per requirement (R1–R6, D1–D17), reviewed in [`ui/spec-approvals/`](../../ui/spec-approvals/README.md). Each action names the item and the SHA-256 of its text (`spec_packet.py`). Idempotent: items that already have a pending, approved or rejected request are skipped, and only items with void requests are filed again. The agent (`--agent`, else `APPROVAL_AGENT_ACCOUNT_ID`, else `agent1`) signs as `request-action.sh` does: `--key-file`, its stored key, or `APPROVAL_AGENT_*` from `.env`. `--setup-agent` creates and registers the stored key with `new-principal.sh` if it is missing. |
| `smoke-test.sh [--cleanup]` | End-to-end check: ensures `smoke-agent` and `smoke-approver` principals, requests, approves and rejects, and asserts `get_approval`, `get_request` and `get_rejection`. `--cleanup` revokes their keys and deletes both accounts. |
| `transfer.sh <receiver> <amount> [--yes]` | Sends NEAR from `NEAR_ACCOUNT_ID`, e.g. to top up the contract's storage balance. |
| `faucet-fund.sh [<receiver>] [--rounds N]` | Testnet only: tops up an existing account (default `NEAR_ACCOUNT_ID`) with 10 NEAR per round from the testnet faucet, which only funds new accounts: each round has the faucet create a throwaway `tf-faucet-….testnet` account and then deletes it with the receiver as beneficiary. Needs no `NEAR_PRIVATE_KEY`. If a deletion fails, the throwaway key is kept and `--recover KEYFILE` finishes the round. Uses `NEAR_FAUCET_URL` (default `https://helper.testnet.near.org/account`; near-cli's own default host fails TLS). |
Expand Down Expand Up @@ -286,7 +286,7 @@ agent or approver holds.
A real approver should not use a key from this repo's credentials dir:
generate it elsewhere, register it with `add-approver.sh`, and sign with
`approve.sh <approver> <id> --action-file action.txt --key-file ~/keys/reviewer.json`.
To sign from a browser wallet instead, open [`ui/approvals/`](../../ui/approvals/README.md) (or [`ui/spec-approvals/`](../../ui/spec-approvals/README.md) for a spec review packet)
To sign from a browser wallet instead, open [`ui/approvals/`](../../ui/approvals/README.md) (or [`ui/spec-approvals/`](../../ui/spec-approvals/README.md) for the 23 requirements, or [`ui/spec-approvals-full/`](../../ui/spec-approvals-full/README.md) for the full spec packet)
and register the wallet's public key with `add-approver.sh … --force`
(a full-access key; the page cannot select a different key than the one
the wallet connects with).
Expand Down
11 changes: 6 additions & 5 deletions scripts/near/spec_packet.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
"""Spec review packets on the approval contract: one request per packet item.

Each item of a packet manifest (ui/spec-approvals/packets/*.json, built by
ui/spec-approvals/tools/build-packet.py) becomes one `request_action`. The
action names the packet, the item and the SHA-256 of the item's canonical
payload, so an approval on chain binds to the exact text the reviewer read.
ui/spec-approvals/spec-kit.js computes the same payload, hash and action;
Each item of a packet manifest (ui/spec-approvals/packets/*.json or
ui/spec-approvals-full/packets/*.json, built by the tools/build-packet.py
next to it) becomes one `request_action`. The action names the packet, the
item and the SHA-256 of the item's canonical payload, so an approval on
chain binds to the exact text the reviewer read.
ui/shared/spec-kit.js computes the same payload, hash and action;
`check` prints them so the two can be compared.

Canonical payload of item X (UTF-8 JSON, object keys sorted at every level,
Expand Down
15 changes: 9 additions & 6 deletions scripts/near/submit-spec-packet.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#
# File each item of a spec review packet as one request on the approval
# contract (APPROVAL_CONTRACT_ID, from NEAR_ACCOUNT_ID), for a reviewer to approve or
# reject in ui/spec-approvals/. Each action names the packet, the item and the
# reject in ui/spec-approvals/ or ui/spec-approvals-full/. Each action names the packet, the item and the
# SHA-256 of the item's canonical text (scripts/near/spec_packet.py), so the
# approval on chain binds to exactly what the reviewer read.
#
Expand All @@ -15,7 +15,7 @@
# them (the contract has no cancel), so the reviewer should reject them.
#
# Credentials come from .env (ENV_FILE), like every script here. The agent
# is --agent, else APPROVAL_AGENT_ACCOUNT_ID, else spec-agent (a short name
# is --agent, else APPROVAL_AGENT_ACCOUNT_ID, else agent1 (a short name
# means <name>.<NEAR_ACCOUNT_ID>). It signs the way request-action.sh does:
# --key-file PATH, else the stored key
# <NEAR_CREDENTIALS_DIR>/<network>/<agent>.agent.json, else APPROVAL_AGENT_*
Expand All @@ -30,7 +30,7 @@
# Prints one line per filed request, "<item><TAB><request_id>", on stdout.
#
# Options:
# --packet PATH manifest (default ui/spec-approvals/packets/near-approval.json)
# --packet PATH manifest (default ui/spec-approvals-full/packets/near-approval.json)
# --item ID only this item (repeatable)
# --agent NAME agent account (overrides APPROVAL_AGENT_ACCOUNT_ID)
# --key-file PATH sign with this key file
Expand All @@ -48,7 +48,7 @@ done
# shellcheck source=SCRIPTDIR/lib.sh
. "$(cd "$(dirname "$NEAR_SELF")" && pwd -P)/lib.sh"

PACKET="$REPO_ROOT/ui/spec-approvals/packets/near-approval.json"
PACKET="$REPO_ROOT/ui/spec-approvals-full/packets/near-approval.json"
ITEMS=() AGENT_ARG="" KEY_FILE="" SETUP=0 DRY=0
while [ $# -gt 0 ]; do
case $1 in
Expand Down Expand Up @@ -89,7 +89,7 @@ case $PACKET in /*) ;; *) PACKET="$PWD/$PACKET" ;; esac
near_load_config
SPY() { "$NEAR_PYTHON" -I -X utf8 "$NEAR_SCRIPTS_DIR/spec_packet.py" "$@"; }
SPY check "$PACKET" >/dev/null || die "invalid packet manifest $PACKET"
AGENT=$(principal_account "${AGENT_ARG:-${APPROVAL_AGENT_ACCOUNT_ID:-spec-agent}}")
AGENT=$(principal_account "${AGENT_ARG:-${APPROVAL_AGENT_ACCOUNT_ID:-agent1}}")
near_require_contract

# Every request on the contract (get_request per id; there is no index).
Expand Down Expand Up @@ -152,4 +152,7 @@ for id in "${TODO[@]}"; do
ok "item $id is request $rid"
printf '%s\t%s\n' "$id" "$rid"
done
info "review them in ui/spec-approvals/?agent=$AGENT (see its README for how to run it)"
# The page that loads this packet is the ui/* directory that contains it.
packet_dir=$(cd "$(dirname "$PACKET")" && pwd -P)
ui_name=$(basename "$(dirname "$packet_dir")")
info "review them in ui/${ui_name}/?agent=$AGENT (see its README for how to run it)"
2 changes: 1 addition & 1 deletion ui/approvals/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ submits is the one the approver's wallet signs.
`index.html` is the application. Contract reads, the wallet connector,
signing and the text-safety helpers live in `../shared/approval-kit.js`,
and the base styles in `../shared/base.css`. Both are shared with
`../spec-approvals/`. No build, no framework, no backend. Views
`../spec-approvals/` and `../spec-approvals-full/`. No build, no framework, no backend. Views
are `fetch` calls to a NEAR JSON-RPC at `finality: final`. Signing uses
[NEAR Connect](https://docs.near.org/tools/near-connect)
(`@hot-labs/near-connect` 0.11.4), loaded from a pinned URL with
Expand Down
3 changes: 2 additions & 1 deletion ui/approvals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ cd ui && python3 -m http.server 8080

Open <http://127.0.0.1:8080/approvals/>. Serve `ui/`, not this directory:
the page loads `../shared/` (code shared with
[`../spec-approvals/`](../spec-approvals/README.md)). Use HTTP on localhost,
[`../spec-approvals/`](../spec-approvals/README.md) and
[`../spec-approvals-full/`](../spec-approvals-full/README.md)). Use HTTP on localhost,
not `file://`: wallet extensions and the clipboard do not reliably work from
a file URL. No install and no build.

Expand Down
4 changes: 2 additions & 2 deletions ui/approvals/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,12 @@ <h2 id="confirm-title"></h2>
src="https://cdn.jsdelivr.net/gh/azbang/near-connect@de0f08af1e07c19fe5f80070383231d16ef924f6/cdn/hot-connect.iife.js"
integrity="sha384-6eNPlV+Bf92wTtH7ZfZE8sZPdohJ84VDXuVVegFjBvJsGWE6BXTT1he2jKjalJ9L"
crossorigin="anonymous"></script>
<script src="../shared/approval-kit.js"></script>
<script src="../shared/approval-kit.js?v=2"></script>
<script>
(function () {
"use strict";

// Shared with ui/spec-approvals: ../shared/approval-kit.js.
// Shared with ui/spec-approvals and ui/spec-approvals-full: ../shared/approval-kit.js.
var K = window.ApprovalKit;
var DEFAULT_CONTRACT = K.DEFAULT_CONTRACT;
var DEFAULT_HASH = K.DEFAULT_HASH;
Expand Down
111 changes: 83 additions & 28 deletions ui/shared/approval-kit.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
* Shared pieces of the approval contract UIs (ui/approvals, ui/spec-approvals).
* Shared pieces of the approval contract UIs (ui/approvals, ui/spec-approvals,
* ui/spec-approvals-full).
* A classic script: it defines window.ApprovalKit and nothing else. No build,
* no dependencies. The wallet connector (NEAR Connect) is loaded by each page
* with its own pinned <script integrity=...> tag; this file only uses
Expand Down Expand Up @@ -255,54 +256,108 @@
return { requests: got.filter(Boolean), failed: failed };
}

// Wallets report the key as "ed25519:…", as bare base58, or not at all.
// near-sdk accepts only the prefixed form.
function normalizePublicKey(raw) {
if (!raw) return "";
if (typeof raw !== "string") {
if (typeof raw === "object") return normalizePublicKey(raw.publicKey || raw.public_key || raw.key || "");
return "";
}
var s = raw.trim();
var prefixed = /^(ed25519|secp256k1):/i.exec(s);
if (prefixed) return prefixed[1].toLowerCase() + ":" + s.slice(prefixed[0].length);
if (/^[1-9A-HJ-NP-Za-km-z]{32,}$/.test(s)) return "ed25519:" + s;
return s;
}

function reportedPublicKey(account) {
return normalizePublicKey(account.publicKey || account.public_key || "");
}

async function registeredApproverKeys(accountId) {
var list = await rpcQuery({ request_type: "view_access_key_list", finality: "final", account_id: accountId });
var found = [];
var keys = list.keys || [];
for (var i = 0; i < keys.length; i++) {
var pk = keys[i].public_key;
var principal = null;
try { principal = await view("get_principal", { public_key: pk }); } catch (e) { continue; }
if (principal && principal.role === "approver" && principal.account_id === accountId) {
found.push({
publicKey: pk,
principal: principal,
permission: keys[i].access_key && keys[i].access_key.permission
});
}
}
return found;
}

// The wallet account's key: its permission on the account and its
// registration on this contract. Returns {session, lines}.
// A browser wallet often omits publicKey, or names a key the contract
// cannot parse. The account may still sign if one of its access keys is
// a registered approver key; the contract checks the key that signs.
async function describeSession(account) {
var reported = reportedPublicKey(account);
var session = {
accountId: account.accountId,
publicKey: account.publicKey || "",
publicKey: reported,
principal: null,
permission: null
};
var lines = ["Connected as " + account.accountId + "."];
if (!account.publicKey) {
lines.push("The wallet did not report a public key. approve will fail unless the key it signs with is already registered.");
return { session: session, lines: lines };
}
lines.push("Signing key " + account.publicKey + ".");
try {
var access = await rpcQuery({
request_type: "view_access_key",
finality: "final",
account_id: account.accountId,
public_key: account.publicKey
});
session.permission = access.permission;
lines.push("On the account this key is " + permissionLabel(access.permission) + ".");
if (access.permission === "FullAccess") {
lines.push("A full-access key can be registered with add-approver.sh --force. It is weaker than a key limited to approve and reject on this contract.");
if (reported) {
lines.push("Wallet signing key " + reported + ".");
try {
var principal = await view("get_principal", { public_key: reported });
if (principal && principal.role === "approver" && principal.account_id === account.accountId) {
session.principal = principal;
lines.push("Registered approver, registration " + principal.registration_id + ".");
return { session: session, lines: lines };
}
if (principal && principal.role !== "approver") lines.push("That key is registered as " + principal.role + ", not approver.");
else if (principal) lines.push("That key is registered to " + principal.account_id + ", not this account.");
} catch (err) {
lines.push("Could not read get_principal for the wallet key (" + errorText(err) + ").");
}
} catch (err) {
lines.push("Could not read that access key (" + errorText(err) + ").");
} else {
lines.push("The wallet did not report a signing key.");
}
try {
var principal = await view("get_principal", { public_key: account.publicKey });
session.principal = principal;
if (!principal) lines.push("Not registered on this contract. The owner has to add it before you can sign.");
else if (principal.role !== "approver") lines.push("Registered as " + principal.role + ", not approver.");
else if (principal.account_id !== account.accountId) lines.push("Registered to " + principal.account_id + ", not this account.");
else lines.push("Registered approver, registration " + principal.registration_id + ".");
var found = await registeredApproverKeys(account.accountId);
var chosen = found.filter(function (k) { return k.publicKey === reported; })[0]
|| found.filter(function (k) { return k.permission === "FullAccess"; })[0]
|| found[0];
if (chosen) {
session.publicKey = chosen.publicKey;
session.principal = chosen.principal;
session.permission = chosen.permission;
lines.push("Registered approver key on this account: " + chosen.publicKey + " (registration " + chosen.principal.registration_id + "). The wallet must sign with that key.");
if (chosen.permission === "FullAccess") {
lines.push("That key is full-access. A key limited to approve and reject is stronger.");
}
return { session: session, lines: lines };
}
} catch (err) {
lines.push("Could not read get_principal (" + errorText(err) + ").");
lines.push("Could not list this account's keys (" + errorText(err) + ").");
}
lines.push(reported
? "Not registered on this contract. The owner has to add " + reported + " before you can sign."
: "This account has no registered approver key.");
return { session: session, lines: lines };
}

// "" when this session may sign approve/reject, else why not.
function signingBlock(session) {
if (!cfg.codeOk) return "Signing is disabled until the contract code hash matches the expected hash.";
if (!session) return "Connect the wallet that holds your approver key.";
if (!session.principal || session.principal.role !== "approver") return "This key is not a registered approver key.";
if (!session.principal || session.principal.role !== "approver") {
return session.publicKey
? "This key is not a registered approver key (" + session.publicKey + ")."
: "This account has no registered approver key.";
}
if (session.principal.account_id !== session.accountId) return "The registered key is bound to a different account.";
return "";
}
Expand Down
2 changes: 1 addition & 1 deletion ui/shared/base.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* Shared by ui/approvals and ui/spec-approvals. System colours and fonts, light and dark. */
/* Shared by ui/approvals, ui/spec-approvals and ui/spec-approvals-full. System colours and fonts, light and dark. */
:root {
color-scheme: light dark;
--text: CanvasText;
Expand Down
Loading
Loading