@nibgat/ncli 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/dist/bin/ncli.d.ts +2 -0
  4. package/dist/bin/ncli.js +9 -0
  5. package/dist/bin/ncli.js.map +1 -0
  6. package/dist/commands/auth.d.ts +2 -0
  7. package/dist/commands/auth.js +723 -0
  8. package/dist/commands/auth.js.map +1 -0
  9. package/dist/commands/buyment.d.ts +2 -0
  10. package/dist/commands/buyment.js +174 -0
  11. package/dist/commands/buyment.js.map +1 -0
  12. package/dist/commands/cloud.d.ts +2 -0
  13. package/dist/commands/cloud.js +281 -0
  14. package/dist/commands/cloud.js.map +1 -0
  15. package/dist/commands/context.d.ts +25 -0
  16. package/dist/commands/context.js +92 -0
  17. package/dist/commands/context.js.map +1 -0
  18. package/dist/commands/front.d.ts +2 -0
  19. package/dist/commands/front.js +135 -0
  20. package/dist/commands/front.js.map +1 -0
  21. package/dist/commands/git.d.ts +2 -0
  22. package/dist/commands/git.js +726 -0
  23. package/dist/commands/git.js.map +1 -0
  24. package/dist/commands/health.d.ts +2 -0
  25. package/dist/commands/health.js +99 -0
  26. package/dist/commands/health.js.map +1 -0
  27. package/dist/commands/mail.d.ts +2 -0
  28. package/dist/commands/mail.js +265 -0
  29. package/dist/commands/mail.js.map +1 -0
  30. package/dist/commands/pipeline.d.ts +2 -0
  31. package/dist/commands/pipeline.js +333 -0
  32. package/dist/commands/pipeline.js.map +1 -0
  33. package/dist/commands/profile.d.ts +2 -0
  34. package/dist/commands/profile.js +229 -0
  35. package/dist/commands/profile.js.map +1 -0
  36. package/dist/commands/runner.d.ts +2 -0
  37. package/dist/commands/runner.js +266 -0
  38. package/dist/commands/runner.js.map +1 -0
  39. package/dist/commands/support.d.ts +2 -0
  40. package/dist/commands/support.js +133 -0
  41. package/dist/commands/support.js.map +1 -0
  42. package/dist/constants/index.d.ts +26 -0
  43. package/dist/constants/index.js +40 -0
  44. package/dist/constants/index.js.map +1 -0
  45. package/dist/http/client.d.ts +46 -0
  46. package/dist/http/client.js +262 -0
  47. package/dist/http/client.js.map +1 -0
  48. package/dist/http/coreApi.d.ts +136 -0
  49. package/dist/http/coreApi.js +485 -0
  50. package/dist/http/coreApi.js.map +1 -0
  51. package/dist/http/gitApi.d.ts +128 -0
  52. package/dist/http/gitApi.js +255 -0
  53. package/dist/http/gitApi.js.map +1 -0
  54. package/dist/index.d.ts +10 -0
  55. package/dist/index.js +46 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/pipeline/detect.d.ts +13 -0
  58. package/dist/pipeline/detect.js +90 -0
  59. package/dist/pipeline/detect.js.map +1 -0
  60. package/dist/pipeline/release.d.ts +36 -0
  61. package/dist/pipeline/release.js +250 -0
  62. package/dist/pipeline/release.js.map +1 -0
  63. package/dist/pipeline/schema.d.ts +10 -0
  64. package/dist/pipeline/schema.js +155 -0
  65. package/dist/pipeline/schema.js.map +1 -0
  66. package/dist/runner/config.d.ts +21 -0
  67. package/dist/runner/config.js +235 -0
  68. package/dist/runner/config.js.map +1 -0
  69. package/dist/runner/server.d.ts +25 -0
  70. package/dist/runner/server.js +803 -0
  71. package/dist/runner/server.js.map +1 -0
  72. package/dist/runner/systemd.d.ts +14 -0
  73. package/dist/runner/systemd.js +82 -0
  74. package/dist/runner/systemd.js.map +1 -0
  75. package/dist/runner/tarExtract.d.ts +4 -0
  76. package/dist/runner/tarExtract.js +215 -0
  77. package/dist/runner/tarExtract.js.map +1 -0
  78. package/dist/security/execSafe.d.ts +20 -0
  79. package/dist/security/execSafe.js +216 -0
  80. package/dist/security/execSafe.js.map +1 -0
  81. package/dist/security/pkce.d.ts +9 -0
  82. package/dist/security/pkce.js +35 -0
  83. package/dist/security/pkce.js.map +1 -0
  84. package/dist/security/redact.d.ts +3 -0
  85. package/dist/security/redact.js +76 -0
  86. package/dist/security/redact.js.map +1 -0
  87. package/dist/security/sanitize.d.ts +18 -0
  88. package/dist/security/sanitize.js +216 -0
  89. package/dist/security/sanitize.js.map +1 -0
  90. package/dist/security/vault.d.ts +34 -0
  91. package/dist/security/vault.js +291 -0
  92. package/dist/security/vault.js.map +1 -0
  93. package/dist/types/index.d.ts +116 -0
  94. package/dist/types/index.js +2 -0
  95. package/dist/types/index.js.map +1 -0
  96. package/dist/ui/output.d.ts +25 -0
  97. package/dist/ui/output.js +100 -0
  98. package/dist/ui/output.js.map +1 -0
  99. package/dist/ui/prompt.d.ts +4 -0
  100. package/dist/ui/prompt.js +100 -0
  101. package/dist/ui/prompt.js.map +1 -0
  102. package/package.json +54 -5
