@burdenoff/cli-sdk 2026.504.1

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 (107) hide show
  1. package/README.md +60 -0
  2. package/dist/chunk-KTKHJORN.js +1 -0
  3. package/dist/chunk-MRONTCXQ.js +879 -0
  4. package/dist/chunk-RNWXATAC.js +32 -0
  5. package/dist/core/index.cjs +32 -0
  6. package/dist/core/index.d.cts +57 -0
  7. package/dist/core/index.d.ts +57 -0
  8. package/dist/core/index.js +1 -0
  9. package/dist/index.cjs +32 -0
  10. package/dist/index.d.cts +4 -0
  11. package/dist/index.d.ts +4 -0
  12. package/dist/index.js +1 -0
  13. package/dist/module-Bv5zhYt2.d.cts +166 -0
  14. package/dist/module-Bv5zhYt2.d.ts +166 -0
  15. package/dist/modules/auth/index.cjs +183 -0
  16. package/dist/modules/auth/index.d.cts +7 -0
  17. package/dist/modules/auth/index.d.ts +7 -0
  18. package/dist/modules/auth/index.js +160 -0
  19. package/dist/modules/billing/index.cjs +105 -0
  20. package/dist/modules/billing/index.d.cts +7 -0
  21. package/dist/modules/billing/index.d.ts +7 -0
  22. package/dist/modules/billing/index.js +105 -0
  23. package/dist/modules/channels/index.cjs +70 -0
  24. package/dist/modules/channels/index.d.cts +7 -0
  25. package/dist/modules/channels/index.d.ts +7 -0
  26. package/dist/modules/channels/index.js +70 -0
  27. package/dist/modules/conversations/index.cjs +37 -0
  28. package/dist/modules/conversations/index.d.cts +7 -0
  29. package/dist/modules/conversations/index.d.ts +7 -0
  30. package/dist/modules/conversations/index.js +37 -0
  31. package/dist/modules/devportal/index.cjs +133 -0
  32. package/dist/modules/devportal/index.d.cts +7 -0
  33. package/dist/modules/devportal/index.d.ts +7 -0
  34. package/dist/modules/devportal/index.js +133 -0
  35. package/dist/modules/export/index.cjs +37 -0
  36. package/dist/modules/export/index.d.cts +7 -0
  37. package/dist/modules/export/index.d.ts +7 -0
  38. package/dist/modules/export/index.js +37 -0
  39. package/dist/modules/files/index.cjs +49 -0
  40. package/dist/modules/files/index.d.cts +7 -0
  41. package/dist/modules/files/index.d.ts +7 -0
  42. package/dist/modules/files/index.js +49 -0
  43. package/dist/modules/groups/index.cjs +67 -0
  44. package/dist/modules/groups/index.d.cts +7 -0
  45. package/dist/modules/groups/index.d.ts +7 -0
  46. package/dist/modules/groups/index.js +67 -0
  47. package/dist/modules/health/index.cjs +1 -0
  48. package/dist/modules/health/index.d.cts +7 -0
  49. package/dist/modules/health/index.d.ts +7 -0
  50. package/dist/modules/health/index.js +1 -0
  51. package/dist/modules/integrations/index.cjs +44 -0
  52. package/dist/modules/integrations/index.d.cts +7 -0
  53. package/dist/modules/integrations/index.d.ts +7 -0
  54. package/dist/modules/integrations/index.js +44 -0
  55. package/dist/modules/notifications/index.cjs +26 -0
  56. package/dist/modules/notifications/index.d.cts +7 -0
  57. package/dist/modules/notifications/index.d.ts +7 -0
  58. package/dist/modules/notifications/index.js +26 -0
  59. package/dist/modules/organizations/index.cjs +53 -0
  60. package/dist/modules/organizations/index.d.cts +7 -0
  61. package/dist/modules/organizations/index.d.ts +7 -0
  62. package/dist/modules/organizations/index.js +53 -0
  63. package/dist/modules/products/index.cjs +102 -0
  64. package/dist/modules/products/index.d.cts +7 -0
  65. package/dist/modules/products/index.d.ts +7 -0
  66. package/dist/modules/products/index.js +102 -0
  67. package/dist/modules/rbac/index.cjs +63 -0
  68. package/dist/modules/rbac/index.d.cts +7 -0
  69. package/dist/modules/rbac/index.d.ts +7 -0
  70. package/dist/modules/rbac/index.js +63 -0
  71. package/dist/modules/sandbox/index.cjs +33 -0
  72. package/dist/modules/sandbox/index.d.cts +7 -0
  73. package/dist/modules/sandbox/index.d.ts +7 -0
  74. package/dist/modules/sandbox/index.js +1 -0
  75. package/dist/modules/scheduler/index.cjs +32 -0
  76. package/dist/modules/scheduler/index.d.cts +7 -0
  77. package/dist/modules/scheduler/index.d.ts +7 -0
  78. package/dist/modules/scheduler/index.js +32 -0
  79. package/dist/modules/security/index.cjs +69 -0
  80. package/dist/modules/security/index.d.cts +7 -0
  81. package/dist/modules/security/index.d.ts +7 -0
  82. package/dist/modules/security/index.js +69 -0
  83. package/dist/modules/store/index.cjs +63 -0
  84. package/dist/modules/store/index.d.cts +7 -0
  85. package/dist/modules/store/index.d.ts +7 -0
  86. package/dist/modules/store/index.js +63 -0
  87. package/dist/modules/support/index.cjs +45 -0
  88. package/dist/modules/support/index.d.cts +7 -0
  89. package/dist/modules/support/index.d.ts +7 -0
  90. package/dist/modules/support/index.js +45 -0
  91. package/dist/modules/tags/index.cjs +54 -0
  92. package/dist/modules/tags/index.d.cts +7 -0
  93. package/dist/modules/tags/index.d.ts +7 -0
  94. package/dist/modules/tags/index.js +54 -0
  95. package/dist/modules/tours/index.cjs +48 -0
  96. package/dist/modules/tours/index.d.cts +7 -0
  97. package/dist/modules/tours/index.d.ts +7 -0
  98. package/dist/modules/tours/index.js +48 -0
  99. package/dist/modules/vibecontrols/index.cjs +844 -0
  100. package/dist/modules/vibecontrols/index.d.cts +7 -0
  101. package/dist/modules/vibecontrols/index.d.ts +7 -0
  102. package/dist/modules/vibecontrols/index.js +2 -0
  103. package/dist/modules/workspaces/index.cjs +90 -0
  104. package/dist/modules/workspaces/index.d.cts +7 -0
  105. package/dist/modules/workspaces/index.d.ts +7 -0
  106. package/dist/modules/workspaces/index.js +77 -0
  107. package/package.json +104 -0
