openany-cli-dev 0.0.0-stage → 0.1.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 (73) hide show
  1. package/README.md +461 -2
  2. package/bin/openany.js +3 -0
  3. package/package.json +27 -4
  4. package/skills/openany/SKILL.md +347 -0
  5. package/skills/openany/SKILL.zh-CN.md +496 -0
  6. package/skills/openany-provider/SKILL.md +26 -0
  7. package/skills/openany-provider/SKILL.zh-CN.md +26 -0
  8. package/skills/openany-provider/references/apis.md +60 -0
  9. package/skills/openany-provider/references/application.md +49 -0
  10. package/skills/openany-provider/references/application.zh-CN.md +51 -0
  11. package/skills/openany-provider/references/auth.md +59 -0
  12. package/skills/openany-provider/references/connections.md +38 -0
  13. package/skills/openany-provider/references/connections.zh-CN.md +33 -0
  14. package/skills/openany-provider/references/imports.md +38 -0
  15. package/skills/openany-provider/references/imports.zh-CN.md +55 -0
  16. package/skills/openany-provider/references/listing.md +29 -0
  17. package/skills/openany-provider/references/login.md +58 -0
  18. package/skills/openany-provider/references/login.zh-CN.md +59 -0
  19. package/skills/openany-provider/references/model-import.zh-CN.md +12 -0
  20. package/skills/openany-provider/references/models.md +107 -0
  21. package/skills/openany-provider/references/publishing.md +83 -0
  22. package/skills/openany-provider/references/publishing.zh-CN.md +81 -0
  23. package/skills/openany-provider/references/reviews.md +22 -0
  24. package/skills/openany-provider/templates/api-metadata.json +27 -0
  25. package/skills/openany-provider/templates/bindings.json +1 -0
  26. package/skills/openany-provider/templates/models-v2.json +545 -0
  27. package/skills/openany-provider/templates/models.json +10 -0
  28. package/skills/openany-provider/templates/provider-agent-api-template.json +697 -0
  29. package/skills/openany-provider/templates/seller-agent-api-import-template.json +839 -0
  30. package/skills/openany-provider/templates/seller-registration.json +26 -0
  31. package/src/auth-recovery.js +179 -0
  32. package/src/auth.js +1001 -0
  33. package/src/catalog.js +306 -0
  34. package/src/cli.js +601 -0
  35. package/src/config.js +260 -0
  36. package/src/errors.js +53 -0
  37. package/src/http.js +237 -0
  38. package/src/model-curl.js +359 -0
  39. package/src/model-materials.js +58 -0
  40. package/src/model-request.js +402 -0
  41. package/src/model-validation.js +56 -0
  42. package/src/models.js +188 -0
  43. package/src/native/config-acl.ps1 +34 -0
  44. package/src/native/connection-macos.js +109 -0
  45. package/src/native/connection-windows.ps1 +98 -0
  46. package/src/native/setup-macos.js +72 -0
  47. package/src/native/setup-windows.ps1 +83 -0
  48. package/src/native-prompt.js +85 -0
  49. package/src/payment-signing.js +362 -0
  50. package/src/prompt.js +69 -0
  51. package/src/provider-api-import-v2.js +72 -0
  52. package/src/provider-apis.js +3 -0
  53. package/src/provider-client.js +153 -0
  54. package/src/provider-connections.js +152 -0
  55. package/src/provider-import-format.js +289 -0
  56. package/src/provider-imports.js +402 -0
  57. package/src/provider-json.js +49 -0
  58. package/src/provider-model-import-v2.js +61 -0
  59. package/src/provider-models.js +253 -0
  60. package/src/provider-profile.js +65 -0
  61. package/src/provider-reviews.js +61 -0
  62. package/src/provider-state.js +176 -0
  63. package/src/provider.js +75 -0
  64. package/src/setup.js +201 -0
  65. package/src/topups.js +845 -0
  66. package/src/vendor/provider-apply/market-taxonomy.mjs +22 -0
  67. package/src/vendor/provider-apply/provenance.json +8 -0
  68. package/src/vendor/provider-apply/registration.mjs +151 -0
  69. package/src/vendor/provider-import/api-categories.json +29 -0
  70. package/src/vendor/provider-import/api-fields.json +33 -0
  71. package/src/vendor/provider-import/model-fields.json +44 -0
  72. package/src/wallet.js +213 -0
  73. package/src/windows-permissions.js +22 -0