@@ -0,0 +1,723 @@
1
+ import http from "node:http";
2
+ import os from "node:os";
3
+ import { DEFAULT_NAUTH_FRONT_URL, DEFAULT_OAUTH_SCOPES, DEFAULT_PAT_SCOPES } from "../constants/index.js";
4
+ import { generateRandomBase64Url, timingSafeStringEqual, generatePkcePair } from "../security/pkce.js";
5
+ import { openUrlInBrowser } from "../security/execSafe.js";
6
+ import { validateHttpUrl } from "../security/sanitize.js";
7
+ import { maskSecret } from "../security/redact.js";
8
+ import { CoreApiClient } from "../http/coreApi.js";
9
+ import { GitApiClient } from "../http/gitApi.js";
10
+ import { promptConfirm, readStdinAll, promptSecret, promptLine } from "../ui/prompt.js";
11
+ import { runCommandAction } from "./context.js";
12
+ const runOAuthPkceBrowserLogin = async (ctx, options) => {
13
+ const clientId = (options.clientId || process.env.NCLI_OAUTH_CLIENT_ID || "").trim();
14
+ if (!clientId) {
15
+ throw new Error("OAuth2 PKCE browser login requires --client-id <clientId> (or NCLI_OAUTH_CLIENT_ID).");
16
+ }
17
+ const frontUrl = validateHttpUrl(options.nauthFrontUrl || DEFAULT_NAUTH_FRONT_URL, true);
18
+ const scopes = (options.scope || DEFAULT_OAUTH_SCOPES.join(" ")).trim();
19
+ const pkce = generatePkcePair(48);
20
+ const state = generateRandomBase64Url(32);
21
+ const listenPort = Number.isInteger(options.port) && options.port >= 0 ? options.port : 0;
22
+ let resolveCallback;
23
+ let rejectCallback;
24
+ const callbackPromise = new Promise((resolve, reject) => {
25
+ resolveCallback = resolve;
26
+ rejectCallback = reject;
27
+ });
28
+ const server = http.createServer((req, res) => {
29
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
30
+ if (reqUrl.pathname !== "/callback") {
31
+ res.writeHead(404, {
32
+ "Content-Type": "text/plain; charset=utf-8"
33
+ });
34
+ res.end("Not found");
35
+ return;
36
+ }
37
+ const errorParam = reqUrl.searchParams.get("error");
38
+ if (errorParam) {
39
+ const desc = reqUrl.searchParams.get("error_description") || errorParam;
40
+ res.writeHead(400, {
41
+ "Content-Type": "text/html; charset=utf-8"
42
+ });
43
+ res.end("<html><body><h2>Authentication cancelled or failed.</h2><p>You can close this tab.</p></body></html>");
44
+ rejectCallback(new Error(`OAuth authorization error: ${desc}`));
45
+ return;
46
+ }
47
+ const returnedState = reqUrl.searchParams.get("state") || "";
48
+ const code = reqUrl.searchParams.get("code") || "";
49
+ if (!code || !timingSafeStringEqual(returnedState, state)) {
50
+ res.writeHead(400, {
51
+ "Content-Type": "text/html; charset=utf-8"
52
+ });
53
+ res.end("<html><body><h2>Invalid OAuth state or missing code.</h2></body></html>");
54
+ rejectCallback(new Error("OAuth callback state mismatch or missing authorization code."));
55
+ return;
56
+ }
57
+ res.writeHead(200, {
58
+ "Content-Type": "text/html; charset=utf-8"
59
+ });
60
+ res.end("<html><body><h2>NİBGAT® ncli authentication complete.</h2><p>You may safely close this browser window.</p></body></html>");
61
+ resolveCallback({
62
+ code
63
+ });
64
+ });
65
+ await new Promise((resolve, reject) => {
66
+ server.once("error", reject);
67
+ server.listen(listenPort, "127.0.0.1", () => {
68
+ server.removeListener("error", reject);
69
+ resolve();
70
+ });
71
+ });
72
+ const addr = server.address();
73
+ const actualPort = typeof addr === "object" && addr ? addr.port : listenPort;
74
+ const redirectUri = `http://127.0.0.1:${actualPort}/callback`;
75
+ const authUrl = new URL(`${frontUrl}/oauth/authorize`);
76
+ authUrl.searchParams.set("response_type", "code");
77
+ authUrl.searchParams.set("client_id", clientId);
78
+ authUrl.searchParams.set("redirect_uri", redirectUri);
79
+ authUrl.searchParams.set("scope", scopes);
80
+ authUrl.searchParams.set("state", state);
81
+ authUrl.searchParams.set("code_challenge", pkce.codeChallenge);
82
+ authUrl.searchParams.set("code_challenge_method", pkce.codeChallengeMethod);
83
+ const timeout = setTimeout(() => {
84
+ rejectCallback(new Error("Timed out waiting for OAuth browser callback (5 minutes)."));
85
+ }, 5 * 60 * 1000);
86
+ timeout.unref();
87
+ try {
88
+ ctx.output.info(`Opening browser for N - Auth OAuth2 + PKCE (S256) login...`);
89
+ ctx.output.info(`If the browser did not open automatically, visit:\n ${authUrl.toString()}`);
90
+ await openUrlInBrowser(authUrl.toString());
91
+ const { code } = await callbackPromise;
92
+ const tokenRes = await ctx.coreClient.exchangeOAuthToken({
93
+ codeVerifier: pkce.codeVerifier,
94
+ redirectUri,
95
+ clientId,
96
+ code
97
+ });
98
+ const payload = tokenRes.data;
99
+ const accessToken = payload.accessToken || payload.access_token;
100
+ const refreshToken = payload.refreshToken || payload.refresh_token || undefined;
101
+ const expiresIn = payload.expiresIn || payload.expires_in || 900;
102
+ if (!accessToken) {
103
+ throw new Error("OAuth token endpoint returned no accessToken.");
104
+ }
105
+ const authedCore = new CoreApiClient(ctx.coreUrl, {
106
+ bearerToken: accessToken
107
+ });
108
+ let userName;
109
+ let userEmail;
110
+ let userId;
111
+ try {
112
+ const sessionRes = await authedCore.ssoGetSession();
113
+ userName = sessionRes.data?.user?.userName;
114
+ userEmail = sessionRes.data?.user?.mail;
115
+ userId = sessionRes.data?.user?.userID;
116
+ }
117
+ catch {
118
+ // Optional profile enrichment
119
+ }
120
+ const stored = {
121
+ oauthExpiresAt: new Date(Date.now() + (expiresIn * 1000)).toISOString(),
122
+ updatedAt: new Date().toISOString(),
123
+ coreUrl: ctx.coreUrl,
124
+ gitUrl: ctx.gitUrl,
125
+ refreshToken,
126
+ accessToken,
127
+ userEmail,
128
+ userName,
129
+ userId
130
+ };
131
+ ctx.vault.setProfile(ctx.profileName, stored, true);
132
+ ctx.output.data({
133
+ ok: true,
134
+ mode: "oauth-pkce",
135
+ profile: ctx.profileName,
136
+ userName: userName || null,
137
+ accessTokenMasked: maskSecret(accessToken),
138
+ expiresAt: stored.oauthExpiresAt
139
+ }, () => {
140
+ ctx.output.success(`Authenticated via OAuth2 PKCE (profile: ${ctx.profileName})`);
141
+ ctx.output.kv([
142
+ [
143
+ "Profile",
144
+ ctx.profileName
145
+ ],
146
+ [
147
+ "User",
148
+ userName || "-"
149
+ ],
150
+ [
151
+ "Access Token",
152
+ maskSecret(accessToken)
153
+ ],
154
+ [
155
+ "Vault",
156
+ ctx.vault.vaultPath
157
+ ]
158
+ ]);
159
+ });
160
+ }
161
+ finally {
162
+ clearTimeout(timeout);
163
+ await new Promise((resolve) => {
164
+ server.close(() => resolve());
165
+ });
166
+ }
167
+ };
168
+ const runPatLogin = async (ctx, rawToken, noVerify) => {
169
+ const token = rawToken.trim();
170
+ if (!token) {
171
+ throw new Error("Personal Access Token cannot be empty.");
172
+ }
173
+ let ngitUsername;
174
+ let userEmail;
175
+ let userId;
176
+ if (!noVerify) {
177
+ const gitClient = new GitApiClient(ctx.gitUrl, {
178
+ bearerToken: token
179
+ });
180
+ const meRes = await gitClient.me();
181
+ const user = meRes.data?.user;
182
+ if (!user?.username) {
183
+ throw new Error("Token verification succeeded with unexpected response (missing user).");
184
+ }
185
+ ngitUsername = user.username;
186
+ userEmail = user.email;
187
+ userId = user.id;
188
+ }
189
+ ctx.vault.updateProfile(ctx.profileName, {
190
+ ngitUsername,
191
+ ngitToken: token,
192
+ coreUrl: ctx.coreUrl,
193
+ gitUrl: ctx.gitUrl,
194
+ userEmail,
195
+ userName: ngitUsername,
196
+ userId
197
+ });
198
+ ctx.output.data({
199
+ ok: true,
200
+ mode: "pat",
201
+ profile: ctx.profileName,
202
+ username: ngitUsername || null,
203
+ tokenMasked: maskSecret(token)
204
+ }, () => {
205
+ ctx.output.success(`Saved encrypted N - Git PAT for profile "${ctx.profileName}".`);
206
+ ctx.output.kv([
207
+ [
208
+ "Profile",
209
+ ctx.profileName
210
+ ],
211
+ [
212
+ "Username",
213
+ ngitUsername || "(unverified)"
214
+ ],
215
+ [
216
+ "Token",
217
+ maskSecret(token)
218
+ ],
219
+ [
220
+ "Vault",
221
+ ctx.vault.vaultPath
222
+ ]
223
+ ]);
224
+ });
225
+ };
226
+ const runInteractiveSsoLogin = async (ctx, options) => {
227
+ const identifier = (options.identifier || await promptLine("N - Auth Email or Username")).trim();
228
+ if (!identifier) {
229
+ throw new Error("Email or username is required.");
230
+ }
231
+ const password = await promptSecret("Password");
232
+ if (!password) {
233
+ throw new Error("Password is required.");
234
+ }
235
+ let loginRes = await ctx.coreClient.ssoLogin(identifier, password);
236
+ let sessionCookie = loginRes.cookies.sessionCookie;
237
+ let sessionCookieName = loginRes.cookies.sessionCookieName;
238
+ let deviceCookie = loginRes.cookies.deviceCookie;
239
+ // Handle 2FA challenge if required
240
+ if (loginRes.data?.requiresTwoFactor && loginRes.data.challengeToken) {
241
+ const channels = Array.isArray(loginRes.data.availableChannels) && loginRes.data.availableChannels.length > 0
242
+ ? loginRes.data.availableChannels
243
+ : [
244
+ "totp"
245
+ ];
246
+ const preferred = loginRes.data.preferredChannel || channels[0];
247
+ let selectedChannel = preferred;
248
+ if (channels.length > 1) {
249
+ const chosen = (await promptLine(`2FA channel (${channels.join(" / ")})`, preferred)).trim().toLowerCase();
250
+ if (channels.includes(chosen)) {
251
+ selectedChannel = chosen;
252
+ }
253
+ }
254
+ if (selectedChannel === "sms" || selectedChannel === "mail") {
255
+ ctx.output.info(`Requesting 2FA verification code via ${selectedChannel}...`);
256
+ await ctx.coreClient.ssoRequestTwoFactor(loginRes.data.challengeToken, selectedChannel);
257
+ }
258
+ const code = (await promptLine(`Enter 2FA code (${selectedChannel})`)).trim();
259
+ if (!code) {
260
+ throw new Error("2FA verification code is required.");
261
+ }
262
+ loginRes = await ctx.coreClient.ssoVerifyTwoFactor(loginRes.data.challengeToken, selectedChannel, code);
263
+ sessionCookie = loginRes.cookies.sessionCookie || sessionCookie;
264
+ sessionCookieName = loginRes.cookies.sessionCookieName || sessionCookieName;
265
+ deviceCookie = loginRes.cookies.deviceCookie || deviceCookie;
266
+ }
267
+ else if (loginRes.data?.requiresOtp && identifier.includes("@")) {
268
+ const otpCode = (await promptLine("Enter SMS/Email OTP code")).trim();
269
+ loginRes = await ctx.coreClient.ssoVerifySmsOtp(identifier, otpCode);
270
+ sessionCookie = loginRes.cookies.sessionCookie || sessionCookie;
271
+ sessionCookieName = loginRes.cookies.sessionCookieName || sessionCookieName;
272
+ deviceCookie = loginRes.cookies.deviceCookie || deviceCookie;
273
+ }
274
+ if (!sessionCookie) {
275
+ throw new Error("N - Auth SSO login did not return a session cookie.");
276
+ }
277
+ const user = loginRes.data?.user;
278
+ const authedGit = new GitApiClient(ctx.gitUrl, {
279
+ sessionCookieName,
280
+ sessionCookie,
281
+ deviceCookie
282
+ });
283
+ let ngitUsername;
284
+ let ngitToken;
285
+ try {
286
+ const gitMe = await authedGit.me();
287
+ ngitUsername = gitMe.data?.user?.username;
288
+ ctx.output.info(`Verified N - Git access as @${ngitUsername || user?.userName || "user"}.`);
289
+ const shouldMint = options.mintPat === true
290
+ ? true
291
+ : (options.noPat === true
292
+ ? false
293
+ : (process.stdin.isTTY ? await promptConfirm("Mint a scoped CLI PAT for Git HTTPS & OCI Registry?", true) : false));
294
+ if (shouldMint) {
295
+ const patName = `ncli-${os.hostname()}-${Date.now().toString(36)}`;
296
+ const patRes = await authedGit.createToken(patName, DEFAULT_PAT_SCOPES);
297
+ ngitToken = patRes.data?.plainToken;
298
+ if (ngitToken) {
299
+ ctx.output.success(`Minted scoped CLI PAT (${maskSecret(ngitToken)}).`);
300
+ }
301
+ }
302
+ }
303
+ catch (err) {
304
+ ctx.output.warn(`N - Git verification skipped: ${err instanceof Error ? err.message : "unavailable"}`);
305
+ }
306
+ const stored = {
307
+ updatedAt: new Date().toISOString(),
308
+ ngitUsername: ngitUsername || user?.userName,
309
+ userName: user?.userName || ngitUsername,
310
+ userEmail: user?.mail,
311
+ userId: user?.userID,
312
+ coreUrl: ctx.coreUrl,
313
+ gitUrl: ctx.gitUrl,
314
+ sessionCookieName,
315
+ sessionCookie,
316
+ deviceCookie,
317
+ ngitToken
318
+ };
319
+ ctx.vault.setProfile(ctx.profileName, stored, true);
320
+ ctx.output.data({
321
+ ok: true,
322
+ mode: "sso",
323
+ profile: ctx.profileName,
324
+ userName: stored.userName || null,
325
+ userEmail: stored.userEmail || null,
326
+ hasSessionCookie: true,
327
+ ngitTokenMasked: ngitToken ? maskSecret(ngitToken) : null
328
+ }, () => {
329
+ ctx.output.success(`Logged in to NİBGAT® Core Complex (profile: ${ctx.profileName}).`);
330
+ ctx.output.kv([
331
+ [
332
+ "Profile",
333
+ ctx.profileName
334
+ ],
335
+ [
336
+ "User",
337
+ stored.userName || "-"
338
+ ],
339
+ [
340
+ "Email",
341
+ stored.userEmail || "-"
342
+ ],
343
+ [
344
+ "Session Cookie",
345
+ maskSecret(sessionCookie)
346
+ ],
347
+ [
348
+ "N - Git CLI PAT",
349
+ ngitToken ? maskSecret(ngitToken) : "(not minted)"
350
+ ],
351
+ [
352
+ "Encrypted Vault",
353
+ ctx.vault.vaultPath
354
+ ]
355
+ ]);
356
+ });
357
+ };
358
+ export const registerAuthCommands = (program) => {
359
+ const auth = program
360
+ .command("auth")
361
+ .description("Zero-trust N - Auth SSO, OAuth2 PKCE & N - Git PAT authentication");
362
+ auth
363
+ .command("login")
364
+ .description("Authenticate with N - Auth SSO (+ 2FA), OAuth2 PKCE browser flow, or N - Git PAT")
365
+ .option("--browser", "Use OAuth2 + PKCE (S256) browser flow")
366
+ .option("--client-id <id>", "OAuth2 client ID for --browser flow")
367
+ .option("--scope <scopes>", "OAuth2 space-separated scopes")
368
+ .option("--port <port>", "Loopback callback port for --browser flow", (v) => parseInt(v, 10))
369
+ .option("--nauth-front-url <url>", "N - Auth authorization portal URL")
370
+ .option("--token <pat>", "Store a Personal Access Token directly (non-interactive)")
371
+ .option("--token-stdin", "Read Personal Access Token from stdin")
372
+ .option("--no-verify", "Skip remote verification when saving --token")
373
+ .option("-u, --identifier <id>", "Email or username for SSO login")
374
+ .option("--mint-pat", "Automatically mint a scoped CLI PAT after SSO login")
375
+ .option("--no-pat", "Skip minting a CLI PAT after SSO login")
376
+ .action(async (opts, cmd) => {
377
+ await runCommandAction(cmd, async (ctx) => {
378
+ if (opts.tokenStdin) {
379
+ const token = await readStdinAll();
380
+ await runPatLogin(ctx, token, opts.verify === false);
381
+ return;
382
+ }
383
+ if (typeof opts.token === "string") {
384
+ await runPatLogin(ctx, opts.token, opts.verify === false);
385
+ return;
386
+ }
387
+ if (opts.browser) {
388
+ await runOAuthPkceBrowserLogin(ctx, {
389
+ nauthFrontUrl: opts.nauthFrontUrl,
390
+ clientId: opts.clientId,
391
+ scope: opts.scope,
392
+ port: opts.port
393
+ });
394
+ return;
395
+ }
396
+ await runInteractiveSsoLogin(ctx, {
397
+ identifier: opts.identifier,
398
+ mintPat: Boolean(opts.mintPat),
399
+ noPat: opts.pat === false
400
+ });
401
+ });
402
+ });
403
+ auth
404
+ .command("status")
405
+ .description("Show active profile, encrypted vault status and masked credentials")
406
+ .action(async (_opts, cmd) => {
407
+ await runCommandAction(cmd, async (ctx) => {
408
+ const creds = ctx.credentials;
409
+ const mode = ctx.vault.getFileModeOctal();
410
+ const profiles = ctx.vault.exists() ? ctx.vault.listProfiles() : {
411
+ activeProfile: ctx.profileName,
412
+ profiles: []
413
+ };
414
+ const summary = {
415
+ profile: ctx.profileName,
416
+ vaultExists: ctx.vault.exists(),
417
+ vaultPath: ctx.vault.vaultPath,
418
+ vaultMode: mode,
419
+ availableProfiles: profiles.profiles,
420
+ coreUrl: ctx.coreUrl,
421
+ gitUrl: ctx.gitUrl,
422
+ authenticated: Boolean(creds?.sessionCookie ||
423
+ creds?.accessToken ||
424
+ creds?.ngitToken ||
425
+ ctx.envOverrides.ngitToken ||
426
+ ctx.envOverrides.sessionCookie),
427
+ userName: creds?.userName || creds?.ngitUsername || null,
428
+ userEmail: creds?.userEmail || null,
429
+ sessionCookieMasked: creds?.sessionCookie ? maskSecret(creds.sessionCookie) : null,
430
+ accessTokenMasked: creds?.accessToken ? maskSecret(creds.accessToken) : null,
431
+ ngitTokenMasked: creds?.ngitToken ? maskSecret(creds.ngitToken) : null,
432
+ envOverrides: ctx.envOverrides
433
+ };
434
+ ctx.output.data(summary, () => {
435
+ ctx.output.kv([
436
+ [
437
+ "Active Profile",
438
+ summary.profile
439
+ ],
440
+ [
441
+ "Authenticated",
442
+ summary.authenticated ? "yes" : "no"
443
+ ],
444
+ [
445
+ "User",
446
+ summary.userName || "-"
447
+ ],
448
+ [
449
+ "Email",
450
+ summary.userEmail || "-"
451
+ ],
452
+ [
453
+ "Core API URL",
454
+ summary.coreUrl
455
+ ],
456
+ [
457
+ "N - Git API URL",
458
+ summary.gitUrl
459
+ ],
460
+ [
461
+ "SSO Session",
462
+ summary.sessionCookieMasked || (ctx.envOverrides.sessionCookie ? "(via NCLI_SESSION_COOKIE)" : "-")
463
+ ],
464
+ [
465
+ "OAuth Token",
466
+ summary.accessTokenMasked || "-"
467
+ ],
468
+ [
469
+ "N - Git PAT",
470
+ summary.ngitTokenMasked || (ctx.envOverrides.ngitToken ? "(via NCLI_TOKEN/NGIT_TOKEN)" : "-")
471
+ ],
472
+ [
473
+ "Vault Path",
474
+ `${summary.vaultPath}${mode ? ` (mode ${mode})` : " (not initialized)"}`
475
+ ]
476
+ ]);
477
+ });
478
+ });
479
+ });
480
+ auth
481
+ .command("whoami")
482
+ .description("Verify live identity against N - Auth SSO and N - Git")
483
+ .action(async (_opts, cmd) => {
484
+ await runCommandAction(cmd, async (ctx) => {
485
+ let nauthSession = null;
486
+ let ngitUser = null;
487
+ try {
488
+ const res = await ctx.coreClient.ssoGetSession();
489
+ nauthSession = res.data;
490
+ }
491
+ catch {
492
+ nauthSession = null;
493
+ }
494
+ try {
495
+ const res = await ctx.gitClient.me();
496
+ ngitUser = (res.data?.user || null);
497
+ }
498
+ catch {
499
+ ngitUser = null;
500
+ }
501
+ if (!nauthSession && !ngitUser) {
502
+ throw new Error("Not authenticated. Run 'ncli auth login' first.");
503
+ }
504
+ const result = {
505
+ profile: ctx.profileName,
506
+ nauth: nauthSession,
507
+ ngit: ngitUser
508
+ };
509
+ ctx.output.data(result, () => {
510
+ const nauthUser = (nauthSession?.user || {});
511
+ ctx.output.kv([
512
+ [
513
+ "Profile",
514
+ ctx.profileName
515
+ ],
516
+ [
517
+ "N - Auth User",
518
+ String(nauthUser.userName || "-")
519
+ ],
520
+ [
521
+ "N - Auth Email",
522
+ String(nauthUser.mail || "-")
523
+ ],
524
+ [
525
+ "N - Git User",
526
+ String(ngitUser?.username || "-")
527
+ ],
528
+ [
529
+ "N - Git Auth Via",
530
+ String(ngitUser?.authVia || "-")
531
+ ]
532
+ ]);
533
+ });
534
+ });
535
+ });
536
+ auth
537
+ .command("logout")
538
+ .description("End N - Auth session and erase local encrypted credentials")
539
+ .option("--all", "Logout across all devices, revoke apps, and wipe the entire local vault")
540
+ .action(async (opts, cmd) => {
541
+ await runCommandAction(cmd, async (ctx) => {
542
+ let remoteLoggedOut = false;
543
+ try {
544
+ await ctx.coreClient.ssoLogout({
545
+ logoutAllDevices: Boolean(opts.all),
546
+ revokeAllApps: Boolean(opts.all)
547
+ });
548
+ remoteLoggedOut = true;
549
+ }
550
+ catch {
551
+ // Continue clearing local credentials even if remote session already expired
552
+ }
553
+ if (opts.all) {
554
+ ctx.vault.wipe();
555
+ }
556
+ else {
557
+ ctx.vault.deleteProfile(ctx.profileName);
558
+ }
559
+ ctx.output.data({
560
+ ok: true,
561
+ profile: ctx.profileName,
562
+ wipedVault: Boolean(opts.all),
563
+ remoteLoggedOut
564
+ }, () => {
565
+ ctx.output.success(opts.all
566
+ ? "Logged out globally and wiped encrypted vault."
567
+ : `Cleared credentials for profile "${ctx.profileName}".`);
568
+ });
569
+ });
570
+ });
571
+ const sessions = auth
572
+ .command("sessions")
573
+ .description("Inspect and revoke active N - Auth SSO/app sessions");
574
+ sessions
575
+ .command("list")
576
+ .description("List active sessions and app consents")
577
+ .action(async (_opts, cmd) => {
578
+ await runCommandAction(cmd, async (ctx) => {
579
+ const res = await ctx.coreClient.ssoListSessions();
580
+ ctx.output.data(res.data, () => {
581
+ const data = res.data;
582
+ const rows = [];
583
+ for (const s of data.ssoSessions || []) {
584
+ rows.push([
585
+ "sso_session",
586
+ String(s.id || s.sessionID || "-"),
587
+ String(s.ipAddress || "-"),
588
+ String(s.createdAt || "-")
589
+ ]);
590
+ }
591
+ for (const a of data.appSessions || []) {
592
+ rows.push([
593
+ "app_session",
594
+ String(a.id || a.sessionID || "-"),
595
+ String(a.appName || a.clientID || "-"),
596
+ String(a.createdAt || "-")
597
+ ]);
598
+ }
599
+ ctx.output.table([
600
+ "TYPE",
601
+ "ID",
602
+ "DETAIL",
603
+ "CREATED"
604
+ ], rows);
605
+ });
606
+ });
607
+ });
608
+ sessions
609
+ .command("revoke <type> <id>")
610
+ .description("Revoke a session (type: sso_session | app_session | app_consent)")
611
+ .action(async (targetType, targetID, _opts, cmd) => {
612
+ await runCommandAction(cmd, async (ctx) => {
613
+ if (targetType !== "sso_session" &&
614
+ targetType !== "app_session" &&
615
+ targetType !== "app_consent") {
616
+ throw new Error('Invalid session type. Expected "sso_session", "app_session", or "app_consent".');
617
+ }
618
+ const res = await ctx.coreClient.ssoRevokeSession(targetType, targetID);
619
+ ctx.output.data(res.data, () => {
620
+ ctx.output.success(`Revoked ${targetType} ${targetID}.`);
621
+ });
622
+ });
623
+ });
624
+ const twoFa = auth
625
+ .command("2fa")
626
+ .description("Inspect N - Auth two-factor authentication settings");
627
+ twoFa
628
+ .command("status")
629
+ .description("Show current 2FA enrollment and preferred channel")
630
+ .action(async (_opts, cmd) => {
631
+ await runCommandAction(cmd, async (ctx) => {
632
+ const res = await ctx.coreClient.ssoTwoFactorStatus();
633
+ ctx.output.data(res.data, () => {
634
+ const data = res.data;
635
+ ctx.output.kv([
636
+ [
637
+ "Enabled",
638
+ String(Boolean(data.enabled))
639
+ ],
640
+ [
641
+ "Preferred Channel",
642
+ String(data.preferredChannel || "-")
643
+ ],
644
+ [
645
+ "TOTP Enabled",
646
+ String(Boolean(data.totpEnabled))
647
+ ],
648
+ [
649
+ "SMS Enabled",
650
+ String(Boolean(data.smsEnabled))
651
+ ],
652
+ [
653
+ "Mail Enabled",
654
+ String(Boolean(data.mailEnabled))
655
+ ]
656
+ ]);
657
+ });
658
+ });
659
+ });
660
+ const tokenCmd = auth
661
+ .command("token")
662
+ .description("Manage N - Git Personal Access Tokens (PATs)");
663
+ tokenCmd
664
+ .command("list")
665
+ .description("List Personal Access Tokens")
666
+ .action(async (_opts, cmd) => {
667
+ await runCommandAction(cmd, async (ctx) => {
668
+ const res = await ctx.gitClient.listTokens();
669
+ const list = (res.data?.tokens || []);
670
+ ctx.output.data(res.data, () => {
671
+ ctx.output.table([
672
+ "ID",
673
+ "NAME",
674
+ "PREFIX",
675
+ "SCOPES",
676
+ "LAST USED"
677
+ ], list.map((t) => [
678
+ String(t.id || "-"),
679
+ String(t.name || "-"),
680
+ String(t.token_prefix || t.tokenPrefix || "-"),
681
+ String(t.scopes || "-"),
682
+ String(t.last_used_at || t.lastUsedAt || "never")
683
+ ]));
684
+ });
685
+ });
686
+ });
687
+ tokenCmd
688
+ .command("create <name>")
689
+ .description("Create a scoped N - Git Personal Access Token")
690
+ .option("--scopes <csv>", "Comma-separated scopes", DEFAULT_PAT_SCOPES.join(","))
691
+ .option("--save", "Also store the minted PAT into the active encrypted profile")
692
+ .action(async (name, opts, cmd) => {
693
+ await runCommandAction(cmd, async (ctx) => {
694
+ const scopes = String(opts.scopes || "")
695
+ .split(",")
696
+ .map((s) => s.trim())
697
+ .filter(Boolean);
698
+ const res = await ctx.gitClient.createToken(name, scopes.length > 0 ? scopes : DEFAULT_PAT_SCOPES);
699
+ if (opts.save && res.data?.plainToken) {
700
+ ctx.vault.updateProfile(ctx.profileName, {
701
+ ngitToken: res.data.plainToken
702
+ });
703
+ }
704
+ ctx.output.data(res.data, () => {
705
+ ctx.output.success(`Created token "${res.data.name}" (${res.data.id}).`);
706
+ ctx.output.warn("Copy the token below now — it will not be shown again:");
707
+ process.stdout.write(`${res.data.plainToken}\n`);
708
+ });
709
+ });
710
+ });
711
+ tokenCmd
712
+ .command("revoke <id>")
713
+ .description("Revoke an N - Git Personal Access Token")
714
+ .action(async (id, _opts, cmd) => {
715
+ await runCommandAction(cmd, async (ctx) => {
716
+ const res = await ctx.gitClient.revokeToken(id);
717
+ ctx.output.data(res.data, () => {
718
+ ctx.output.success(`Revoked token ${id}.`);
719
+ });
720
+ });
721
+ });
722
+ };
723
+ //# sourceMappingURL=auth.js.map