@needmoretruth/nmts-cli 0.39.0 → 0.41.0

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 (65) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.ko.md +27 -1
  3. package/README.md +29 -1
  4. package/dist/api-advice.js +6 -0
  5. package/dist/api.d.ts +10 -1
  6. package/dist/api.js +12 -2
  7. package/dist/arg-options.d.ts +21 -0
  8. package/dist/args.js +12 -1
  9. package/dist/artifact-about.d.ts +1 -1
  10. package/dist/commands/create-link.d.ts +9 -0
  11. package/dist/commands/create-link.js +31 -1
  12. package/dist/commands/create.d.ts +9 -0
  13. package/dist/commands/create.js +17 -0
  14. package/dist/commands/extend.d.ts +3 -3
  15. package/dist/commands/extend.js +52 -161
  16. package/dist/commands/login-passphrase.d.ts +13 -0
  17. package/dist/commands/login-passphrase.js +64 -0
  18. package/dist/commands/login.d.ts +3 -0
  19. package/dist/commands/login.js +15 -55
  20. package/dist/commands/openers-attach.d.ts +38 -0
  21. package/dist/commands/openers-attach.js +97 -0
  22. package/dist/commands/openers.d.ts +23 -0
  23. package/dist/commands/openers.js +195 -0
  24. package/dist/commands/wallet-storage-ops.d.ts +2 -2
  25. package/dist/commands/wallet-storage-ops.js +108 -134
  26. package/dist/commands/wallet-storage.d.ts +3 -8
  27. package/dist/commands/wallet-storage.js +16 -37
  28. package/dist/crypto-surface.d.ts +28 -0
  29. package/dist/crypto-surface.js +7 -0
  30. package/dist/help.js +15 -0
  31. package/dist/main.js +11 -12
  32. package/dist/openers/doors.d.ts +65 -0
  33. package/dist/openers/doors.js +97 -0
  34. package/dist/openers/hints.d.ts +22 -0
  35. package/dist/openers/hints.js +11 -0
  36. package/dist/openers/sign.d.ts +56 -0
  37. package/dist/openers/sign.js +202 -0
  38. package/dist/openers/wallet.d.ts +71 -0
  39. package/dist/openers/wallet.js +210 -0
  40. package/dist/openers-key-file.d.ts +14 -0
  41. package/dist/openers-key-file.js +99 -0
  42. package/dist/openers.d.ts +7 -0
  43. package/dist/openers.js +21 -0
  44. package/dist/product.d.ts +1 -1
  45. package/dist/product.js +1 -1
  46. package/dist/risk.d.ts +11 -0
  47. package/dist/risk.js +15 -0
  48. package/dist/storage-control/extend.d.ts +124 -0
  49. package/dist/storage-control/extend.js +189 -0
  50. package/dist/storage-control/hints.d.ts +20 -0
  51. package/dist/storage-control/hints.js +11 -0
  52. package/dist/storage-control/list.d.ts +55 -0
  53. package/dist/storage-control/list.js +71 -0
  54. package/dist/storage-control/reshape.d.ts +120 -0
  55. package/dist/storage-control/reshape.js +188 -0
  56. package/dist/storage-control-chain.d.ts +1 -1
  57. package/dist/storage-control.d.ts +13 -0
  58. package/dist/storage-control.js +24 -0
  59. package/dist/wallet-storage-chain.d.ts +1 -1
  60. package/docs/commands/openers.md +31 -0
  61. package/package.json +9 -1
  62. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +54 -0
  63. package/vendor/nmts-crypto/nmts_crypto_wasm.js +108 -0
  64. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  65. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +4 -0
@@ -6,9 +6,9 @@
6
6
  // nobody — NMTS included — can reverse it. That difference is said out loud, in the output,
7
7
  // before the agreement is asked for.
8
8
  //
9
- // ⛔ IT PRICES BEFORE IT SPENDS, ALWAYS. The reads and the quote are free and happen first, so
10
- // `--dry-run` answers with a real number and never reaches the key. Nothing below the quote can
11
- // run without `requireWalletGrant("extend", …)` having passed.
9
+ // ⛔ IT PRICES BEFORE IT SPENDS, ALWAYS. The reads and the quote are free and happen first
10
+ // (`planExtension`), so `--dry-run` answers with a real number and never reaches the key.
11
+ // Nothing below the quote can run without `requireWalletGrant("extend", …)` having passed.
12
12
  //
13
13
  // ⛔ THE SERVER DOES NOT EXTEND ANYTHING, and this command is shaped by that. `POST
14
14
  // /v1/items/{id}/extended` means "record an extension the device already signed": the storage is
@@ -19,21 +19,19 @@
19
19
  // ⛔ AND A FILE THAT IS NOT RUNNING OUT IS NOT EXTENDED BY ACCIDENT. Extending early loses nothing
20
20
  // — epochs are added to what is left — so this is not a refusal on principle; it is a refusal
21
21
  // to spend money on a deadline nobody is near, unless somebody says so with `--yes`.
22
+ //
23
+ // ⚠ WHAT IS DECIDED HERE AND WHAT IS NOT. The reads, the arithmetic, the price, the balances, the
24
+ // signature and the recording are `storage-control.ts`, which the SDK calls as well; this file is
25
+ // the terminal over them — the sentences, the agreement, the standing gift and the exit code.
22
26
  import { recordWalletSpend, requireWalletGrant } from "../wallet-grant.js";