package/src/auth.js ADDED
@@ -0,0 +1,1001 @@
1
+ import { readFile, open, unlink } from "node:fs/promises";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { fingerprint, readRecovery, applyRecovery } from "./auth-recovery.js";
6
+ import { CLIError, requireValue } from "./errors.js";
7
+ import { unwrap, BACKEND_ORIGIN } from "./http.js";
8
+ import {
9
+ getWallet,
10
+ validateChallenge,
11
+ verifyWalletMessage,
12
+ sameWallet,
13
+ } from "./wallet.js";
14
+
15
+ export const SIGNING_ORIGIN = "https://dev.openany.si";
16
+ const encodeId = (value) => {
17
+ if (
18
+ typeof value !== "string" ||
19
+ !value ||
20
+ /[\/\\?#\s]/.test(value) ||
21
+ value === "." ||
22
+ value === ".."
23
+ )
24
+ throw new CLIError("INPUT_INVALID", "Invalid resource ID.");
25
+ return encodeURIComponent(value);
26
+ };
27
+ const normalizeEmail = (value) => {
28
+ if (typeof value !== "string" || !/^\S+@[^\s@]+\.[^\s@]+$/.test(value))
29
+ throw new CLIError("CONFIG_REQUIRED", "Configure OPENANY_DEV_EMAIL.", {
30
+ missing: ["OPENANY_DEV_EMAIL"],
31
+ });
32
+ return value.trim().toLowerCase();
33
+ };
34
+ function assertLabel(label) {
35
+ if (
36
+ typeof label !== "string" ||
37
+ !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(label) ||
38
+ ["__proto__", "constructor", "prototype"].includes(label)
39
+ )
40
+ throw new CLIError(
41
+ "INPUT_INVALID",
42
+ "Key labels must use 1–64 letters, digits, dots, underscores or hyphens.",
43
+ );
44
+ }
45
+ function mergeCookies(previous, headers, now) {
46
+ const cookies = [...(previous || [])];
47
+ for (const raw of headers.getSetCookie()) {
48
+ const [pair, ...attrs] = raw.split(";");
49
+ const index = pair.indexOf("=");
50
+ if (index < 1) continue;
51
+ const item = {
52
+ name: pair.slice(0, index).trim(),
53
+ value: pair.slice(index + 1).trim(),
54
+ path: "/",
55
+ };
56
+ if (
57
+ !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(item.name) ||
58
+ /[\r\n;]/.test(item.value)
59
+ )
60
+ throw new CLIError("COOKIE_INVALID", "The login response contains an invalid cookie.");
61
+ let maxAge;
62
+ for (const attr of attrs) {
63
+ const equal = attr.indexOf("=");
64
+ const name = (equal < 0 ? attr : attr.slice(0, equal))
65
+ .trim()
66
+ .toLowerCase();
67
+ const value = equal < 0 ? "" : attr.slice(equal + 1).trim();
68
+ if (
69
+ name === "domain" &&
70
+ value.replace(/^\./, "").toLowerCase() !==
71
+ new URL(BACKEND_ORIGIN).hostname
72
+ )
73
+ throw new CLIError("COOKIE_INVALID", "The login cookie does not belong to the fixed backend.");
74
+ if (name === "path") item.path = value;
75
+ if (name === "max-age") maxAge = Number(value);
76
+ if (name === "expires") item.expiresAt = Date.parse(value);
77
+ }
78
+ if (Number.isFinite(maxAge)) item.expiresAt = now + maxAge * 1000;
79
+ const old = cookies.findIndex(
80
+ (c) => c.name === item.name && c.path === item.path,
81
+ );
82
+ if (old >= 0) cookies.splice(old, 1);
83
+ if (!item.expiresAt || item.expiresAt > now) cookies.push(item);
84
+ }
85
+ return cookies;
86
+ }
87
+ function cookieHeader(cookies, path, now) {
88
+ return (cookies || [])
89
+ .filter(
90
+ (c) =>
91
+ (!c.expiresAt || c.expiresAt > now) &&
92
+ (path === c.path ||
93
+ path.startsWith(c.path.endsWith("/") ? c.path : c.path + "/")),
94
+ )
95
+ .map((c) => `${c.name}=${c.value}`)
96
+ .join("; ");
97
+ }
98
+ function safeKeyResult(value) {
99
+ if (Array.isArray(value)) return value.map(safeKeyResult);
100
+ if (value && typeof value === "object")
101
+ return Object.fromEntries(
102
+ Object.entries(value)
103
+ .filter(
104
+ ([k]) =>
105
+ ![
106
+ "plaintextKey",
107
+ "accessToken",
108
+ "refreshToken",
109
+ "token",
110
+ "cookies",
111
+ "key",
112
+ "secret",
113
+ ].includes(k),
114
+ )
115
+ .map(([k, v]) => [k, safeKeyResult(v)]),
116
+ );
117
+ return value;
118
+ }
119
+
120
+ const knownDenied = (error) =>
121
+ [400, 401, 403, 404, 405, 413, 415, 422, 429].includes(error.details?.status);
122
+ function expiredReservation(reservation, now) {
123
+ if (
124
+ !reservation ||
125
+ !Number.isFinite(reservation.createdAt) ||
126
+ now - reservation.createdAt < 300000 ||
127
+ !Number.isSafeInteger(reservation.pid) ||
128
+ reservation.pid <= 0
129
+ )
130
+ return false;
131
+ try {
132
+ process.kill(reservation.pid, 0);
133
+ return false;
134
+ } catch (error) {
135
+ return error.code === "ESRCH";
136
+ }
137
+ }
138
+
139
+ export class AuthService {
140
+ constructor({
141
+ env = process.env,
142
+ store,
143
+ http,
144
+ now = () => Date.now(),
145
+ sleep = delay,
146
+ stderr = process.stderr,
147
+ signingOrigin = SIGNING_ORIGIN,
148
+ secrets = [],
149
+ }) {
150
+ Object.assign(this, { env, store, http, now, sleep, stderr, signingOrigin, secrets });
151
+ }
152
+ // Preserve one-time credentials before merging config, so a lock/write error cannot silently lose them.
153
+ async saveSecret(kind, secret, context) {
154
+ this.secrets.push(
155
+ secret.plaintextKey,
156
+ secret.accessToken,
157
+ secret.token,
158
+ ...(secret.cookies || []).map((c) => c.value),
159
+ );
160
+ const id = randomUUID();
161
+ const record = {
162
+ version: 1,
163
+ id,
164
+ kind,
165
+ receivedAt: new Date(this.now()).toISOString(),
166
+ data: secret,
167
+ context,
168
+ };
169
+ const path = join(this.store.directory, `recovery-${kind}-${id}.json`);
170
+ const file = await open(path, "wx", 0o600);
171
+ try {
172
+ await file.writeFile(JSON.stringify(record) + "\n");
173
+ await file.sync();
174
+ } finally {
175
+ await file.close();
176
+ }
177
+ try {
178
+ await this.store.update((s) => applyRecovery(s, record, this.now()));
179
+ } catch {
180
+ throw new CLIError(
181
+ "CREDENTIAL_SAVE_FAILED",
182
+ "New credentials were saved to a restricted recovery file; recover them before creating or rotating credentials again.",
183
+ { recoveryFile: path },
184
+ );
185
+ }
186
+ await unlink(path);
187
+ }
188
+ async recover(path) {
189
+ let record;
190
+ try {
191
+ record = await readRecovery(path, this.store.directory);
192
+ } catch (error) {
193
+ if (error instanceof CLIError) throw error;
194
+ throw new CLIError("RECOVERY_INVALID", "Unable to read the restricted recovery file.");
195
+ }
196
+ this.secrets.push(
197
+ record.data?.plaintextKey,
198
+ record.data?.accessToken,
199
+ record.data?.token,
200
+ ...(record.data?.cookies || []).map((c) => c.value),
201
+ );
202
+ await this.store.update((s) => applyRecovery(s, record, this.now()));
203
+ await unlink(path);
204
+ return {
205
+ recovered: true,
206
+ kind: record.kind,
207
+ ...(record.context.label ? { label: record.context.label } : {}),
208
+ };
209
+ }
210
+ async wallet(
211
+ operation,
212
+ {
213
+ prepare = false,
214
+ challengeId,
215
+ signature,
216
+ label = "main",
217
+ expectedKeyId,
218
+ } = {},
219
+ ) {
220
+ if (!["session", "create_key", "rotate_key"].includes(operation))
221
+ throw new CLIError("INPUT_INVALID", "Invalid wallet operation.");
222
+ const signer = getWallet(this.env, {
223
+ requirePrivateKey: !prepare && !signature,
224
+ });
225
+ const agentId = this.env.OPENANY_DEV_AGENT_ID;
226
+ if (
227
+ operation !== "session" &&
228
+ (!agentId || !/^[A-Za-z0-9._:-]{6,128}$/.test(agentId))
229
+ )
230
+ throw new CLIError(
231
+ "CONFIG_REQUIRED",
232
+ "Configure a stable OPENANY_DEV_AGENT_ID using 6–128 allowed characters.",
233
+ { missing: ["OPENANY_DEV_AGENT_ID"] },
234
+ );
235
+ assertLabel(label);
236
+ const expected = {
237
+ walletAddress: signer.address,
238
+ agentId,
239
+ operation,
240
+ expectedKeyId,
241
+ serviceOrigin: this.signingOrigin,
242
+ };
243
+ let state = await this.store.read(),
244
+ pending;
245
+ if (challengeId) {
246
+ pending = state.authChallenges?.[challengeId];
247
+ if (!pending || pending.status !== "prepared")
248
+ throw new CLIError(
249
+ "CHALLENGE_NOT_PENDING",
250
+ "No saved challenge is available for submission; do not resubmit a consumed challenge.",
251
+ );
252
+ if (
253
+ pending.operation !== operation ||
254
+ pending.label !== label ||
255
+ pending.agentId !== agentId ||
256
+ !sameWallet(pending.walletAddress, signer.address)
257
+ )
258
+ throw new CLIError("CHALLENGE_INVALID", "The submission parameters do not match the saved challenge.");
259
+ } else {
260
+ if (signature)
261
+ throw new CLIError("INPUT_REQUIRED", "External signing requires --challenge-id.");
262
+ const existingKey = state.keys.find((k) => k.label === label);
263
+ if (operation === "create_key" && existingKey)
264
+ throw new CLIError(
265
+ "KEY_LABEL_EXISTS",
266
+ "This label already has a key; reuse it or explicitly choose another label.",
267
+ );
268
+ if (operation === "rotate_key" && existingKey) {
269
+ if (
270
+ existingKey.metadata?.identity !== "wallet" ||
271
+ existingKey.metadata.agentId !== agentId ||
272
+ !sameWallet(existingKey.metadata.walletAddress, signer.address)
273
+ )
274
+ throw new CLIError(
275
+ "KEY_IDENTITY_MISMATCH",
276
+ "The existing key under this label does not belong to the specified wallet agent.",
277
+ );
278
+ expected.expectedKeyId ||= existingKey.metadata.keyId;
279
+ }
280
+ const previous = Object.values(state.authChallenges || {}).find(
281
+ (p) =>
282
+ p.operation === operation &&
283
+ p.agentId === agentId &&
284
+ p.walletAddress === signer.address &&
285
+ !(p.status === "awaiting_authorization" && p.authorizationDeadline <= this.now()) &&
286
+ p.status !== "completed" &&
287
+ p.status !== "rejected" &&
288
+ (p.status !== "prepared" ||
289
+ Date.parse(p.challenge.expiresAt) > this.now()),
290
+ );
291
+ if (previous) {
292
+ if (previous.status !== "prepared")
293
+ throw new CLIError(
294
+ "OPERATION_UNCERTAIN",
295
+ "The previous submission result is unconfirmed; recover credentials or check the account before creating again.",
296
+ { challengeId: previous.challenge.challengeId },
297
+ );
298
+ if (previous.label !== label)
299
+ throw new CLIError("CHALLENGE_PENDING", "An unfinished challenge already exists for another label.");
300
+ pending = previous;
301
+ } else {
302
+ const prefix =
303
+ operation === "session"
304
+ ? "/api/v1/agent-sessions"
305
+ : "/api/v1/agent-keys";
306
+ // Persist a reservation before requesting a challenge to serialize same-identity operations.
307
+ const reservation = {
308
+ id: randomUUID(),
309
+ pid: process.pid,
310
+ createdAt: this.now(),
311
+ };
312
+ await this.store.update((s) => {
313
+ s.authReservations ||= {};
314
+ const id = `${operation}:${signer.address}:${agentId || ""}`;
315
+ if (
316
+ s.authReservations[id] &&
317
+ !expiredReservation(s.authReservations[id], this.now())
318
+ )
319
+ throw new CLIError(
320
+ "OPERATION_PENDING",
321
+ "A challenge request is already in progress for this identity.",
322
+ );
323
+ s.authReservations[id] = reservation;
324
+ });
325
+ const reservationId = `${operation}:${signer.address}:${agentId || ""}`;
326
+ try {
327
+ const challenge = unwrap(
328
+ await this.http.backend(prefix + "/challenges", {
329
+ method: "POST",
330
+ json:
331
+ operation === "session"
332
+ ? { walletAddress: signer.address }
333
+ : { walletAddress: signer.address, agentId, operation },
334
+ }),
335
+ );
336
+ validateChallenge(challenge, expected, this.now());
337
+ pending = {
338
+ challenge,
339
+ operation,
340
+ agentId,
341
+ walletAddress: signer.address,
342
+ label,
343
+ status: "prepared",
344
+ expectedKeyId: expected.expectedKeyId,
345
+ };
346
+ await this.store.update((s) => {
347
+ s.authChallenges ||= {};
348
+ s.authChallenges[challenge.challengeId] = pending;
349
+ if (s.authReservations[reservationId]?.id === reservation.id)
350
+ delete s.authReservations[reservationId];
351
+ });
352
+ } catch (error) {
353
+ await this.store.update((s) => {
354
+ if (s.authReservations?.[reservationId]?.id === reservation.id)
355
+ delete s.authReservations[reservationId];
356
+ });
357
+ throw error;
358
+ }
359
+ }
360
+ }
361
+ expected.expectedKeyId ||= pending.expectedKeyId;
362
+ validateChallenge(pending.challenge, expected, this.now());
363
+ if (prepare)
364
+ return {
365
+ status: "signature_required",
366
+ ...pending.challenge,
367
+ operation,
368
+ walletAddress: signer.address,
369
+ label,
370
+ agentId,
371
+ };
372
+ const proof =
373
+ signature || (await signer.signMessage(pending.challenge.message));
374
+ this.secrets.push(proof);
375
+ if (!verifyWalletMessage(signer.address, pending.challenge.message, proof))
376
+ throw new CLIError("SIGNATURE_INVALID", "The signature does not match the specified wallet or original challenge message.");
377
+ await this.store.update((s) => {
378
+ const p = s.authChallenges?.[pending.challenge.challengeId];
379
+ if (p?.status !== "prepared")
380
+ throw new CLIError("CHALLENGE_NOT_PENDING", "The challenge has already been submitted.");
381
+ p.status = "submitting";
382
+ });
383
+ const endpoint =
384
+ operation === "session"
385
+ ? "/api/v1/agent-sessions"
386
+ : operation === "rotate_key"
387
+ ? "/api/v1/agent-keys/rotate"
388
+ : "/api/v1/agent-keys";
389
+ let result;
390
+ try {
391
+ const request = {
392
+ method: "POST",
393
+ json: { challengeId: pending.challenge.challengeId, signature: proof },
394
+ };
395
+ const response = await this.http.backend(endpoint, request);
396
+ result = operation === "create_key" && response.status === 202
397
+ ? await this.awaitKeyAuthorization(endpoint, request, response)
398
+ : unwrap(response);
399
+ } catch (error) {
400
+ await this.store.update((s) => {
401
+ s.authChallenges[pending.challenge.challengeId].status =
402
+ error.code === "AUTHORIZATION_EXPIRED" || (error.details?.status >= 400 && error.details.status < 500)
403
+ ? "rejected"
404
+ : "uncertain";
405
+ });
406
+ throw error;
407
+ }
408
+ if (
409
+ !result?.walletAddress ||
410
+ !sameWallet(result.walletAddress, signer.address) ||
411
+ (operation !== "session" && result.agentId !== agentId)
412
+ )
413
+ throw new CLIError(
414
+ "IDENTITY_RESPONSE_INVALID",
415
+ "The identity returned by the service does not match the challenge; check the account status.",
416
+ );
417
+ if (operation === "session") {
418
+ if (
419
+ typeof result.token !== "string" ||
420
+ !result.token ||
421
+ !Number.isFinite(Date.parse(result.expiresAt)) ||
422
+ Date.parse(result.expiresAt) <= this.now()
423
+ )
424
+ throw new CLIError(
425
+ "IDENTITY_RESPONSE_INVALID",
426
+ "The service did not return a valid wallet session.",
427
+ );
428
+ await this.saveSecret("wallet-session", result, {
429
+ operation,
430
+ challengeId: pending.challenge.challengeId,
431
+ label,
432
+ agentId,
433
+ walletAddress: signer.address,
434
+ previousSession: fingerprint(state.sessions.wallet),
435
+ });
436
+ } else {
437
+ if (
438
+ typeof result.plaintextKey !== "string" ||
439
+ !result.plaintextKey ||
440
+ !result.keyId
441
+ )
442
+ throw new CLIError(
443
+ "IDENTITY_RESPONSE_INVALID",
444
+ "The service did not return an API key that can be saved.",
445
+ );
446
+ await this.saveSecret(
447
+ "wallet-key",
448
+ { ...result, label },
449
+ {
450
+ operation,
451
+ challengeId: pending.challenge.challengeId,
452
+ label,
453
+ agentId,
454
+ walletAddress: signer.address,
455
+ previousKey: fingerprint(state.keys.find((k) => k.label === label)),
456
+ metadata: {
457
+ identity: "wallet",
458
+ accountId: result.accountId,
459
+ workspaceId: result.workspaceId,
460
+ walletAddress: signer.address,
461
+ agentId,
462
+ keyId: result.keyId,
463
+ },
464
+ },
465
+ );
466
+ }
467
+ return {
468
+ ...safeKeyResult(result),
469
+ saved: true,
470
+ ...(operation === "session"
471
+ ? {}
472
+ : {
473
+ label,
474
+ active: true,
475
+ environmentOverride: Boolean(this.env.OPENANY_DEV_API_KEY),
476
+ }),
477
+ };
478
+ }
479
+ async awaitKeyAuthorization(endpoint, request, response) {
480
+ const challengeId = request.json.challengeId;
481
+ const reasons = {
482
+ insufficient_balance: "Insufficient balance for automatic registration. The signed wallet must hold more than 1 official USDC on its mainnet (Base for EVM wallets, Solana for Solana wallets). You can continue without funding it.",
483
+ balance_unavailable: "OpenAny could not verify the wallet balance.",
484
+ };
485
+ let deadline = Infinity;
486
+ let interval;
487
+ let lastNotice;
488
+ while (response.status === 202 || response.status === 429) {
489
+ let waitMs;
490
+ if (response.status === 202) {
491
+ const data = unwrap(response);
492
+ const url = URL.parse(data?.verificationUrl);
493
+ const expiry = Date.parse(data?.expiresAt);
494
+ const localHttp = url?.protocol === "http:" &&
495
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
496
+ if (
497
+ data?.status !== "authorization_required" ||
498
+ !Object.hasOwn(reasons, data.reason) ||
499
+ (url?.protocol !== "https:" && !localHttp) ||
500
+ url.username || url.password ||
501
+ !Number.isFinite(expiry) ||
502
+ !Number.isSafeInteger(data.interval) || data.interval < 1
503
+ )
504
+ throw new CLIError("INVALID_RESPONSE", "The service returned an invalid key authorization request.");
505
+ deadline = Math.min(deadline, expiry);
506
+ interval = data.interval * 1000;
507
+ const notice = reasons[data.reason] + "\nOpen this link in a browser to authorize key creation:\n" + url.href + "\n";
508
+ if (notice !== lastNotice) this.stderr.write(notice);
509
+ lastNotice = notice;
510
+ waitMs = interval;
511
+ } else {
512
+ const retryAfter = response.headers.get("retry-after");
513
+ const retryMs = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - this.now();
514
+ waitMs = Math.max(interval, retryMs || 0);
515
+ }
516
+ // Only a confirmed pending response can be safely abandoned after expiry.
517
+ await this.store.update((s) => {
518
+ const pending = s.authChallenges[challengeId];
519
+ pending.status = "awaiting_authorization";
520
+ pending.authorizationDeadline = deadline;
521
+ });
522
+ const remaining = deadline - this.now();
523
+ if (remaining > 0) await this.sleep(Math.min(waitMs, remaining));
524
+ if (this.now() >= deadline)
525
+ throw new CLIError("AUTHORIZATION_EXPIRED", "The authorization link expired. Run key creation again.");
526
+ await this.store.update((s) => {
527
+ s.authChallenges[challengeId].status = "submitting";
528
+ });
529
+ response = await this.http.backend(endpoint, { ...request, allowStatuses: [429] });
530
+ }
531
+ return unwrap(response);
532
+ }
533
+ async emailSend({ email = this.env.OPENANY_DEV_EMAIL } = {}) {
534
+ email = normalizeEmail(email);
535
+ await this.store.update((s) => {
536
+ if (
537
+ s.emailChallenge?.email === email &&
538
+ s.emailChallenge.resendAt > this.now()
539
+ )
540
+ throw new CLIError("EMAIL_COOLDOWN", "Wait for the verification code resend cooldown to end.", {
541
+ retryAt: new Date(s.emailChallenge.resendAt).toISOString(),
542
+ });
543
+ s.emailChallenge = {
544
+ email,
545
+ status: "sending",
546
+ resendAt: this.now() + 60000,
547
+ };
548
+ });
549
+ const result = unwrap(
550
+ await this.http.backend("/api/v1/auth/cli/email-login/send", {
551
+ method: "POST",
552
+ json: { email },
553
+ }),
554
+ );
555
+ if (!result?.challengeId || !Number.isFinite(Date.parse(result.expiresAt)))
556
+ throw new CLIError("INVALID_RESPONSE", "The verification code challenge response is incomplete.");
557
+ if (result.registrationRequired !== undefined && typeof result.registrationRequired !== "boolean")
558
+ throw new CLIError("INVALID_RESPONSE", "The email registration requirement is invalid.");
559
+ if (result.registrationRequired) {
560
+ const url = typeof result.verificationUrl === "string" ? URL.parse(result.verificationUrl) : null;
561
+ const localHttp = url?.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
562
+ if (!url || (url.protocol !== "https:" && !localHttp) || url.username || url.password ||
563
+ url.pathname !== "/email-registration/authorize" || url.search ||
564
+ url.hash !== "#" + result.challengeId || /[\u0000-\u0020\u007f]/.test(result.verificationUrl))
565
+ throw new CLIError("INVALID_RESPONSE", "The service returned an invalid email registration link.");
566
+ }
567
+ await this.store.update((s) => {
568
+ s.emailChallenge = {
569
+ ...result,
570
+ email,
571
+ status: "prepared",
572
+ resendAt:
573
+ this.now() + Math.max(60, result.resendAfterSeconds || 60) * 1000,
574
+ };
575
+ });
576
+ if (result.registrationRequired) {
577
+ this.stderr.write("This email needs registration. Open this link in your browser and complete Turnstile:\n" +
578
+ result.verificationUrl + "\nThen verify the email verification code to finish registration. You may enter the temporary code in the agent form or chat for this login.\n");
579
+ }
580
+ return {
581
+ ...result,
582
+ email,
583
+ inboxSubject: "OpenAny CLI sign-in verification code",
584
+ };
585
+ }
586
+ async emailVerify({ email, challengeId, code, displayName, workspace } = {}) {
587
+ if (typeof code !== "string" || !/^\d{6}$/.test(code))
588
+ throw new CLIError(
589
+ "INPUT_INVALID",
590
+ "The verification code must be a six-digit string, preserving leading zeros.",
591
+ );
592
+ this.secrets.push(code);
593
+ const initialState = await this.store.read();
594
+ let pending = initialState.emailChallenge;
595
+ email = normalizeEmail(email || pending?.email || this.env.OPENANY_DEV_EMAIL);
596
+ challengeId ||= pending?.challengeId;
597
+ if (
598
+ !pending ||
599
+ pending.email !== email ||
600
+ pending.challengeId !== challengeId ||
601
+ pending.status !== "prepared" ||
602
+ Date.parse(pending.expiresAt) <= this.now()
603
+ )
604
+ throw new CLIError("CHALLENGE_NOT_PENDING", "Send a new email verification code first.");
605
+ if (
606
+ displayName !== undefined &&
607
+ (typeof displayName !== "string" || Buffer.byteLength(displayName) > 100)
608
+ )
609
+ throw new CLIError("INPUT_INVALID", "The display name must not exceed 100 bytes.");
610
+ await this.store.update((s) => {
611
+ if (
612
+ s.emailChallenge?.challengeId !== challengeId ||
613
+ s.emailChallenge.status !== "prepared"
614
+ )
615
+ throw new CLIError("CHALLENGE_NOT_PENDING", "The verification code has already been submitted.");
616
+ s.emailChallenge.status = "submitting";
617
+ });
618
+ let response;
619
+ try {
620
+ response = await this.http.backend("/api/v1/auth/cli/email-login/verify", {
621
+ method: "POST",
622
+ json: {
623
+ email,
624
+ challengeId,
625
+ code,
626
+ ...(displayName ? { displayName } : {}),
627
+ },
628
+ });
629
+ } catch (error) {
630
+ await this.store.update((s) => {
631
+ if (
632
+ s.emailChallenge?.challengeId === challengeId &&
633
+ s.emailChallenge.status === "submitting"
634
+ )
635
+ s.emailChallenge.status =
636
+ error.details?.status === 401 ||
637
+ (error.details?.status === 403 && error.code === "HUMAN_VERIFICATION_REQUIRED")
638
+ ? "prepared" : "uncertain";
639
+ });
640
+ throw error;
641
+ }
642
+ const result = unwrap(response);
643
+ if (
644
+ typeof result?.accessToken !== "string" ||
645
+ !Array.isArray(result.workspaces) ||
646
+ !result.user?.id
647
+ )
648
+ throw new CLIError("INVALID_RESPONSE", "The email verification response is missing the account or session.");
649
+ const selected =
650
+ workspace ||
651
+ (result.workspaces.length === 1 ? result.workspaces[0].id : undefined);
652
+ const session = {
653
+ email,
654
+ userId: result.user.id,
655
+ accessToken: result.accessToken,
656
+ workspaces: result.workspaces,
657
+ workspaceId: result.workspaces.some((w) => w.id === selected)
658
+ ? selected
659
+ : undefined,
660
+ cookies: mergeCookies([], response.headers, this.now()),
661
+ };
662
+ await this.saveSecret("email-session", session, {
663
+ operation: "verify",
664
+ challengeId,
665
+ email,
666
+ previousSession: fingerprint(initialState.sessions.email),
667
+ previousRefresh: initialState.emailRefreshPending,
668
+ });
669
+ return {
670
+ email,
671
+ workspaces: session.workspaces,
672
+ workspaceId: session.workspaceId,
673
+ workspaceRequired: !session.workspaceId,
674
+ saved: true,
675
+ };
676
+ }
677
+ async accountCredential({ email = this.env.OPENANY_DEV_EMAIL, userId } = {}) {
678
+ const state = await this.store.read();
679
+ const session = state.sessions.email;
680
+ if (!session?.accessToken || !session.userId || !session.email)
681
+ throw new CLIError(
682
+ "CONFIG_REQUIRED",
683
+ "Sign in with an email verification code first.",
684
+ {
685
+ missing: ["email_session"],
686
+ },
687
+ );
688
+ if (state.emailRefreshPending)
689
+ throw new CLIError(
690
+ "OPERATION_UNCERTAIN",
691
+ "Recover the pending session refresh or sign in again first.",
692
+ );
693
+ if (
694
+ (email && normalizeEmail(email) !== session.email.trim().toLowerCase()) ||
695
+ (userId && userId !== session.userId)
696
+ )
697
+ throw new CLIError(
698
+ "SESSION_CHANGED",
699
+ "The signed-in account differs from the authorized provider account.",
700
+ );
701
+ this.secrets.push(
702
+ session.accessToken,
703
+ ...(session.cookies || []).map((c) => c.value),
704
+ );
705
+ return {
706
+ token: session.accessToken,
707
+ userId: session.userId,
708
+ email: session.email,
709
+ };
710
+ }
711
+ async emailCredential({ workspace } = {}) {
712
+ const session = (await this.store.read()).sessions.email;
713
+ if (!session?.accessToken)
714
+ throw new CLIError("CONFIG_REQUIRED", "Sign in with an email verification code first.", {
715
+ missing: ["email_session"],
716
+ });
717
+ this.secrets.push(
718
+ session.accessToken,
719
+ ...(session.cookies || []).map((c) => c.value),
720
+ );
721
+ const selected = workspace || session.workspaceId;
722
+ if (!selected)
723
+ throw new CLIError("WORKSPACE_REQUIRED", "Select the workspace for this task.", {
724
+ workspaces: session.workspaces,
725
+ });
726
+ if (!session.workspaces?.some((w) => w.id === selected))
727
+ throw new CLIError(
728
+ "WORKSPACE_INVALID",
729
+ "This workspace does not belong to the signed-in account.",
730
+ );
731
+ return { token: session.accessToken, workspaceId: selected };
732
+ }
733
+ async selectWorkspace(workspace) {
734
+ await this.emailCredential({ workspace });
735
+ await this.store.update((s) => {
736
+ s.sessions.email.workspaceId = workspace;
737
+ });
738
+ return { workspaceId: workspace };
739
+ }
740
+ async emailRefresh() {
741
+ const session = (await this.store.read()).sessions.email;
742
+ if (!session?.cookies?.length)
743
+ throw new CLIError(
744
+ "CONFIG_REQUIRED",
745
+ "No email cookie is available to refresh; sign in again.",
746
+ { missing: ["email_refresh_cookie"] },
747
+ );
748
+ this.secrets.push(
749
+ session.accessToken,
750
+ ...session.cookies.map((c) => c.value),
751
+ );
752
+ if ((await this.store.read()).emailRefreshPending)
753
+ throw new CLIError(
754
+ "OPERATION_UNCERTAIN",
755
+ "The previous refresh may have rotated the cookie; check the recovery file or sign in again first.",
756
+ );
757
+ const csrfResponse = await this.http.backend("/api/v1/auth/csrf", {
758
+ credential: {
759
+ cookie: cookieHeader(session.cookies, "/api/v1/auth/csrf", this.now()),
760
+ },
761
+ });
762
+ const cookies = mergeCookies(
763
+ session.cookies,
764
+ csrfResponse.headers,
765
+ this.now(),
766
+ );
767
+ const csrf = unwrap(csrfResponse)?.csrfToken;
768
+ this.secrets.push(csrf, ...cookies.map((c) => c.value));
769
+ if (typeof csrf !== "string" || !csrf)
770
+ throw new CLIError("INVALID_RESPONSE", "No CSRF token was obtained.");
771
+ const reservation = randomUUID(),
772
+ prepared = { ...session, cookies };
773
+ await this.store.update((s) => {
774
+ if (s.emailRefreshPending)
775
+ throw new CLIError("OPERATION_UNCERTAIN", "An unconfirmed refresh operation already exists.");
776
+ if (fingerprint(s.sessions.email) !== fingerprint(session))
777
+ throw new CLIError(
778
+ "SESSION_CHANGED",
779
+ "The email session was updated by another operation; try again.",
780
+ );
781
+ s.sessions.email = prepared;
782
+ s.emailRefreshPending = reservation;
783
+ });
784
+ let response;
785
+ try {
786
+ response = await this.http.backend("/api/v1/auth/refresh", {
787
+ method: "POST",
788
+ json: {},
789
+ headers: { "X-CSRF-Token": csrf },
790
+ credential: {
791
+ cookie: cookieHeader(cookies, "/api/v1/auth/refresh", this.now()),
792
+ },
793
+ });
794
+ } catch (error) {
795
+ if (knownDenied(error))
796
+ await this.store.update((s) => {
797
+ if (s.emailRefreshPending === reservation)
798
+ delete s.emailRefreshPending;
799
+ });
800
+ throw error;
801
+ }
802
+ const result = unwrap(response);
803
+ if (typeof result?.accessToken !== "string" || !result.accessToken)
804
+ throw new CLIError("INVALID_RESPONSE", "The refresh response is missing the access token.");
805
+ const refreshed = {
806
+ ...session,
807
+ accessToken: result.accessToken,
808
+ cookies: mergeCookies(cookies, response.headers, this.now()),
809
+ };
810
+ await this.saveSecret("email-session", refreshed, {
811
+ operation: "refresh",
812
+ reservation,
813
+ previousSession: fingerprint(prepared),
814
+ });
815
+ return { refreshed: true, workspaceId: session.workspaceId };
816
+ }
817
+ async remoteKeys(operation, { workspace, label, id, limit, offset } = {}) {
818
+ const credential = await this.emailCredential({ workspace });
819
+ const path = "/api/v1/key-market/api-keys";
820
+ if (operation === "list") {
821
+ if (
822
+ (limit !== undefined &&
823
+ (!Number.isSafeInteger(Number(limit)) ||
824
+ Number(limit) < 1 ||
825
+ Number(limit) > 100)) ||
826
+ (offset !== undefined &&
827
+ (!Number.isSafeInteger(Number(offset)) || Number(offset) < 0))
828
+ )
829
+ throw new CLIError(
830
+ "INPUT_INVALID",
831
+ "limit must be between 1 and 100; offset must be a non-negative integer.",
832
+ );
833
+ return safeKeyResult(
834
+ unwrap(
835
+ await this.http.backend(path, {
836
+ credential,
837
+ query: { limit, offset },
838
+ }),
839
+ ),
840
+ );
841
+ }
842
+ if (operation === "get")
843
+ return safeKeyResult(
844
+ unwrap(
845
+ await this.http.backend(
846
+ `${path}/${encodeId(requireValue(id, "--id"))}`,
847
+ { credential },
848
+ ),
849
+ ),
850
+ );
851
+ if (operation === "revoke") {
852
+ requireValue(id, "--id");
853
+ const result = unwrap(
854
+ await this.http.backend(`${path}/${encodeId(id)}/revoke`, {
855
+ method: "POST",
856
+ json: {},
857
+ credential,
858
+ }),
859
+ );
860
+ await this.store.update((s) => {
861
+ const removed = s.keys
862
+ .filter(
863
+ (k) =>
864
+ k.metadata?.identity === "email" &&
865
+ k.metadata.workspaceId === credential.workspaceId &&
866
+ k.metadata.keyId === id,
867
+ )
868
+ .map((k) => k.label);
869
+ s.keys = s.keys.filter((k) => !removed.includes(k.label));
870
+ if (removed.includes(s.activeKey)) s.activeKey = null;
871
+ });
872
+ return safeKeyResult(result);
873
+ }
874
+ if (operation !== "create")
875
+ throw new CLIError("COMMAND_INVALID", "Unsupported server key operation.");
876
+ assertLabel(label);
877
+ const reservation = randomUUID();
878
+ await this.store.update((s) => {
879
+ if (s.keys.some((k) => k.label === label))
880
+ throw new CLIError(
881
+ "KEY_LABEL_EXISTS",
882
+ "The label already exists; use a new label to save the new key.",
883
+ );
884
+ s.keyReservations ||= {};
885
+ if (s.keyReservations[label])
886
+ throw new CLIError(
887
+ "OPERATION_UNCERTAIN",
888
+ "An unconfirmed creation request already exists for this label; check the account first.",
889
+ );
890
+ s.keyReservations[label] = reservation;
891
+ });
892
+ const userId = (await this.store.read()).sessions.email?.userId;
893
+ let result;
894
+ try {
895
+ result = unwrap(
896
+ await this.http.backend(path, {
897
+ method: "POST",
898
+ json: { label },
899
+ credential,
900
+ }),
901
+ );
902
+ } catch (error) {
903
+ if (knownDenied(error))
904
+ await this.store.update((s) => {
905
+ if (s.keyReservations?.[label] === reservation)
906
+ delete s.keyReservations[label];
907
+ });
908
+ throw error;
909
+ }
910
+ if (
911
+ typeof result?.plaintextKey !== "string" ||
912
+ !result.plaintextKey ||
913
+ !(result.id || result.keyId)
914
+ )
915
+ throw new CLIError(
916
+ "INVALID_RESPONSE",
917
+ "The creation result is missing key information; check the account before creating again.",
918
+ );
919
+ await this.saveSecret(
920
+ "email-key",
921
+ { ...result, label, workspaceId: credential.workspaceId },
922
+ {
923
+ operation: "create_key",
924
+ label,
925
+ reservation,
926
+ userId,
927
+ workspaceId: credential.workspaceId,
928
+ previousKey: fingerprint(null),
929
+ metadata: {
930
+ identity: "email",
931
+ workspaceId: credential.workspaceId,
932
+ keyId: result.id || result.keyId,
933
+ },
934
+ },
935
+ );
936
+ return {
937
+ ...safeKeyResult(result),
938
+ label,
939
+ saved: true,
940
+ active: true,
941
+ environmentOverride: Boolean(this.env.OPENANY_DEV_API_KEY),
942
+ };
943
+ }
944
+ }
945
+ export async function runAuth(args, ctx) {
946
+ const service = new AuthService(ctx);
947
+ const o = ctx.options;
948
+ if (args[0] === "auth" && args[1] === "recover")
949
+ return service.recover(requireValue(o.file, "--file"));
950
+ if (args[0] === "auth" && args[1] === "wallet")
951
+ return service.wallet("session", {
952
+ prepare: o.prepare,
953
+ challengeId: o["challenge-id"],
954
+ signature:
955
+ o.signature ||
956
+ (o["signature-file"]
957
+ ? (await readFile(o["signature-file"], "utf8")).trim()
958
+ : undefined),
959
+ });
960
+ if (args[0] === "auth" && args[1] === "email") {
961
+ if (args[2] === "send") return service.emailSend({ email: o.email });
962
+ if (args[2] === "verify")
963
+ return service.emailVerify({
964
+ email: o.email,
965
+ challengeId: o["challenge-id"],
966
+ code: o.code || ctx.env.OPENANY_DEV_EMAIL_CODE,
967
+ displayName: o["display-name"],
968
+ workspace: o.workspace,
969
+ });
970
+ if (args[2] === "refresh") return service.emailRefresh();
971
+ if (args[2] === "workspace")
972
+ return service.selectWorkspace(requireValue(o.workspace, "--workspace"));
973
+ }
974
+ if (args[0] === "keys" && args[1] === "remote")
975
+ return service.remoteKeys(args[2], {
976
+ workspace: o.workspace,
977
+ label: o.label,
978
+ id: o.id,
979
+ limit: o.limit,
980
+ offset: o.offset,
981
+ });
982
+ if (args[0] === "keys" && ["create", "rotate"].includes(args[1])) {
983
+ if (o.identity !== "wallet")
984
+ throw new CLIError(
985
+ "INPUT_REQUIRED",
986
+ "Use --identity wallet for wallet operations or keys remote for email operations.",
987
+ );
988
+ return service.wallet(args[1] === "create" ? "create_key" : "rotate_key", {
989
+ prepare: o.prepare,
990
+ challengeId: o["challenge-id"],
991
+ signature:
992
+ o.signature ||
993
+ (o["signature-file"]
994
+ ? (await readFile(o["signature-file"], "utf8")).trim()
995
+ : undefined),
996
+ label: o.label || "main",
997
+ expectedKeyId: o["expected-key-id"],
998
+ });
999
+ }
1000
+ throw new CLIError("COMMAND_INVALID", "Unknown identity management command.");
1001
+ }