nameslink 1.0.2 → 1.0.3

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.
package/README.md CHANGED
@@ -300,6 +300,10 @@ For a remote shell that should not open a browser automatically:
300
300
  nameslink login --no-browser
301
301
  ```
302
302
 
303
+ If the browser launcher fails, the CLI offers the manual authorization URL for the same login
304
+ instead of silently waiting. Remote shells still need a route to the CLI's loopback callback;
305
+ `--no-browser` does not add cross-device login. Keep authorization URLs private.
306
+
303
307
  For CI, configure a NamesLink AK/SK instead:
304
308
 
305
309
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nameslink",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "NamesLink command-line client for domains, DNS, intelligent site building, Security Acceleration and automation",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -437,6 +437,9 @@ export async function main(argv, runtime = {}) {
437
437
  const globalShortCircuit = (parsed.options.help && command !== 'help')
438
438
  || (parsed.options.version && command !== 'version');
439
439
  if (!globalShortCircuit) assertPositionalArity(command, parsed.positionals);
440
+ if (parsed.options.help || (command === 'help' && !parsed.options.version)) {
441
+ return help(i18n, parsed.options.json);
442
+ }
440
443
  if (command === 'version' || parsed.options.version) {
441
444
  if (parsed.options.check) {
442
445
  if (!parsed.options.json) stdout.write(`${cliVersion}\n`);
@@ -488,7 +491,6 @@ export async function main(argv, runtime = {}) {
488
491
  })}\n`);
489
492
  return;
490
493
  }
491
- if (command === 'help' || parsed.options.help) return help(i18n, parsed.options.json);
492
494
  // An interrupted cross-media credential commit may deliberately fail closed. The three
493
495
  // credential-replacement routes must still be able to repair it; ordinary commands never get
494
496
  // that bypass and therefore cannot transmit an uncommitted/mismatched token.