@@ -0,0 +1,166 @@
1
+ import { Command } from 'commander';
2
+ import { RequestDocument, Variables } from 'graphql-request';
3
+
4
+ interface StoredAuth {
5
+ accessToken: string;
6
+ refreshToken: string;
7
+ expiresAt?: number;
8
+ workspaceToken?: string;
9
+ workspaceTokenExpiresAt?: number;
10
+ workspaceId?: string;
11
+ organizationId?: string;
12
+ authMethod?: 'device_code' | 'client_credentials';
13
+ clientId?: string;
14
+ clientSecret?: string;
15
+ }
16
+ interface AuthStore {
17
+ read(): StoredAuth | null;
18
+ write(auth: StoredAuth): void;
19
+ clear(): void;
20
+ isTokenExpired(): boolean;
21
+ isTokenExpiringSoon(): boolean;
22
+ isWorkspaceTokenExpired(): boolean;
23
+ isWorkspaceTokenExpiringSoon(): boolean;
24
+ isAuthenticated(): boolean;
25
+ }
26
+ declare function createAuthStore(configDir: string): AuthStore;
27
+
28
+ interface CLIConfig {
29
+ workspaceEndpoint: string;
30
+ globalEndpoint: string;
31
+ oidcIssuer?: string;
32
+ clientId?: string;
33
+ defaultFormat?: string;
34
+ verbose?: boolean;
35
+ authServiceEndpoint?: string;
36
+ }
37
+ interface ProductDefaults {
38
+ configDirName: string;
39
+ oidcClientId: string;
40
+ oidcIssuerProd?: string;
41
+ workspaceEndpointDefault: string;
42
+ globalEndpointDefault: string;
43
+ }
44
+ interface ConfigStore {
45
+ read(): CLIConfig;
46
+ write(config: CLIConfig): void;
47
+ get(key: string): string | undefined;
48
+ set(key: string, value: string): void;
49
+ path(): string;
50
+ dir(): string;
51
+ resolveOIDC(): {
52
+ oidcIssuer: string;
53
+ clientId: string;
54
+ };
55
+ }
56
+ declare const KNOWN_CONFIG_KEYS: readonly ["workspaceEndpoint", "globalEndpoint", "oidcIssuer", "clientId", "defaultFormat", "verbose", "authServiceEndpoint"];
57
+ declare function createConfigStore(defaults: ProductDefaults): ConfigStore;
58
+
59
+ interface GqlClient {
60
+ request<T>(document: RequestDocument, variables?: Variables): Promise<T>;
61
+ }
62
+ interface GqlClients {
63
+ workspace: GqlClient;
64
+ global: GqlClient;
65
+ workspaceAuthOnly: GqlClient;
66
+ reset(): void;
67
+ }
68
+ declare function extractGqlErrorMessage(error: unknown): string;
69
+ declare function createGqlClients(config: ConfigStore, authStore: AuthStore): GqlClients;
70
+
71
+ type OutputFormat = 'json' | 'table' | 'yaml';
72
+ interface TableConfig {
73
+ headers: string[];
74
+ rows: string[][];
75
+ }
76
+ interface OutputAdapter {
77
+ isInteractive(): boolean;
78
+ getFormat(options: {
79
+ format?: string;
80
+ }): OutputFormat;
81
+ formatAndOutput(options: {
82
+ format?: string;
83
+ }, data: unknown, table?: TableConfig): void;
84
+ printJson(data: unknown): void;
85
+ printTable(headers: string[], rows: string[][]): void;
86
+ printYaml(data: unknown): void;
87
+ printSuccess(message: string): void;
88
+ printError(message: string): void;
89
+ printWarning(message: string): void;
90
+ printInfo(message: string): void;
91
+ formatDate(date: string | null | undefined): string;
92
+ formatStatus(status: string | null | undefined): string;
93
+ truncate(str: string | null | undefined, maxLen: number): string;
94
+ confirm(message: string, force?: boolean): Promise<boolean>;
95
+ }
96
+ declare const defaultOutputAdapter: OutputAdapter;
97
+
98
+ interface Logger {
99
+ debug(message: string, ...args: unknown[]): void;
100
+ info(message: string, ...args: unknown[]): void;
101
+ warn(message: string, ...args: unknown[]): void;
102
+ error(message: string, ...args: unknown[]): void;
103
+ }
104
+ interface LoggerOptions {
105
+ verbose?: boolean;
106
+ quiet?: boolean;
107
+ }
108
+ declare function createLogger(opts?: LoggerOptions): Logger;
109
+
110
+ type Environment = 'prod' | 'staging' | 'dev' | 'local';
111
+ interface CLIContext {
112
+ productName: string;
113
+ productVersion: string;
114
+ defaults: ProductDefaults;
115
+ config: ConfigStore;
116
+ auth: AuthStore;
117
+ gql: GqlClients;
118
+ output: OutputAdapter;
119
+ logger: Logger;
120
+ env: Environment;
121
+ }
122
+ interface BuildContextOptions {
123
+ productName: string;
124
+ productVersion: string;
125
+ defaults: ProductDefaults;
126
+ output?: OutputAdapter;
127
+ logger?: LoggerOptions | Logger;
128
+ env?: Environment;
129
+ }
130
+ declare function buildContext(opts: BuildContextOptions): CLIContext;
131
+
132
+ declare class CliUserError extends Error {
133
+ readonly exitCode: number;
134
+ readonly hint: string | undefined;
135
+ constructor(message: string, opts?: {
136
+ exitCode?: number;
137
+ hint?: string;
138
+ });
139
+ }
140
+ declare class CliAuthError extends CliUserError {
141
+ constructor(message: string, opts?: {
142
+ hint?: string;
143
+ });
144
+ }
145
+ declare class CliInternalError extends Error {
146
+ readonly cause: unknown;
147
+ constructor(message: string, cause?: unknown);
148
+ }
149
+
150
+ interface CliModule {
151
+ readonly id: string;
152
+ readonly version: string;
153
+ readonly displayName: string;
154
+ readonly dependsOn?: readonly string[];
155
+ register(program: Command, ctx: CLIContext): void;
156
+ api?: (ctx: CLIContext) => unknown;
157
+ }
158
+ declare class MissingDependencyError extends CliInternalError {
159
+ constructor(moduleId: string, missingDep: string);
160
+ }
161
+ declare class CircularDependencyError extends CliInternalError {
162
+ constructor(cycle: readonly string[]);
163
+ }
164
+ declare function sortModules(modules: readonly CliModule[]): CliModule[];
165
+
166
+ export { type AuthStore as A, type BuildContextOptions as B, type CliModule as C, type Environment as E, type GqlClient as G, KNOWN_CONFIG_KEYS as K, type Logger as L, MissingDependencyError as M, type OutputAdapter as O, type ProductDefaults as P, type StoredAuth as S, type TableConfig as T, type CLIContext as a, type CLIConfig as b, CircularDependencyError as c, CliAuthError as d, CliInternalError as e, CliUserError as f, type ConfigStore as g, type GqlClients as h, type LoggerOptions as i, type OutputFormat as j, buildContext as k, createAuthStore as l, createConfigStore as m, createGqlClients as n, createLogger as o, defaultOutputAdapter as p, extractGqlErrorMessage as q, sortModules as s };
@@ -0,0 +1,183 @@
1
+ 'use strict';require('graphql-request');var W=require('cross-fetch');require('commander');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var W__default=/*#__PURE__*/_interopDefault(W);async function Z(n){let s=`${n.oidcIssuer}/oidc/device/code`,i=new URLSearchParams({client_id:n.clientId,scope:"openid profile email offline_access"}),r=await W__default.default(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});if(!r.ok){let p=await r.text().catch(()=>"Unknown error");throw new Error(`Device code request failed (${r.status}): ${p}`)}let a=await r.json();return {deviceCode:a.device_code,userCode:a.user_code,verificationUri:a.verification_uri,verificationUriComplete:a.verification_uri_complete??null,expiresIn:a.expires_in,interval:a.interval??5}}async function ee(n,s,i){let r=`${i.oidcIssuer}/oauth/device/token`,a=s;for(;;){await new Promise(I=>setTimeout(I,a*1e3));let p=await W__default.default(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:n,client_id:i.clientId}).toString()}),c=await p.json();if(p.ok&&c.access_token)return {accessToken:c.access_token,refreshToken:c.refresh_token??"",expiresIn:c.expires_in??3600};let d=c.error;switch(d){case "authorization_pending":continue;case "slow_down":a+=5;continue;case "expired_token":throw new Error("Device code has expired. Please try again.");case "access_denied":throw new Error("Authorization was denied by the user.");default:throw new Error(`Device code polling failed: ${c.error_description??d??"Unknown error"}`)}}}async function V(n,s,i,r){let p=await W__default.default(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`
2
+ mutation AuthenticateApp($input: AuthenticateAppInput!) {
3
+ authenticateApp(input: $input) {
4
+ accessToken tokenType expiresIn scopes
5
+ }
6
+ }
7
+ `,variables:{input:{clientId:s,clientSecret:i,scopes:r}}})});if(!p.ok){let d=await p.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${p.status}): ${d}`)}let c=await p.json();if(c.errors?.length)throw new Error(`App authentication failed: ${c.errors[0]?.message??"unknown error"}`);if(!c.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return c.data.authenticateApp}async function v(n,s,i,r){let p=await W__default.default(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:`
8
+ mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
9
+ issueWorkspaceToken(input: $input) {
10
+ success token expiresAt scopes
11
+ error { code message }
12
+ }
13
+ }
14
+ `,variables:{input:{workspaceId:i,organizationId:r}}})});if(!p.ok){let I=await p.text().catch(()=>"Unknown error");throw new Error(`Workspace token request failed (${p.status}): ${I}`)}let c=await p.json();if(c.errors?.length)throw new Error(`Workspace token failed: ${c.errors[0]?.message??"unknown error"}`);let d=c.data?.issueWorkspaceToken;if(!d?.success||!d.token){let I=d?.error?.message??"Unknown error";throw new Error(`Workspace token failed: ${I}`)}return {token:d.token,expiresAt:d.expiresAt??"",scopes:d.scopes??[]}}async function H(n,s){let r=await W__default.default(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:`
15
+ query MyWorkspaces($limit: Int) {
16
+ myWorkspaces(limit: $limit) {
17
+ items { id name slug tenantId organizationId }
18
+ }
19
+ }
20
+ `,variables:{limit:50}})});if(!r.ok){let p=await r.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${r.status}): ${p}`)}let a=await r.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function Ze(n){try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}async function te(n){try{if(!Ze(n))return !1;let{execFile:s}=await import('child_process'),i=process.platform,r,a;return i==="darwin"?(r="open",a=[n]):i==="win32"?(r="cmd",a=["/c","start","",n]):(r="xdg-open",a=[n]),new Promise(p=>{s(r,a,c=>{p(!c);});})}catch{return false}}var S=class extends Error{exitCode;hint;constructor(s,i){super(s),this.name="CliUserError",this.exitCode=i?.exitCode??1,this.hint=i?.hint;}};var x=class extends Error{cause;constructor(s,i){super(s),this.name="CliInternalError",this.cause=i;}};var pe=null;function me(n){pe=n;}function E(){if(!pe)throw new x("vibecontrols module helpers used before setHelpersContext was called");return pe}async function l(n,s){return E().gql.global.request(n,s)}async function ue(n,s){return E().gql.global.request(n,s)}function C(){E().gql.reset();}function u(n){let s=n instanceof Error?n.message:String(n);throw new S(s)}function m(n,s,i){E().output.formatAndOutput(n,s,i);}function g(n){E().output.printSuccess(n);}function k(n){E().output.printInfo(n);}function R(n){E().output.printWarning(n);}function z(n){E().output.printJson(n);}function j(n){return E().output.formatStatus(n)}function _(n){return E().output.formatDate(n)}function q(n,s){return E().output.truncate(n,s)}function G(){return E().auth.read()}function O(n){E().auth.write(n);}function Ie(){E().auth.clear();}function F(){return E().config.read()}function fe(){return E().config.resolveOIDC()}function $e(n){return n?n.expiresAt?Date.now()>=n.expiresAt:false:E().auth.isTokenExpired()}var ke="mutation { signOut }",ye=`
21
+ mutation RefreshToken($token: String!) {
22
+ refreshToken(token: $token) { accessToken refreshToken expiresIn }
23
+ }
24
+ `;function De(n){let s=n.command("auth").description("Authentication commands");s.command("login").description("Authenticate with VibeControls").option("--client-credentials","Authenticate as an app with client ID and secret").option("--workspace-id <id>","Workspace ID (for app auth)").action(async i=>{try{i.clientCredentials?await pt(i.workspaceId):await ct();}catch(r){u(r);}}),s.command("logout").description("Revoke tokens and clear stored auth").action(async()=>{try{if(G()?.accessToken)try{await ue(ke);}catch{R("Server-side logout failed, clearing local tokens");}Ie(),C(),g("Logged out successfully");}catch(i){u(i);}}),s.command("status").description("Show current auth state").option("-f, --format <format>","Output format (json, table)").action(i=>{let r=G(),a=F(),p=!!r?.accessToken,c=r?.accessToken?$e(r):false,d=r?.expiresAt?_(new Date(r.expiresAt).toISOString()):"-",I=r?.authMethod==="client_credentials"?"Client Credentials":"OAuth2 Device Code",e=r?.workspaceTokenExpiresAt?_(new Date(r.workspaceTokenExpiresAt).toISOString()):"-";m(i,{authenticated:p,method:I,expired:c,expiresAt:d,workspaceId:r?.workspaceId??"-",organizationId:r?.organizationId??"-",workspaceTokenExpiresAt:e,workspaceEndpoint:a.workspaceEndpoint,globalEndpoint:a.globalEndpoint},{headers:["Key","Value"],rows:[["Authenticated",String(p)],["Method",I],["Expired",String(c)],["Expires At",d],["Workspace ID",r?.workspaceId??"-"],["Organization ID",r?.organizationId??"-"],["Workspace Token Expires",e],["Workspace Endpoint",a.workspaceEndpoint],["Global Endpoint",a.globalEndpoint]]});}),s.command("token").description("Print access token to stdout").option("--workspace","Print workspace token instead").action(i=>{let r=G();if(i.workspace){if(!r?.workspaceToken)throw new S("No workspace token. Set a workspace: vibecontrols workspace set <id>");process.stdout.write(r.workspaceToken);return}if(!r?.accessToken)throw new S("Not authenticated. Run: vibecontrols auth login");process.stdout.write(r.accessToken);}),s.command("refresh").description("Force token refresh").action(async()=>{try{let i=G();if(!i?.refreshToken&&i?.authMethod!=="client_credentials")throw new S("No refresh token available. Run: vibecontrols auth login");if(i?.authMethod==="client_credentials"&&i.clientId&&i.clientSecret){let p=F(),c=await V(p.globalEndpoint,i.clientId,i.clientSecret);O({...i,accessToken:c.accessToken,expiresAt:Date.now()+c.expiresIn*1e3}),C(),g("App token refreshed successfully"),i.workspaceId&&i.organizationId&&await he();return}let a=(await ue(ye,{token:i.refreshToken})).refreshToken;O({...i,accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3}),C(),g("Token refreshed successfully"),i.workspaceId&&i.organizationId&&await he();}catch(i){u(i);}});}async function he(){let n=G();if(!n?.accessToken||!n.workspaceId||!n.organizationId)return;let s=F();try{let i=await v(s.workspaceEndpoint,n.accessToken,n.workspaceId,n.organizationId);O({...n,workspaceToken:i.token,workspaceTokenExpiresAt:new Date(i.expiresAt).getTime()}),C(),g("Workspace token refreshed");}catch{R("Workspace token refresh failed \u2014 workspace operations may require re-login");}}async function ct(){let n=F(),{oidcIssuer:s,clientId:i}=fe(),r={...n,oidcIssuer:s,clientId:i};k("Starting device code authentication...");let a=await Z(r);console.log(""),console.log(` Open: ${a.verificationUri}`),console.log(` Code: ${a.userCode}`),console.log(""),await te(a.verificationUriComplete??a.verificationUri)?k("Browser opened"):R("Could not open browser \u2014 open the URL manually"),k("Waiting for authorization...");let c=await ee(a.deviceCode,a.interval,r),d=c.accessToken,I=Date.now()+c.expiresIn*1e3;k("Fetching workspaces...");try{let e=await H(n.globalEndpoint,d);if(e.length===0){O({accessToken:d,refreshToken:c.refreshToken,expiresAt:I,authMethod:"device_code"}),C(),g("Authentication successful (no workspaces found)");return}let t=e[0];if(e.length>1){console.log(`
25
+ Available workspaces:`),e.forEach((Q,ce)=>console.log(` ${ce+1}. ${Q.name} (${Q.slug})`));let A=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),$=await new Promise(Q=>{A.question(`
26
+ Select workspace [1-${e.length}]: `,ce=>{A.close(),Q(ce.trim());});}),w=parseInt($,10)-1;w>=0&&w<e.length&&(t=e[w]);}k(`Using workspace: ${t.name} (${t.id})`);let o=await v(n.workspaceEndpoint,d,t.id,t.organizationId);O({accessToken:d,refreshToken:c.refreshToken,expiresAt:I,workspaceToken:o.token,workspaceTokenExpiresAt:new Date(o.expiresAt).getTime(),workspaceId:t.id,organizationId:t.organizationId,authMethod:"device_code"}),C(),g("Authentication successful");}catch(e){O({accessToken:d,refreshToken:c.refreshToken,expiresAt:I,authMethod:"device_code"}),C(),g("Authentication successful"),R(`Workspace token not obtained: ${e instanceof Error?e.message:String(e)}`),k("Set workspace manually: vibecontrols workspace set <id>");}}async function pt(n){let s=F(),r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),a=await new Promise(A=>{r.question("Client ID: ",$=>A($.trim()));}),p=await new Promise(A=>{r.question("Client Secret: ",$=>{r.close(),A($.trim());});});if(!a||!p)throw new S("Client ID and secret cannot be empty");k("Authenticating app...");let c=await V(s.globalEndpoint,a,p),d=c.accessToken,I=Date.now()+c.expiresIn*1e3,e,t,o=n,f;if(o)try{let $=(await H(s.globalEndpoint,d)).find(w=>w.id===o);if($){f=$.organizationId;let w=await v(s.workspaceEndpoint,d,o,f);e=w.token,t=new Date(w.expiresAt).getTime(),k(`Workspace token issued for: ${$.name}`);}else R(`Workspace ${o} not found \u2014 skipping workspace token`),o=void 0;}catch(A){R(`Workspace token failed: ${A instanceof Error?A.message:String(A)}`);}O({accessToken:d,refreshToken:"",expiresAt:I,workspaceToken:e,workspaceTokenExpiresAt:t,workspaceId:o,organizationId:f,authMethod:"client_credentials",clientId:a,clientSecret:p}),C(),g("App authentication successful");}var xe=`
27
+ query currentUser {
28
+ currentUser {
29
+ id email firstName lastName username phoneNumber name
30
+ emailVerified mfaEnabled isAdmin role status createdAt lastLoginAt
31
+ }
32
+ }
33
+ `,Ce=`
34
+ mutation updateCurrentUserProfile($input: UpdateUserInput!) {
35
+ updateCurrentUserProfile(input: $input) {
36
+ id name firstName lastName username phoneNumber timezone language
37
+ }
38
+ }
39
+ `,le=`
40
+ query authAuditLogs($pagination: PaginationInput) {
41
+ authAuditLogs(pagination: $pagination) {
42
+ id action resource resourceType resourceId description
43
+ ipAddress userAgent metadata createdAt
44
+ }
45
+ }
46
+ `,_e=`
47
+ query activeSessions($pagination: PaginationInput) {
48
+ activeSessions(pagination: $pagination) {
49
+ id status ipAddress userAgent location lastActivityAt expiresAt createdAt isCurrent
50
+ }
51
+ }
52
+ `,be=`
53
+ query currentUserMFAMethods($pagination: PaginationInput) {
54
+ currentUserMFAMethods(pagination: $pagination) {
55
+ id method status createdAt updatedAt
56
+ }
57
+ }
58
+ `,we=`
59
+ mutation setupMFA($method: MFAMethod!) {
60
+ setupMFA(method: $method) {
61
+ method backupCodes qrCode secret
62
+ }
63
+ }
64
+ `;var Oe=`
65
+ mutation enableMFA($code: String!) {
66
+ enableMFA(code: $code)
67
+ }
68
+ `,Ne=`
69
+ mutation disableMFA {
70
+ disableMFA
71
+ }
72
+ `,ve=`
73
+ query myApiKeys($pagination: PaginationInput) {
74
+ myApiKeys(pagination: $pagination) {
75
+ id name prefix appId appName scopes expiresAt lastUsedAt createdAt
76
+ }
77
+ }
78
+ `,Re=`
79
+ query appApiKeys($appId: ID!, $pagination: PaginationInput) {
80
+ appApiKeys(appId: $appId, pagination: $pagination) {
81
+ id name prefix appId appName scopes expiresAt lastUsedAt createdAt
82
+ }
83
+ }
84
+ `,Ue=`
85
+ mutation generateAPIKey($input: GenerateAPIKeyInput!) {
86
+ generateAPIKey(input: $input) {
87
+ keyId apiKey apiSecret
88
+ }
89
+ }
90
+ `;var Le=`
91
+ mutation revokeAPIKey($keyId: String!) {
92
+ revokeAPIKey(keyId: $keyId)
93
+ }
94
+ `,Pe=`
95
+ mutation rotateAPIKey($keyId: String!) {
96
+ rotateAPIKey(keyId: $keyId) {
97
+ apiSecret
98
+ }
99
+ }
100
+ `,Ve=`
101
+ query currentUserDelegations($pagination: PaginationInput) {
102
+ currentUserDelegations(pagination: $pagination) {
103
+ id appId userId grantedBy grantedAt expiresAt scopes workspaceIds
104
+ status revokedAt revokedBy
105
+ app { id name }
106
+ }
107
+ }
108
+ `,qe=`
109
+ mutation grantDelegation($input: GrantDelegationInput!) {
110
+ grantDelegation(input: $input) {
111
+ id appId userId grantedBy grantedAt expiresAt scopes workspaceIds status
112
+ }
113
+ }
114
+ `,Ge=`
115
+ mutation revokeDelegation($id: ID!, $reason: String) {
116
+ revokeDelegation(id: $id, reason: $reason)
117
+ }
118
+ `,Fe=`
119
+ query currentUserApps($pagination: PaginationInput) {
120
+ currentUserApps(pagination: $pagination) {
121
+ id clientId name description type actorType status ownerUserId
122
+ redirectUris scopes createdAt updatedAt
123
+ }
124
+ }
125
+ `,Be=`
126
+ query app($id: ID!) {
127
+ app(id: $id) {
128
+ id clientId name description type actorType status ownerUserId redirectUris scopes
129
+ }
130
+ }
131
+ `,Me=`
132
+ mutation createApp($input: CreateAppInput!) {
133
+ createApp(input: $input) {
134
+ app { id clientId name type status }
135
+ clientSecret
136
+ }
137
+ }
138
+ `,Ke=`
139
+ mutation updateApp($id: ID!, $input: UpdateAppInput!) {
140
+ updateApp(id: $id, input: $input) {
141
+ id name description redirectUris scopes status
142
+ }
143
+ }
144
+ `,We=`
145
+ mutation deactivateApp($id: ID!) {
146
+ deactivateApp(id: $id)
147
+ }
148
+ `,He=`
149
+ query getSSOConfig($tenantId: String!) {
150
+ getSSOConfig(tenantId: $tenantId) {
151
+ id identifier tenantId entityId ssoUrl sloUrl certificate enabled metadata
152
+ }
153
+ }
154
+ `,ze=`
155
+ mutation saveSSOConfig($tenantId: String!, $input: SSOConfigInput!) {
156
+ saveSSOConfig(tenantId: $tenantId, input: $input) {
157
+ id identifier entityId ssoUrl sloUrl certificate enabled
158
+ }
159
+ }
160
+ `,je=`
161
+ mutation deleteSSOConfig($tenantId: String!) {
162
+ deleteSSOConfig(tenantId: $tenantId)
163
+ }
164
+ `,Ye=`
165
+ query users($filter: UserFilterInput, $pagination: PaginationInput) {
166
+ users(filter: $filter, pagination: $pagination) {
167
+ users { id email firstName lastName username role status createdAt }
168
+ totalCount hasMore
169
+ }
170
+ }
171
+ `,Je=`
172
+ query user($id: ID!) {
173
+ user(id: $id) {
174
+ id email firstName lastName username role status emailVerified lastLoginAt
175
+ }
176
+ }
177
+ `,Xe=`
178
+ mutation updateUser($id: ID!, $input: AdminUpdateUserInput!) {
179
+ updateUser(id: $id, input: $input) {
180
+ id email firstName lastName username role status
181
+ }
182
+ }
183
+ `;function Qe(n){let s=n.command("profile").description("Current user profile");s.command("show").description("Show current user").option("-f, --format <format>").action(async e=>{try{let t=await l(xe);m(e,t.currentUser);}catch(t){u(t);}}),s.command("update").description("Update current user profile").option("--first-name <s>").option("--last-name <s>").option("--name <s>").option("--username <s>").option("--phone <s>").option("--timezone <s>").option("--language <s>").option("-f, --format <format>").action(async e=>{try{let t={};if(e.firstName&&(t.firstName=e.firstName),e.lastName&&(t.lastName=e.lastName),e.name&&(t.name=e.name),e.username&&(t.username=e.username),e.phone&&(t.phoneNumber=e.phone),e.timezone&&(t.timezone=e.timezone),e.language&&(t.language=e.language),!Object.keys(t).length)throw new S("No updates specified");let o=await l(Ce,{input:t});g("Profile updated"),m(e,o.updateCurrentUserProfile);}catch(t){u(t);}});let i=n.command("security").description("Account security overview");i.command("audit-log").description("Recent auth audit events for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(le,{pagination:{limit:e.limit,offset:0}});m(e,t.authAuditLogs,{headers:["When","Action","Resource","IP"],rows:t.authAuditLogs.map(o=>[_(o.createdAt),o.action,o.resource??"-",o.ipAddress??"-"])});}catch(t){u(t);}}),i.command("sessions").description("Active sessions for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(_e,{pagination:{limit:e.limit,offset:0}});m(e,t.activeSessions,{headers:["ID","Status","IP","LastActivity","Current"],rows:t.activeSessions.map(o=>[q(o.id,12),j(o.status),o.ipAddress??"-",_(o.lastActivityAt),String(!!o.isCurrent)])});}catch(t){u(t);}});let r=n.command("mfa").description("Multi-factor authentication");r.command("list").description("List MFA methods enrolled for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(be,{pagination:{limit:e.limit,offset:0}});m(e,t.currentUserMFAMethods,{headers:["Method","Status","Created"],rows:t.currentUserMFAMethods.map(o=>[o.method,j(o.status),_(o.createdAt)])});}catch(t){u(t);}}),r.command("enroll").description("Begin MFA enrollment (TOTP/SMS/EMAIL)").requiredOption("--method <m>","TOTP|SMS|EMAIL").option("-f, --format <format>").action(async e=>{try{let t=await l(we,{method:e.method.toUpperCase()});e.format?m(e,t.setupMFA):(g("MFA enrollment started"),z(t.setupMFA),k("Save your backup codes; verify with `auth mfa verify --code <CODE>`."));}catch(t){u(t);}}),r.command("verify").description("Verify MFA enrollment code").requiredOption("--code <code>").action(async e=>{try{await l(Oe,{code:e.code}),g("MFA enabled");}catch(t){u(t);}}),r.command("disable").description("Disable MFA for the current user").action(async()=>{try{await l(Ne),g("MFA disabled");}catch(e){u(e);}});let a=n.command("api-keys").description("API key management");a.command("list").description("List your API keys").option("--app <id>","Restrict to keys for an app id").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=e.app?Re:ve,o=e.app?{appId:e.app,pagination:{limit:e.limit,offset:0}}:{pagination:{limit:e.limit,offset:0}},f=await l(t,o),A=f.myApiKeys??f.appApiKeys??[];m(e,A,{headers:["ID","Name","Prefix","App","Scopes","LastUsed"],rows:A.map($=>[q($.id,12),$.name??"-",$.prefix??"-",$.appName??"-",Array.isArray($.scopes)?$.scopes.join(","):"-",_($.lastUsedAt)])});}catch(t){u(t);}}),a.command("create").description("Generate a new API key").requiredOption("--name <name>").requiredOption("--app <appId>","Owning app id").option("--scope <scope>","Comma-separated scopes").option("--expires <iso>","ISO expiry").option("-f, --format <format>").action(async e=>{try{let t={name:e.name,appId:e.app,scope:e.scope?e.scope.split(","):void 0,expiresAt:e.expires},o=await l(Ue,{input:t});g("API key generated. Store the secret \u2014 it is only shown once."),z(o.generateAPIKey);}catch(t){u(t);}}),a.command("revoke").description("Revoke an API key").argument("<keyId>").action(async e=>{try{await l(Le,{keyId:e}),g("API key revoked");}catch(t){u(t);}}),a.command("rotate").description("Rotate an API key (returns new secret)").argument("<keyId>").action(async e=>{try{let t=await l(Pe,{keyId:e});g("API key rotated"),z(t.rotateAPIKey);}catch(t){u(t);}}),n.command("audit-log").description("Auth audit log").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(le,{pagination:{limit:e.limit,offset:0}});m(e,t.authAuditLogs);}catch(t){u(t);}});let p=n.command("delegations").description("Delegation management");p.command("list").description("Delegations granted to the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(Ve,{pagination:{limit:e.limit,offset:0}});m(e,t.currentUserDelegations);}catch(t){u(t);}}),p.command("grant").description("Grant a delegation to an app").requiredOption("--app <appId>").requiredOption("--user <userId>","User to delegate as").option("--scope <s>","Comma-separated scopes").option("--workspace <ids>","Comma-separated workspace ids").option("--expires <iso>").option("-f, --format <format>").action(async e=>{try{let t={appId:e.app,userId:e.user,scopes:e.scope?e.scope.split(","):void 0,workspaceIds:e.workspace?e.workspace.split(","):void 0,expiresAt:e.expires},o=await l(qe,{input:t});g("Delegation granted"),m(e,o.grantDelegation);}catch(t){u(t);}}),p.command("revoke").description("Revoke a delegation").argument("<id>").option("--reason <text>").action(async(e,t)=>{try{await l(Ge,{id:e,reason:t.reason}),g("Delegation revoked");}catch(o){u(o);}});let c=n.command("apps").description("OAuth/system app management");c.command("list").description("Apps owned by the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await l(Fe,{pagination:{limit:e.limit,offset:0}});m(e,t.currentUserApps,{headers:["ID","ClientID","Name","Type","Status"],rows:t.currentUserApps.map(o=>[q(o.id,12),q(o.clientId,24),o.name??"-",o.type??"-",j(o.status)])});}catch(t){u(t);}}),c.command("get").description("Get an app by id").argument("<id>").option("-f, --format <format>").action(async(e,t)=>{try{let o=await l(Be,{id:e});if(!o.app)throw new S(`App ${e} not found`);m(t,o.app);}catch(o){u(o);}}),c.command("create").description("Create an OAuth app").requiredOption("--name <s>").option("--description <s>").option("--type <t>","OAUTH|SYSTEM","OAUTH").option("--actor-type <t>","USER|APP|SERVICE","APP").option("--redirect <urls>","Comma-separated redirect URIs").option("--scopes <s>","Comma-separated scopes").option("-f, --format <format>").action(async e=>{try{let t={name:e.name,description:e.description,type:(e.type??"OAUTH").toUpperCase(),actorType:(e.actorType??"APP").toUpperCase(),redirectUris:e.redirect?e.redirect.split(","):void 0,scopes:e.scopes?e.scopes.split(","):void 0},o=await l(Me,{input:t});g("App created. Client secret only shown once."),z(o.createApp);}catch(t){u(t);}}),c.command("update").description("Update an app").argument("<id>").option("--name <s>").option("--description <s>").option("--redirect <urls>","Comma-separated redirect URIs").option("--scopes <s>","Comma-separated scopes").option("--status <s>").option("-f, --format <format>").action(async(e,t)=>{try{let o={};if(t.name&&(o.name=t.name),t.description!==void 0&&(o.description=t.description),t.redirect&&(o.redirectUris=t.redirect.split(",")),t.scopes&&(o.scopes=t.scopes.split(",")),t.status&&(o.status=t.status.toUpperCase()),!Object.keys(o).length)throw new S("No updates specified");let f=await l(Ke,{id:e,input:o});g("App updated"),m(t,f.updateApp);}catch(o){u(o);}}),c.command("deactivate").description("Deactivate an app").argument("<id>").action(async e=>{try{await l(We,{id:e}),g("App deactivated");}catch(t){u(t);}});let d=n.command("sso").description("SSO (SAML/OIDC) configuration");d.command("get").description("Get SSO config for a tenant").requiredOption("--tenant <id>").option("-f, --format <format>").action(async e=>{try{let t=await l(He,{tenantId:e.tenant});m(e,t.getSSOConfig);}catch(t){u(t);}}),d.command("save").description("Save (upsert) SSO config for a tenant").requiredOption("--tenant <id>").requiredOption("--entity <s>","EntityID / Issuer").requiredOption("--sso-url <url>").option("--slo-url <url>").option("--certificate <pem>","X.509 certificate PEM").option("--enabled","Enable after save",false).option("-f, --format <format>").action(async e=>{try{let t={entityId:e.entity,ssoUrl:e.ssoUrl,sloUrl:e.sloUrl,certificate:e.certificate,enabled:!!e.enabled},o=await l(ze,{tenantId:e.tenant,input:t});g("SSO config saved"),m(e,o.saveSSOConfig);}catch(t){u(t);}}),d.command("delete").description("Delete SSO config for a tenant").requiredOption("--tenant <id>").action(async e=>{try{await l(je,{tenantId:e.tenant}),g("SSO config deleted");}catch(t){u(t);}});let I=n.command("users").description("User admin (requires admin permissions)");I.command("list").description("List users (admin)").option("--email <s>").option("--username <s>").option("--role <s>").option("--status <s>").option("--search <s>").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t={};e.email&&(t.email=e.email),e.username&&(t.username=e.username),e.role&&(t.role=e.role.toUpperCase()),e.status&&(t.status=e.status.toUpperCase()),e.search&&(t.search=e.search);let o=await l(Ye,{filter:Object.keys(t).length?t:void 0,pagination:{limit:e.limit,offset:0}});m(e,o.users.users,{headers:["ID","Email","Username","Role","Status","Created"],rows:o.users.users.map(f=>[q(f.id,12),f.email,f.username??"-",f.role??"-",j(f.status),_(f.createdAt)])});}catch(t){u(t);}}),I.command("get").description("Get user by id (admin)").argument("<id>").option("-f, --format <format>").action(async(e,t)=>{try{let o=await l(Je,{id:e});if(!o.user)throw new S(`User ${e} not found`);m(t,o.user);}catch(o){u(o);}}),I.command("update").description("Update a user (admin)").argument("<id>").option("--first-name <s>").option("--last-name <s>").option("--username <s>").option("--phone <s>").option("--role <s>").option("--status <s>").option("--email-verified <bool>").option("-f, --format <format>").action(async(e,t)=>{try{let o={};if(t.firstName&&(o.firstName=t.firstName),t.lastName&&(o.lastName=t.lastName),t.username&&(o.username=t.username),t.phone&&(o.phoneNumber=t.phone),t.role&&(o.role=t.role.toUpperCase()),t.status&&(o.status=t.status.toUpperCase()),t.emailVerified!==void 0&&(o.emailVerified=t.emailVerified==="true"),!Object.keys(o).length)throw new S("No updates specified");let f=await l(Xe,{id:e,input:o});g("User updated"),m(t,f.updateUser);}catch(o){u(o);}});}var dt={id:"auth",version:"1.0.0",displayName:"Authentication",register(n,s){me(s),De(n);let i=n.commands.find(r=>r.name()==="auth");if(!i)throw new x("auth command group missing after registerAuthCommands");Qe(i);}},ur=dt;module.exports=ur;
@@ -0,0 +1,7 @@
1
+ import { C as CliModule } from '../../module-Bv5zhYt2.cjs';
2
+ import 'commander';
3
+ import 'graphql-request';
4
+
5
+ declare const authModule: CliModule;
6
+
7
+ export { authModule as default };
@@ -0,0 +1,7 @@
1
+ import { C as CliModule } from '../../module-Bv5zhYt2.js';
2
+ import 'commander';
3
+ import 'graphql-request';
4
+
5
+ declare const authModule: CliModule;
6
+
7
+ export { authModule as default };
@@ -0,0 +1,160 @@
1
+ import {Bc,Cc}from'../../chunk-MRONTCXQ.js';import {a,f,s,d,k,u,e,h,v,B,n,g,t,c,o as o$1,m,l,j,A}from'../../chunk-KTKHJORN.js';import {q,o,f as f$1,h as h$1,g as g$1,d as d$1,i,e as e$1}from'../../chunk-RNWXATAC.js';function X(s$1){let u$1=s$1.command("auth").description("Authentication commands");u$1.command("login").description("Authenticate with VibeControls").option("--client-credentials","Authenticate as an app with client ID and secret").option("--workspace-id <id>","Workspace ID (for app auth)").action(async i=>{try{i.clientCredentials?await Ce(i.workspaceId):await Ue();}catch(r){f(r);}}),u$1.command("logout").description("Revoke tokens and clear stored auth").action(async()=>{try{if(s()?.accessToken)try{await d(Bc);}catch{k("Server-side logout failed, clearing local tokens");}u(),e(),h("Logged out successfully");}catch(i){f(i);}}),u$1.command("status").description("Show current auth state").option("-f, --format <format>","Output format (json, table)").action(i=>{let r=s(),p=v(),I=!!r?.accessToken,m=r?.accessToken?B(r):false,f=r?.expiresAt?n(new Date(r.expiresAt).toISOString()):"-",h=r?.authMethod==="client_credentials"?"Client Credentials":"OAuth2 Device Code",e=r?.workspaceTokenExpiresAt?n(new Date(r.workspaceTokenExpiresAt).toISOString()):"-";g(i,{authenticated:I,method:h,expired:m,expiresAt:f,workspaceId:r?.workspaceId??"-",organizationId:r?.organizationId??"-",workspaceTokenExpiresAt:e,workspaceEndpoint:p.workspaceEndpoint,globalEndpoint:p.globalEndpoint},{headers:["Key","Value"],rows:[["Authenticated",String(I)],["Method",h],["Expired",String(m)],["Expires At",f],["Workspace ID",r?.workspaceId??"-"],["Organization ID",r?.organizationId??"-"],["Workspace Token Expires",e],["Workspace Endpoint",p.workspaceEndpoint],["Global Endpoint",p.globalEndpoint]]});}),u$1.command("token").description("Print access token to stdout").option("--workspace","Print workspace token instead").action(i=>{let r=s();if(i.workspace){if(!r?.workspaceToken)throw new o("No workspace token. Set a workspace: vibecontrols workspace set <id>");process.stdout.write(r.workspaceToken);return}if(!r?.accessToken)throw new o("Not authenticated. Run: vibecontrols auth login");process.stdout.write(r.accessToken);}),u$1.command("refresh").description("Force token refresh").action(async()=>{try{let i=s();if(!i?.refreshToken&&i?.authMethod!=="client_credentials")throw new o("No refresh token available. Run: vibecontrols auth login");if(i?.authMethod==="client_credentials"&&i.clientId&&i.clientSecret){let I=v(),m=await f$1(I.globalEndpoint,i.clientId,i.clientSecret);t({...i,accessToken:m.accessToken,expiresAt:Date.now()+m.expiresIn*1e3}),e(),h("App token refreshed successfully"),i.workspaceId&&i.organizationId&&await J();return}let p=(await d(Cc,{token:i.refreshToken})).refreshToken;t({...i,accessToken:p.accessToken,refreshToken:p.refreshToken,expiresAt:Date.now()+p.expiresIn*1e3}),e(),h("Token refreshed successfully"),i.workspaceId&&i.organizationId&&await J();}catch(i){f(i);}});}async function J(){let s$1=s();if(!s$1?.accessToken||!s$1.workspaceId||!s$1.organizationId)return;let u=v();try{let i=await g$1(u.workspaceEndpoint,s$1.accessToken,s$1.workspaceId,s$1.organizationId);t({...s$1,workspaceToken:i.token,workspaceTokenExpiresAt:new Date(i.expiresAt).getTime()}),e(),h("Workspace token refreshed");}catch{k("Workspace token refresh failed \u2014 workspace operations may require re-login");}}async function Ue(){let s=v(),{oidcIssuer:u,clientId:i$1}=A(),r={...s,oidcIssuer:u,clientId:i$1};j("Starting device code authentication...");let p=await d$1(r);console.log(""),console.log(` Open: ${p.verificationUri}`),console.log(` Code: ${p.userCode}`),console.log(""),await i(p.verificationUriComplete??p.verificationUri)?j("Browser opened"):k("Could not open browser \u2014 open the URL manually"),j("Waiting for authorization...");let m=await e$1(p.deviceCode,p.interval,r),f=m.accessToken,h$2=Date.now()+m.expiresIn*1e3;j("Fetching workspaces...");try{let e$1=await h$1(s.globalEndpoint,f);if(e$1.length===0){t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,authMethod:"device_code"}),e(),h("Authentication successful (no workspaces found)");return}let t$1=e$1[0];if(e$1.length>1){console.log(`
2
+ Available workspaces:`),e$1.forEach((O,$)=>console.log(` ${$+1}. ${O.name} (${O.slug})`));let A=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),g=await new Promise(O=>{A.question(`
3
+ Select workspace [1-${e$1.length}]: `,$=>{A.close(),O($.trim());});}),S=parseInt(g,10)-1;S>=0&&S<e$1.length&&(t$1=e$1[S]);}j(`Using workspace: ${t$1.name} (${t$1.id})`);let n=await g$1(s.workspaceEndpoint,f,t$1.id,t$1.organizationId);t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,workspaceToken:n.token,workspaceTokenExpiresAt:new Date(n.expiresAt).getTime(),workspaceId:t$1.id,organizationId:t$1.organizationId,authMethod:"device_code"}),e(),h("Authentication successful");}catch(e$1){t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,authMethod:"device_code"}),e(),h("Authentication successful"),k(`Workspace token not obtained: ${e$1 instanceof Error?e$1.message:String(e$1)}`),j("Set workspace manually: vibecontrols workspace set <id>");}}async function Ce(s){let u=v(),r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(A=>{r.question("Client ID: ",g=>A(g.trim()));}),I=await new Promise(A=>{r.question("Client Secret: ",g=>{r.close(),A(g.trim());});});if(!p||!I)throw new o("Client ID and secret cannot be empty");j("Authenticating app...");let m=await f$1(u.globalEndpoint,p,I),f=m.accessToken,h$2=Date.now()+m.expiresIn*1e3,e$1,t$1,n=s,l;if(n)try{let g=(await h$1(u.globalEndpoint,f)).find(S=>S.id===n);if(g){l=g.organizationId;let S=await g$1(u.workspaceEndpoint,f,n,l);e$1=S.token,t$1=new Date(S.expiresAt).getTime(),j(`Workspace token issued for: ${g.name}`);}else k(`Workspace ${n} not found \u2014 skipping workspace token`),n=void 0;}catch(A){k(`Workspace token failed: ${A instanceof Error?A.message:String(A)}`);}t({accessToken:f,refreshToken:"",expiresAt:h$2,workspaceToken:e$1,workspaceTokenExpiresAt:t$1,workspaceId:n,organizationId:l,authMethod:"client_credentials",clientId:p,clientSecret:I}),e(),h("App authentication successful");}var Q=`
4
+ query currentUser {
5
+ currentUser {
6
+ id email firstName lastName username phoneNumber name
7
+ emailVerified mfaEnabled isAdmin role status createdAt lastLoginAt
8
+ }
9
+ }
10
+ `,Z=`
11
+ mutation updateCurrentUserProfile($input: UpdateUserInput!) {
12
+ updateCurrentUserProfile(input: $input) {
13
+ id name firstName lastName username phoneNumber timezone language
14
+ }
15
+ }
16
+ `,K=`
17
+ query authAuditLogs($pagination: PaginationInput) {
18
+ authAuditLogs(pagination: $pagination) {
19
+ id action resource resourceType resourceId description
20
+ ipAddress userAgent metadata createdAt
21
+ }
22
+ }
23
+ `,ee=`
24
+ query activeSessions($pagination: PaginationInput) {
25
+ activeSessions(pagination: $pagination) {
26
+ id status ipAddress userAgent location lastActivityAt expiresAt createdAt isCurrent
27
+ }
28
+ }
29
+ `,te=`
30
+ query currentUserMFAMethods($pagination: PaginationInput) {
31
+ currentUserMFAMethods(pagination: $pagination) {
32
+ id method status createdAt updatedAt
33
+ }
34
+ }
35
+ `,ne=`
36
+ mutation setupMFA($method: MFAMethod!) {
37
+ setupMFA(method: $method) {
38
+ method backupCodes qrCode secret
39
+ }
40
+ }
41
+ `;var ie=`
42
+ mutation enableMFA($code: String!) {
43
+ enableMFA(code: $code)
44
+ }
45
+ `,re=`
46
+ mutation disableMFA {
47
+ disableMFA
48
+ }
49
+ `,oe=`
50
+ query myApiKeys($pagination: PaginationInput) {
51
+ myApiKeys(pagination: $pagination) {
52
+ id name prefix appId appName scopes expiresAt lastUsedAt createdAt
53
+ }
54
+ }
55
+ `,se=`
56
+ query appApiKeys($appId: ID!, $pagination: PaginationInput) {
57
+ appApiKeys(appId: $appId, pagination: $pagination) {
58
+ id name prefix appId appName scopes expiresAt lastUsedAt createdAt
59
+ }
60
+ }
61
+ `,ae=`
62
+ mutation generateAPIKey($input: GenerateAPIKeyInput!) {
63
+ generateAPIKey(input: $input) {
64
+ keyId apiKey apiSecret
65
+ }
66
+ }
67
+ `;var ce=`
68
+ mutation revokeAPIKey($keyId: String!) {
69
+ revokeAPIKey(keyId: $keyId)
70
+ }
71
+ `,pe=`
72
+ mutation rotateAPIKey($keyId: String!) {
73
+ rotateAPIKey(keyId: $keyId) {
74
+ apiSecret
75
+ }
76
+ }
77
+ `,de=`
78
+ query currentUserDelegations($pagination: PaginationInput) {
79
+ currentUserDelegations(pagination: $pagination) {
80
+ id appId userId grantedBy grantedAt expiresAt scopes workspaceIds
81
+ status revokedAt revokedBy
82
+ app { id name }
83
+ }
84
+ }
85
+ `,me=`
86
+ mutation grantDelegation($input: GrantDelegationInput!) {
87
+ grantDelegation(input: $input) {
88
+ id appId userId grantedBy grantedAt expiresAt scopes workspaceIds status
89
+ }
90
+ }
91
+ `,ue=`
92
+ mutation revokeDelegation($id: ID!, $reason: String) {
93
+ revokeDelegation(id: $id, reason: $reason)
94
+ }
95
+ `,le=`
96
+ query currentUserApps($pagination: PaginationInput) {
97
+ currentUserApps(pagination: $pagination) {
98
+ id clientId name description type actorType status ownerUserId
99
+ redirectUris scopes createdAt updatedAt
100
+ }
101
+ }
102
+ `,ge=`
103
+ query app($id: ID!) {
104
+ app(id: $id) {
105
+ id clientId name description type actorType status ownerUserId redirectUris scopes
106
+ }
107
+ }
108
+ `,fe=`
109
+ mutation createApp($input: CreateAppInput!) {
110
+ createApp(input: $input) {
111
+ app { id clientId name type status }
112
+ clientSecret
113
+ }
114
+ }
115
+ `,Ae=`
116
+ mutation updateApp($id: ID!, $input: UpdateAppInput!) {
117
+ updateApp(id: $id, input: $input) {
118
+ id name description redirectUris scopes status
119
+ }
120
+ }
121
+ `,Ie=`
122
+ mutation deactivateApp($id: ID!) {
123
+ deactivateApp(id: $id)
124
+ }
125
+ `,he=`
126
+ query getSSOConfig($tenantId: String!) {
127
+ getSSOConfig(tenantId: $tenantId) {
128
+ id identifier tenantId entityId ssoUrl sloUrl certificate enabled metadata
129
+ }
130
+ }
131
+ `,ye=`
132
+ mutation saveSSOConfig($tenantId: String!, $input: SSOConfigInput!) {
133
+ saveSSOConfig(tenantId: $tenantId, input: $input) {
134
+ id identifier entityId ssoUrl sloUrl certificate enabled
135
+ }
136
+ }
137
+ `,we=`
138
+ mutation deleteSSOConfig($tenantId: String!) {
139
+ deleteSSOConfig(tenantId: $tenantId)
140
+ }
141
+ `,ke=`
142
+ query users($filter: UserFilterInput, $pagination: PaginationInput) {
143
+ users(filter: $filter, pagination: $pagination) {
144
+ users { id email firstName lastName username role status createdAt }
145
+ totalCount hasMore
146
+ }
147
+ }
148
+ `,Ee=`
149
+ query user($id: ID!) {
150
+ user(id: $id) {
151
+ id email firstName lastName username role status emailVerified lastLoginAt
152
+ }
153
+ }
154
+ `,Se=`
155
+ mutation updateUser($id: ID!, $input: AdminUpdateUserInput!) {
156
+ updateUser(id: $id, input: $input) {
157
+ id email firstName lastName username role status
158
+ }
159
+ }
160
+ `;function Te(s){let u=s.command("profile").description("Current user profile");u.command("show").description("Show current user").option("-f, --format <format>").action(async e=>{try{let t=await c(Q);g(e,t.currentUser);}catch(t){f(t);}}),u.command("update").description("Update current user profile").option("--first-name <s>").option("--last-name <s>").option("--name <s>").option("--username <s>").option("--phone <s>").option("--timezone <s>").option("--language <s>").option("-f, --format <format>").action(async e=>{try{let t={};if(e.firstName&&(t.firstName=e.firstName),e.lastName&&(t.lastName=e.lastName),e.name&&(t.name=e.name),e.username&&(t.username=e.username),e.phone&&(t.phoneNumber=e.phone),e.timezone&&(t.timezone=e.timezone),e.language&&(t.language=e.language),!Object.keys(t).length)throw new o("No updates specified");let n=await c(Z,{input:t});h("Profile updated"),g(e,n.updateCurrentUserProfile);}catch(t){f(t);}});let i=s.command("security").description("Account security overview");i.command("audit-log").description("Recent auth audit events for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(K,{pagination:{limit:e.limit,offset:0}});g(e,t.authAuditLogs,{headers:["When","Action","Resource","IP"],rows:t.authAuditLogs.map(n$1=>[n(n$1.createdAt),n$1.action,n$1.resource??"-",n$1.ipAddress??"-"])});}catch(t){f(t);}}),i.command("sessions").description("Active sessions for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(ee,{pagination:{limit:e.limit,offset:0}});g(e,t.activeSessions,{headers:["ID","Status","IP","LastActivity","Current"],rows:t.activeSessions.map(n$1=>[o$1(n$1.id,12),m(n$1.status),n$1.ipAddress??"-",n(n$1.lastActivityAt),String(!!n$1.isCurrent)])});}catch(t){f(t);}});let r=s.command("mfa").description("Multi-factor authentication");r.command("list").description("List MFA methods enrolled for the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(te,{pagination:{limit:e.limit,offset:0}});g(e,t.currentUserMFAMethods,{headers:["Method","Status","Created"],rows:t.currentUserMFAMethods.map(n$1=>[n$1.method,m(n$1.status),n(n$1.createdAt)])});}catch(t){f(t);}}),r.command("enroll").description("Begin MFA enrollment (TOTP/SMS/EMAIL)").requiredOption("--method <m>","TOTP|SMS|EMAIL").option("-f, --format <format>").action(async e=>{try{let t=await c(ne,{method:e.method.toUpperCase()});e.format?g(e,t.setupMFA):(h("MFA enrollment started"),l(t.setupMFA),j("Save your backup codes; verify with `auth mfa verify --code <CODE>`."));}catch(t){f(t);}}),r.command("verify").description("Verify MFA enrollment code").requiredOption("--code <code>").action(async e=>{try{await c(ie,{code:e.code}),h("MFA enabled");}catch(t){f(t);}}),r.command("disable").description("Disable MFA for the current user").action(async()=>{try{await c(re),h("MFA disabled");}catch(e){f(e);}});let p=s.command("api-keys").description("API key management");p.command("list").description("List your API keys").option("--app <id>","Restrict to keys for an app id").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=e.app?se:oe,n$1=e.app?{appId:e.app,pagination:{limit:e.limit,offset:0}}:{pagination:{limit:e.limit,offset:0}},l=await c(t,n$1),A=l.myApiKeys??l.appApiKeys??[];g(e,A,{headers:["ID","Name","Prefix","App","Scopes","LastUsed"],rows:A.map(g=>[o$1(g.id,12),g.name??"-",g.prefix??"-",g.appName??"-",Array.isArray(g.scopes)?g.scopes.join(","):"-",n(g.lastUsedAt)])});}catch(t){f(t);}}),p.command("create").description("Generate a new API key").requiredOption("--name <name>").requiredOption("--app <appId>","Owning app id").option("--scope <scope>","Comma-separated scopes").option("--expires <iso>","ISO expiry").option("-f, --format <format>").action(async e=>{try{let t={name:e.name,appId:e.app,scope:e.scope?e.scope.split(","):void 0,expiresAt:e.expires},n=await c(ae,{input:t});h("API key generated. Store the secret \u2014 it is only shown once."),l(n.generateAPIKey);}catch(t){f(t);}}),p.command("revoke").description("Revoke an API key").argument("<keyId>").action(async e=>{try{await c(ce,{keyId:e}),h("API key revoked");}catch(t){f(t);}}),p.command("rotate").description("Rotate an API key (returns new secret)").argument("<keyId>").action(async e=>{try{let t=await c(pe,{keyId:e});h("API key rotated"),l(t.rotateAPIKey);}catch(t){f(t);}}),s.command("audit-log").description("Auth audit log").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(K,{pagination:{limit:e.limit,offset:0}});g(e,t.authAuditLogs);}catch(t){f(t);}});let I=s.command("delegations").description("Delegation management");I.command("list").description("Delegations granted to the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(de,{pagination:{limit:e.limit,offset:0}});g(e,t.currentUserDelegations);}catch(t){f(t);}}),I.command("grant").description("Grant a delegation to an app").requiredOption("--app <appId>").requiredOption("--user <userId>","User to delegate as").option("--scope <s>","Comma-separated scopes").option("--workspace <ids>","Comma-separated workspace ids").option("--expires <iso>").option("-f, --format <format>").action(async e=>{try{let t={appId:e.app,userId:e.user,scopes:e.scope?e.scope.split(","):void 0,workspaceIds:e.workspace?e.workspace.split(","):void 0,expiresAt:e.expires},n=await c(me,{input:t});h("Delegation granted"),g(e,n.grantDelegation);}catch(t){f(t);}}),I.command("revoke").description("Revoke a delegation").argument("<id>").option("--reason <text>").action(async(e,t)=>{try{await c(ue,{id:e,reason:t.reason}),h("Delegation revoked");}catch(n){f(n);}});let m$1=s.command("apps").description("OAuth/system app management");m$1.command("list").description("Apps owned by the current user").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t=await c(le,{pagination:{limit:e.limit,offset:0}});g(e,t.currentUserApps,{headers:["ID","ClientID","Name","Type","Status"],rows:t.currentUserApps.map(n=>[o$1(n.id,12),o$1(n.clientId,24),n.name??"-",n.type??"-",m(n.status)])});}catch(t){f(t);}}),m$1.command("get").description("Get an app by id").argument("<id>").option("-f, --format <format>").action(async(e,t)=>{try{let n=await c(ge,{id:e});if(!n.app)throw new o(`App ${e} not found`);g(t,n.app);}catch(n){f(n);}}),m$1.command("create").description("Create an OAuth app").requiredOption("--name <s>").option("--description <s>").option("--type <t>","OAUTH|SYSTEM","OAUTH").option("--actor-type <t>","USER|APP|SERVICE","APP").option("--redirect <urls>","Comma-separated redirect URIs").option("--scopes <s>","Comma-separated scopes").option("-f, --format <format>").action(async e=>{try{let t={name:e.name,description:e.description,type:(e.type??"OAUTH").toUpperCase(),actorType:(e.actorType??"APP").toUpperCase(),redirectUris:e.redirect?e.redirect.split(","):void 0,scopes:e.scopes?e.scopes.split(","):void 0},n=await c(fe,{input:t});h("App created. Client secret only shown once."),l(n.createApp);}catch(t){f(t);}}),m$1.command("update").description("Update an app").argument("<id>").option("--name <s>").option("--description <s>").option("--redirect <urls>","Comma-separated redirect URIs").option("--scopes <s>","Comma-separated scopes").option("--status <s>").option("-f, --format <format>").action(async(e,t)=>{try{let n={};if(t.name&&(n.name=t.name),t.description!==void 0&&(n.description=t.description),t.redirect&&(n.redirectUris=t.redirect.split(",")),t.scopes&&(n.scopes=t.scopes.split(",")),t.status&&(n.status=t.status.toUpperCase()),!Object.keys(n).length)throw new o("No updates specified");let l=await c(Ae,{id:e,input:n});h("App updated"),g(t,l.updateApp);}catch(n){f(n);}}),m$1.command("deactivate").description("Deactivate an app").argument("<id>").action(async e=>{try{await c(Ie,{id:e}),h("App deactivated");}catch(t){f(t);}});let f$1=s.command("sso").description("SSO (SAML/OIDC) configuration");f$1.command("get").description("Get SSO config for a tenant").requiredOption("--tenant <id>").option("-f, --format <format>").action(async e=>{try{let t=await c(he,{tenantId:e.tenant});g(e,t.getSSOConfig);}catch(t){f(t);}}),f$1.command("save").description("Save (upsert) SSO config for a tenant").requiredOption("--tenant <id>").requiredOption("--entity <s>","EntityID / Issuer").requiredOption("--sso-url <url>").option("--slo-url <url>").option("--certificate <pem>","X.509 certificate PEM").option("--enabled","Enable after save",false).option("-f, --format <format>").action(async e=>{try{let t={entityId:e.entity,ssoUrl:e.ssoUrl,sloUrl:e.sloUrl,certificate:e.certificate,enabled:!!e.enabled},n=await c(ye,{tenantId:e.tenant,input:t});h("SSO config saved"),g(e,n.saveSSOConfig);}catch(t){f(t);}}),f$1.command("delete").description("Delete SSO config for a tenant").requiredOption("--tenant <id>").action(async e=>{try{await c(we,{tenantId:e.tenant}),h("SSO config deleted");}catch(t){f(t);}});let h$1=s.command("users").description("User admin (requires admin permissions)");h$1.command("list").description("List users (admin)").option("--email <s>").option("--username <s>").option("--role <s>").option("--status <s>").option("--search <s>").option("--limit <n>","Page size",e=>parseInt(e,10),50).option("-f, --format <format>").action(async e=>{try{let t={};e.email&&(t.email=e.email),e.username&&(t.username=e.username),e.role&&(t.role=e.role.toUpperCase()),e.status&&(t.status=e.status.toUpperCase()),e.search&&(t.search=e.search);let n$1=await c(ke,{filter:Object.keys(t).length?t:void 0,pagination:{limit:e.limit,offset:0}});g(e,n$1.users.users,{headers:["ID","Email","Username","Role","Status","Created"],rows:n$1.users.users.map(l=>[o$1(l.id,12),l.email,l.username??"-",l.role??"-",m(l.status),n(l.createdAt)])});}catch(t){f(t);}}),h$1.command("get").description("Get user by id (admin)").argument("<id>").option("-f, --format <format>").action(async(e,t)=>{try{let n=await c(Ee,{id:e});if(!n.user)throw new o(`User ${e} not found`);g(t,n.user);}catch(n){f(n);}}),h$1.command("update").description("Update a user (admin)").argument("<id>").option("--first-name <s>").option("--last-name <s>").option("--username <s>").option("--phone <s>").option("--role <s>").option("--status <s>").option("--email-verified <bool>").option("-f, --format <format>").action(async(e,t)=>{try{let n={};if(t.firstName&&(n.firstName=t.firstName),t.lastName&&(n.lastName=t.lastName),t.username&&(n.username=t.username),t.phone&&(n.phoneNumber=t.phone),t.role&&(n.role=t.role.toUpperCase()),t.status&&(n.status=t.status.toUpperCase()),t.emailVerified!==void 0&&(n.emailVerified=t.emailVerified==="true"),!Object.keys(n).length)throw new o("No updates specified");let l=await c(Se,{id:e,input:n});h("User updated"),g(t,l.updateUser);}catch(n){f(n);}});}var Re={id:"auth",version:"1.0.0",displayName:"Authentication",register(s,u){a(u),X(s);let i=s.commands.find(r=>r.name()==="auth");if(!i)throw new q("auth command group missing after registerAuthCommands");Te(i);}},Ye=Re;export{Ye as default};