@defdone/annon 0.1.0-alpha.1 → 0.1.0-alpha.2

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 (55) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/CLI.md +116 -10
  3. package/README.md +41 -9
  4. package/dist/api/annon-types.d.ts +2 -1
  5. package/dist/api/annon.js +9 -2
  6. package/dist/browser/index.d.ts +1 -1
  7. package/dist/browser/login-bundle.js +61 -60
  8. package/dist/browser/login-dom.d.ts +13 -0
  9. package/dist/browser/login-dom.js +67 -0
  10. package/dist/browser/login-dropdown.d.ts +32 -0
  11. package/dist/browser/login-dropdown.js +129 -0
  12. package/dist/browser/login-format.d.ts +16 -0
  13. package/dist/browser/login-format.js +52 -0
  14. package/dist/browser/login-status.d.ts +70 -0
  15. package/dist/browser/login-status.js +85 -0
  16. package/dist/browser/login-terms.d.ts +10 -0
  17. package/dist/browser/login-terms.js +69 -0
  18. package/dist/browser/login-view.d.ts +34 -0
  19. package/dist/browser/login-view.js +227 -0
  20. package/dist/browser/login-wallet.d.ts +28 -0
  21. package/dist/browser/login-wallet.js +179 -0
  22. package/dist/browser/login.js +115 -140
  23. package/dist/browser/purchase-bundle.js +29 -29
  24. package/dist/browser/purchases.d.ts +4 -0
  25. package/dist/browser/purchases.js +14 -0
  26. package/dist/browser/reconcile.d.ts +41 -0
  27. package/dist/browser/reconcile.js +77 -0
  28. package/dist/node/adapter.js +5 -2
  29. package/dist/node/approval-status.d.ts +34 -0
  30. package/dist/node/approval-status.js +71 -0
  31. package/dist/node/backup-secret-init.d.ts +9 -0
  32. package/dist/node/backup-secret-init.js +103 -0
  33. package/dist/node/backup-secret.d.ts +35 -0
  34. package/dist/node/backup-secret.js +104 -0
  35. package/dist/node/browser-login.d.ts +2 -0
  36. package/dist/node/browser-login.js +67 -13
  37. package/dist/node/buy-commands.js +9 -2
  38. package/dist/node/cli.js +23 -7
  39. package/dist/node/command-context.js +1 -1
  40. package/dist/node/config.d.ts +2 -0
  41. package/dist/node/config.js +3 -1
  42. package/dist/node/login-page.d.ts +7 -0
  43. package/dist/node/login-page.js +71 -0
  44. package/dist/node/purchase-commands.d.ts +2 -2
  45. package/dist/node/purchase-commands.js +10 -6
  46. package/dist/node/saved-state.d.ts +4 -0
  47. package/dist/node/saved-state.js +50 -0
  48. package/dist/node/version.d.ts +1 -0
  49. package/dist/node/version.js +3 -0
  50. package/dist/node/wallets.d.ts +1 -1
  51. package/dist/node/wallets.js +2 -10
  52. package/dist/pay/purchase.d.ts +2 -1
  53. package/dist/wallet/uncertain.d.ts +6 -3
  54. package/dist/wallet/uncertain.js +4 -1
  55. package/package.json +1 -1
@@ -1,32 +1,14 @@
1
1
  import { Buffer } from 'buffer';
2
- import { signInAccountOnly } from '../wallet/account-only.js';
3
- import { evmWallet } from '../wallet/wallet.js';
2
+ import { pageElements, renderSummary, showStatus } from './login-dom.js';
3
+ import { walletPicker } from './login-dropdown.js';
4
+ import { expiryText } from './login-format.js';
5
+ import { connected, SendUncertain, STATUS, walletFailure } from './login-status.js';
6
+ import { describeRequest, technicalDetails } from './login-view.js';
7
+ import { pageWallets } from './login-wallet.js';
4
8
  Object.assign(globalThis, { Buffer });