@@ -1694,7 +1696,13 @@ function authStatusSummary(config) {
1694
1696
  * <li>任何失败静默:提醒失败不能影响一条已经成功的命令的退出码。</li>
1695
1697
  * </ul>
1696
1698
  */
1699
+ function helpRequested(argv) {
1700
+ const { positionals, options } = parseArgs(argv);
1701
+ return options.help || (positionals.length === 0 && !options.version) || positionals[0] === 'help';
1702
+ }
1703
+
1697
1704
  export async function remindAboutUpdate(argv = [], i18n, runtime = {}) {
1705
+ if (helpRequested(argv)) return;
1698
1706
  const environment = runtime.environment || process.env;
1699
1707
  const write = runtime.writeReminder || ((value) => stderr.write(value));
1700
1708
  const interactive = runtime.interactive ?? Boolean(stderr.isTTY);
@@ -1748,6 +1756,7 @@ export async function remindAboutUpdate(argv = [], i18n, runtime = {}) {
1748
1756
  * 否则调用方解析 stderr 时直接抛错。stdout 全程不受影响。
1749
1757
  */
1750
1758
  export async function provisionSkillQuietly(argv = [], i18n, runtime = {}) {
1759
+ if (helpRequested(argv)) return;
1751
1760
  const environment = runtime.environment || process.env;
1752
1761
  const write = runtime.writeReminder || ((value) => stderr.write(value));
1753
1762
  if (environment.NAMESLINK_NO_SKILL_NOTIFIER === '1') return;
package/src/domain.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  import { stdout } from 'node:process';
2
+ import { isIP } from 'node:net';
3
+ import { domainToASCII } from 'node:url';
4
+ import { createI18n } from './i18n.mjs';
2
5
 
3
6
  const API_VERSION = 'domain-discovery.nameslink.com/v1';
4
7
  const PORTFOLIO_API_VERSION = 'domain-portfolio.nameslink.com/v1';
@@ -36,7 +39,7 @@ export async function domainCommand(client, positionals, options, i18n, runtime
36
39
  if (domains.length === 0 || domains.length > MAX_CHECK_DOMAINS) {
37
40
  throw new Error(i18n.t('error.domainCheckUsage', { max: MAX_CHECK_DOMAINS }));
38
41
  }
39
- const result = await checkDomains(client, domains);
42
+ const result = await checkDomains(client, domains, i18n);
40
43
  return printDomainCheck(result, options.json, i18n, runtime.write);
41
44
  }
42
45
  throw new Error(i18n.t('error.domainUsage'));
@@ -80,19 +83,51 @@ export async function searchDomains(client, keyword, { category, limit = DEFAULT
80
83
  const sourceCandidates = Array.isArray(searchResponse?.data)
81
84
  ? searchResponse.data.slice(0, limit)
82
85
  : [];
86
+ // Share exact reads within this CLI invocation. Never change the public search/recommendation
87
+ // contracts, ranking, or keyword handling to fill a terminal presentation field.
88
+ const availabilityReads = new Map();
89
+ const readAvailability = (domainName) => {
90
+ const key = String(domainName).toLowerCase();
91
+ if (!availabilityReads.has(key)) {
92
+ availabilityReads.set(key, client.publicRequest(
93
+ 'POST', '/domain/registry/check-domain/check', { domainName },
94
+ ));
95
+ }
96
+ return availabilityReads.get(key);
97
+ };
83
98
  const checked = await Promise.all(sourceCandidates.map(async (candidate) => {
84
99
  if (candidate?.onSale) return normalizeSearchCandidate(candidate, null);
85
100
  try {
86
- const availability = await client.publicRequest(
87
- 'POST',
88
- '/domain/registry/check-domain/check',
89
- { domainName: candidate.domainName },
90
- );
101
+ const availability = await readAvailability(candidate.domainName);
91
102
  return normalizeSearchCandidate(candidate, availability);
92
103
  } catch (error) {
93
104
  return normalizeSearchCandidate(candidate, null, error);
94
105
  }
95
106
  }));
107
+ const recommendations = await Promise.all(
108
+ (Array.isArray(recommendationsResponse?.cards) ? recommendationsResponse.cards : [])
109
+ .map(async (card) => {
110
+ if (card.onSale || !card.domainName
111
+ || !card.prices?.some((price) => price.price != null && !price.currency)) {
112
+ return normalizeRecommendation(card);
113
+ }
114
+ try {
115
+ const exact = await readAvailability(card.domainName);
116
+ const prices = card.prices.map((price) => {
117
+ if (price.currency || price.price == null) return price;
118
+ const match = exact?.prices?.find((item) => item.currency
119
+ && item.action === price.action && item.period === price.period
120
+ && item.price != null && Number(item.price) === Number(price.price));
121
+ return match ? { ...price, currency: match.currency } : price;
122
+ });
123
+ return normalizeRecommendation({ ...card, prices });
124
+ } catch {
125
+ // Discovery remains useful when an exact read fails. Unknown currency is explicit in
126
+ // human output; never assume USD or combine a currency with a different priced item.
127
+ return normalizeRecommendation(card);
128
+ }
129
+ }),
130
+ );
96
131
  return {
97
132
  apiVersion: API_VERSION,
98
133
  mode: 'SEARCH',
@@ -101,14 +136,22 @@ export async function searchDomains(client, keyword, { category, limit = DEFAULT
101
136
  priceBinding: 'INDICATIVE',
102
137
  total: numberOrNull(searchResponse?.total),
103
138
  recommendationsStatus: recommendationsResponse ? 'AVAILABLE' : 'UNAVAILABLE',
104
- recommendations: Array.isArray(recommendationsResponse?.cards)
105
- ? recommendationsResponse.cards.map(normalizeRecommendation)
106
- : [],
139
+ recommendations,
107
140
  candidates: checked,
108
141
  };
109
142
  }
110
143
 
111
- export async function checkDomains(client, domains) {
144
+ export async function checkDomains(client, domains, i18n = createI18n('en-US')) {
145
+ // Exact-check input only: search accepts brand phrases, Unicode and punctuation and deliberately
146
+ // does not share this validator. Reject the entire malformed batch before making any requests.
147
+ const invalid = domains.filter((domain) => !validDomainName(domain));
148
+ if (invalid.length > 0) {
149
+ const message = i18n.t('error.domainInvalidName', { domains: invalid.join(', ') });
150
+ const error = new Error(message);
151
+ error.body = { code: 'Cli.Domain.InvalidName', message, data: { domains: invalid } };
152
+ error.machineReadable = true;
153
+ throw error;
154
+ }
112
155
  const settled = await Promise.all(domains.map(async (domainName) => {
113
156
  try {
114
157
  const result = await client.publicRequest(
@@ -129,6 +172,14 @@ export async function checkDomains(client, domains) {
129
172
  };
130
173
  }
131
174
 
175
+ function validDomainName(domain) {
176
+ if (typeof domain !== 'string' || /[\s\u0000-\u001f\u007f/:@?#%\\]/u.test(domain)) return false;
177
+ const ascii = domainToASCII(domain).replace(/\.$/u, '');
178
+ const labels = ascii.split('.');
179
+ return ascii.length <= 253 && isIP(ascii) === 0 && labels.length >= 2
180
+ && labels.every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/iu.test(label));
181
+ }
182
+
132
183
  // Only fields the domain-portfolio API returns under both credential types are exposed, so a
133
184
  // listing does not change shape with the credential in use. The registrar and holder-contact
134
185
  // template are deliberately omitted: neither belongs in a portfolio listing, and the contact
@@ -371,7 +422,7 @@ function printDomainCheck(result, json, i18n, write = (value) => stdout.write(va
371
422
  function writeDomainLine(item, i18n, write, label) {
372
423
  const status = i18n.t(`code.${item.status}`);
373
424
  const price = item.displayPrice ?? item.registerPrice;
374
- const priceText = price == null ? '-' : amountWithCurrency(price, item.registerCurrency);
425
+ const priceText = price == null ? '-' : amountWithCurrency(price, item.registerCurrency, i18n);
375
426
  const premium = item.premium === true
376
427
  ? i18n.t('domain.premium')
377
428
  : item.premium === false
@@ -381,12 +432,12 @@ function writeDomainLine(item, i18n, write, label) {
381
432
  const prefix = label ? `[${i18n.t(`code.${label}`)}] ` : '';
382
433
  const renewal = item.renewPrice == null
383
434
  ? ''
384
- : ` | ${i18n.t('domain.renewPrice')} ${amountWithCurrency(item.renewPrice, item.renewCurrency)}`;
435
+ : ` | ${i18n.t('domain.renewPrice')} ${amountWithCurrency(item.renewPrice, item.renewCurrency, i18n)}`;
385
436
  write(` ${prefix}${item.domainName || '-'} | ${status} | ${i18n.t('domain.displayPrice')} ${priceText}${renewal} | ${premium} | ${eligibility}\n`);
386
437
  if (item.tldDescription) write(` ${i18n.t('domain.tldPolicy')}${i18n.colon}${item.tldDescription}\n`);
387
438
  if (item.reason) write(` ${i18n.t('domain.reason')}${i18n.colon}${item.reason}\n`);
388
439
  }
389
440
 
390
- function amountWithCurrency(amount, currency) {
391
- return currency ? `${currency} ${amount}` : String(amount);
441
+ function amountWithCurrency(amount, currency, i18n) {
442
+ return currency ? `${currency} ${amount}` : i18n.t('domain.currencyUnknown', { amount });
392
443
  }
package/src/i18n.mjs CHANGED
@@ -128,6 +128,9 @@ const EN_US = {
128
128
  'error.domainUsage': 'Usage: nameslink domain list | nameslink domain search <keyword-or-domain> | nameslink domain check <domain> [more-domains...]',
129
129
  'error.domainSearchUsage': 'Usage: nameslink domain search <keyword-or-domain> [--category <category>] [--limit 10]',
130
130
  'error.domainCheckUsage': 'Usage: nameslink domain check <domain> [more-domains...] (up to {max})',
131
+ 'error.domainInvalidName': 'Invalid domain name: {domains}. Enter a domain such as example.com, without a URL, spaces, or empty labels.',
132
+ 'domain.currencyUnknown': '{amount} (currency unavailable)',
133
+ 'apiError.Cli.Browser.Unavailable': 'The browser could not be opened. Retry from a session with a working browser.',
131
134
  'error.domainLimit': '--limit must be an integer from {min} to {max}.',
132
135
  'error.domainInteger': '--{name} must be an integer from {min} to {max}.',
133
136
  'error.domainSuffixFilter': '--suffix must be a domain suffix such as com or com.cn, not "{suffix}".',
@@ -210,6 +213,7 @@ const EN_US = {
210
213
  'The top-up has not been credited yet. Do not create or pay another top-up. Check `{balanceCommand}`; after the balance arrives, continue the same reviewed purchase with `{resumeCommand}`.',
211
214
  'login.opening': 'Opening NamesLink authorization in your browser…',
212
215
  'login.openingManual': 'Open this NamesLink authorization URL in your browser:',
216
+ 'login.browserUnavailable': 'Could not open a browser automatically. Continue with the URL below. A remote shell needs access to this CLI process\'s loopback callback; --no-browser does not provide cross-device login.',
213
217
  'login.openingHint':
214
218
  'The page shows which account is about to be authorized. Same account: confirm. Different account: choose "Use another account" on that page - signing out of the CLI does not sign the browser out.',
215
219
  'login.success': 'Logged in to NamesLink as {accountNo}.',
@@ -858,6 +862,9 @@ const ZH_CN = {
858
862
  'error.domainUsage': '用法:nameslink domain list | nameslink domain search <关键词或域名> | nameslink domain check <域名> [更多域名...]',
859
863
  'error.domainSearchUsage': '用法:nameslink domain search <关键词或域名> [--category <分类>] [--limit 10]',
860
864
  'error.domainCheckUsage': '用法:nameslink domain check <域名> [更多域名...](最多 {max} 个)',
865
+ 'error.domainInvalidName': '域名格式不正确:{domains}。请输入 example.com 这样的域名,不要包含网址、空格或空标签。',
866
+ 'domain.currencyUnknown': '{amount}(币种暂不可用)',
867
+ 'apiError.Cli.Browser.Unavailable': '无法打开浏览器,请在浏览器可用的会话中重试。',
861
868
  'error.domainLimit': '--limit 必须是 {min}~{max} 的整数。',
862
869
  'error.domainInteger': '--{name} 必须是 {min}~{max} 的整数。',
863
870
  'error.domainSuffixFilter': '--suffix 需要是域名后缀(如 com、com.cn),当前值无效:"{suffix}"。',
@@ -937,6 +944,7 @@ const ZH_CN = {
937
944
  '充值尚未到账。请勿创建或支付另一笔充值。先运行 `{balanceCommand}` 查余额;到账后运行 `{resumeCommand}` 继续同一份已审核购买。',
938
945
  'login.opening': '正在打开 NamesLink 授权页…',
939
946
  'login.openingManual': '请在浏览器中打开以下 NamesLink 授权链接:',
947
+ 'login.browserUnavailable': '无法自动打开浏览器,请用下方链接继续。远程终端仍需能访问此 CLI 进程的本机回调,--no-browser 不代表支持跨设备登录。',
940
948
  'login.openingHint': '页面上会写明将要授权哪个账号。同一账号就直接确认;要换账号请点页面上的「换其他账号」——退出 CLI 并不会退出浏览器登录态。',
941
949
  'login.success': 'NamesLink 登录成功,账号:{accountNo}。',
942
950
  'logout.success':
package/src/oauth.mjs CHANGED
@@ -15,6 +15,8 @@ export async function browserLogin(endpoint, i18n = createI18n('en-US'), options
15
15
  const challenge = createHash('sha256').update(verifier).digest('base64url');
16
16
  const state = randomBytes(16).toString('hex');
17
17
  const callback = deferred();
18
+ // A callback may arrive (or reject) before the browser launcher exits.
19
+ callback.promise.catch(() => {});
18
20
  let completed = false;
19
21
  const server = createServer((request, response) => {
20
22
  const url = new URL(request.url, 'http://127.0.0.1');
@@ -52,23 +54,33 @@ export async function browserLogin(endpoint, i18n = createI18n('en-US'), options
52
54
  options.journeyContext,
53
55
  );
54
56
  const browserUrl = authorize.toString();
55
- const browserOpened = options.openBrowser !== false;
56
- if (options.json) {
57
- const writeProgress = options.writeProgress || ((value) => process.stderr.write(value));
58
- writeProgress(`${JSON.stringify({
59
- type: 'oauth.authorization',
60
- browserOpened,
61
- nextAction: browserOpened ? 'COMPLETE_BROWSER_SIGN_IN' : 'OPEN_AUTHORIZATION_URL',
62
- ...(browserOpened ? {} : { authorizationUrl: browserUrl }),
63
- })}\n`);
64
- } else {
65
- process.stdout.write(`${i18n.t(browserOpened ? 'login.opening' : 'login.openingManual')}\n`);
66
- if (!browserOpened) process.stdout.write(`${browserUrl}\n`);
67
- process.stdout.write(`${i18n.t('login.openingHint')}\n`);
68
- }
69
- if (browserOpened) (options.openBrowserFn || openBrowser)(browserUrl);
70
57
  let code;
71
58
  try {
59
+ let browserOpened = options.openBrowser !== false;
60
+ let launchFailed = false;
61
+ if (browserOpened) {
62
+ try {
63
+ await (options.openBrowserFn || openBrowser)(browserUrl);
64
+ } catch {
65
+ browserOpened = false;
66
+ launchFailed = true;
67
+ }
68
+ }
69
+ if (options.json) {
70
+ const writeProgress = options.writeProgress || ((value) => process.stderr.write(value));
71
+ writeProgress(`${JSON.stringify({
72
+ type: 'oauth.authorization',
73
+ browserOpened,
74
+ nextAction: browserOpened ? 'COMPLETE_BROWSER_SIGN_IN' : 'OPEN_AUTHORIZATION_URL',
75
+ ...(browserOpened ? {} : { authorizationUrl: browserUrl }),
76
+ ...(launchFailed ? { reason: 'BROWSER_UNAVAILABLE' } : {}),
77
+ })}\n`);
78
+ } else {
79
+ if (launchFailed) process.stdout.write(`${i18n.t('login.browserUnavailable')}\n`);
80
+ process.stdout.write(`${i18n.t(browserOpened ? 'login.opening' : 'login.openingManual')}\n`);
81
+ if (!browserOpened) process.stdout.write(`${browserUrl}\n`);
82
+ process.stdout.write(`${i18n.t('login.openingHint')}\n`);
83
+ }
72
84
  code = await waitForOAuthCallback(callback.promise, 300_000, setTimeout, clearTimeout, i18n);
73
85
  } finally {
74
86
  await new Promise((resolve) => server.close(resolve));
@@ -279,9 +291,18 @@ function escapeHtml(value) {
279
291
  })[character]);
280
292
  }
281
293
 
282
- export function openBrowser(url) {
294
+ export function openBrowser(url, execute = execFile) {
283
295
  const { command, args } = browserLaunchSpec(url);
284
- execFile(command, args, { windowsHide: true }, () => {});
296
+ return new Promise((resolve, reject) => {
297
+ execute(command, args, { windowsHide: true, timeout: 10_000 }, (error) => {
298
+ if (!error) return resolve();
299
+ // execFile errors contain argv, including the one-time handoff URL. Never propagate them.
300
+ const failure = new Error('The browser could not be opened.');
301
+ failure.body = { code: 'Cli.Browser.Unavailable' };
302
+ failure.machineReadable = true;
303
+ reject(failure);
304
+ });
305
+ });
285
306
  }
286
307
 
287
308
  export function browserLaunchSpec(url, platform = process.platform) {