23
- import { request } from "../api.js";
24
- import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "../drive-paths.js";
25
27
  import { NmtsError } from "../errors.js";
26
- import { daysLeftInWords, daysLeftUntilEpoch, stageOf, } from "../expiry.js";
27
- import { asExtendPreview, chooseEpochs, headroom, soonestEnd, } from "../extend-plan.js";
28
- import { isRecord } from "../guards.js";
29
- import { readFileList } from "../manifest.js";
28
+ import { daysLeftInWords } from "../expiry.js";
29
+ import { describeBudget, shortfallNextStep } from "../extend-budget.js";
30
30
  import { resolveNetwork } from "../network.js";
31
31
  import { BINARY_NAME } from "../product.js";
32
32
  import { openSession } from "../session.js";
33
- import { coinAmount, walletAddress } from "../wallet.js";
34
- import { payingWalletIndex } from "../wallet-pay-index.js";
35
- import { activeWalletOf } from "../shared/lib/drive/manifest-settings.js";
36
- import { budgetFacts, describeBudget, readBudget, shortfallNextStep } from "../extend-budget.js";
33
+ import { applyExtension, planExtension } from "../storage-control.js";
34
+ import { walletIndexOf } from "../wallet-pay-index.js";
37
35
  export async function extend(target, options = {}) {
38
36
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
39
37
  const now = options.now ?? Date.now();
@@ -44,129 +42,50 @@ export async function extend(target, options = {}) {
44
42
  });
45
43
  }
46
44
  const session = await openSession(options);
