netlify 27.17.0 → 27.18.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.
@@ -24,7 +24,7 @@ export declare function storeToken(globalConfig: Awaited<ReturnType<typeof getGl
24
24
  name?: string;
25
25
  email?: string;
26
26
  accessToken: string;
27
- }): void;
27
+ }): Promise<void>;
28
28
  /** Base command class that provides tracking and config initialization */
29
29
  export default class BaseCommand extends Command {
30
30
  #private;
@@ -14,6 +14,7 @@ import debug from 'debug';
14
14
  import { findUp } from 'find-up';
15
15
  import { deepMerge, pick } from '../utils/object-utilities.js';
16
16
  import { getAgent } from '../lib/http-agent.js';
17
+ import { skipKeychainMigrationPrompt, writeAuthTokenForStorage } from '../lib/secure-storage.js';
17
18
  import { NETLIFY_CYAN, USER_AGENT, chalk, logAndThrowError, logJson, exit, getRequestUserAgent, getToken, log, version, normalizeConfig, padLeft, pollForToken, sortOptions, warn, logError, } from '../utils/command-helpers.js';
18
19
  import { handleOptionError, isOptionError } from '../utils/command-error-handler.js';
19
20
  import { EXIT_CODES } from '../utils/exit-codes.js';
@@ -114,7 +115,9 @@ async function getRepositoryRoot(cwd) {
114
115
  return join(res, '..');
115
116
  }
116
117
  }
117
- export function storeToken(globalConfig, { userId, name, email, accessToken }) {
118
+ export async function storeToken(globalConfig, { userId, name, email, accessToken }) {
119
+ globalConfig.set('userId', userId);
120
+ const mode = await writeAuthTokenForStorage(userId, accessToken);
118
121
  const userData = deepMerge(globalConfig.get(`users.${userId}`), {
119
122
  id: userId,
120
123
  name,
@@ -127,7 +130,8 @@ export function storeToken(globalConfig, { userId, name, email, accessToken }) {
127
130
  },
128
131
  },
129
132
  });
130
- globalConfig.set('userId', userId);
133
+ if (mode === 'keychain')
134
+ delete userData.auth?.token;
131
135
  globalConfig.set(`users.${userId}`, userData);
132
136
  }
133
137
  /** Base command class that provides tracking and config initialization */
