nameslink 1.1.16 → 1.1.18
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 +6 -0
- package/bin/nameslink.mjs +5 -2
- package/package.json +3 -2
- package/src/cli.mjs +37 -9
- package/src/client.mjs +97 -12
- package/src/config.mjs +51 -3
- package/src/credential-store.mjs +55 -10
- package/src/domain.mjs +118 -17
- package/src/hosted-site.mjs +35 -11
- package/src/i18n.mjs +48 -11
- package/src/oauth.mjs +20 -7
- package/src/startup-telemetry.mjs +118 -0
package/README.md
CHANGED
|
@@ -669,3 +669,9 @@ The bootstrap address and operation semantics remain stable; resource locations
|
|
|
669
669
|
Only endpoint-relative URI templates are accepted. Credentials are signed/sent after resolution; redirects remain disabled.
|
|
670
670
|
A missing GET route can refresh discovery once. Writes are never replayed to follow a moved route; recover the original receipt with the original request key.
|
|
671
671
|
The existing domain-portfolio and OAuth login protocols are outside this resource migration.
|
|
672
|
+
|
|
673
|
+
### Startup diagnostics
|
|
674
|
+
|
|
675
|
+
The CLI sends best-effort first-run and sign-in checkpoints to NamesLink. It sends fixed
|
|
676
|
+
event names and random journey IDs, without credentials, verification codes, or command
|
|
677
|
+
arguments. Set `NAMESLINK_TELEMETRY_DISABLED=1` to turn off these client reports.
|
package/bin/nameslink.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { main, provisionSkillQuietly, remindAboutUpdate } from '../src/cli.mjs';
|
|
4
|
+
import { createStartupTelemetry } from '../src/startup-telemetry.mjs';
|
|
4
5
|
import { loadLanguagePreference, saveLanguagePreference } from '../src/config.mjs';
|
|
5
6
|
import { createI18n, formatRecoveryGuidance, languageOptionFromArgv, localizeError } from '../src/i18n.mjs';
|
|
6
7
|
|
|
@@ -66,8 +67,9 @@ if (i18n && requestedLanguage) {
|
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
const startupTelemetry = createStartupTelemetry();
|
|
69
71
|
if (i18n)
|
|
70
|
-
main(argv, { i18n })
|
|
72
|
+
main(argv, { i18n, startupTelemetry })
|
|
71
73
|
// 只在命令成功后提醒,且提醒自身吞掉所有异常:一条已经跑成功的命令的退出码不能被它改写。
|
|
72
74
|
.then(() => remindAboutUpdate(argv, i18n))
|
|
73
75
|
.then(() => provisionSkillQuietly(argv, i18n))
|
|
@@ -79,4 +81,5 @@ if (i18n)
|
|
|
79
81
|
}
|
|
80
82
|
reportError(error, i18n);
|
|
81
83
|
process.exitCode = 1;
|
|
82
|
-
})
|
|
84
|
+
})
|
|
85
|
+
.finally(() => startupTelemetry?.drain());
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nameslink",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.18",
|
|
4
4
|
"description": "NamesLink command-line client for domains, DNS, intelligent site building, Security Acceleration and automation",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -35,7 +35,8 @@
|
|
|
35
35
|
"skill/nameslink/SKILL.md",
|
|
36
36
|
"skill/nameslink/agents/openai.yaml",
|
|
37
37
|
"README.md",
|
|
38
|
-
"scripts/postinstall.mjs"
|
|
38
|
+
"scripts/postinstall.mjs",
|
|
39
|
+
"src/startup-telemetry.mjs"
|
|
39
40
|
],
|
|
40
41
|
"engines": {
|
|
41
42
|
"node": ">=20"
|
package/src/cli.mjs
CHANGED
|
@@ -7,9 +7,10 @@ import { stdin, stderr, stdout } from 'node:process';
|
|
|
7
7
|
import { ApiError, NamesLinkClient } from './client.mjs';
|
|
8
8
|
import { detectShell, generateCompletion, installCompletion } from './completion.mjs';
|
|
9
9
|
import {
|
|
10
|
-
clearCredentials, DEFAULT_ENDPOINT, loadConfig, saveConfig,
|
|
11
|
-
saveSkillCheckMetadata, saveUpdateCheckMetadata, validateEndpoint,
|
|
10
|
+
clearCredentials, DEFAULT_ENDPOINT, loadConfig, saveConfig, saveDiscoveryCacheEntry,
|
|
11
|
+
saveJourneyMetadata, saveSkillCheckMetadata, saveUpdateCheckMetadata, validateEndpoint,
|
|
12
12
|
} from './config.mjs';
|
|
13
|
+
import { classifyCredentialSaveError } from './credential-store.mjs';
|
|
13
14
|
import { createI18n, formatCode, formatContractLabel, formatDisplayLabel, formatRecoveryGuidance, localizeServerMessage } from './i18n.mjs';
|
|
14
15
|
import { browserLogin, browserMfa } from './oauth.mjs';
|
|
15
16
|
import { completeProfile } from './profile.mjs';
|
|
@@ -420,6 +421,7 @@ export async function main(argv, runtime = {}) {
|
|
|
420
421
|
const i18n = runtime.i18n || createI18n(parsed.options.lang);
|
|
421
422
|
const noCommand = parsed.positionals.length === 0;
|
|
422
423
|
const command = parsed.positionals.shift() || 'help';
|
|
424
|
+
const firstRunJourney = await runtime.startupTelemetry?.firstRun(parsed.options.endpoint, 'unknown', cliVersion);
|
|
423
425
|
const interactive = runtime.interactive ?? Boolean(stdout.isTTY && !parsed.options.json);
|
|
424
426
|
if (noCommand && !parsed.options.help && !parsed.options.version && interactive) {
|
|
425
427
|
const write = runtime.write || ((value) => stdout.write(value));
|
|
@@ -504,19 +506,29 @@ export async function main(argv, runtime = {}) {
|
|
|
504
506
|
config.endpointPersistent = endpointSelection.persistent;
|
|
505
507
|
}
|
|
506
508
|
const invocation = prepareJourney(
|
|
507
|
-
config,
|
|
509
|
+
config.journey ? config : { journey: firstRunJourney },
|
|
508
510
|
journeyCommand.replaceAll(' ', ':'),
|
|
509
511
|
cliVersion,
|
|
510
512
|
);
|
|
511
513
|
config.journey = invocation.journey;
|
|
512
514
|
if (command === 'login') {
|
|
515
|
+
const observe = (checkpoint, metadata) =>
|
|
516
|
+
runtime.startupTelemetry?.report(config.endpoint, invocation.context, checkpoint, metadata);
|
|
517
|
+
observe('LOGIN_STARTED');
|
|
513
518
|
config.credentials = await browserLogin(config.endpoint, i18n, {
|
|
514
519
|
openBrowser: parsed.options['no-browser'] !== true,
|
|
515
520
|
json: parsed.options.json,
|
|
516
521
|
writeProgress: runtime.writeProgress,
|
|
517
522
|
journeyContext: invocation.context,
|
|
523
|
+
observe,
|
|
518
524
|
});
|
|
519
|
-
|
|
525
|
+
try {
|
|
526
|
+
await saveConfig(config);
|
|
527
|
+
} catch (error) {
|
|
528
|
+
observe('CREDENTIAL_SAVE_FAILED', classifyCredentialSaveError(error));
|
|
529
|
+
throw error;
|
|
530
|
+
}
|
|
531
|
+
observe('CREDENTIAL_SAVED');
|
|
520
532
|
if (parsed.options.json) {
|
|
521
533
|
return print({ loggedIn: true, ...authStatusSummary(config) }, true);
|
|
522
534
|
}
|
|
@@ -527,7 +539,7 @@ export async function main(argv, runtime = {}) {
|
|
|
527
539
|
// keeps related commands in one journey while rotating stale/week-long profiles deterministically.
|
|
528
540
|
await saveJourneyMetadata(config.journey);
|
|
529
541
|
if (command === 'whoami') return printAuthStatus(config, parsed.options.json, i18n);
|
|
530
|
-
if (command === 'doctor') return doctor(config, parsed.options, i18n);
|
|
542
|
+
if (command === 'doctor') return doctor(config, parsed.options, i18n, invocation.context);
|
|
531
543
|
if (command === 'auth') {
|
|
532
544
|
const subcommand = parsed.positionals.shift();
|
|
533
545
|
if (subcommand === 'status') return printAuthStatus(config, parsed.options.json, i18n);
|
|
@@ -538,7 +550,7 @@ export async function main(argv, runtime = {}) {
|
|
|
538
550
|
let revocationError;
|
|
539
551
|
try {
|
|
540
552
|
if (config.credentials?.type === 'oauth' && config.credentials.refreshToken) {
|
|
541
|
-
await
|
|
553
|
+
await createClient(config, i18n, invocation.context).request(
|
|
542
554
|
'POST', resource('mfa.revoke'), {});
|
|
543
555
|
}
|
|
544
556
|
} catch (error) { revocationError = error; }
|
|
@@ -555,7 +567,7 @@ export async function main(argv, runtime = {}) {
|
|
|
555
567
|
return;
|
|
556
568
|
}
|
|
557
569
|
|
|
558
|
-
const client =
|
|
570
|
+
const client = createClient(config, i18n, invocation.context);
|
|
559
571
|
if (!parsed.options['mfa-stdin'] && !parsed.options['mfa-code-file'] && !parsed.options['mfa-challenge']) {
|
|
560
572
|
client.mfaBrowser = (url, { expiresAt } = {}) => browserMfa(url, i18n, {
|
|
561
573
|
json: parsed.options.json, expiresAt, openBrowser: parsed.options['no-browser'] !== true,
|
|
@@ -1538,7 +1550,23 @@ function jsonProgressOutput(type, runtime = {}) {
|
|
|
1538
1550
|
};
|
|
1539
1551
|
}
|
|
1540
1552
|
|
|
1541
|
-
|
|
1553
|
+
function createClient(config, i18n, journeyContext) {
|
|
1554
|
+
return new NamesLinkClient(config, i18n, journeyContext, {
|
|
1555
|
+
saveDiscoveryCache: async (endpoint, entry) => {
|
|
1556
|
+
if (!(await saveDiscoveryCacheEntry(endpoint, entry))) return;
|
|
1557
|
+
if (!Object.isFrozen(config)) {
|
|
1558
|
+
const next = config.discoveryCache && typeof config.discoveryCache === 'object'
|
|
1559
|
+
? { ...config.discoveryCache }
|
|
1560
|
+
: {};
|
|
1561
|
+
if (entry) next[endpoint] = entry;
|
|
1562
|
+
else delete next[endpoint];
|
|
1563
|
+
config.discoveryCache = Object.keys(next).length > 0 ? next : undefined;
|
|
1564
|
+
}
|
|
1565
|
+
},
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
async function doctor(config, options, i18n, journeyContext) {
|
|
1542
1570
|
const summary = authStatusSummary(config);
|
|
1543
1571
|
const [releaseChannel, skillStatus] = await Promise.all([
|
|
1544
1572
|
checkForUpdate(cliVersion),
|
|
@@ -1564,7 +1592,7 @@ async function doctor(config, options, i18n) {
|
|
|
1564
1592
|
printReleaseChannelDiagnostic(releaseChannel, i18n);
|
|
1565
1593
|
return;
|
|
1566
1594
|
}
|
|
1567
|
-
const client =
|
|
1595
|
+
const client = createClient(config, i18n, journeyContext);
|
|
1568
1596
|
try {
|
|
1569
1597
|
const capabilities = publicCapabilitiesContract(
|
|
1570
1598
|
await client.request('GET', resource('capabilities.get')),
|
package/src/client.mjs
CHANGED
|
@@ -8,6 +8,36 @@ import { setTimeout as delay } from 'node:timers/promises';
|
|
|
8
8
|
const require = createRequire(import.meta.url);
|
|
9
9
|
const { version: packageVersion } = require('../package.json');
|
|
10
10
|
export const USER_AGENT = `nameslink-cli/${packageVersion}`;
|
|
11
|
+
export const DISCOVERY_CACHE_TTL_MS = 10 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
function isSafeHrefTemplate(template) {
|
|
14
|
+
return typeof template === 'string'
|
|
15
|
+
&& /^\/(?!\/)[A-Za-z0-9_/{}/.-]*$/.test(template)
|
|
16
|
+
&& !template.includes('..')
|
|
17
|
+
&& !template.includes('//');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sanitizeDiscoveryOperations(operations) {
|
|
21
|
+
if (!operations || typeof operations !== 'object' || Array.isArray(operations)) return null;
|
|
22
|
+
const sanitized = {};
|
|
23
|
+
for (const [name, descriptor] of Object.entries(operations)) {
|
|
24
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(name)) continue;
|
|
25
|
+
if (!descriptor || typeof descriptor !== 'object' || Array.isArray(descriptor)) continue;
|
|
26
|
+
if (typeof descriptor.method !== 'string' || !/^[A-Z]{3,12}$/.test(descriptor.method)) continue;
|
|
27
|
+
if (!isSafeHrefTemplate(descriptor.hrefTemplate)) continue;
|
|
28
|
+
sanitized[name] = { method: descriptor.method, hrefTemplate: descriptor.hrefTemplate };
|
|
29
|
+
}
|
|
30
|
+
return Object.keys(sanitized).length > 0 ? sanitized : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readCachedDiscovery(config, endpoint, now) {
|
|
34
|
+
const entry = config?.discoveryCache?.[endpoint];
|
|
35
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;
|
|
36
|
+
const fetchedAt = Number(entry.fetchedAt);
|
|
37
|
+
if (!Number.isFinite(fetchedAt) || now < fetchedAt || now - fetchedAt >= DISCOVERY_CACHE_TTL_MS) return null;
|
|
38
|
+
const operations = sanitizeDiscoveryOperations(entry.operations);
|
|
39
|
+
return operations ? { operations } : null;
|
|
40
|
+
}
|
|
11
41
|
|
|
12
42
|
// Domain-separated proof derived from the already-secured OAuth session. Never derive from an
|
|
13
43
|
// OTP, an access token, account number or an IP. Refresh keeps this secret stable across processes;
|
|
@@ -154,12 +184,16 @@ async function fetchOrThrow(config, endpoint, url, init) {
|
|
|
154
184
|
}
|
|
155
185
|
|
|
156
186
|
export class NamesLinkClient {
|
|
157
|
-
constructor(config, i18n = createI18n('en-US'), journeyContext) {
|
|
187
|
+
constructor(config, i18n = createI18n('en-US'), journeyContext, options = {}) {
|
|
158
188
|
this.config = config;
|
|
159
189
|
this.i18n = i18n;
|
|
160
190
|
this.endpoint = validateEndpoint(config.endpoint).endpoint;
|
|
161
191
|
this.csrfToken = null;
|
|
162
192
|
this.csrfCookie = null;
|
|
193
|
+
this.saveDiscoveryCache = typeof options.saveDiscoveryCache === 'function' ? options.saveDiscoveryCache : null;
|
|
194
|
+
this.now = typeof options.now === 'function' ? options.now : Date.now;
|
|
195
|
+
this.discoveryFromCache = false;
|
|
196
|
+
this.ignoreConfigDiscoveryCache = false;
|
|
163
197
|
// Library callers use the same transport as CLI commands. Optional instrumentation must not
|
|
164
198
|
// mean silent data loss when the third constructor argument is omitted. No disk/network I/O
|
|
165
199
|
// or mutation of caller-owned (possibly frozen) configuration objects.
|
|
@@ -173,20 +207,66 @@ export class NamesLinkClient {
|
|
|
173
207
|
}
|
|
174
208
|
}
|
|
175
209
|
|
|
210
|
+
async invalidateDiscoveryCache() {
|
|
211
|
+
this.discovery = null;
|
|
212
|
+
this.discoveryFromCache = false;
|
|
213
|
+
this.ignoreConfigDiscoveryCache = true;
|
|
214
|
+
if (this.saveDiscoveryCache && this.persistConfig !== false) {
|
|
215
|
+
await Promise.resolve(this.saveDiscoveryCache(this.endpoint, null)).catch(() => {});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async loadDiscovery({ refresh = false } = {}) {
|
|
220
|
+
if (refresh) {
|
|
221
|
+
this.discovery = null;
|
|
222
|
+
this.discoveryFromCache = false;
|
|
223
|
+
this.ignoreConfigDiscoveryCache = true;
|
|
224
|
+
}
|
|
225
|
+
if (!this.discovery && !this.ignoreConfigDiscoveryCache) {
|
|
226
|
+
const cached = readCachedDiscovery(this.config, this.endpoint, this.now());
|
|
227
|
+
if (cached) {
|
|
228
|
+
this.discoveryFromCache = true;
|
|
229
|
+
this.discovery = Promise.resolve(cached);
|
|
230
|
+
return this.discovery;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (!this.discovery) {
|
|
234
|
+
this.discoveryFromCache = false;
|
|
235
|
+
this.discovery = this.publicRequest('GET', '/').then(async (document) => {
|
|
236
|
+
const operations = sanitizeDiscoveryOperations(document?.operations);
|
|
237
|
+
if (operations && this.saveDiscoveryCache && this.persistConfig !== false) {
|
|
238
|
+
await Promise.resolve(this.saveDiscoveryCache(this.endpoint, {
|
|
239
|
+
fetchedAt: this.now(),
|
|
240
|
+
operations,
|
|
241
|
+
})).catch(() => {});
|
|
242
|
+
}
|
|
243
|
+
return document;
|
|
244
|
+
}).catch((error) => {
|
|
245
|
+
this.discovery = null;
|
|
246
|
+
throw error;
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return this.discovery;
|
|
250
|
+
}
|
|
251
|
+
|
|
176
252
|
/** Resolve only server-advertised endpoint-relative operations; no redirects or code download. */
|
|
177
|
-
async resolveOperation(method, reference) {
|
|
253
|
+
async resolveOperation(method, reference, { refresh = false } = {}) {
|
|
178
254
|
if (!reference || typeof reference !== 'object' || !reference.operation) return reference;
|
|
179
|
-
|
|
180
|
-
this.discovery = null;
|
|
181
|
-
throw error;
|
|
182
|
-
});
|
|
183
|
-
const document = await this.discovery;
|
|
255
|
+
const document = await this.loadDiscovery({ refresh });
|
|
184
256
|
const operation = document?.operations?.[reference.operation];
|
|
185
257
|
if (!operation || operation.method !== method || typeof operation.hrefTemplate !== 'string') {
|
|
258
|
+
if (this.discoveryFromCache && !refresh) {
|
|
259
|
+
await this.invalidateDiscoveryCache();
|
|
260
|
+
return this.resolveOperation(method, reference, { refresh: true });
|
|
261
|
+
}
|
|
186
262
|
throw discoveryError('UnsupportedOperation', reference.operation);
|
|
187
263
|
}
|
|
188
264
|
const template = operation.hrefTemplate;
|
|
189
|
-
if (
|
|
265
|
+
if (!isSafeHrefTemplate(template)) {
|
|
266
|
+
if (this.discoveryFromCache && !refresh) {
|
|
267
|
+
await this.invalidateDiscoveryCache();
|
|
268
|
+
return this.resolveOperation(method, reference, { refresh: true });
|
|
269
|
+
}
|
|
190
270
|
throw discoveryError('InvalidLocation', reference.operation);
|
|
191
271
|
}
|
|
192
272
|
const used = new Set();
|
|
@@ -287,10 +367,15 @@ export class NamesLinkClient {
|
|
|
287
367
|
redirect: 'error',
|
|
288
368
|
signal: AbortSignal.timeout(timeoutMs),
|
|
289
369
|
});
|
|
290
|
-
// A missing read route can refresh discovery once. Mutations are never replayed for relocation
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
370
|
+
// A missing read route can refresh discovery once. Mutations are never replayed for relocation,
|
|
371
|
+
// though a stale cached discovery entry is still cleared so the next command sees fresh routes.
|
|
372
|
+
if (response.status === 404 && reference?.operation) {
|
|
373
|
+
if (this.discoveryFromCache) await this.invalidateDiscoveryCache();
|
|
374
|
+
if (method === 'GET' && retry) {
|
|
375
|
+
this.discovery = null;
|
|
376
|
+
this.ignoreConfigDiscoveryCache = true;
|
|
377
|
+
return this.request(method, reference, body, { ...options, retry: false });
|
|
378
|
+
}
|
|
294
379
|
}
|
|
295
380
|
const payload = await parsePayload(response, this.endpoint, method);
|
|
296
381
|
this.lastMfaAssurance = null;
|
package/src/config.mjs
CHANGED
|
@@ -128,6 +128,7 @@ export async function loadConfigWith(store = { read: readCredential }, options =
|
|
|
128
128
|
return { endpoint: selection.endpoint, endpointPersistent: selection.persistent, profile,
|
|
129
129
|
language: config.language, lastPlan: config.lastPlan, journey: config.journey,
|
|
130
130
|
updateCheck: config.updateCheck, skillCheck: config.skillCheck,
|
|
131
|
+
discoveryCache: config.discoveryCache,
|
|
131
132
|
credentialState: config.credentialState, credentialStorage: 'not-read' };
|
|
132
133
|
}
|
|
133
134
|
// A file credential exists only because an earlier keyring write could not complete. It is the
|
|
@@ -194,6 +195,7 @@ export async function loadConfigWith(store = { read: readCredential }, options =
|
|
|
194
195
|
// 于是每条命令都去查一次 registry —— 正是加缓存要避免的开销。skillCheck 同理。
|
|
195
196
|
updateCheck: config.updateCheck,
|
|
196
197
|
skillCheck: config.skillCheck,
|
|
198
|
+
discoveryCache: config.discoveryCache,
|
|
197
199
|
credentials,
|
|
198
200
|
credentialStorage,
|
|
199
201
|
credentialState: config.credentialState,
|
|
@@ -226,10 +228,17 @@ export async function loadLanguagePreference() {
|
|
|
226
228
|
}
|
|
227
229
|
|
|
228
230
|
export class ConfigUnwritableError extends Error {
|
|
229
|
-
constructor(file) {
|
|
231
|
+
constructor(file, options = {}) {
|
|
230
232
|
super(`The NamesLink CLI configuration file could not be written: ${file}`);
|
|
231
233
|
this.name = 'ConfigUnwritableError';
|
|
232
|
-
this.body = {
|
|
234
|
+
this.body = {
|
|
235
|
+
code: 'Cli.Config.Unwritable',
|
|
236
|
+
data: {
|
|
237
|
+
path: file,
|
|
238
|
+
...(options.reason ? { reason: options.reason } : {}),
|
|
239
|
+
...(options.dir ? { dir: options.dir } : {}),
|
|
240
|
+
},
|
|
241
|
+
};
|
|
233
242
|
this.machineReadable = true;
|
|
234
243
|
}
|
|
235
244
|
}
|
|
@@ -247,6 +256,7 @@ export async function persistConfigFile(dir, file, payload, deps = {}) {
|
|
|
247
256
|
const temporary = join(dir, `.${basename(file)}.${suffix}.tmp`);
|
|
248
257
|
let handle;
|
|
249
258
|
let temporaryExists = false;
|
|
259
|
+
let failureReason;
|
|
250
260
|
try {
|
|
251
261
|
await makeDirectory(dir, { recursive: true, mode: 0o700 });
|
|
252
262
|
// mkdir's mode applies only when it creates the directory. Do not chmod an existing path: the
|
|
@@ -254,6 +264,7 @@ export async function persistConfigFile(dir, file, payload, deps = {}) {
|
|
|
254
264
|
// POSIX user could replace/remove the 0600 config through a group/world-writable parent.
|
|
255
265
|
// Windows chmod is not an ACL; credential-file fallback there is separately explicit-opt-in.
|
|
256
266
|
if (platform !== 'win32' && ((await inspectPath(dir)).mode & 0o022) !== 0) {
|
|
267
|
+
failureReason = 'INSECURE_PERMISSIONS';
|
|
257
268
|
throw new Error('NamesLink config directory is writable by another user');
|
|
258
269
|
}
|
|
259
270
|
handle = await openFile(temporary, 'wx', 0o600);
|
|
@@ -278,6 +289,10 @@ export async function persistConfigFile(dir, file, payload, deps = {}) {
|
|
|
278
289
|
const directoryHandle = await openDirectory(dir, 'r');
|
|
279
290
|
try {
|
|
280
291
|
await directoryHandle.sync();
|
|
292
|
+
} catch (syncError) {
|
|
293
|
+
// Some POSIX virtual/network filesystems (FUSE, 9p, overlayfs, NFS) reject fsync on
|
|
294
|
+
// directory descriptors after an already-completed atomic rename. Real I/O errors fail.
|
|
295
|
+
if (!['EINVAL', 'ENOTSUP', 'EOPNOTSUPP'].includes(syncError?.code)) throw syncError;
|
|
281
296
|
} finally {
|
|
282
297
|
await directoryHandle.close();
|
|
283
298
|
}
|
|
@@ -296,7 +311,7 @@ export async function persistConfigFile(dir, file, payload, deps = {}) {
|
|
|
296
311
|
// an existing config or hiding the reason the atomic replacement failed.
|
|
297
312
|
}
|
|
298
313
|
}
|
|
299
|
-
throw new ConfigUnwritableError(file);
|
|
314
|
+
throw new ConfigUnwritableError(file, failureReason ? { reason: failureReason, dir } : {});
|
|
300
315
|
}
|
|
301
316
|
}
|
|
302
317
|
|
|
@@ -355,6 +370,39 @@ export async function saveSkillCheckMetadata(skillCheck) {
|
|
|
355
370
|
await persistConfigFile(dir, file, config);
|
|
356
371
|
}
|
|
357
372
|
|
|
373
|
+
const MAX_DISCOVERY_CACHE_ENDPOINTS = 8;
|
|
374
|
+
|
|
375
|
+
// Endpoint-scoped public API discovery cache (`GET /`). Persisted via metadata-only write — never
|
|
376
|
+
// through saveConfig — so resolving resource templates never touches credentials or prompts Keychain.
|
|
377
|
+
export async function saveDiscoveryCacheEntry(endpoint, entry, deps = {}) {
|
|
378
|
+
const selection = validateEndpoint(endpoint);
|
|
379
|
+
if (!selection.persistent) return false;
|
|
380
|
+
const { dir, file } = deps.paths || configPaths();
|
|
381
|
+
let config = {};
|
|
382
|
+
try {
|
|
383
|
+
config = JSON.parse(await readFile(file, 'utf8'));
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (error.code !== 'ENOENT') throw new ConfigUnreadableError(file);
|
|
386
|
+
}
|
|
387
|
+
const existing = config.discoveryCache && typeof config.discoveryCache === 'object'
|
|
388
|
+
&& !Array.isArray(config.discoveryCache)
|
|
389
|
+
? { ...config.discoveryCache }
|
|
390
|
+
: {};
|
|
391
|
+
if (entry) {
|
|
392
|
+
existing[selection.endpoint] = entry;
|
|
393
|
+
const bounded = Object.entries(existing)
|
|
394
|
+
.sort(([, left], [, right]) => Number(right?.fetchedAt || 0) - Number(left?.fetchedAt || 0))
|
|
395
|
+
.slice(0, MAX_DISCOVERY_CACHE_ENDPOINTS);
|
|
396
|
+
config.discoveryCache = Object.fromEntries(bounded);
|
|
397
|
+
} else {
|
|
398
|
+
delete existing[selection.endpoint];
|
|
399
|
+
if (Object.keys(existing).length > 0) config.discoveryCache = existing;
|
|
400
|
+
else delete config.discoveryCache;
|
|
401
|
+
}
|
|
402
|
+
await persistConfigFile(dir, file, config);
|
|
403
|
+
return true;
|
|
404
|
+
}
|
|
405
|
+
|
|
358
406
|
export async function saveConfig(config) {
|
|
359
407
|
return saveConfigWith(config, { write: writeCredential });
|
|
360
408
|
}
|
package/src/credential-store.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
|
+
import { deflateRawSync, inflateRawSync } from 'node:zlib';
|
|
2
3
|
|
|
3
4
|
const service = 'com.nameslink.cli';
|
|
4
5
|
const KEYCHAIN_COMMAND_TIMEOUT_MS = 10_000;
|
|
@@ -7,6 +8,13 @@ const KEYCHAIN_COMMAND_TIMEOUT_MS = 10_000;
|
|
|
7
8
|
// encourages agents to spawn another dialog. Keep one asynchronous, bounded request alive.
|
|
8
9
|
const MACOS_KEYCHAIN_PERMISSION_TIMEOUT_MS = 60_000;
|
|
9
10
|
const SECURITY_COMMAND = '/usr/bin/security';
|
|
11
|
+
// Real OAuth credentials carry two HS512 JWTs (~1.6 KiB base64url), which exceeds Windows
|
|
12
|
+
// Credential Manager's 2560-byte UTF-16LE blob limit (1280 chars) unless compressed. A dot can
|
|
13
|
+
// never appear in base64url, so `z1.` cleanly distinguishes compressed entries from legacy ones.
|
|
14
|
+
const COMPRESSED_PREFIX = 'z1.';
|
|
15
|
+
const COMPRESS_THRESHOLD_CHARS = 512;
|
|
16
|
+
const MAX_DECOMPRESSED_CREDENTIAL_BYTES = 64 * 1024;
|
|
17
|
+
const TELEMETRY_PLATFORMS = new Set(['darwin', 'win32', 'linux']);
|
|
10
18
|
|
|
11
19
|
export class KeychainUnavailableError extends Error {
|
|
12
20
|
constructor(reason = 'TIMEOUT') {
|
|
@@ -163,7 +171,7 @@ export async function writeCredential(profile, credentials, deps = {}) {
|
|
|
163
171
|
} catch (error) {
|
|
164
172
|
const classified = classifyKeychainError(error);
|
|
165
173
|
if (!(classified instanceof KeychainUnavailableError)
|
|
166
|
-
|| classified.body.data.reason
|
|
174
|
+
|| classified.body.data.reason !== 'BACKEND_UNAVAILABLE') throw classified;
|
|
167
175
|
}
|
|
168
176
|
}
|
|
169
177
|
}
|
|
@@ -278,19 +286,51 @@ function normalizeDeleteResult(value) {
|
|
|
278
286
|
return { supported: Boolean(value), deleted: Boolean(value), missing: false };
|
|
279
287
|
}
|
|
280
288
|
|
|
281
|
-
function encode(credentials) {
|
|
282
|
-
|
|
289
|
+
export function encode(credentials) {
|
|
290
|
+
const json = JSON.stringify(credentials);
|
|
291
|
+
const raw = Buffer.from(json).toString('base64url');
|
|
292
|
+
if (raw.length <= COMPRESS_THRESHOLD_CHARS) return raw;
|
|
293
|
+
const compressed = `${COMPRESSED_PREFIX}${deflateRawSync(Buffer.from(json)).toString('base64url')}`;
|
|
294
|
+
return compressed.length < raw.length ? compressed : raw;
|
|
283
295
|
}
|
|
284
296
|
|
|
285
|
-
function decodeCredential(value, backend) {
|
|
297
|
+
export function decodeCredential(value, backend) {
|
|
286
298
|
try {
|
|
287
|
-
|
|
299
|
+
if (typeof value !== 'string' || !value) throw new Error('empty');
|
|
300
|
+
const json = value.startsWith(COMPRESSED_PREFIX)
|
|
301
|
+
? inflateRawSync(Buffer.from(value.slice(COMPRESSED_PREFIX.length), 'base64url'), {
|
|
302
|
+
maxOutputLength: MAX_DECOMPRESSED_CREDENTIAL_BYTES,
|
|
303
|
+
}).toString('utf8')
|
|
304
|
+
: Buffer.from(value, 'base64url').toString('utf8');
|
|
305
|
+
const decoded = JSON.parse(json);
|
|
288
306
|
return validateCredentialShape(decoded, backend);
|
|
289
307
|
} catch {
|
|
290
308
|
throw new CredentialCorruptError(backend);
|
|
291
309
|
}
|
|
292
310
|
}
|
|
293
311
|
|
|
312
|
+
export function classifyCredentialSaveError(error, platform = process.platform) {
|
|
313
|
+
const normalizedPlatform = TELEMETRY_PLATFORMS.has(platform) ? platform : 'other';
|
|
314
|
+
const code = error?.body?.code;
|
|
315
|
+
const dataReason = error?.body?.data?.reason;
|
|
316
|
+
let reason = 'UNKNOWN';
|
|
317
|
+
if (error instanceof KeychainLockedError || code === 'Cli.Keychain.Locked') {
|
|
318
|
+
reason = 'KEYCHAIN_LOCKED';
|
|
319
|
+
} else if (code === 'Cli.Keychain.Unavailable' && dataReason === 'TIMEOUT') {
|
|
320
|
+
reason = 'KEYCHAIN_TIMEOUT';
|
|
321
|
+
} else if (code === 'Cli.Keychain.Unavailable' && dataReason === 'INPUT_TOO_LARGE') {
|
|
322
|
+
reason = 'KEYCHAIN_INPUT_TOO_LARGE';
|
|
323
|
+
} else if (error instanceof KeychainUnavailableError || code === 'Cli.Keychain.Unavailable') {
|
|
324
|
+
reason = 'KEYCHAIN_UNAVAILABLE';
|
|
325
|
+
} else if (error instanceof PlaintextCredentialFallbackDeniedError
|
|
326
|
+
|| code === 'Cli.Credential.PlaintextFallbackDenied') {
|
|
327
|
+
reason = 'PLAINTEXT_DENIED';
|
|
328
|
+
} else if (code === 'Cli.Config.Unwritable') {
|
|
329
|
+
reason = 'CONFIG_UNWRITABLE';
|
|
330
|
+
}
|
|
331
|
+
return { reason, platform: normalizedPlatform };
|
|
332
|
+
}
|
|
333
|
+
|
|
294
334
|
export function validateCredentialShape(value, backend) {
|
|
295
335
|
if (!validCredentialShape(value)) throw new CredentialCorruptError(backend);
|
|
296
336
|
return value;
|
|
@@ -317,17 +357,22 @@ function classifyKeychainError(error, backend = 'system-keyring') {
|
|
|
317
357
|
|| error instanceof KeychainLockedError
|
|
318
358
|
|| error instanceof CredentialCorruptError
|
|
319
359
|
|| error instanceof CredentialMissingError) return error;
|
|
320
|
-
|
|
321
|
-
|
|
360
|
+
// Raw error text is used solely for classification and never copied into returned error bodies.
|
|
361
|
+
const detail = `${error?.code || ''} ${error?.name || ''} ${error?.message || ''} ${error?.stderr || ''}`;
|
|
362
|
+
if (/NoEntry|NoSuchEntry|ItemNotFound|No matching entry|credential.*not found|item.*not found/i.test(detail)) {
|
|
322
363
|
return new CredentialMissingError(backend);
|
|
323
364
|
}
|
|
324
|
-
if (/BadEncoding|BadDataFormat|BadStoreFormat/i.test(detail)) {
|
|
365
|
+
if (/BadEncoding|BadDataFormat|BadStoreFormat|not valid UTF-8/i.test(detail)) {
|
|
325
366
|
return new CredentialCorruptError(backend);
|
|
326
367
|
}
|
|
327
|
-
if (/
|
|
368
|
+
if (/TooLong|longer than.*limit|exceeds.*limit|too long|CRED_MAX_CREDENTIAL_BLOB_SIZE|\b1783\b/i.test(detail)) {
|
|
369
|
+
return new KeychainUnavailableError('INPUT_TOO_LARGE');
|
|
370
|
+
}
|
|
371
|
+
// Check locked/denied before backend-unavailable so a locked keyring never downgrades to file.
|
|
372
|
+
if (/locked|interaction.*not allowed|permission|access.*denied|auth(?:entication)?.*failed|user cancel|(?<!\w)-25308\b|(?<!\w)-25293\b|(?<!\w)-128\b/i.test(detail)) {
|
|
328
373
|
return new KeychainLockedError();
|
|
329
374
|
}
|
|
330
|
-
if (/NoStorageAccess|NoDefaultStore|NotSupportedByStore|PlatformFailure|not available|unavailable/i.test(detail)) {
|
|
375
|
+
if (/NoStorageAccess|NoDefaultStore|NotSupportedByStore|PlatformFailure|Platform secure storage failure|Couldn't access platform secure storage|no default store|secret service|org\.freedesktop\.secrets|d-?bus|not available|unavailable/i.test(detail)) {
|
|
331
376
|
return new KeychainUnavailableError('BACKEND_UNAVAILABLE');
|
|
332
377
|
}
|
|
333
378
|
return error;
|
package/src/domain.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { stdout } from 'node:process';
|
|
2
2
|
import { isIP } from 'node:net';
|
|
3
3
|
import { domainToASCII } from 'node:url';
|
|
4
|
+
import { ApiError, resource } from './client.mjs';
|
|
4
5
|
import { createI18n } from './i18n.mjs';
|
|
5
6
|
|
|
6
7
|
const API_VERSION = 'domain-discovery.nameslink.com/v1';
|
|
@@ -83,17 +84,16 @@ export async function searchDomains(client, keyword, { category, limit = DEFAULT
|
|
|
83
84
|
const sourceCandidates = Array.isArray(searchResponse?.data)
|
|
84
85
|
? searchResponse.data.slice(0, limit)
|
|
85
86
|
: [];
|
|
86
|
-
const
|
|
87
|
+
const candidatesToCheck = sourceCandidates.filter((candidate) => !candidate?.onSale && candidate?.domainName);
|
|
88
|
+
const availabilityByDomain = await checkCandidateAvailability(
|
|
89
|
+
client,
|
|
90
|
+
candidatesToCheck.map((candidate) => candidate.domainName),
|
|
91
|
+
);
|
|
92
|
+
const checked = sourceCandidates.map((candidate) => {
|
|
87
93
|
if (candidate?.onSale) return normalizeSearchCandidate(candidate, null);
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
);
|
|
92
|
-
return normalizeSearchCandidate(candidate, availability);
|
|
93
|
-
} catch (error) {
|
|
94
|
-
return normalizeSearchCandidate(candidate, null, error);
|
|
95
|
-
}
|
|
96
|
-
}));
|
|
94
|
+
const entry = availabilityByDomain.get(String(candidate?.domainName || '').trim().toLowerCase());
|
|
95
|
+
return normalizeSearchCandidate(candidate, entry?.availability || null, entry?.error);
|
|
96
|
+
});
|
|
97
97
|
return {
|
|
98
98
|
apiVersion: API_VERSION,
|
|
99
99
|
mode: 'SEARCH',
|
|
@@ -120,7 +120,67 @@ export async function checkDomains(client, domains, i18n = createI18n('en-US'))
|
|
|
120
120
|
error.machineReadable = true;
|
|
121
121
|
throw error;
|
|
122
122
|
}
|
|
123
|
-
const settled = await
|
|
123
|
+
const settled = await checkDomainBatchOrSingle(client, domains);
|
|
124
|
+
return {
|
|
125
|
+
apiVersion: API_VERSION,
|
|
126
|
+
mode: 'CHECK',
|
|
127
|
+
priceBinding: 'INDICATIVE',
|
|
128
|
+
results: settled,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function tryResolveBatchCheckPath(client) {
|
|
133
|
+
if (typeof client?.resolveOperation !== 'function') return null;
|
|
134
|
+
try {
|
|
135
|
+
return await client.resolveOperation('POST', resource('domains.batchCheck'));
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function queryBatchResults(client, domains, batchPath) {
|
|
142
|
+
const response = await client.publicRequest('POST', batchPath, { domainNames: domains });
|
|
143
|
+
if (!Array.isArray(response?.results)) return null;
|
|
144
|
+
const normalizeKey = (name) => String(name || '').trim().replace(/\.$/, '').toLowerCase();
|
|
145
|
+
const byName = new Map();
|
|
146
|
+
for (const item of response.results) {
|
|
147
|
+
const key = normalizeKey(item?.domainName);
|
|
148
|
+
if (key && !byName.has(key)) byName.set(key, item);
|
|
149
|
+
}
|
|
150
|
+
return domains.map((domainName, index) => {
|
|
151
|
+
const target = normalizeKey(domainName);
|
|
152
|
+
const positional = response.results[index];
|
|
153
|
+
const positionalName = normalizeKey(positional?.domainName);
|
|
154
|
+
if (positional && positionalName === target) return positional;
|
|
155
|
+
if (byName.has(target)) return byName.get(target);
|
|
156
|
+
// Never attribute another domain's availability/price if the response is partial or reordered.
|
|
157
|
+
return positional && !positionalName ? positional : null;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function checkDomainBatchOrSingle(client, domains) {
|
|
162
|
+
if (domains.length > 1) {
|
|
163
|
+
const batchPath = await tryResolveBatchCheckPath(client);
|
|
164
|
+
if (batchPath) {
|
|
165
|
+
try {
|
|
166
|
+
const batched = await queryBatchResults(client, domains, batchPath);
|
|
167
|
+
if (batched) {
|
|
168
|
+
return domains.map((domainName, index) => (
|
|
169
|
+
batched[index]
|
|
170
|
+
? normalizeAvailability(batched[index], domainName)
|
|
171
|
+
: unavailableResult(domainName, null)
|
|
172
|
+
));
|
|
173
|
+
}
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (error instanceof ApiError && [404, 405].includes(error.status)) {
|
|
176
|
+
await client.invalidateDiscoveryCache?.();
|
|
177
|
+
} else if (!(error instanceof ApiError && error.status === 400)) {
|
|
178
|
+
return domains.map((domainName) => unavailableResult(domainName, error));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return Promise.all(domains.map(async (domainName) => {
|
|
124
184
|
try {
|
|
125
185
|
const result = await client.publicRequest(
|
|
126
186
|
'POST',
|
|
@@ -132,12 +192,53 @@ export async function checkDomains(client, domains, i18n = createI18n('en-US'))
|
|
|
132
192
|
return unavailableResult(domainName, error);
|
|
133
193
|
}
|
|
134
194
|
}));
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function checkCandidateAvailability(client, domainNames) {
|
|
198
|
+
const results = new Map();
|
|
199
|
+
if (domainNames.length === 0) return results;
|
|
200
|
+
let batchPath = domainNames.length > 1 ? await tryResolveBatchCheckPath(client) : null;
|
|
201
|
+
if (batchPath) {
|
|
202
|
+
let fallbackToSingle = false;
|
|
203
|
+
for (let offset = 0; offset < domainNames.length; offset += MAX_CHECK_DOMAINS) {
|
|
204
|
+
const chunk = domainNames.slice(offset, offset + MAX_CHECK_DOMAINS);
|
|
205
|
+
try {
|
|
206
|
+
const batched = await queryBatchResults(client, chunk, batchPath);
|
|
207
|
+
if (!batched) { fallbackToSingle = true; break; }
|
|
208
|
+
chunk.forEach((domainName, index) => {
|
|
209
|
+
results.set(domainName.trim().toLowerCase(), { availability: batched[index] });
|
|
210
|
+
});
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (error instanceof ApiError && [404, 405].includes(error.status)) {
|
|
213
|
+
await client.invalidateDiscoveryCache?.();
|
|
214
|
+
batchPath = null;
|
|
215
|
+
fallbackToSingle = true;
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
if (error instanceof ApiError && error.status === 400) {
|
|
219
|
+
fallbackToSingle = true;
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
chunk.forEach((domainName) => {
|
|
223
|
+
results.set(domainName.trim().toLowerCase(), { availability: null, error });
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (!fallbackToSingle) return results;
|
|
228
|
+
}
|
|
229
|
+
await Promise.all(domainNames.map(async (domainName) => {
|
|
230
|
+
const key = domainName.trim().toLowerCase();
|
|
231
|
+
if (results.has(key)) return;
|
|
232
|
+
try {
|
|
233
|
+
const availability = await client.publicRequest(
|
|
234
|
+
'POST', '/domain/registry/check-domain/check', { domainName },
|
|
235
|
+
);
|
|
236
|
+
results.set(key, { availability });
|
|
237
|
+
} catch (error) {
|
|
238
|
+
results.set(key, { availability: null, error });
|
|
239
|
+
}
|
|
240
|
+
}));
|
|
241
|
+
return results;
|
|
141
242
|
}
|
|
142
243
|
|
|
143
244
|
function validDomainName(domain) {
|
package/src/hosted-site.mjs
CHANGED
|
@@ -211,19 +211,37 @@ async function siteFreeDestination(client, host) {
|
|
|
211
211
|
|
|
212
212
|
async function operationResult(client, siteId, original, operationKey, options, runtime, automaticDns = false) {
|
|
213
213
|
let operation = publicOperation(original);
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
let dns =
|
|
217
|
-
|
|
218
|
-
|
|
214
|
+
if (operation.hostedSiteId !== siteId) throw failure('InvalidReceipt');
|
|
215
|
+
let site = null;
|
|
216
|
+
let dns = null;
|
|
217
|
+
let siteFresh = false;
|
|
218
|
+
const current = () => Boolean(site && site.bindingId === operation.bindingId && site.generation === operation.generation);
|
|
219
|
+
const refreshSiteAndDns = async () => {
|
|
219
220
|
site = publicSite(await get(client, 'sites.get', { siteId }));
|
|
220
|
-
|
|
221
|
-
|
|
221
|
+
dns = automaticDns && current() ? await publicationProgress(client, site) : null;
|
|
222
|
+
siteFresh = true;
|
|
222
223
|
};
|
|
223
224
|
const progressing = () => dns?.status === 'RUNNING';
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
225
|
+
const terminal = (item) => item.status === 'SUCCEEDED' || (item.status !== 'RUNNING' && !progressing());
|
|
226
|
+
// Only read site/DNS up front when we are not going straight into operation polling, or when
|
|
227
|
+
// an automatic-DNS operation is already non-RUNNING (e.g. NEEDS_ACTION while DNS is configuring).
|
|
228
|
+
if (options['no-wait'] || operation.status !== 'RUNNING') {
|
|
229
|
+
await refreshSiteAndDns();
|
|
230
|
+
}
|
|
231
|
+
if (!options['no-wait'] && !terminal(operation)) {
|
|
232
|
+
const read = async () => {
|
|
233
|
+
siteFresh = false;
|
|
234
|
+
const next = publicOperation(await get(client, 'sites.operation', { siteId, operationId: operation.operationId }));
|
|
235
|
+
operation = next;
|
|
236
|
+
// Avoid alternating GET /sites/{siteId} on every tick while the operation itself is RUNNING.
|
|
237
|
+
if (automaticDns && next.status !== 'RUNNING' && next.status !== 'SUCCEEDED') {
|
|
238
|
+
await refreshSiteAndDns();
|
|
239
|
+
}
|
|
240
|
+
return next;
|
|
241
|
+
};
|
|
242
|
+
operation = await poll(read, operation, terminal, runtime);
|
|
243
|
+
if (!siteFresh) await refreshSiteAndDns();
|
|
244
|
+
}
|
|
227
245
|
return { operation, site, idempotencyKey: operationKey, complete: operation.status === 'SUCCEEDED',
|
|
228
246
|
...(dns ? { domainSetup: dns } : {}),
|
|
229
247
|
nextAction: operation.status === 'SUCCEEDED' ? operation.nextAction : publicationNextAction(dns, site) || operation.nextAction,
|
|
@@ -424,15 +442,21 @@ async function preview(client, siteId, capability, options, i18n, runtime, prepa
|
|
|
424
442
|
return withHostedJournal(client, `${siteId || 'new'}:preview:${operationKey}`, runtime, async (stored, save) => {
|
|
425
443
|
const body = freeze(stored, request);
|
|
426
444
|
const state = stored || { body, finalizeKey: randomUUID(), candidateKey: randomUUID(),
|
|
445
|
+
...(siteId ? { scopedPreview: { hostedSiteId: siteId } } : {}),
|
|
427
446
|
destination: { ...(siteId ? { hostedSiteId: siteId } : {}), sourceName: basename(resolve(options.dir || options.file)).slice(0, 255) } };
|
|
428
447
|
state.publishKey ||= randomUUID();
|
|
429
448
|
await save(state);
|
|
430
449
|
try {
|
|
431
450
|
if (!state.previewSiteId || !state.uploadStarted || options['retry-upload']) {
|
|
432
|
-
const session = await client.request('POST', resource('previews.sessions.create'), body);
|
|
451
|
+
const session = await client.request('POST', resource('previews.sessions.create'), { ...body, ...state.scopedPreview });
|
|
433
452
|
validateSession(session, body);
|
|
453
|
+
if (state.scopedPreview && state.confirmHostedScope === undefined) {
|
|
454
|
+
state.confirmHostedScope = session.monthlyPreviewQuotaApplies === false;
|
|
455
|
+
await save(state);
|
|
456
|
+
}
|
|
434
457
|
const confirmed = await client.request('POST', resource('previews.sessions.confirm', { sessionId: id(session.sessionId) }), {
|
|
435
458
|
confirmationToken: session.confirmationToken, idempotencyKey: body.idempotencyKey, confirmed: true,
|
|
459
|
+
...(state.confirmHostedScope ? state.scopedPreview : {}),
|
|
436
460
|
});
|
|
437
461
|
if (state.previewSiteId && state.previewSiteId !== confirmed.siteId) throw failure('InvalidReceipt');
|
|
438
462
|
state.previewSiteId = id(confirmed.siteId);
|
package/src/i18n.mjs
CHANGED
|
@@ -23,6 +23,7 @@ const EN_US = {
|
|
|
23
23
|
'apiError.Drop.Hosted.Dns.MANUAL_REQUIRED': 'Add the records shown by domain show at your DNS provider.',
|
|
24
24
|
'apiError.Drop.Hosted.Dns.PLAN_EXPIRED': 'This DNS plan expired. Review a new plan before authorizing it.',
|
|
25
25
|
'apiError.Drop.Hosted.Dns.PLAN_CONFLICT': 'Existing DNS records conflict with this publication. Nothing was overwritten. Review them or choose another address.',
|
|
26
|
+
'apiError.Drop.Hosted.Dns.HOST_IN_USE': 'This address already serves another website. Choose another prefix, or stop that website first.',
|
|
26
27
|
'apiError.Drop.Hosted.Dns.PLAN_CHANGED': 'The site or DNS settings changed. Review the current configuration before continuing.',
|
|
27
28
|
'apiError.Drop.Hosted.Dns.OPERATION_UNKNOWN': 'The DNS change is unconfirmed. Check its original plan; do not submit it again.',
|
|
28
29
|
'apiError.Drop.Hosted.Dns.INCONSISTENT': 'We could not verify the DNS setup records. Contact support with the original plan ID.',
|
|
@@ -569,7 +570,7 @@ const EN_US = {
|
|
|
569
570
|
'apiError.Account.Mfa.CliSessionRevoked': 'This CLI verification session was revoked. Run nameslink login again.',
|
|
570
571
|
'apiError.Account.Mfa.FlowExpired': 'The MFA challenge expired. The reviewed plan was not executed.',
|
|
571
572
|
'apiError.Account.Mfa.FlowLoginStatusChanged':
|
|
572
|
-
'The MFA
|
|
573
|
+
'The MFA verification context changed (for example, a proxy/VPN egress IP switch or completing the challenge in a different browser). The operation was not executed.',
|
|
573
574
|
'apiError.Pay.WalletBalanceInsufficient': 'The wallet balance is insufficient for this reviewed plan.',
|
|
574
575
|
'guidance.resumeHint': 'Next step: {hint}',
|
|
575
576
|
'guidance.consoleUrl': 'Open in NamesLink: {url}',
|
|
@@ -587,7 +588,7 @@ const EN_US = {
|
|
|
587
588
|
'After the top-up is credited, continue the same reviewed plan: `nameslink execution resume {token}`.',
|
|
588
589
|
'guidance.mfaRetryApply': 'Start a fresh MFA challenge for the same reviewed plan: `{command}`.',
|
|
589
590
|
'guidance.mfaStableContext':
|
|
590
|
-
'
|
|
591
|
+
'Keep your proxy/VPN egress IP stable and complete verification in the originating browser and network. If it still fails, run `nameslink login` and retry the command.',
|
|
591
592
|
'guidance.mfaSecurityCenter': 'Set up a security phone or authenticator in NamesLink Security Center: {url}',
|
|
592
593
|
'guidance.mfaLocked': 'Wait for the stated cooldown. Repeated attempts will not bypass the lock.',
|
|
593
594
|
'guidance.mfaAccountLocked': 'Use the NamesLink support process to unlock the account before retrying.',
|
|
@@ -627,9 +628,13 @@ const EN_US = {
|
|
|
627
628
|
'apiError.Automation.Dns.SiteQueryFailed':
|
|
628
629
|
'Could not reach the DNS service for this domain. Try again shortly.',
|
|
629
630
|
'apiError.Automation.Dns.SiteNotFound':
|
|
630
|
-
'NamesLink does not host DNS for this domain, so
|
|
631
|
-
+ '
|
|
632
|
-
+ '
|
|
631
|
+
'NamesLink does not currently host DNS for this domain, so records cannot be managed or published here. '
|
|
632
|
+
+ 'This happens when the domain uses third-party nameservers instead of NamesLink DNS, or is not registered '
|
|
633
|
+
+ 'in this NamesLink account. Retrying will not change this.',
|
|
634
|
+
'guidance.dnsSiteNotFound':
|
|
635
|
+
'Check the domain\'s current nameservers with `nameslink domain list` (or in the NamesLink console). '
|
|
636
|
+
+ 'If the domain is in your account, switch its authoritative nameservers back to NamesLink DNS; '
|
|
637
|
+
+ 'otherwise transfer the domain to NamesLink first.',
|
|
633
638
|
'apiError.Automation.Dns.PageInvalid': '--page must be 1 or greater and --page-size must be 1-1000.',
|
|
634
639
|
'apiError.Automation.Dns.RecordListFailed': 'Unable to list the DNS records right now. Try again shortly.',
|
|
635
640
|
'apiError.Automation.Dns.RecordCreateFailed': 'The DNS record could not be created.',
|
|
@@ -692,6 +697,8 @@ const EN_US = {
|
|
|
692
697
|
'For an intentional local HTTP server, use 127.0.0.1/localhost and set NAMESLINK_ALLOW_INSECURE_ENDPOINT=1 for that one process.',
|
|
693
698
|
'guidance.configWritable':
|
|
694
699
|
'Make sure that directory is writable and has free space, then run the command again.',
|
|
700
|
+
'guidance.configPermissions':
|
|
701
|
+
'That directory is writable by other users. Tighten its permissions with `chmod 700 {dir}`, then run the command again.',
|
|
695
702
|
'guidance.configPath': 'Configuration file: {path}',
|
|
696
703
|
'guidance.configRepair':
|
|
697
704
|
'Delete that file and run `nameslink login` again. It only holds settings and a credential reference, so nothing else is lost.',
|
|
@@ -699,6 +706,10 @@ const EN_US = {
|
|
|
699
706
|
'Unlock your system credential store. For the macOS “security” prompt, enter the login Keychain password in that system dialog and click Always Allow.',
|
|
700
707
|
'guidance.keychainRetry':
|
|
701
708
|
'Keep one CLI command running while approving access. If it has already timed out, dismiss stale dialogs before retrying once; do not repeatedly run doctor or login.',
|
|
709
|
+
'guidance.keychainUnavailable':
|
|
710
|
+
'Ensure your operating system credential store is available and unlocked (macOS Keychain, Windows Credential Manager, or Linux Secret Service), then run `nameslink login` again.',
|
|
711
|
+
'guidance.keychainInputTooLarge':
|
|
712
|
+
'The login credential exceeded your system keychain\'s single-entry size limit. Update NamesLink CLI to the latest version and run `nameslink login` again.',
|
|
702
713
|
'guidance.plaintextCredentialOptIn':
|
|
703
714
|
'Prefer restoring Windows Credential Manager. For an intentional local-only exception, set `NAMESLINK_ALLOW_PLAINTEXT_CREDENTIAL_FILE=1` for the login process and protect the config file with Windows ACLs.',
|
|
704
715
|
'guidance.credentialCorrupt':
|
|
@@ -774,6 +785,7 @@ const ZH_CN = {
|
|
|
774
785
|
'apiError.Drop.Hosted.Dns.MANUAL_REQUIRED': '请将 domain show 返回的记录添加到你的解析服务商。',
|
|
775
786
|
'apiError.Drop.Hosted.Dns.PLAN_EXPIRED': '此解析计划已过期,请查看并确认新的计划。',
|
|
776
787
|
'apiError.Drop.Hosted.Dns.PLAN_CONFLICT': '已有解析与本次发布冲突,未作覆盖。请先核对,或换个地址。',
|
|
788
|
+
'apiError.Drop.Hosted.Dns.HOST_IN_USE': '这个地址已经发布了另一个网站。请换个前缀,或先停止那个网站。',
|
|
777
789
|
'apiError.Drop.Hosted.Dns.PLAN_CHANGED': '网站或解析配置已变化,请检查当前配置后继续。',
|
|
778
790
|
'apiError.Drop.Hosted.Dns.OPERATION_UNKNOWN': '本次解析结果尚未确认,请核对原计划,不要重新提交。',
|
|
779
791
|
'apiError.Drop.Hosted.Dns.INCONSISTENT': '解析配置记录需要核对,请携带原计划编号联系支持。',
|
|
@@ -1289,7 +1301,8 @@ const ZH_CN = {
|
|
|
1289
1301
|
'apiError.Account.Mfa.OnlyEmailMfa': '本操作除了安全邮箱,还必须配置安全手机或身份验证器。',
|
|
1290
1302
|
'apiError.Account.Mfa.CliSessionRevoked': 'CLI 验证会话已注销,请运行 nameslink login 重新登录。',
|
|
1291
1303
|
'apiError.Account.Mfa.FlowExpired': 'MFA 挑战已过期;已审核计划尚未执行。',
|
|
1292
|
-
'apiError.Account.Mfa.FlowLoginStatusChanged':
|
|
1304
|
+
'apiError.Account.Mfa.FlowLoginStatusChanged':
|
|
1305
|
+
'MFA 验证上下文发生变化(可能是代理/VPN 出口 IP 切换,或跨浏览器完成了同一挑战);本次操作尚未执行。',
|
|
1293
1306
|
'apiError.Pay.WalletBalanceInsufficient': '当前已审核计划对应的钱包余额不足。',
|
|
1294
1307
|
'guidance.resumeHint': '下一步:{hint}',
|
|
1295
1308
|
'guidance.consoleUrl': '请在 NamesLink 中打开:{url}',
|
|
@@ -1305,7 +1318,7 @@ const ZH_CN = {
|
|
|
1305
1318
|
'guidance.walletResumeCommand': '充值到账后继续同一个已审核计划:`nameslink execution resume {token}`。',
|
|
1306
1319
|
'guidance.mfaRetryApply': '为同一个已审核计划发起新的 MFA 挑战:`{command}`。',
|
|
1307
1320
|
'guidance.mfaStableContext':
|
|
1308
|
-
'
|
|
1321
|
+
'请保持代理/VPN 出口网络稳定,并在发起验证的原浏览器与原网络中完成验证;如仍失败,请先运行 `nameslink login` 后重试。',
|
|
1309
1322
|
'guidance.mfaSecurityCenter': '请在 NamesLink 安全中心添加安全手机或身份验证器:{url}',
|
|
1310
1323
|
'guidance.mfaLocked': '请等待错误中提示的冷却时间;反复重试不会绕过锁定。',
|
|
1311
1324
|
'guidance.mfaAccountLocked': '请先通过 NamesLink 支持流程解锁账号,再重试。',
|
|
@@ -1339,8 +1352,11 @@ const ZH_CN = {
|
|
|
1339
1352
|
'apiError.Dns.UnauthorizedOperation.Error': '无权操作该记录。',
|
|
1340
1353
|
'apiError.Automation.Dns.SiteQueryFailed': '连不上该域名的 DNS 服务,请稍后重试。',
|
|
1341
1354
|
'apiError.Automation.Dns.SiteNotFound':
|
|
1342
|
-
'NamesLink
|
|
1343
|
-
+ '
|
|
1355
|
+
'NamesLink 当前未托管该域名的 DNS,因此无法在这里管理解析或发布网站。'
|
|
1356
|
+
+ '这通常是因为该域名正在使用第三方 DNS 服务器(而非 NamesLink DNS),或该域名未注册在当前 NamesLink 账号下。直接重试不会改变这个结果。',
|
|
1357
|
+
'guidance.dnsSiteNotFound':
|
|
1358
|
+
'可先运行 `nameslink domain list`(或在 NamesLink 控制台)核对域名当前使用的 NS 服务器。'
|
|
1359
|
+
+ '若域名已在当前账号下,请将其权威 DNS 切回 NamesLink DNS;若尚未转入,请先将域名转入 NamesLink。',
|
|
1344
1360
|
'apiError.Automation.Dns.PageInvalid': '--page 需要大于等于 1,--page-size 需要在 1 到 1000 之间。',
|
|
1345
1361
|
'apiError.Automation.Dns.RecordListFailed': '暂时拉不到 DNS 记录列表,请稍后重试。',
|
|
1346
1362
|
'apiError.Automation.Dns.RecordCreateFailed': 'DNS 记录创建失败。',
|
|
@@ -1392,12 +1408,17 @@ const ZH_CN = {
|
|
|
1392
1408
|
'guidance.endpointLoopbackOptIn':
|
|
1393
1409
|
'若确实在调试本机 HTTP 服务,请使用 127.0.0.1/localhost,并只为当前进程设置 NAMESLINK_ALLOW_INSECURE_ENDPOINT=1。',
|
|
1394
1410
|
'guidance.configWritable': '请确认该目录可写且磁盘有空间,然后重新执行该命令。',
|
|
1411
|
+
'guidance.configPermissions': '该目录对其他用户可写,安全策略已拒绝写入。请先执行 `chmod 700 {dir}` 收紧权限,再重新运行命令。',
|
|
1395
1412
|
'guidance.configPath': '配置文件:{path}',
|
|
1396
1413
|
'guidance.configRepair':
|
|
1397
1414
|
'删掉该文件后重新运行 `nameslink login`。它只存偏好设置和一个凭据引用,删掉不会丢别的东西。',
|
|
1398
1415
|
'guidance.keychainUnlock': '请解锁系统凭据存储。macOS 若弹出 security 访问请求,请只在系统框内输入“登录”钥匙串密码,然后点“始终允许”。',
|
|
1399
1416
|
'guidance.keychainRetry':
|
|
1400
1417
|
'授权期间只保留一个 CLI 请求。若命令已经超时,先关闭遗留弹窗,准备好后再重试一次;不要连续重跑 doctor 或 login。',
|
|
1418
|
+
'guidance.keychainUnavailable':
|
|
1419
|
+
'请确认系统凭据服务可用且已解锁(macOS 钥匙串、Windows 凭据管理器或 Linux Secret Service),然后重新运行 `nameslink login`。',
|
|
1420
|
+
'guidance.keychainInputTooLarge':
|
|
1421
|
+
'登录凭据超出了系统钥匙串单条记录的长度限制。请先将 NamesLink CLI 升级到最新版本,再重新运行 `nameslink login`。',
|
|
1401
1422
|
'guidance.plaintextCredentialOptIn':
|
|
1402
1423
|
'优先恢复 Windows Credential Manager。若明确接受仅本机开发环境的例外,请只为登录进程设置 `NAMESLINK_ALLOW_PLAINTEXT_CREDENTIAL_FILE=1`,并用 Windows ACL 保护配置文件。',
|
|
1403
1424
|
'guidance.credentialCorrupt':
|
|
@@ -1617,7 +1638,16 @@ export function formatRecoveryGuidance(error, i18n) {
|
|
|
1617
1638
|
const body = error?.body || {};
|
|
1618
1639
|
const interruption = body.data;
|
|
1619
1640
|
const resumeToken = interruption?.resumeToken;
|
|
1620
|
-
if (body.code === 'Cli.Keychain.
|
|
1641
|
+
if (body.code === 'Cli.Keychain.Locked') {
|
|
1642
|
+
return [i18n.t('guidance.keychainUnlock'), i18n.t('guidance.keychainRetry')];
|
|
1643
|
+
}
|
|
1644
|
+
if (body.code === 'Cli.Keychain.Unavailable') {
|
|
1645
|
+
if (interruption?.reason === 'INPUT_TOO_LARGE') {
|
|
1646
|
+
return [i18n.t('guidance.keychainInputTooLarge')];
|
|
1647
|
+
}
|
|
1648
|
+
if (interruption?.reason === 'BACKEND_UNAVAILABLE') {
|
|
1649
|
+
return [i18n.t('guidance.keychainUnavailable')];
|
|
1650
|
+
}
|
|
1621
1651
|
return [i18n.t('guidance.keychainUnlock'), i18n.t('guidance.keychainRetry')];
|
|
1622
1652
|
}
|
|
1623
1653
|
if (body.code === 'Cli.Credential.Corrupt') {
|
|
@@ -1704,9 +1734,16 @@ export function formatRecoveryGuidance(error, i18n) {
|
|
|
1704
1734
|
if (body.code === 'Cli.Config.Unreadable' || body.code === 'Cli.Config.Unwritable') {
|
|
1705
1735
|
return [
|
|
1706
1736
|
i18n.t('guidance.configPath', { path: interruption?.path || '-' }),
|
|
1707
|
-
|
|
1737
|
+
body.code === 'Cli.Config.Unreadable'
|
|
1738
|
+
? i18n.t('guidance.configRepair')
|
|
1739
|
+
: interruption?.reason === 'INSECURE_PERMISSIONS'
|
|
1740
|
+
? i18n.t('guidance.configPermissions', { dir: interruption?.dir || '-' })
|
|
1741
|
+
: i18n.t('guidance.configWritable'),
|
|
1708
1742
|
];
|
|
1709
1743
|
}
|
|
1744
|
+
if (body.code === 'Automation.Dns.SiteNotFound') {
|
|
1745
|
+
return [i18n.t('guidance.dnsSiteNotFound')];
|
|
1746
|
+
}
|
|
1710
1747
|
if (body.code === 'Account.ContactInfo.NotFilled' && resumeToken) {
|
|
1711
1748
|
const lines = [i18n.t('guidance.profileComplete', { token: resumeToken })];
|
|
1712
1749
|
if (interruption?.nextAction?.consoleUrl) {
|
package/src/oauth.mjs
CHANGED
|
@@ -90,6 +90,8 @@ export async function browserLogin(endpoint, i18n = createI18n('en-US'), options
|
|
|
90
90
|
launchFailed = true;
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
+
options.observe?.(browserOpened ? 'BROWSER_LAUNCHED'
|
|
94
|
+
: launchFailed ? 'BROWSER_LAUNCH_FAILED' : 'BROWSER_MANUAL');
|
|
93
95
|
if (options.json) {
|
|
94
96
|
const writeProgress = options.writeProgress || ((value) => process.stderr.write(value));
|
|
95
97
|
writeProgress(`${JSON.stringify({
|
|
@@ -106,16 +108,23 @@ export async function browserLogin(endpoint, i18n = createI18n('en-US'), options
|
|
|
106
108
|
process.stdout.write(`${i18n.t('login.openingHint')}\n`);
|
|
107
109
|
}
|
|
108
110
|
code = await waitForOAuthCallback(callback.promise, 300_000, setTimeout, clearTimeout, i18n);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
options.observe?.('CALLBACK_NOT_COMPLETED');
|
|
113
|
+
throw error;
|
|
109
114
|
} finally {
|
|
110
115
|
await new Promise((resolve) => server.close(resolve));
|
|
111
116
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
options.
|
|
118
|
-
|
|
117
|
+
options.observe?.('CALLBACK_RECEIVED');
|
|
118
|
+
try {
|
|
119
|
+
const credentials = await exchangeOAuthCode(
|
|
120
|
+
endpoint, { code, verifier, redirectUri }, i18n, options.fetchFn || fetch, options.journeyContext,
|
|
121
|
+
);
|
|
122
|
+
options.observe?.('TOKEN_RECEIVED');
|
|
123
|
+
return credentials;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
options.observe?.('TOKEN_NOT_RECEIVED');
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
119
128
|
}
|
|
120
129
|
|
|
121
130
|
export async function exchangeOAuthCode(
|
|
@@ -168,6 +177,10 @@ export async function exchangeOAuthCode(
|
|
|
168
177
|
if (!tokenResponse.ok || payload.code !== '200') {
|
|
169
178
|
throw new ApiError(payload, tokenResponse.status, i18n, endpoint);
|
|
170
179
|
}
|
|
180
|
+
if (typeof payload.data?.accessToken !== 'string' || !payload.data.accessToken
|
|
181
|
+
|| typeof payload.data?.refreshToken !== 'string' || !payload.data.refreshToken) {
|
|
182
|
+
throw new UnexpectedResponseError(endpoint, tokenResponse.status, 'MISSING_TOKENS');
|
|
183
|
+
}
|
|
171
184
|
return {
|
|
172
185
|
type: 'oauth',
|
|
173
186
|
endpoint: endpoint.replace(/\/$/, ''),
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { configPaths, loadConfig, validateEndpoint } from './config.mjs';
|
|
5
|
+
import { prepareJourney, requestJourneyHeaders } from './journey.mjs';
|
|
6
|
+
|
|
7
|
+
const ENDPOINTS = new Set([
|
|
8
|
+
'nameslink.com', 'www.nameslink.com', 'api.nameslink.com',
|
|
9
|
+
]);
|
|
10
|
+
const SAVE_FAILURE_REASONS = new Set([
|
|
11
|
+
'KEYCHAIN_LOCKED', 'KEYCHAIN_TIMEOUT', 'KEYCHAIN_UNAVAILABLE',
|
|
12
|
+
'KEYCHAIN_INPUT_TOO_LARGE', 'PLAINTEXT_DENIED', 'CONFIG_UNWRITABLE', 'UNKNOWN',
|
|
13
|
+
]);
|
|
14
|
+
const TELEMETRY_PLATFORMS = new Set(['darwin', 'win32', 'linux', 'other']);
|
|
15
|
+
|
|
16
|
+
/** Best-effort usage observations. Only the existing random journey, fixed event names, and allowlisted diagnostic enums leave the CLI. */
|
|
17
|
+
export function createStartupTelemetry({
|
|
18
|
+
environment = process.env, paths = configPaths(), readPreferences = loadConfig,
|
|
19
|
+
transport = () => fetch,
|
|
20
|
+
} = {}) {
|
|
21
|
+
if (environment.NAMESLINK_TELEMETRY_DISABLED === '1' || environment.NODE_TEST_CONTEXT) return undefined;
|
|
22
|
+
const pending = new Set();
|
|
23
|
+
const transports = new Map();
|
|
24
|
+
|
|
25
|
+
function report(endpoint, context, checkpoint, metadata) {
|
|
26
|
+
const delivery = send(endpoint, context, checkpoint, metadata);
|
|
27
|
+
pending.add(delivery);
|
|
28
|
+
delivery.then(() => pending.delete(delivery));
|
|
29
|
+
return delivery;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function send(endpoint, context, checkpoint, metadata) {
|
|
33
|
+
try {
|
|
34
|
+
if (!context || !isTelemetryEndpoint(endpoint)) return false;
|
|
35
|
+
if (!transports.has(endpoint)) transports.set(endpoint, transport(endpoint));
|
|
36
|
+
const response = await transports.get(endpoint)(telemetryUrl(endpoint, checkpoint, metadata), {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
credentials: 'omit',
|
|
39
|
+
redirect: 'error',
|
|
40
|
+
headers: requestJourneyHeaders(context),
|
|
41
|
+
signal: AbortSignal.timeout(2500),
|
|
42
|
+
});
|
|
43
|
+
await response.body?.cancel();
|
|
44
|
+
return response.status === 204;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function firstRun(endpointOption, command, version) {
|
|
51
|
+
try {
|
|
52
|
+
const preferences = await readPreferences({ readCredentials: false });
|
|
53
|
+
const { endpoint } = validateEndpoint(endpointOption || preferences.endpoint, environment);
|
|
54
|
+
if (!isTelemetryEndpoint(endpoint)) return undefined;
|
|
55
|
+
const key = createHash('sha256').update(endpoint).digest('hex').slice(0, 16);
|
|
56
|
+
const dir = join(paths.dir, 'observability');
|
|
57
|
+
const seed = join(dir, `first-run-${key}.json`);
|
|
58
|
+
const receipt = join(dir, `first-run-${key}.sent`);
|
|
59
|
+
let existing;
|
|
60
|
+
try {
|
|
61
|
+
await readFile(receipt);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error.code !== 'ENOENT') return undefined;
|
|
64
|
+
existing = await prepareFirstRun(dir, seed, preferences, command, version, environment);
|
|
65
|
+
const delivery = report(endpoint, existing.context, 'FIRST_RUN').then(async (accepted) => {
|
|
66
|
+
if (accepted) await writeFile(receipt, '', { mode: 0o600 }).catch(() => {});
|
|
67
|
+
});
|
|
68
|
+
pending.add(delivery);
|
|
69
|
+
delivery.then(() => pending.delete(delivery));
|
|
70
|
+
return existing.journey;
|
|
71
|
+
}
|
|
72
|
+
// A first invocation may have exited after --help without creating config.json.
|
|
73
|
+
return JSON.parse(await readFile(seed, 'utf8')).journey;
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return { firstRun, report, drain: () => Promise.all(pending) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function prepareFirstRun(dir, seed, preferences, command, version, environment) {
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(await readFile(seed, 'utf8'));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code !== 'ENOENT') throw error;
|
|
87
|
+
}
|
|
88
|
+
const first = prepareJourney(preferences, command, version, environment);
|
|
89
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
90
|
+
try {
|
|
91
|
+
await writeFile(seed, JSON.stringify(first), { flag: 'wx', mode: 0o600 });
|
|
92
|
+
return first;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error.code !== 'EEXIST') throw error;
|
|
95
|
+
return JSON.parse(await readFile(seed, 'utf8'));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function telemetryUrl(endpoint, checkpoint, metadata) {
|
|
100
|
+
const url = new URL(`${endpoint}/account/oauth/cli/telemetry/${checkpoint}`);
|
|
101
|
+
if (checkpoint === 'CREDENTIAL_SAVE_FAILED' && metadata && typeof metadata === 'object') {
|
|
102
|
+
if (typeof metadata.reason === 'string' && metadata.reason.trim()) {
|
|
103
|
+
const reason = metadata.reason.trim().toUpperCase();
|
|
104
|
+
url.searchParams.set('reason', SAVE_FAILURE_REASONS.has(reason) ? reason : 'UNKNOWN');
|
|
105
|
+
}
|
|
106
|
+
if (typeof metadata.platform === 'string' && metadata.platform.trim()) {
|
|
107
|
+
const platform = metadata.platform.trim().toLowerCase();
|
|
108
|
+
url.searchParams.set('platform', TELEMETRY_PLATFORMS.has(platform) ? platform : 'other');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return url.toString();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isTelemetryEndpoint(endpoint) {
|
|
115
|
+
const url = new URL(endpoint);
|
|
116
|
+
return url.protocol === 'https:' && ENDPOINTS.has(url.hostname) && url.pathname === '/api'
|
|
117
|
+
&& !url.port && !url.username && !url.password && !url.search && !url.hash;
|
|
118
|
+
}
|