47
- const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
48
- if (list.manifest === null) {
49
- throw new NmtsError("This account has no file list, so there is nothing to extend.", { exitCode: 4 });
50
- }
51
- const entries = list.manifest.entries;
52
- // The standing share is the person's, and it is read from the same sealed list this file came from.
53
- const settings = list.manifest.settings;
54
- const entry = entryAt(entries, normalisePath(target), {
55
- nothingHappened: "Nothing was signed and nothing was charged.",
56
- });
57
- if (entry.kind !== KIND_FILE) {
58
- throw new NmtsError(`No file at "${fullPathOf(buildIndex(entries), entry)}".`, {
59
- exitCode: 4,
60
- nextStep: "That is a folder. Nothing was signed and nothing was charged — storage is bought per " +
61
- "file, so this takes one file at a time.",
62
- });
63
- }
64
- const path = fullPathOf(buildIndex(entries), entry);
65
- // ⛔ THE SERVER SAYS WHICH BLOBS, AND NOTHING ELSE. Its `expiry_epoch` is client-reported and
66
- // advisory; a command that spends money reads the chain's own answer below.
67
- const preview = asExtendPreview(await request(session.server, `/v1/items/${encodeURIComponent(entry.id)}/extend-preview`, {
68
- token: session.apiKey,
69
- }));
70
- if (preview.targets.length === 0) {
71
- throw new NmtsError(`Nothing on "${path}" can be extended from here.`, {
72
- exitCode: 4,
73
- nextStep: nothingToExtend(preview),
74
- });
75
- }
76
- const reads = await (options.readChain ?? defaultReads)(session.network);
77
- const window = await reads.readWindow();
78
- if (window === null) {
79
- // ⛔ Not "nothing needs extending". The two look identical from outside and mean opposite things.
80
- throw new NmtsError(`The ${session.network} storage network could not be read.`, {
81
- exitCode: 1,
82
- nextStep: `Nothing was signed and nothing was charged. Which epoch the network is in, and how far ` +
83
- `ahead it will sell, are facts only the chain has — this tool will not spend against a ` +
84
- `guess. Try again, or name a different Sui node in NMTS_SUI_RPC.`,
85
- });
86
- }
87
- const clock = window.clock;
88
- const leases = await reads.readLeases(preview.targets.map((t) => t.objectId));
89
- const endEpoch = soonestEnd(leases);
90
- if (endEpoch === null) {
91
- throw new NmtsError(`The chain holds no storage term for "${path}".`, {
92
- exitCode: 4,
93
- nextStep: nothingToExtend(preview),
94
- });
95
- }
96
- const stage = stageOf(clock, endEpoch, now);
97
- if (stage === "lapsed") {
98
- throw new NmtsError(`The storage term for "${path}" has already ended.`, {
99
- exitCode: 4,
100
- nextStep: `Nothing was signed and nothing was charged. A lease is extended before it ends — once it ` +
45
+ // ⛔ A NUMBER THAT IS NOT ONE IS REFUSED BEFORE ANYTHING IS READ. Absent, the account's own number
46
+ // comes out of the sealed list the plan reads — one read, so the address that is priced and
47
+ // the address that signs cannot differ.
48
+ const named = options.wallet === undefined || options.wallet === "" ? undefined : walletIndexOf(options.wallet);
49
+ const plan = await planExtension(session, target, {
50
+ now,
51
+ epochs: options.epochs,
52
+ wallet: named,
53
+ readChain: options.readChain,
54
+ // ⚠ THE LAST SENTENCE IS THIS FILE'S: `nmts get` is a command at a prompt.
55
+ hints: {
56
+ lapsed: `Nothing was signed and nothing was charged. A lease is extended before it ends — once it ` +
101
57
  `is over there is no storage object left to extend, and the bytes may already be gone. ` +
102
58
  `\`${BINARY_NAME} get\` says whether they can still be read.`,
103
- });
104
- }
105
- const epochs = chooseEpochs(options.epochs, headroom(leases, clock.current, window.maxAhead));
106
- const newEndEpoch = endEpoch + epochs;
107
- const before = daysLeftUntilEpoch(clock, endEpoch, now);
108
- const after = daysLeftUntilEpoch(clock, newEndEpoch, now);
109
- // ⛔ A COST THAT COULD NOT BE COMPUTED MUST NOT BECOME A COST OF ZERO. `quote` rejects rather
110
- // than defaulting, and that rejection stops this run before the agreement is asked for.
111
- const frost = await reads.quote(leases, epochs);
112
- const cohort = Math.max(0, ...preview.targets.map((t) => t.sharedItems));
113
- const unreachable = preview.treasuryParts + preview.untrackedParts;
114
- // What the wallet holds and what the chain would charge — read, never assumed (`extend-budget.ts`).
115
- // ⛔ WHICH WALLET PAYS comes out of the list this run already read, before the price is measured
116
- // against a balance: the address below is the one that will sign (`wallet-pay-index.ts`).
117
- const wallet = await payingWalletIndex({ ...options, readActiveWallet: async () => activeWalletOf(settings) });
118
- const address = await walletAddress(session.code, wallet);
119
- const budget = await readBudget(reads, {
120
- address,
121
- objectIds: preview.targets.map((t) => t.objectId),
122
- epochs,
123
- priceFrost: frost,
59
+ },
124
60
  });
125
- const facts = {
126
- file: path,
127
- itemId: entry.id,
128
- network: session.network,
129
- epoch: clock.current,
130
- endEpoch,
131
- epochs,
132
- newEndEpoch,
133
- daysLeft: before,
134
- daysLeftAfter: after,
135
- blobs: leases.length,
136
- priceFrost: frost.toString(),
137
- priceWal: coinAmount(frost),
138
- paidFrom: "wallet",
139
- filesOnTheSameBlobs: cohort,
140
- partsThatCannotBeExtended: unreachable,
141
- ...budgetFacts(budget),
142
- };
61
+ const { facts, budget } = plan;
143
62
  if (options.dryRun === true) {
144
- // ⛔ NOTHING BELOW THIS BRANCH RUNS. No key is derived, no agreement is asked for, and the
145
- // signing module is not even loaded — `--dry-run` is a price and nothing else.
63
+ // ⛔ NOTHING BELOW THIS BRANCH RUNS. No key is derived for signing, no agreement is asked for,
64
+ // and the signing module is not even loaded — `--dry-run` is a price and nothing else.
146
65
  if (options.json) {
147
66
  say(JSON.stringify({ ...facts, dryRun: true, signed: false }));
148
67
  return 0;
149
68
  }
150
- describe(say, facts, cohort, unreachable);
69
+ describe(say, facts);
151
70
  describeBudget(say, budget);
152
71
  say(``);
153
72
  if (budget.shortfall !== null)
154
73
  say(` ⚠ ${budget.shortfall} As it stands, it would be refused.`);
155
74
  say(` Nothing was signed and nothing was charged. Run the same command without --dry-run to`);
156
75
  say(` buy it.`);
157
- if (stage === "later")
76
+ if (plan.stage === "later")
158
77
  say(` It is not near its deadline, so buying it also needs --yes.`);
159
78
  return 0;
160
79
  }
161
80
  if (!options.json) {
162
- describe(say, facts, cohort, unreachable);
81
+ describe(say, facts);
163
82
  describeBudget(say, budget);
164
83
  }
165
84
  // ⛔ ASKED AFTER THE PRICE IS KNOWN AND BEFORE ANYTHING IS SIGNED. Extending early loses nothing,
166
85
  // so this is not a refusal on principle — it is a refusal to spend on a deadline that is not
167
86
  // close, unless somebody says otherwise out loud.
168
- if (stage === "later" && options.yes !== true) {
169
- throw new NmtsError(`"${path}" is not near the end of its storage term.`, {
87
+ if (plan.stage === "later" && options.yes !== true) {
88
+ throw new NmtsError(`"${plan.path}" is not near the end of its storage term.`, {
170
89
  exitCode: 4,
171
90
  nextStep: `Nothing was signed and nothing was charged. Extending early loses nothing — the epochs ` +
172
91
  `are added to what is left — but it spends now for time this file does not need yet. ` +
@@ -181,49 +100,37 @@ export async function extend(target, options = {}) {
181
100
  // ⛔ THE ONE GATE THAT STANDS BETWEEN A PROGRAM AND SOMEBODY'S WALLET. Everything above this line
182
101
  // is a read; nothing below it can be undone. The grant names a scope, runs out, and may carry
183
102
  // a ceiling — this signature is held against all three (`wallet-grant.ts`).
184
- const spend = { walFrost: frost, suiMist: budget.feeMist ?? 0n };
103
+ const spend = { walFrost: budget.priceFrost, suiMist: budget.feeMist ?? 0n };
185
104
  requireWalletGrant("extend", spend, new Date(now));
186
- const sign = options.sign ?? (await import("../wallet-sign.js")).signExtension;
187
- const digest = await sign({
188
- network: session.network,
189
- code: session.code,
190
- wallet,
191
- objectIds: preview.targets.map((t) => t.objectId),
192
- epochs,
105
+ const outcome = await applyExtension(session, plan, {
106
+ sign: options.sign,
107
+ // What left the wallet is added to the grant's ledger first — the fee as estimated, since the
108
+ // amount actually charged is not read back here.
109
+ onSigned: () => recordWalletSpend(spend),
193
110
  });
194
- // What left the wallet is added to the grant's ledger first — the fee as estimated, since the
195
- // amount actually charged is not read back here.
196
- recordWalletSpend(spend);
197
- // From here the storage IS extended. Recording it is bookkeeping, and a failure to record must
198
- // never be reported as a failure to extend — that reading invites a second run, which pays again.
199
- let replay = false;
200
- try {
201
- const recorded = await request(session.server, `/v1/items/${encodeURIComponent(entry.id)}/extended`, { method: "POST", token: session.apiKey, body: { epochs, tx_digest: digest } });
202
- replay = isRecord(recorded) && recorded["replay"] === true;
203
- }
204
- catch (error) {
111
+ if (!outcome.recorded) {
205
112
  if (options.json) {
206
- say(JSON.stringify({ ...facts, dryRun: false, signed: true, digest, recorded: false }));
113
+ say(JSON.stringify({ ...facts, dryRun: false, signed: true, digest: outcome.digest, recorded: false }));
207
114
  }
208
115
  else {
209
116
  say(``);
210
- say(` The storage IS extended and the payment has been made — transaction ${digest}.`);
117
+ say(` The storage IS extended and the payment has been made — transaction ${outcome.digest}.`);
211
118
  say(` What failed is telling the NMTS server about it, so the drive will go on showing the`);
212
119
  say(` old date until something tells it. ⛔ Do not run this command again for this file:`);
213
120
  say(` that would buy the same epochs a second time. Opening the account in a browser reads`);
214
121
  say(` the chain directly.`);
215
- say(` Cause: ${error instanceof Error ? error.message : String(error)}`);
122
+ say(` Cause: ${outcome.notRecorded}`);
216
123
  }
217
124
  return 1;
218
125
  }
219
126
  if (options.json) {
220
- say(JSON.stringify({ ...facts, dryRun: false, signed: true, digest, recorded: true, replay }));
127
+ say(JSON.stringify({ ...facts, dryRun: false, signed: true, digest: outcome.digest, recorded: true, replay: outcome.replay }));
221
128
  }
222
129
  else {
223
130
  say(``);
224
- say(` Extended. The storage now ends at epoch ${newEndEpoch} — ${daysLeftInWords(after)}.`);
225
- say(` Transaction ${digest}`);
226
- if (replay)
131
+ say(` Extended. The storage now ends at epoch ${facts.newEndEpoch} — ${daysLeftInWords(facts.daysLeftAfter)}.`);
132
+ say(` Transaction ${outcome.digest}`);
133
+ if (outcome.replay)
227
134
  say(` The server had already recorded this transaction, so nothing was written twice.`);
228
135
  }
229
136
  // ⛔ AFTER THE PAYMENT, NEVER INSIDE IT, and it cannot change the answer above. In --json the
@@ -232,17 +139,19 @@ export async function extend(target, options = {}) {
232
139
  server: session.server,
233
140
  network: resolveNetwork(session.server, session.network),
234
141
  code: session.code,
235
- settings,
236
- wallet,
237
- paidWalFrost: frost,
142
+ settings: plan.settings,
143
+ wallet: plan.wallet,
144
+ paidWalFrost: budget.priceFrost,
238
145
  say: options.json === true ? (line) => void process.stderr.write(`${line}\n`) : say,
239
146
  ...(options.tip ?? {}),
240
147
  });
241
148
  return 0;
242
149
  }
243
150
  /** What the numbers say, for a person, in the order somebody deciding needs them. */
244
- function describe(say, facts, cohort, unreachable) {
151
+ function describe(say, facts) {
245
152
  const when = (epoch, left) => `epoch ${epoch} — ${daysLeftInWords(left)}`;
153
+ const cohort = facts.filesOnTheSameBlobs;
154
+ const unreachable = facts.partsThatCannotBeExtended;
246
155
  say(`${facts.file}`);
247
156
  say(` Storage ends at ${when(facts.endEpoch, facts.daysLeft)}.`);
248
157
  say(` Extending by ${facts.epochs} epoch${facts.epochs === 1 ? "" : "s"} moves that to ` +
@@ -262,21 +171,3 @@ function describe(say, facts, cohort, unreachable) {
262
171
  say(` This is paid in WAL from the wallet this NMTS key derives — not from credits, which`);
263
172
  say(` is what every other command in this tool spends. \`${BINARY_NAME} wallet\` shows what is in it.`);
264
173
  }
265
- /** Why a file has nothing to extend, said as the two different things it can be. */
266
- function nothingToExtend(preview) {
267
- const parts = [];
268
- if (preview.treasuryParts > 0) {
269
- parts.push(`${preview.treasuryParts} part${preview.treasuryParts === 1 ? " is" : "s are"} on storage NMTS ` +
270
- `paid for, which this account cannot extend`);
271
- }
272
- if (preview.untrackedParts > 0) {
273
- parts.push(`${preview.untrackedParts} part${preview.untrackedParts === 1 ? " has" : "s have"} no ` +
274
- `recorded storage object, so there is nothing to name on the chain`);
275
- }
276
- const why = parts.length === 0 ? "The server lists no storage object for it." : `${parts.join(", and ")}.`;
277
- return `Nothing was signed and nothing was charged. ${why} Opening the account in a browser shows what it is stored on.`;
278
- }
279
- /** The real chain reads. Imported only when no seam was supplied — it loads the storage SDK. */
280
- async function defaultReads(network) {
281
- return (await import("../extend-chain.js")).extendReads(network);
282
- }
@@ -0,0 +1,13 @@
1
+ /** What this needs of `login`'s options: the injected prompt, when a test supplies one. */
2
+ export interface PassphraseSource {
3
+ /** Injected in tests. Called twice for a new passphrase — the second is the confirmation. */
4
+ readPassphrase?: ((prompt: string) => Promise<string>) | undefined;
5
+ }
6
+ /**
7
+ * A passphrase for a NEW seal: from the environment, or typed twice.
8
+ *
9
+ * ⚠ The environment form is not confirmed, because there is nothing to confirm it against and
10
+ * asking would hang. A typo there produces a file whose passphrase nobody knows — which is why
11
+ * the message below says to keep it, not merely to choose it.
12
+ */
13
+ export declare function newPassphrase(options: PassphraseSource): Promise<string>;
@@ -0,0 +1,64 @@
1
+ // The passphrase a NEW seal is made under: where it comes from, and the two rules about it.
2
+ //
3
+ // ⛔ MOVED OUT OF `login.ts` RATHER THAN REWRITTEN (2026-09-20). Every line below was in that file
4
+ // and is unchanged; it moved because that file reached the length gate when wallet sign-in
5
+ // arrived, and this is where the seam already was: `login.ts` decides which of the three shapes
6
+ // the NMTS key is stored in and what a person is told, and this answers one question inside one
7
+ // of them. Nothing here reads the code, writes a file or talks to a server.
8
+ import { samePassphrase } from "../code-vault.js";
9
+ import { PASSPHRASE_ENV_VAR } from "../credentials.js";
10
+ import { NmtsError } from "../errors.js";
11
+ import { BINARY_NAME } from "../product.js";
12
+ import { promptSecret, stdinIsATerminal } from "../prompt.js";
13
+ /**
14
+ * ⚠ EIGHT, AND NO COMPOSITION RULES. scrypt makes a short passphrase expensive to attack, not
15
+ * safe: four characters is guessed whatever the cost factor. Requiring a digit and a capital
16
+ * would not change that and would push people to reuse the one they always type.
17
+ */
18
+ const MIN_PASSPHRASE = 8;
19
+ /**
20
+ * A passphrase for a NEW seal: from the environment, or typed twice.
21
+ *
22
+ * ⚠ The environment form is not confirmed, because there is nothing to confirm it against and
23
+ * asking would hang. A typo there produces a file whose passphrase nobody knows — which is why
24
+ * the message below says to keep it, not merely to choose it.
25
+ */
26
+ export async function newPassphrase(options) {
27
+ const ask = options.readPassphrase;
28
+ const fromEnv = process.env[PASSPHRASE_ENV_VAR];
29
+ if (ask === undefined && fromEnv !== undefined && fromEnv.length > 0) {
30
+ if (fromEnv.length < MIN_PASSPHRASE)
31
+ throw tooShort();
32
+ return fromEnv;
33
+ }
34
+ if (ask === undefined && !stdinIsATerminal()) {
35
+ throw new NmtsError("Sealing the NMTS key needs a passphrase, and there is no terminal.", {
36
+ exitCode: 2,
37
+ nextStep: [
38
+ `One of these:`,
39
+ ` · set ${PASSPHRASE_ENV_VAR} and run this again`,
40
+ ` · ${BINARY_NAME} login --plain store it unsealed (asks for an agreement first)`,
41
+ ` · ${BINARY_NAME} login --env store nothing; print the variable to set`,
42
+ ].join("\n"),
43
+ });
44
+ }
45
+ const prompt = ask ?? ((q) => promptSecret(q, PASSPHRASE_ENV_VAR));
46
+ const first = await prompt(`New passphrase for the stored NMTS key (not shown as you type): `);
47
+ if (first.length < MIN_PASSPHRASE)
48
+ throw tooShort();
49
+ const again = await prompt(`Type it again: `);
50
+ if (!samePassphrase(first, again)) {
51
+ throw new NmtsError("Those two passphrases are not the same.", {
52
+ exitCode: 2,
53
+ nextStep: `Nothing was written. Run \`${BINARY_NAME} login\` again.`,
54
+ });
55
+ }
56
+ return first;
57
+ }
58
+ function tooShort() {
59
+ return new NmtsError(`That passphrase is shorter than ${MIN_PASSPHRASE} characters.`, {
60
+ exitCode: 2,
61
+ nextStep: `Nothing was written. A short passphrase is guessed whatever the tool does to slow guessing ` +
62
+ `down. ⛔ If it is lost, the sealed copy cannot be opened by anybody — keep it somewhere.`,
63
+ });
64
+ }
@@ -1,3 +1,4 @@
1
+ import { type WalletOpener } from "../openers.ts";
1
2
  export interface LoginOptions {
2
3
  server?: string | undefined;
3
4
  network?: string | undefined;
@@ -5,6 +6,8 @@ export interface LoginOptions {
5
6
  plain?: boolean | undefined;
6
7
  /** Store nothing; print the environment variable to set. Behind `plain-env`. */
7
8
  env?: boolean | undefined;
9
+ /** `--wallet`: the NMTS key is opened by a wallet's signature instead of being typed. */
10
+ wallet?: WalletOpener | undefined;
8
11
  /** Injected in tests so the terminal is not involved. */
9
12
  readCode?: (() => Promise<string>) | undefined;
10
13
  /** Injected in tests. Called twice for a new passphrase — the second is the confirmation. */
@@ -27,22 +27,18 @@
27
27
  // to stop. What it can do is make the shape it writes ITSELF a decision.
28
28
  import { assertUsableCode } from "../account.js";
29
29
  import { keySourceName, keyToStore, settleApiKey } from "../api-key.js";
30
- import { lockCode, samePassphrase } from "../code-vault.js";
30
+ import { signInWithWallet } from "../openers.js";
31
+ import { lockCode } from "../code-vault.js";
31
32
  import { API_KEY_ENV_VAR, API_KEY_FILE_ENV_VAR, CODE_ENV_VAR, CODE_FILE_ENV_VAR, PASSPHRASE_ENV_VAR, codeStorageIsPrivate, credentialsPath, modesAreEnforced, readCredentialsFile, readSecretFile, writeCredentials, } from "../credentials.js";
32
33
  import { requireConsent } from "../consent.js";
33
34
  import { NmtsError } from "../errors.js";
34
35
  import { firstRunNotice } from "../notice.js";
36
+ import { newPassphrase } from "./login-passphrase.js";
35
37
  import { holdTerminal, promptSecret, stdinIsATerminal } from "../prompt.js";
36
38
  import { askAboutCollisions } from "../setup-questions.js";
37
39
  import { BINARY_NAME, HOME_URL } from "../product.js";
38
40
  import { resolveNetwork } from "../network.js";
39
41
  import { resolveServer } from "../server.js";
40
- /**
41
- * ⚠ EIGHT, AND NO COMPOSITION RULES. scrypt makes a short passphrase expensive to attack, not
42
- * safe: four characters is guessed whatever the cost factor. Requiring a digit and a capital
43
- * would not change that and would push people to reuse the one they always type.
44
- */
45
- const MIN_PASSPHRASE = 8;
46
42
  export async function login(options = {}) {
47
43
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
48
44
  const server = resolveServer(options.server);
@@ -62,7 +58,7 @@ export async function login(options = {}) {
62
58
  // line mode, where it echoes what is typed and swallows lines the next prompt never sees —
63
59
  // and this command asks up to three things with a check in the middle.
64
60
  const exit = await holdTerminal(async () => {
65
- const code = await readTheCode(options);
61
+ const code = await readTheCode(options, server);
66
62
  // ⛔ CHECKED BEFORE IT IS WRITTEN. The engine verifies the code's own check symbol offline, so
67
63
  // a mistyped code fails here as "that is not a code" instead of being stored and coming
68
64
  // back later as a sign-in failure indistinguishable from a wrong password or a suspended
@@ -108,7 +104,14 @@ export async function login(options = {}) {
108
104
  * ⚠ ORDER: a file first, because that is the shape this tool recommends and it asks for nothing;
109
105
  * then the environment, which asks once; then the terminal.
110
106
  */
111
- async function readTheCode(options) {
107
+ async function readTheCode(options, server) {
108
+ // ⛔ A WALLET ANSWERS THE CODE INSTEAD OF A PERSON TYPING IT, and nothing else about this command
109
+ // changes: what comes back is the account's own NMTS key, stored in whichever of the three
110
+ // shapes this run asked for. The sentences a wallet's refusal carries are `openers.ts`'s.
111
+ if (options.wallet !== undefined) {
112
+ const { OPENER_HINTS } = await import("./openers.js");
113
+ return (await signInWithWallet(server, options.wallet, OPENER_HINTS)).accountCode;
114
+ }
112
115
  const fromFile = readSecretFile(CODE_FILE_ENV_VAR);
113
116
  const fromEnv = process.env[CODE_ENV_VAR];
114
117
  if (options.readCode === undefined && fromFile === null && fromEnv !== undefined && fromEnv.length > 0) {
@@ -217,6 +220,9 @@ function printEnvForm(code, say) {
217
220
  * be checked by anybody, because the code never goes to the server. Saying the old sentence
218
221
  * after a key had just been accepted would have been the tool describing the world before it.
219
222
  */
223
+ // Copy facts — the wallet case has a sharper sentence available and does not have one yet. What is
224
+ // true after `--wallet`: a slot for this NMTS key was found on this server and opened, so something
225
+ // registered it — which is more than the check symbol says and less than "the account is live".
220
226
  function sayCheckSymbol(say, keyWasAccepted) {
221
227
  say(``);
222
228
  say(` The NMTS key is well-formed — its own check symbol matches. That was verified here, offline.`);
@@ -287,49 +293,3 @@ function sayAboutTheKey(outcome, server, say) {
287
293
  return;
288
294
  }
289
295
  }
290
- /**
291
- * A passphrase for a NEW seal: from the environment, or typed twice.
292
- *
293
- * ⚠ The environment form is not confirmed, because there is nothing to confirm it against and
294
- * asking would hang. A typo there produces a file whose passphrase nobody knows — which is why
295
- * the message below says to keep it, not merely to choose it.
296
- */
297
- async function newPassphrase(options) {
298
- const ask = options.readPassphrase;
299
- const fromEnv = process.env[PASSPHRASE_ENV_VAR];
300
- if (ask === undefined && fromEnv !== undefined && fromEnv.length > 0) {
301
- if (fromEnv.length < MIN_PASSPHRASE)
302
- throw tooShort();
303
- return fromEnv;
304
- }
305
- if (ask === undefined && !stdinIsATerminal()) {
306
- throw new NmtsError("Sealing the NMTS key needs a passphrase, and there is no terminal.", {
307
- exitCode: 2,
308
- nextStep: [
309
- `One of these:`,
310
- ` · set ${PASSPHRASE_ENV_VAR} and run this again`,
311
- ` · ${BINARY_NAME} login --plain store it unsealed (asks for an agreement first)`,
312
- ` · ${BINARY_NAME} login --env store nothing; print the variable to set`,
313
- ].join("\n"),
314
- });
315
- }
316
- const prompt = ask ?? ((q) => promptSecret(q, PASSPHRASE_ENV_VAR));
317
- const first = await prompt(`New passphrase for the stored NMTS key (not shown as you type): `);
318
- if (first.length < MIN_PASSPHRASE)
319
- throw tooShort();
320
- const again = await prompt(`Type it again: `);
321
- if (!samePassphrase(first, again)) {
322
- throw new NmtsError("Those two passphrases are not the same.", {
323
- exitCode: 2,
324
- nextStep: `Nothing was written. Run \`${BINARY_NAME} login\` again.`,
325
- });
326
- }
327
- return first;
328
- }
329
- function tooShort() {
330
- return new NmtsError(`That passphrase is shorter than ${MIN_PASSPHRASE} characters.`, {
331
- exitCode: 2,
332
- nextStep: `Nothing was written. A short passphrase is guessed whatever the tool does to slow guessing ` +
333
- `down. ⛔ If it is lost, the sealed copy cannot be opened by anybody — keep it somewhere.`,
334
- });
335
- }
@@ -0,0 +1,38 @@
1
+ import { type AttachedWallet, type WalletOpener } from "../openers.ts";
2
+ /** What attaching to a fresh account takes. */
3
+ export interface AttachInput {
4
+ server: string;
5
+ /** The account's NMTS key — made in this run and held by nobody else. */
6
+ code: string;
7
+ wallet: WalletOpener;
8
+ }
9
+ /** What it did, and the one thing that can be left behind by a failure. */
10
+ export interface AttachOutcome extends AttachedWallet {
11
+ /**
12
+ * The id of the borrowed key this run could NOT revoke, or null when nothing was left.
13
+ *
14
+ * ⚠ NOT A FAILURE OF THE ATTACH. The wallet does open the account; what did not happen is the
15
+ * tidying, and a person can cut the key from a browser or with `nmts key revoke`.
16
+ */
17
+ keyLeft: string | null;
18
+ }
19
+ /** Attach `wallet` to the account `code` opens, borrowing a credential for the length of one PUT. */
20
+ export declare function attachWalletToNewAccount(input: AttachInput): Promise<AttachOutcome>;
21
+ /**
22
+ * Ask, before an account is made, whether this wallet already opens one.
23
+ *
24
+ * ⛔ THE ONE STEP THAT HAS TO HAPPEN EARLY. Everywhere else a taken locator is a refusal and
25
+ * nothing else; on `nmts create --wallet` it would be an account that exists, holds a key the
26
+ * person has been handed, and cannot have the wallet they asked for. One signature spent here
27
+ * is cheaper than an account nobody wanted.
28
+ */
29
+ export declare function refuseIfWalletIsTaken(server: string, wallet: WalletOpener): Promise<void>;
30
+ /**
31
+ * What a wallet attached to a new account means, said after the code has been handed over.
32
+ *
33
+ * ⚠ Copy facts — both sentences. Facts for the first: this wallet now opens this account from any
34
+ * machine, so whoever holds it can read every file in it, and `nmts openers remove <locator>`
35
+ * takes it off. For the second: a write-scoped key borrowed for this one step is still live on
36
+ * the brand-new account, and its id is how to cut it.
37
+ */
38
+ export declare function sayWalletAttached(say: (line: string) => void, attached: AttachOutcome): void;
@@ -0,0 +1,97 @@
1
+ // Attaching a wallet to an account THIS RUN JUST CREATED — the one case where the account has no
2
+ // credential on this machine yet.
3
+ //
4
+ // ⛔ WHY THIS FILE EXISTS AT ALL. The three opener doors take a credential AND the NMTS key's own
5
+ // proof: the proof says whoever is asking holds the key, and the credential says which account
6
+ // the server is talking to. A brand-new account has the first and not the second — `nmts create`
7
+ // deliberately stores nothing and switches nothing over (`create.ts`) — so there is nothing to
8
+ // speak with. `POST /v1/account/api-keys/by-code` is the door built for exactly that shape: a
9
+ // program set up from one secret rather than from a browser session plus that secret.
10
+ //
11
+ // ⛔ SO THE KEY IS MINTED, USED ONCE, AND CUT. It lasts a day, carries `write` and nothing else,
12
+ // and is revoked as soon as the slot is stored — through `revoke-by-code`, which needs the same
13
+ // one secret. What is left behind is an account with the wallet attached and no credential,
14
+ // which is what `nmts create` leaves behind today.
15
+ //
16
+ // ⛔ AND A REVOKE THAT FAILED IS REPORTED, NEVER SWALLOWED. A live key on somebody's new account
17
+ // that they were not told about is worse than one they were: the caller is handed the key's id
18
+ // so it can say so, and the attach itself still counts as done, because it is.
19
+ //
20
+ // The sentences the caller prints around this: The facts are in `create.ts` and in
21
+ // the comment above each return.
22
+ import { request } from "../api.js";
23
+ import { addWallet, refuseIfWalletOpensAnAccount, } from "../openers.js";
24
+ import { BINARY_NAME } from "../product.js";
25
+ import { registrationProofOf } from "../registration.js";
26
+ import { OPENER_HINTS } from "./openers.js";
27
+ /** Permission to write this account's own openers, and nothing else. `api/src/domain/api_key.rs`. */
28
+ const WRITE_ONLY = 2;
29
+ /** How long the borrowed key may live. It is cut seconds later; this is what covers a failure. */
30
+ const ONE_DAY = 1;
31
+ /** Attach `wallet` to the account `code` opens, borrowing a credential for the length of one PUT. */
32
+ export async function attachWalletToNewAccount(input) {
33
+ const { accountId, authSecret } = await registrationProofOf(input.code);
34
+ const proven = { account_id: accountId, auth_secret: authSecret };
35
+ const issued = await request(input.server, "/v1/account/api-keys/by-code", {
36
+ method: "POST",
37
+ body: { ...proven, scopes: WRITE_ONLY, lifetime_days: ONE_DAY },
38
+ // ⛔ NOT REPEATED ON A TIMEOUT. A request that reached the server and died on the way back has
39
+ // already spent one of the two live keys this account may hold, and a retry would spend the
40
+ // other — leaving a new account at its cap over a key nobody received.
41
+ retryBudgetMs: 0,
42
+ });
43
+ const apiKey = field(issued, "key");
44
+ const keyId = field(issued, "key_id");
45
+ if (apiKey === null || keyId === null) {
46
+ throw new Error("OPENER_ATTACH_NO_KEY: the server's answer held no usable key.");
47
+ }
48
+ const attached = await addWallet({ server: input.server, apiKey, accountProof: authSecret }, input.code, input.wallet, OPENER_HINTS);
49
+ return { ...attached, keyLeft: (await revoked(input.server, proven, keyId)) ? null : keyId };
50
+ }
51
+ /**
52
+ * Ask, before an account is made, whether this wallet already opens one.
53
+ *
54
+ * ⛔ THE ONE STEP THAT HAS TO HAPPEN EARLY. Everywhere else a taken locator is a refusal and
55
+ * nothing else; on `nmts create --wallet` it would be an account that exists, holds a key the
56
+ * person has been handed, and cannot have the wallet they asked for. One signature spent here
57
+ * is cheaper than an account nobody wanted.
58
+ */
59
+ export async function refuseIfWalletIsTaken(server, wallet) {
60
+ await refuseIfWalletOpensAnAccount(server, wallet, OPENER_HINTS);
61
+ }
62
+ /**
63
+ * What a wallet attached to a new account means, said after the code has been handed over.
64
+ *
65
+ * ⚠ Copy facts — both sentences. Facts for the first: this wallet now opens this account from any
66
+ * machine, so whoever holds it can read every file in it, and `nmts openers remove <locator>`
67
+ * takes it off. For the second: a write-scoped key borrowed for this one step is still live on
68
+ * the brand-new account, and its id is how to cut it.
69
+ */
70
+ export function sayWalletAttached(say, attached) {
71
+ say(``);
72
+ say(`This wallet also opens the new account: ${attached.locator}`);
73
+ if (attached.keyLeft !== null) {
74
+ say(`⚠ The key borrowed to store it — ${attached.keyLeft} — is still live. Cut it with \`${BINARY_NAME} key revoke ${attached.keyLeft}\`.`);
75
+ }
76
+ }
77
+ /** Cut the borrowed key. Its failure is an answer, not a throw: the wallet is attached either way. */
78
+ async function revoked(server, proven, keyId) {
79
+ try {
80
+ await request(server, "/v1/account/api-keys/revoke-by-code", {
81
+ method: "POST",
82
+ body: { ...proven, key_id: keyId },
83
+ retryBudgetMs: 0,
84
+ });
85
+ return true;
86
+ }
87
+ catch {
88
+ // ⚠ The cause is not carried up. What the caller can act on is that a key is still live and
89
+ // which one; why the revoke failed is already in the run log.
90
+ return false;
91
+ }
92
+ }
93
+ /** One string field of the server's answer, or null. ⛔ Nothing here prints what it read. */
94
+ function field(answer, name) {
95
+ const value = typeof answer === "object" && answer !== null ? Reflect.get(answer, name) : undefined;
96
+ return typeof value === "string" && value.length > 0 ? value : null;
97
+ }