5
- const pair = document.getElementById('pair');
6
- const display = document.getElementById('action');
7
- const status = document.getElementById('status');
8
- const approve = document.getElementById('approve');
9
- const nearChoice = document.getElementById('near-wallet');
10
- const hotChoice = document.getElementById('near-wallet-hot');
11
- /** Signing-request chains the page can bind a NEAR wallet to. Anything else is refused. */
12
- const NEAR_NETWORKS = new Map([
13
- ['near:mainnet', 'mainnet'],
14
- ['near:testnet', 'testnet'],
15
- ]);
16
- /** The selector's only RPC per network. The page CSP allows exactly these (browser-login.ts). */
17
- const NEAR_RPC = {
18
- mainnet: 'https://free.rpc.fastnear.com',
19
- testnet: 'https://test.rpc.fastnear.com',
20
- };
21
- /**
22
- * NEAR wallets offered on this page and the networks each is bound to. MyNearWallet is retired
23
- * and no longer connects to apps. HOT's selector module sends no network with its requests, so
24
- * it is offered for mainnet only and never loaded for another network.
25
- */
26
- const NEAR_WALLETS = new Map([
27
- ['meteor-wallet', { name: 'Meteor Wallet', networks: ['mainnet', 'testnet'] }],
28
- ['hot-wallet', { name: 'HOT Wallet', networks: ['mainnet'] }],
29
- ]);
9
+ const el = pageElements(document);
10
+ const approve = el.approve;
11
+ const cancel = document.getElementById('cancel');
30
12
  const fragment = new URLSearchParams(location.hash.slice(1));
31
13
  const redirected = location.pathname === '/callback';
32
14
  let capability = redirected ? '' : location.hash.slice(1);
@@ -44,9 +26,51 @@ const api = async (path, body) => {
44
26
  throw new Error('Session expired or wallet result rejected. Return to the terminal.');
45
27
  return r.json();
46
28
  };
47
- const used = new Set();
29
+ /** Requests whose result went to the CLI, or that ended here: never signed again. */
30
+ const done = new Set();
48
31
  const callbacks = new Map();
32
+ const wallets = pageWallets({
33
+ expect: (state, id) => callbacks.set(state, id),
34
+ forget: (state) => callbacks.delete(state),
35
+ sending: async (id) => {
36
+ // The wallet may broadcast from now on: this request is never attempted again here, and the
37
+ // CLI records it before the wallet is called.
38
+ done.add(id);
39
+ await api('/api/report', { id, reason: 'send_started' });
40
+ },
41
+ });
49
42
  let current;
43
+ let expiry;
44
+ let busy = false;
45
+ const status = (s) => showStatus(el, s);
46
+ const picker = walletPicker(document, () => controls());
47
+ const walletId = () => picker.value();
48
+ /** Buttons and wallet choice follow the request: usable only while it is open and idle. */
49
+ function controls() {
50
+ const q = current;
51
+ const open = !!q && !done.has(q.id) && Date.now() < q.expiresAt;
52
+ approve.disabled = !open || busy;
53
+ if (cancel) {
54
+ cancel.hidden = !open;
55
+ cancel.disabled = busy;
56
+ }
57
+ // No wallet switch while a wallet is open or once the request is finished or sent.
58
+ picker.setLocked(!open || busy);
59
+ approve.textContent =
60
+ q && wallets.needsConnect(q, walletId()) ? 'Connect wallet' : 'Review in wallet';
61
+ }
62
+ async function submit(id, result) {
63
+ done.add(id);
64
+ status(STATUS.verifying);
65
+ controls();
66
+ try {
67
+ await api('/api/result', { id, result });
68
+ status(STATUS.signed);
69
+ }
70
+ catch {
71
+ status(STATUS.rejected);
72
+ }
73
+ }
50
74
  if (redirected) {
51
75
  // Only a per-action opaque nonce leaves this origin. The capability stays in the opener.
52
76
  window.opener?.postMessage({
@@ -58,7 +82,7 @@ if (redirected) {
58
82
  signature: fragment.get('signature'),
59
83
  },
60
84
  }, location.origin);
61
- status.textContent = 'Proof returned to the approval window. Return to your terminal.';
85
+ status(STATUS.redirected);
62
86
  }