@@ -416,12 +420,12 @@ export default class BaseCommand extends Command {
416
420
  if (!userId) {
417
421
  return logAndThrowError('Could not retrieve user ID from Netlify API');
418
422
  }
419
- storeToken(this.netlify.globalConfig, { userId, name, email, accessToken });
420
423
  await identify({
421
424
  name,
422
425
  email,
423
426
  userId,
424
427
  });
428
+ await storeToken(this.netlify.globalConfig, { userId, name, email, accessToken });
425
429
  await track('user_login', {
426
430
  email,
427
431
  });
@@ -505,7 +509,11 @@ export default class BaseCommand extends Command {
505
509
  // Retrieve Site id and build state from the state.json
506
510
  // ==================================================
507
511
  const state = new LocalState(this.workingDir);
508
- const [token] = await getToken(flags.auth);
512
+ const isDiscardingStoredToken = actionCommand.name() === 'logout' || (actionCommand.name() === 'login' && Boolean(flags.new));
513
+ if (isDiscardingStoredToken)
514
+ skipKeychainMigrationPrompt();
515
+ const [token, tokenLocation] = await getToken(flags.auth);
516
+ this.setAnalyticsPayload({ authTokenSource: tokenLocation });
509
517
  const apiUrlOpts = {
510
518
  userAgent: getRequestUserAgent(),
511
519
  };
@@ -565,6 +565,9 @@ const printResults = ({ deployToProduction, uploadSourceZip, json, results, prod
565
565
  'Function logs': terminalLink(results.functionLogsUrl, results.functionLogsUrl, { fallback: false }),
566
566
  'Edge function Logs': terminalLink(results.edgeFunctionLogsUrl, results.edgeFunctionLogsUrl, { fallback: false }),
567
567
  };
568
+ if (results.serverLogsUrl) {
569
+ msgData['Server logs'] = terminalLink(results.serverLogsUrl, results.serverLogsUrl, { fallback: false });
570
+ }
568
571
  log('');
569
572
  // Note: this is leakily mimicking the @netlify/build heading style
570
573
  log(chalk.cyanBright.bold(`🚀 Deploy complete\n${'─'.repeat(64)}`));
@@ -579,6 +582,9 @@ const printResults = ({ deployToProduction, uploadSourceZip, json, results, prod
579
582
  function_logs: results.functionLogsUrl,
580
583
  edge_function_logs: results.edgeFunctionLogsUrl,
581
584
  };
585
+ if (results.serverLogsUrl) {
586
+ jsonData.server_logs = results.serverLogsUrl;
587
+ }
582
588
  if (deployToProduction) {
583
589
  jsonData.url = results.siteUrl;
584
590
  }
@@ -602,6 +608,9 @@ const printResults = ({ deployToProduction, uploadSourceZip, json, results, prod
602
608
  log(`\nBuild logs: <${results.logsUrl}>`);
603
609
  log(`Function logs: <${results.functionLogsUrl}>`);
604
610
  log(`Edge function logs: <${results.edgeFunctionLogsUrl}>`);
611
+ if (results.serverLogsUrl) {
612
+ log(`Server logs: <${results.serverLogsUrl}>`);
613
+ }
605
614
  if (!deployToProduction) {
606
615
  log();
607
616
  log('If everything looks good on your draft URL, deploy it to your main project URL with the --prod flag:');
@@ -2,7 +2,9 @@ import terminalLink from 'terminal-link';
2
2
  export const createLoginCommand = (program) => program
3
3
  .command('login')
4
4
  .description(`Login to your Netlify account
5
- Opens a web browser to acquire an OAuth token.`)
5
+ Opens a web browser to acquire an OAuth token, which is stored in your operating system's keychain
6
+ (macOS Keychain, Windows Credential Manager or Linux Secret Service) when available.
7
+ To store it in a plaintext config file instead, set NETLIFY_USE_LEGACY_AUTH_STORAGE=1. This is not recommended.`)
6
8
  .option('--new', 'Login to new Netlify account')
7
9
  .option('--request <message>', 'Create a login ticket for agent/human-in-the-loop auth')
8
10
  .option('--check <ticket-id>', 'Check the status of a login ticket created with --request')
@@ -32,7 +32,7 @@ export const loginCheck = async (options, apiOpts, globalConfig) => {
32
32
  if (!user.id) {
33
33
  return logAndThrowError('Could not retrieve user ID from Netlify API');
34
34
  }
35
- storeToken(globalConfig, {
35
+ await storeToken(globalConfig, {
36
36
  userId: user.id,
37
37
  name: user.full_name,
38
38
  email: user.email,
@@ -1,4 +1,5 @@
1
1
  import { chalk, exit, getToken, log, logAndThrowError } from '../../utils/command-helpers.js';
2
+ import { isInteractive } from '../../utils/scripted-commands.js';
2
3
  const msg = function (location) {
3
4
  switch (location) {
4
5
  case 'env':
@@ -7,6 +8,8 @@ const msg = function (location) {
7
8
  return 'via CLI --auth flag';
8
9
  case 'config':
9
10
  return 'via netlify config on your machine';
11
+ case 'keychain':
12
+ return "via your operating system's keychain";
10
13
  default:
11
14
  return '';
12
15
  }
@@ -30,6 +33,11 @@ export const login = async (options, command) => {
30
33
  if (accessToken && !options.new) {
31
34
  log(`Already logged in ${msg(location)}`);
32
35
  log();
36
+ // Agents run this when an older @netlify/mcp, which only reads config.json, says they're logged out
37
+ if (location === 'keychain' && !isInteractive()) {
38
+ log(`If another tool says you're not logged in, it may not support tokens stored in your operating system's keychain yet. For the Netlify MCP server, update ${chalk.cyanBright('@netlify/mcp')}, then restart your agent or editor.`);
39
+ log();
40
+ }
33
41
  log(`Run ${chalk.cyanBright('netlify status')} for account details`);
34
42
  log();
35
43
  log(`or run ${chalk.cyanBright('netlify switch')} to switch accounts`);
@@ -9,7 +9,7 @@ export const logout = async (_options, command) => {
9
9
  exit();
10
10
  }
11
11
  await track('user_logout');
12
- // unset userID without deleting key
12
+ // Keep stored tokens so `netlify switch` can return to this account without logging in again
13
13
  command.netlify.globalConfig.set('userId', null);
14
14
  if (location === 'env') {
15
15
  log('The "process.env.NETLIFY_AUTH_TOKEN" is still set in your terminal session');
@@ -74,18 +74,13 @@ export const createLogsCommand = (program) => {
74
74
  .command('logs')
75
75
  .alias('log')
76
76
  .description('View logs from your project')
77
- .addOption(new Option('-s, --source <type...>', 'Log sources to include. Defaults to functions and edge-functions').choices([
78
- 'functions',
79
- 'edge-functions',
80
- 'deploy',
81
- 'server',
82
- ]))
77
+ .addOption(new Option('-s, --source <type...>', 'Log sources to include. Defaults to functions, edge-functions and server').choices(['functions', 'edge-functions', 'deploy', 'server']))
83
78
  .addOption(new Option('--function <name...>', 'Filter to specific functions by name'))
84
79
  .addOption(new Option('--edge-function <name...>', 'Filter to specific edge functions by name or path'))
85
80
  .addOption(new Option('--since <time>', 'Start of the historical log window. Accepts a duration (e.g. 10m, 1h, 24h) or an ISO 8601 timestamp. Defaults to 10m'))
86
81
  .addOption(new Option('--until <time>', 'End of the historical log window. Accepts a duration or an ISO 8601 timestamp (defaults to now)'))
87
82
  .addOption(new Option('-f, --follow', 'Stream logs in real time instead of showing historical logs'))
88
- .addOption(new Option('-u, --url <url>', 'Show logs for the deploy behind the given URL. Supports deploy permalinks and branch subdomains. Can be used with all sources except server.'))
83
+ .addOption(new Option('-u, --url <url>', 'Show logs for the deploy behind the given URL. Supports deploy permalinks and branch subdomains. Server logs support branch subdomains only.'))
89
84
  .addOption(new Option('-d, --deploy-id <deploy-id>', 'Show logs for a specific deploy by ID, including failed builds. Can be used with all sources except server.'))
90
85
  .addOption(new Option('-l, --level <levels...>', `Log levels to include. Choices are:${CLI_LOG_LEVEL_CHOICES_STRING}`))
91
86
  .addOption(new Option('--json', 'Output logs as JSON Lines'))
@@ -54,11 +54,14 @@ export declare const hostnamesForSite: (siteInfo: {
54
54
  canonicalHostnames: Set<string>;
55
55
  netlifyAppBaseHost: string | null;
56
56
  };
57
- export declare const resolveDeployIdFromUrl: (urlInput: string, client: NetlifyAPI, siteId: string, siteInfo: {
57
+ export declare const resolveDeployFromUrl: (urlInput: string, client: NetlifyAPI, siteId: string, siteInfo: {
58
58
  name?: string;
59
59
  custom_domain?: string;
60
60
  domain_aliases?: string[];
61
61
  url?: string;
62
62
  ssl_url?: string;
63
- }) => Promise<string | undefined>;
63
+ }) => Promise<{
64
+ deployId?: string;
65
+ branch?: string;
66
+ }>;
64
67
  //# sourceMappingURL=log-api.d.ts.map
@@ -169,7 +169,9 @@ export const hostnamesForSite = (siteInfo) => {
169
169
  }
170
170
  return { canonicalHostnames: canonical, netlifyAppBaseHost };
171
171
  };
172
- export const resolveDeployIdFromUrl = async (urlInput, client, siteId, siteInfo) => {
172
+ // resolveDeployFromUrl returns nothing for the project's production URLs, a
173
+ // deploy ID for a permalink, and a deploy ID with its branch for a branch subdomain.
174
+ export const resolveDeployFromUrl = async (urlInput, client, siteId, siteInfo) => {
173
175
  let parsed;
174
176
  try {
175
177
  parsed = new URL(urlInput.includes('://') ? urlInput : `https://${urlInput}`);
@@ -180,7 +182,7 @@ export const resolveDeployIdFromUrl = async (urlInput, client, siteId, siteInfo)
180
182
  const hostname = parsed.hostname.toLowerCase();
181
183
  const { canonicalHostnames, netlifyAppBaseHost } = hostnamesForSite(siteInfo);
182
184
  if (canonicalHostnames.has(hostname)) {
183
- return undefined;
185
+ return {};
184
186
  }
185
187
  const mismatchError = new Error(`The URL ${urlInput} doesn't seem to match the linked project${siteInfo.name ? ` (${siteInfo.name})` : ''}.`);
186
188
  if (!netlifyAppBaseHost || !hostname.endsWith(`.netlify.app`)) {
@@ -197,13 +199,14 @@ export const resolveDeployIdFromUrl = async (urlInput, client, siteId, siteInfo)
197
199
  throw mismatchError;
198
200
  }
199
201
  if (DEPLOY_ID_RE.test(prefix)) {
200
- return prefix;
202
+ return { deployId: prefix };
201
203
  }
202
204
  const deploys = (await client.listSiteDeploys({ siteId, branch: prefix, per_page: 20 }));
203
205
  const ready = deploys.find((deploy) => deploy.state === 'ready');
204
206
  if (!ready) {
205
207
  throw new Error(`No ready deploys found for branch ${prefix}`);
206
208
  }
207
- return ready.id;
209
+ // The subdomain holds a slug of the branch, so its name comes from the deploy.
210
+ return { deployId: ready.id, branch: ready.branch ?? prefix };
208
211
  };
209
212
  //# sourceMappingURL=log-api.js.map
@@ -3,7 +3,7 @@ import type BaseCommand from '../base-command.js';
3
3
  import type { LogsOptionValues } from './option_values.js';
4
4
  type Source = 'functions' | 'edge-functions' | 'deploy' | 'server';
5
5
  export declare const logsCommand: (options: LogsOptionValues, command: BaseCommand) => Promise<undefined>;
6
- export declare const runFollowMode: ({ sources, client, siteId, accessToken, deployId, deployTargeted, functionNames, edgeFunctionNames, levelsToPrint, json, }: {
6
+ export declare const runFollowMode: ({ sources, client, siteId, accessToken, deployId, deployTargeted, functionNames, edgeFunctionNames, levelsToPrint, serverBranches, json, }: {
7
7
  sources: Source[];
8
8
  client: NetlifyAPI;
9
9
  siteId: string;
@@ -13,6 +13,7 @@ export declare const runFollowMode: ({ sources, client, siteId, accessToken, dep
13
13
  functionNames: string[];
14
14
  edgeFunctionNames: string[];
15
15
  levelsToPrint: string[];
16
+ serverBranches: string[];
16
17
  json: boolean;
17
18
  }) => Promise<undefined>;
18
19
  export {};
@@ -1,5 +1,5 @@
1
1
  import { chalk, log, logAndThrowError, logError, netlifyCommand, warn } from '../../utils/command-helpers.js';
2
- import { createColorAssigner, DEPLOY_ID_RE, formatJsonLine, formatLogLine, parseTimeValue, resolveDeployIdFromUrl, SOURCE_INDICATORS, SOURCE_LABELS, } from './log-api.js';
2
+ import { createColorAssigner, DEPLOY_ID_RE, formatJsonLine, formatLogLine, parseTimeValue, resolveDeployFromUrl, SOURCE_INDICATORS, SOURCE_LABELS, } from './log-api.js';
3
3
  import { LOG_LEVELS_LIST, CLI_LOG_LEVEL_CHOICES_STRING } from './log-levels.js';
4
4
  import { fetchDeployHistoricalLogs, findCurrentBuildingDeploy, findLatestFinishedDeploy, findLatestReadyDeploy, isDeployFinished, streamDeploy, } from './sources/deploy.js';
5
5
  import { fetchEdgeFunctionHistoricalLogs, streamEdgeFunctions } from './sources/edge-functions.js';
@@ -8,6 +8,18 @@ import { fetchServerHistoricalLogs, streamServer } from './sources/server.js';
8
8
  const VALID_SOURCES = ['functions', 'edge-functions', 'deploy', 'server'];
9
9
  const DEFAULT_SINCE = '10m';
10
10
  const DEPLOY_STREAM_IDLE_CLOSE_MS = 3_000;
11
+ // Server logs from a deploy without a branch are recorded under this branch.
12
+ const NO_BRANCH_PRODUCTION = '__nf-no-branch-production-traffic';
13
+ // getProductionBranches returns the branches that make up production, the same
14
+ // ones the Netlify UI shows as a server's production logs.
15
+ const getProductionBranches = (siteInfo) => {
16
+ const publishedBranch = siteInfo.published_deploy?.branch;
17
+ const branches = siteInfo.build_settings?.provider
18
+ ? [siteInfo.build_settings.repo_branch, publishedBranch]
19
+ : // CLI deploys can have an empty branch.
20
+ [publishedBranch?.length ? publishedBranch : 'main'];
21
+ return [...new Set([...branches.filter((branch) => Boolean(branch)), NO_BRANCH_PRODUCTION])];
22
+ };
11
23
  const parseSources = (rawSources) => {
12
24
  const sources = [];
13
25
  for (const s of rawSources) {
@@ -124,13 +136,15 @@ export const logsCommand = async (options, command) => {
124
136
  }
125
137
  if (sources.length === 0) {
126
138
  sources = ['functions', 'edge-functions'];
139
+ if (siteInfo.published_deploy?.server) {
140
+ sources.push('server');
141
+ }
127
142
  }
128
143
  }
129
- if (sources.includes('server') && (options.deployId || options.url)) {
130
- return logAndThrowError('Server logs cannot be filtered by deploy. Remove --deploy-id and --url, or the server source.');
131
- }
144
+ const serverByDefault = !rawSources && sources.includes('server');
132
145
  let deployId;
133
146
  let deployTargeted = false;
147
+ let urlBranch;
134
148
  if (options.deployId) {
135
149
  const explicitDeployId = options.deployId.trim();
136
150
  if (!DEPLOY_ID_RE.test(explicitDeployId)) {
@@ -144,7 +158,9 @@ export const logsCommand = async (options, command) => {
144
158
  }
145
159
  else if (options.url) {
146
160
  try {
147
- deployId = await resolveDeployIdFromUrl(options.url, client, siteId, siteInfo);
161
+ const resolved = await resolveDeployFromUrl(options.url, client, siteId, siteInfo);
162
+ deployId = resolved.deployId;
163
+ urlBranch = resolved.branch;
148
164
  deployTargeted = deployId !== undefined;
149
165
  }
150
166
  catch (error) {
@@ -161,6 +177,18 @@ export const logsCommand = async (options, command) => {
161
177
  return logAndThrowError(message);
162
178
  }
163
179
  }
180
+ // Server logs can be filtered by branch, but not by deploy.
181
+ if (sources.includes('server') && deployTargeted && !urlBranch) {
182
+ if (serverByDefault) {
183
+ sources = sources.filter((source) => source !== 'server');
184
+ }
185
+ else {
186
+ return logAndThrowError(options.deployId
187
+ ? 'Server logs cannot be filtered by deploy. Remove --deploy-id or the server source.'
188
+ : 'Server logs cannot be filtered by deploy. Use a branch URL instead of a deploy permalink, or remove the server source.');
189
+ }
190
+ }
191
+ const serverBranches = urlBranch ? [urlBranch] : getProductionBranches(siteInfo);
164
192
  const now = Date.now();
165
193
  let historicalRange;
166
194
  if (!follow) {
@@ -213,6 +241,7 @@ export const logsCommand = async (options, command) => {
213
241
  from: historicalRange.from,
214
242
  to: historicalRange.to,
215
243
  levelsToPrint,
244
+ serverBranches,
216
245
  json,
217
246
  timeDescription: humanizeTimeRange(sinceValue, untilValue),
218
247
  });
@@ -231,10 +260,11 @@ export const logsCommand = async (options, command) => {
231
260
  functionNames,
232
261
  edgeFunctionNames,
233
262
  levelsToPrint,
263
+ serverBranches,
234
264
  json,
235
265
  });
236
266
  };
237
- const runHistoricalMode = async ({ sources, client, siteId, accessToken, deployId, functionNames, edgeFunctionNames, from, to, levelsToPrint, json, timeDescription, }) => {
267
+ const runHistoricalMode = async ({ sources, client, siteId, accessToken, deployId, functionNames, edgeFunctionNames, from, to, levelsToPrint, serverBranches, json, timeDescription, }) => {
238
268
  const allEntries = [];
239
269
  if (sources.includes('deploy') && deployId) {
240
270
  const deployEntries = await fetchDeployHistoricalLogs({
@@ -285,6 +315,7 @@ const runHistoricalMode = async ({ sources, client, siteId, accessToken, deployI
285
315
  from,
286
316
  to,
287
317
  levels: levelsToPrint,
318
+ branches: serverBranches,
288
319
  });
289
320
  allEntries.push(...entries);
290
321
  serverLogsTruncated = truncated;
@@ -312,7 +343,7 @@ const runHistoricalMode = async ({ sources, client, siteId, accessToken, deployI
312
343
  }
313
344
  }
314
345
  };
315
- export const runFollowMode = async ({ sources, client, siteId, accessToken, deployId, deployTargeted, functionNames, edgeFunctionNames, levelsToPrint, json, }) => {
346
+ export const runFollowMode = async ({ sources, client, siteId, accessToken, deployId, deployTargeted, functionNames, edgeFunctionNames, levelsToPrint, serverBranches, json, }) => {
316
347
  const assignColor = createColorAssigner();
317
348
  const onEntry = (entry) => {
318
349
  const key = `${entry.source}:${entry.name}`;
@@ -355,6 +386,7 @@ export const runFollowMode = async ({ sources, client, siteId, accessToken, depl
355
386
  siteId,
356
387
  accessToken,
357
388
  levels: levelsToPrint,
389
+ branches: serverBranches,
358
390
  onEntry,
359
391
  onError: logError,
360
392
  });
@@ -6,15 +6,17 @@ export declare const fetchServerHistoricalLogs: (options: {
6
6
  from: number;
7
7
  to: number;
8
8
  levels?: string[];
9
+ branches: string[];
9
10
  }) => Promise<{
10
11
  entries: LogEntry[];
11
12
  truncated: boolean;
12
13
  }>;
13
- export declare const streamServer: ({ apiBase, siteId, accessToken, levels, onEntry, onError, intervalMs, }: {
14
+ export declare const streamServer: ({ apiBase, siteId, accessToken, levels, branches, onEntry, onError, intervalMs, }: {
14
15
  apiBase: string;
15
16
  siteId: string;
16
17
  accessToken: string | null | undefined;
17
18
  levels?: string[];
19
+ branches: string[];
18
20
  onEntry: (entry: LogEntry) => void;
19
21
  onError?: (error: Error) => void;
20
22
  intervalMs?: number;
@@ -37,7 +37,7 @@ const toEntry = (line) => ({
37
37
  level: line.severity ? line.severity.toUpperCase() : 'INFO',
38
38
  message: line.body,
39
39
  });
40
- const fetchServerLogLines = async ({ apiBase, siteId, accessToken, from, to, levels, }) => {
40
+ const fetchServerLogLines = async ({ apiBase, siteId, accessToken, from, to, levels, branches, }) => {
41
41
  // The API pages newest first and sends millisecond timestamps, though it
42
42
  // orders by finer ones, so reversing is what keeps same-millisecond lines in order.
43
43
  const lines = [];
@@ -58,6 +58,9 @@ const fetchServerLogLines = async ({ apiBase, siteId, accessToken, from, to, lev
58
58
  if (severity) {
59
59
  url.searchParams.set('severity', severity);
60
60
  }
61
+ for (const branch of branches) {
62
+ url.searchParams.append('branch', branch);
63
+ }
61
64
  const response = await debugFetch(url.toString(), {
62
65
  headers: {
63
66
  Authorization: `Bearer ${accessToken ?? ''}`,
@@ -79,7 +82,7 @@ export const fetchServerHistoricalLogs = async (options) => {
79
82
  const { lines, truncated } = await fetchServerLogLines(options);
80
83
  return { entries: lines.map(toEntry), truncated };
81
84
  };
82
- export const streamServer = ({ apiBase, siteId, accessToken, levels, onEntry, onError, intervalMs = POLL_INTERVAL_MS, }) => {
85
+ export const streamServer = ({ apiBase, siteId, accessToken, levels, branches, onEntry, onError, intervalMs = POLL_INTERVAL_MS, }) => {
83
86
  let newest = Date.now();
84
87
  let seen = new Map();
85
88
  let failing = false;
@@ -93,6 +96,7 @@ export const streamServer = ({ apiBase, siteId, accessToken, levels, onEntry, on
93
96
  siteId,
94
97
  accessToken,
95
98
  levels,
99
+ branches,
96
100
  from: newest - LOOK_BACK_MS,
97
101
  to: Date.now(),
98
102
  });
@@ -1,4 +1,5 @@
1
1
  import clean from 'clean-deep';
2
+ import { getLegacyConfigFilePath } from '@netlify/dev-utils';
2
3
  import prettyjson from 'prettyjson';
3
4
  import { chalk, logAndThrowError, exit, getToken, log, logJson, warn, } from '../../utils/command-helpers.js';
4
5
  import { isInteractive } from '../../utils/scripted-commands.js';
@@ -7,10 +8,24 @@ export const STATUS_ERROR_CODES = {
7
8
  NOT_LOGGED_IN: 'NOT_LOGGED_IN',
8
9
  NOT_LINKED: 'NOT_LINKED',
9
10
  };
11
+ const formatTokenStorage = (location) => {
12
+ switch (location) {
13
+ case 'keychain':
14
+ return "operating system's keychain";
15
+ case 'config':
16
+ return `plaintext config file (${getLegacyConfigFilePath()})`;
17
+ case 'env':
18
+ return 'NETLIFY_AUTH_TOKEN environment variable';
19
+ case 'flag':
20
+ return '--auth flag';
21
+ default:
22
+ return 'not stored';
23
+ }
24
+ };
10
25
  export const status = async (options, command) => {
11
26
  const { accounts, api, globalConfig, site, siteInfo } = command.netlify;
12
27
  const currentUserId = globalConfig.get('userId');
13
- const [accessToken] = await getToken();
28
+ const [accessToken, tokenLocation] = await getToken(options.auth);
14
29
  if (!accessToken) {
15
30
  if (options.json) {
16
31
  logJson({
@@ -76,7 +91,7 @@ export const status = async (options, command) => {
76
91
  // TODO(serhalp) `deep-clean` type declaration is invalid (this is obscured by `skipLibCheck`). Open a PR or use
77
92
  // another lib.
78
93
  clean(accountData);
79
- log(prettyjson.render(cleanAccountData));
94
+ log(prettyjson.render({ ...cleanAccountData, 'Auth token storage': formatTokenStorage(tokenLocation) }));
80
95
  if (!siteId) {
81
96
  if (options.json) {
82
97
  logJson({
@@ -97,6 +112,10 @@ export const status = async (options, command) => {
97
112
  if (options.json) {
98
113
  logJson({
99
114
  account: cleanAccountData,
115
+ authTokenStorage: {
116
+ source: tokenLocation,
117
+ ...(tokenLocation === 'config' ? { configPath: getLegacyConfigFilePath() } : {}),
118
+ },
100
119
  siteData: {
101
120
  'site-name': siteInfo.name,
102
121
  'config-path': site.configPath,
@@ -0,0 +1,8 @@
1
+ export type TokenStorageMode = 'keychain' | 'legacy';
2
+ export declare const skipKeychainMigrationPrompt: () => void;
3
+ export declare const getStoredAPIToken: (env?: NodeJS.ProcessEnv) => Promise<{
4
+ token: string | undefined;
5
+ fromKeychain: boolean;
6
+ }>;
7
+ export declare const writeAuthTokenForStorage: (userId: string, accessToken: string, env?: NodeJS.ProcessEnv) => Promise<TokenStorageMode>;
8
+ //# sourceMappingURL=secure-storage.d.ts.map
@@ -0,0 +1,98 @@
1
+ import { confirm } from '@inquirer/prompts';
2
+ import { getGlobalConfigStore, getLegacyConfigFilePath, isLegacyAuthStorageForced, LEGACY_STORAGE_ENV_VAR, readStoredAPIToken, storeTokenInKeychain, } from '@netlify/dev-utils';
3
+ import { chalk, isLogSuppressed, log, warn } from '../utils/command-helpers.js';
4
+ import { isInteractive } from '../utils/scripted-commands.js';
5
+ import { reportError, track } from '../utils/telemetry/index.js';
6
+ let skipMigrationThisSession = false;
7
+ let keychainReadFailureWarned = false;
8
+ const skipMigrationKey = (userId) => `users.${userId}.auth.skipKeychainMigration`;
9
+ const trackStored = (mode, migrated, keychainFailed = false) => {
10
+ void track('user_authTokenStored', { mode, migrated, ...(keychainFailed ? { keychainFailed: true } : {}) });
11
+ };
12
+ const warnKeychainReadFailed = (error) => {
13
+ if (keychainReadFailureWarned)
14
+ return;
15
+ keychainReadFailureWarned = true;
16
+ warn(`Could not read your Netlify auth token from your keychain: ${error.message}
17
+ If your keychain is locked or access was denied, unlock it or allow access and try again, or run ${chalk.cyanBright('netlify login --new')}. In scripts, CI or agents, set ${chalk.cyanBright('NETLIFY_AUTH_TOKEN')} instead.`);
18
+ };
19
+ export const skipKeychainMigrationPrompt = () => {
20
+ skipMigrationThisSession = true;
21
+ };
22
+ const canUseKeychainInteractively = (env) => isInteractive() || env.TESTING_PROMPTS === 'true';
23
+ const isPromptExit = (error) => error instanceof Error && error.name === 'ExitPromptError';
24
+ const attemptMigration = async (token, env) => {
25
+ if (isLegacyAuthStorageForced(env) ||
26
+ !canUseKeychainInteractively(env) ||
27
+ skipMigrationThisSession ||
28
+ // --json and --silent hide the prompt's context lines but not the question itself
29
+ isLogSuppressed())
30
+ return false;
31
+ const globalConfig = await getGlobalConfigStore();
32
+ const userId = globalConfig.get('userId');
33
+ if (userId == null || globalConfig.get(skipMigrationKey(userId)) === true)
34
+ return false;
35
+ skipMigrationThisSession = true;
36
+ log();
37
+ log(`Your Netlify auth token is stored in plaintext at ${chalk.cyanBright(getLegacyConfigFilePath())}.`);
38
+ log(`The CLI can move it to your operating system's keychain, which is more secure. You may be asked to allow access.`);
39
+ log();
40
+ let confirmed;
41
+ try {
42
+ confirmed = await confirm({ message: 'Move the token to the keychain now?', default: true });
43
+ }
44
+ catch (error) {
45
+ if (isPromptExit(error))
46
+ throw error;
47
+ void reportError(error, { severity: 'error' });
48
+ return false;
49
+ }
50
+ if (!confirmed) {
51
+ globalConfig.set(skipMigrationKey(userId), true);
52
+ log(chalk.dim(`The CLI won't ask again. To move it later, run ${chalk.cyanBright('netlify login --new')} in a terminal.`));
53
+ void track('user_authTokenMigrationDeclined', {});
54
+ return false;
55
+ }
56
+ const write = await storeTokenInKeychain(userId, token);
57
+ if (write.status === 'error') {
58
+ globalConfig.set(skipMigrationKey(userId), true);
59
+ warn(`Could not save your token to your keychain: ${write.error.message}
60
+ It stays in plaintext and the CLI won't ask again. To retry, unlock your keychain and run ${chalk.cyanBright('netlify login --new')}.`);
61
+ trackStored('legacy', false, true);
62
+ return false;
63
+ }
64
+ globalConfig.set(`users.${userId}.auth.token`, undefined);
65
+ log(chalk.green('Auth token moved to your keychain.'));
66
+ trackStored('keychain', true);
67
+ return true;
68
+ };
69
+ export const getStoredAPIToken = async (env = process.env) => {
70
+ const stored = await readStoredAPIToken(env);
71
+ switch (stored.source) {
72
+ case 'keychain':
73
+ return { token: stored.token, fromKeychain: true };
74
+ case 'config':
75
+ return { token: stored.token, fromKeychain: await attemptMigration(stored.token, env) };
76
+ case 'none':
77
+ if (stored.keychainError)
78
+ warnKeychainReadFailed(stored.keychainError);
79
+ return { token: undefined, fromKeychain: false };
80
+ }
81
+ };
82
+ // Non-interactive logins never touch the keychain, so they can't trigger an OS dialog nobody answers
83
+ export const writeAuthTokenForStorage = async (userId, accessToken, env = process.env) => {
84
+ if (isLegacyAuthStorageForced(env) || !canUseKeychainInteractively(env)) {
85
+ trackStored('legacy', false);
86
+ return 'legacy';
87
+ }
88
+ const write = await storeTokenInKeychain(userId, accessToken);
89
+ if (write.status === 'stored') {
90
+ trackStored('keychain', false);
91
+ return 'keychain';
92
+ }
93
+ warn(`Could not save your auth token to your keychain: ${write.error.message}
94
+ It was saved in plaintext at ${getLegacyConfigFilePath()} instead. To retry, unlock your keychain and run ${chalk.cyanBright('netlify login --new')}. To always use plaintext storage and hide this warning, set ${chalk.cyanBright(`${LEGACY_STORAGE_ENV_VAR}=1`)}.`);
95
+ trackStored('legacy', false, true);
96
+ return 'legacy';
97
+ };
98
+ //# sourceMappingURL=secure-storage.js.map
@@ -43,7 +43,6 @@ export declare const pollForToken: ({ api, ticket, }: {
43
43
  /**
44
44
  * Get a netlify token
45
45
  * @param {string} [tokenFromOptions] optional token from the provided --auth options
46
- * @returns {Promise<[null|string, 'flag' | 'env' |'config' |'not found']>}
47
46
  */
48
47
  export type TokenTuple = [string | null, TokenLocation];
49
48
  export declare const getToken: (tokenFromOptions?: string) => Promise<TokenTuple>;
@@ -51,6 +50,7 @@ export declare const getToken: (tokenFromOptions?: string) => Promise<TokenTuple
51
50
  * logs a json message
52
51
  */
53
52
  export declare const logJson: (message?: unknown) => void;
53
+ export declare const isLogSuppressed: () => boolean;
54
54
  export declare const log: (message?: string, ...args: string[]) => void;
55
55
  export declare const logPadded: (message?: string, ...args: string[]) => void;
56
56
  /**
@@ -2,10 +2,10 @@ import os from 'os';
2
2
  import fs from 'fs';
3
3
  import process from 'process';
4
4
  import { format, inspect } from 'util';
5
- import { getAPIToken } from '@netlify/dev-utils';
6
5
  import { Chalk } from 'chalk';
7
6
  import WSL from 'is-wsl';
8
7
  import terminalLink from 'terminal-link';
8
+ import { getStoredAPIToken } from '../lib/secure-storage.js';
9
9
  import { startSpinner } from '../lib/spinner.js';
10
10
  import { getDrivingAgent } from './agent-detection.js';
11
11
  import getCLIPackageJson from './get-cli-package-json.js';
@@ -104,10 +104,9 @@ export const getToken = async (tokenFromOptions) => {
104
104
  if (NETLIFY_AUTH_TOKEN && NETLIFY_AUTH_TOKEN !== 'null') {
105
105
  return [NETLIFY_AUTH_TOKEN, 'env'];
106
106
  }
107
- // 3. If no env var use global user setting
108
- const tokenFromConfig = await getAPIToken();
109
- if (tokenFromConfig) {
110
- return [tokenFromConfig, 'config'];
107
+ const { token, fromKeychain } = await getStoredAPIToken();
108
+ if (token) {
109
+ return [token, fromKeychain ? 'keychain' : 'config'];
111
110
  }
112
111
  return [null, 'not found'];
113
112
  };
@@ -122,9 +121,9 @@ export const logJson = (message = '') => {
122
121
  process.stdout.write(JSON.stringify(message, null, 2));
123
122
  }
124
123
  };
124
+ export const isLogSuppressed = () => argv.includes('--json') || argv.includes('--silent') || isDefaultJson();
125
125
  export const log = (message = '', ...args) => {
126
- // If --silent or --json flag passed disable logger
127
- if (argv.includes('--json') || argv.includes('--silent') || isDefaultJson()) {
126
+ if (isLogSuppressed()) {
128
127
  return;
129
128
  }
130
129
  message = typeof message === 'string' ? message : inspect(message);
@@ -4,6 +4,7 @@ export interface DeployUrls {
4
4
  logsUrl: string;
5
5
  functionLogsUrl: string;
6
6
  edgeFunctionLogsUrl: string;
7
+ serverLogsUrl?: string | undefined;
7
8
  }
8
9
  interface DeployUrlFields {
9
10
  id?: string;
@@ -12,6 +13,8 @@ interface DeployUrlFields {
12
13
  deploy_ssl_url?: string;
13
14
  deploy_url?: string;
14
15
  admin_url?: string;
16
+ branch?: string;
17
+ server?: object | null;
15
18
  }
16
19
  export declare const getDeployUrls: (deploy: DeployUrlFields, { deployToProduction }: {
17
20
  deployToProduction: boolean;
@@ -1,3 +1,14 @@
1
+ const getServerLogsUrl = (deploy, deployToProduction) => {
2
+ if (!deploy.server) {
3
+ return undefined;
4
+ }
5
+ const params = new URLSearchParams({ panel: 'logs' });
6
+ // Server logs are kept per branch, not per deploy.
7
+ if (!deployToProduction && deploy.branch) {
8
+ params.set('branch', deploy.branch);
9
+ }
10
+ return `${deploy.admin_url ?? ''}/server?${params.toString()}`;
11
+ };
1
12
  export const getDeployUrls = (deploy, { deployToProduction }) => {
2
13
  const functionLogsUrl = `${deploy.admin_url ?? ''}/logs/functions`;
3
14
  const edgeFunctionLogsUrl = `${deploy.admin_url ?? ''}/logs/edge-functions`;
@@ -9,6 +20,7 @@ export const getDeployUrls = (deploy, { deployToProduction }) => {
9
20
  edgeFunctionLogsUrl: deployToProduction
10
21
  ? edgeFunctionLogsUrl
11
22
  : `${edgeFunctionLogsUrl}?scope=deployid:${deploy.id ?? ''}`,
23
+ serverLogsUrl: getServerLogsUrl(deploy, deployToProduction),
12
24
  };
13
25
  };
14
26
  //# sourceMappingURL=deploy-urls.js.map
@@ -140,6 +140,10 @@ export interface SiteInfo {
140
140
  published_at: string;
141
141
  required: string[];
142
142
  required_functions: string[];
143
+ server?: {
144
+ region: string;
145
+ script_id: string;
146
+ } | null;
143
147
  review_id: number;
144
148
  review_url: string;
145
149
  screenshot_url: string;
@@ -171,7 +175,7 @@ export interface SiteInfo {
171
175
  url: string;
172
176
  user_id: string;
173
177
  }
174
- export type TokenLocation = 'env' | 'flag' | 'config' | 'not found';
178
+ export type TokenLocation = 'env' | 'flag' | 'config' | 'keychain' | 'not found';
175
179
  export type EnvVar = {
176
180
  key: string;
177
181
  scopes: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "netlify",
3
- "version": "27.17.0",
3
+ "version": "27.18.0",
4
4
  "description": "Netlify command line tool",
5
5
  "keywords": [
6
6
  "api",
@@ -55,12 +55,12 @@
55
55
  "@inquirer/prompts": "^8.7.2",
56
56
  "@netlify/ai": "^1.0.2",
57
57
  "@netlify/api": "^15.1.6",
58
- "@netlify/blobs": "^11.1.7",
58
+ "@netlify/blobs": "^11.1.9",
59
59
  "@netlify/build": "^37.7.6",
60
60
  "@netlify/build-info": "^11.3.1",
61
61
  "@netlify/config": "^25.6.2",
62
- "@netlify/dev": "^5.1.12",
63
- "@netlify/dev-utils": "^6.0.4",
62
+ "@netlify/dev": "^5.1.16",
63
+ "@netlify/dev-utils": "^6.1.0",
64
64
  "@netlify/edge-bundler": "^16.2.0",
65
65
  "@netlify/edge-functions": "^4.0.3",
66
66
  "@netlify/edge-functions-bootstrap": "^3.2.0",