63
87
  else {
64
88
  window.addEventListener('message', (event) => {
@@ -68,149 +92,100 @@ else {
68
92
  if (!id)
69
93
  return;
70
94
  callbacks.delete(event.data.state);
71
- void api('/api/result', { id, result: event.data.result })
72
- .then(() => {
73
- status.textContent = 'Proof verified. Return to your terminal.';
74
- })
75
- .catch((e) => {
76
- status.textContent = e.message;
77
- });
95
+ void submit(id, event.data.result);
78
96
  });
79
97
  }
98
+ /** Shows the CLI's current request; a finished one stays on screen with its outcome. */
99
+ function show(q, sendStarted = false) {
100
+ if (q && q.id !== current?.id) {
101
+ current = q;
102
+ expiry = renderSummary(document, el, describeRequest(q), technicalDetails(q));
103
+ el['wallet-field'].hidden = !q.operation.startsWith('near.');
104
+ picker.setDisabled('hot-wallet', q.chain !== 'near:mainnet');
105
+ status(wallets.needsConnect(q, walletId()) ? STATUS.connect : STATUS.ready);
106
+ }
107
+ const last = current;
108
+ // A send started from an earlier load of this page: the wallet may have broadcast it.
109
+ if (last && q && sendStarted && !done.has(last.id)) {
110
+ done.add(last.id);
111
+ status({ tone: 'error', text: walletFailure(new SendUncertain()).text });
112
+ }
113
+ if (!last || !expiry) {
114
+ status(STATUS.waitingCli);
115
+ }
116
+ else {
117
+ expiry.textContent = expiryText(last.expiresAt, Date.now());
118
+ const expired = Date.now() >= last.expiresAt;
119
+ // The CLI dropped the request (expired, cancelled or session over) before a result was sent.
120
+ if (!done.has(last.id) && (!q || expired)) {
121
+ done.add(last.id);
122
+ status(expired ? STATUS.expired : STATUS.ended);
123
+ }
124
+ }
125
+ controls();
126
+ }
80
127
  async function poll() {
81
128
  if (!capability) {
82
- status.textContent = 'Open the exact URL printed by your CLI.';
129
+ status(STATUS.noCapability);
83
130
  return;
84
131
  }
85
132
  try {
86
133
  const r = await api('/api/action');
87
- pair.textContent = `Pairing code: ${r.pairingCode}. Match this with your terminal.`;
88
- current = r.action ?? undefined;
89
- display.textContent = current ? JSON.stringify(current, null, 2) : 'Waiting for the CLI…';
90
- approve.disabled = !current || used.has(current.id);
91
- if (hotChoice)
92
- hotChoice.disabled =
93
- current?.chain?.startsWith('near:') === true && current.chain !== 'near:mainnet';
134
+ el.pair.textContent = String(r.pairingCode);
135
+ show(r.action ?? undefined, r.sendStarted === true);
94
136
  setTimeout(() => {
95
137
  void poll();
96
138
  }, 1000);
97
139
  }
98
140
  catch (e) {
99
- status.textContent = e.message;
141
+ status({ tone: 'error', text: e.message });
100
142
  capability = '';
101
143
  approve.disabled = true;
102
144
  }
103
145
  }
104
146
  approve.onclick = async () => {
105
147
  const q = current;
106
- if (!q || used.has(q.id) || Date.now() >= q.expiresAt)
148
+ if (!q || busy || done.has(q.id) || Date.now() >= q.expiresAt)
107
149
  return;
108
- used.add(q.id);
109
- approve.disabled = true;
150
+ busy = true;
151
+ controls();
152
+ status(STATUS.wallet);
110
153
  try {
111
- let result;
112
- if (q.operation.startsWith('evm.')) {
113
- const provider = window.ethereum;
114
- if (!provider)
115
- throw new Error('Install an injected EVM wallet.');
116
- const accounts = (await provider.request({ method: 'eth_requestAccounts' }));
117
- const address = q.account || accounts[0];
118
- if (!address)
119
- throw new Error('No account');
120
- const chain = await provider.request({ method: 'eth_chainId' });
121
- if (`eip155:${BigInt(String(chain))}` !== q.chain)
122
- throw new Error(`Select ${q.chain} in your wallet.`);
123
- const wallet = evmWallet(provider, address.toLowerCase());
124
- result =
125
- q.operation === 'evm.personalSign'
126
- ? {
127
- signature: (await wallet.authorize(q.payload.message))?.sig ?? '',
128
- account: wallet.identity.id,
129
- }
130
- : { signature: await wallet.signTypedData(q.payload) };
131
- }
132
- else {
133
- const networkId = NEAR_NETWORKS.get(q.chain);
134
- if (!networkId)
135
- throw new Error(`Browser NEAR wallets support near:mainnet and near:testnet, not ${q.chain}.`);
136
- const id = nearChoice?.value || 'meteor-wallet';
137
- const offered = NEAR_WALLETS.get(id);
138
- if (!offered)
139
- throw new Error('Unknown NEAR wallet');
140
- if (!offered.networks.includes(networkId))
141
- throw new Error(`${offered.name} is offered for near:mainnet only. Pick Meteor Wallet.`);
142
- // Only the chosen wallet is loaded, on first use: the page starts without wallet code
143
- // touching storage or listeners, and a refused wallet never runs.
144
- const [{ setupWalletSelector }, module] = await Promise.all([
145
- import('@near-wallet-selector/core'),
146
- id === 'hot-wallet'
147
- ? import('@near-wallet-selector/hot-wallet').then((m) => m.setupHotWallet())
148
- : import('@near-wallet-selector/meteor-wallet').then((m) => m.setupMeteorWallet()),
149
- ]);
150
- const selector = await setupWalletSelector({
151
- network: networkId,
152
- fallbackRpcUrls: [NEAR_RPC[networkId]],
153
- modules: [module],
154
- });
155
- const wallet = await selector.wallet(id);
156
- const accounts = await signInAccountOnly(wallet);
157
- const account = q.account || accounts[0]?.accountId;
158
- if (!account || !accounts.some((a) => a.accountId === account))
159
- throw new Error('Select the requested NEAR account.');
160
- if (q.operation === 'near.nep413') {
161
- if (!wallet.signMessage)
162
- throw new Error('NEP-413 unavailable');
163
- const p = q.payload;
164
- const state = crypto.randomUUID();
165
- callbacks.set(state, q.id);
166
- const signed = await wallet.signMessage({
167
- ...p,
168
- nonce: Buffer.from(p.nonce),
169
- state,
170
- });
171
- if (!signed)
172
- return; // redirect wallets: /callback forwards the fragment
173
- callbacks.delete(state);
174
- result = signed;
175
- }
176
- else {
177
- const p = q.payload;
178
- const outcome = await wallet.signAndSendTransaction({
179
- signerId: account,
180
- receiverId: p.receiverId,
181
- // Selector v10 passes Borsh Action structs through to its transaction encoder.
182
- actions: [
183
- {
184
- functionCall: {
185
- methodName: p.method,
186
- args: Buffer.from(JSON.stringify(p.args)),
187
- gas: BigInt(p.gas),
188
- deposit: BigInt(p.deposit),
189
- },
190
- },
191
- ],
192
- });
193
- if (!outcome)
194
- return;
195
- result = { txHash: outcome.transaction.hash };
196
- }
197
- }
198
- await api('/api/result', { id: q.id, result });
199
- status.textContent = 'Verified. Return to the terminal.';
154
+ const outcome = await wallets.run(q, walletId());
155
+ busy = false;
156
+ if (outcome.kind === 'connected')
157
+ status(connected(outcome.account));
158
+ else if (outcome.kind === 'result')
159
+ await submit(q.id, outcome.result);
200
160
  }
201
161
  catch (e) {
202
- status.textContent = e.message;
162
+ // One click per attempt, never retried here: the person may try this request again until it
163
+ // expires. The CLI hears only a fixed reason name.
164
+ const failure = walletFailure(e);
165
+ status({ tone: 'error', text: failure.text });
166
+ void api('/api/report', { id: q.id, reason: failure.reason }).catch(() => { });
203
167
  }
204
168
  finally {
205
- approve.disabled = true;
169
+ busy = false;
170
+ controls();
206
171
  }
207
172
  };
173
+ if (cancel)
174
+ cancel.onclick = () => {
175
+ const q = current;
176
+ if (!q || busy || done.has(q.id))
177
+ return;
178
+ done.add(q.id);
179
+ controls();
180
+ status({ tone: 'error', text: 'Cancelled. Return to the terminal.' });
181
+ void api('/api/report', { id: q.id, reason: 'cancelled' }).catch(() => { });
182
+ };
208
183
  if (!redirected) {
209
184
  void (async () => {
210
185
  if (!capability)
211
186
  capability = (await api('/api/bootstrap')).capability;
212
187
  await poll();
213
188
  })().catch((e) => {
214
- status.textContent = e.message;
189
+ status({ tone: 'error', text: e.message });
215
190
  });
216
191
  }