@contrail/cli 3.6.0 → 3.7.0-alpha.1c66a91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -3
- package/dist/auth/login.d.ts +4 -0
- package/dist/auth/login.js +134 -54
- package/dist/auth/login.spec.js +117 -3
- package/dist/auth/sign-in-error.d.ts +7 -0
- package/dist/auth/sign-in-error.js +24 -0
- package/dist/auth/sign-in-error.spec.d.ts +1 -0
- package/dist/auth/sign-in-error.spec.js +22 -0
- package/dist/auth/sso.d.ts +38 -0
- package/dist/auth/sso.js +184 -0
- package/dist/auth/sso.spec.d.ts +1 -0
- package/dist/auth/sso.spec.js +191 -0
- package/dist/basecommand.d.ts +3 -0
- package/dist/basecommand.js +8 -1
- package/dist/commands/app/publish.js +1 -1
- package/dist/commands/app/version/prerelease.d.ts +11 -0
- package/dist/commands/app/version/prerelease.js +32 -0
- package/dist/commands/login.d.ts +12 -0
- package/dist/commands/login.js +25 -0
- package/dist/helpers/app/app-config-validators.js +4 -4
- package/dist/helpers/app/app-config-validators.spec.js +36 -0
- package/dist/helpers/app/app-deployer.d.ts +1 -0
- package/dist/helpers/app/app-deployer.js +34 -0
- package/dist/helpers/app/upgrade-version.d.ts +3 -1
- package/dist/helpers/app/upgrade-version.js +7 -8
- package/dist/helpers/app/upgrade-version.spec.js +15 -0
- package/oclif.manifest.json +93 -2
- package/package.json +1 -1
package/dist/auth/sso.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.refreshSsoAccessToken = exports.exchangeCodeForTokens = exports.buildOpenBrowserCommand = exports.openBrowser = exports.canOpenBrowser = exports.listenForLoopbackCode = exports.parsePastedSignInCode = exports.buildAuthorizeUrl = exports.createSignInAttempt = exports.fetchSsoDomainCheck = exports.LOOPBACK_CALLBACK_URL = exports.LOOPBACK_PORT = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const node_http_1 = require("node:http");
|
|
6
|
+
const node_child_process_1 = require("node:child_process");
|
|
7
|
+
const sign_in_error_1 = require("./sign-in-error");
|
|
8
|
+
// Must match the CLI client's loopback callback URL in contrail-api resources/cognito.
|
|
9
|
+
exports.LOOPBACK_PORT = 7731;
|
|
10
|
+
exports.LOOPBACK_CALLBACK_URL = `http://localhost:${exports.LOOPBACK_PORT}/callback`;
|
|
11
|
+
const BROWSER_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
12
|
+
const OAUTH_SCOPES = ['openid', 'email', 'api.vibeiq.default/read', 'api.vibeiq.default/write'];
|
|
13
|
+
async function fetchSsoDomainCheck(email, apiGateway) {
|
|
14
|
+
const domain = email.split('@').pop().toLowerCase();
|
|
15
|
+
const response = await fetch(`${apiGateway}/sso-login/domain-check/${encodeURIComponent(domain)}`);
|
|
16
|
+
if (!response.ok) {
|
|
17
|
+
throw new sign_in_error_1.SignInError('SSO_DOMAIN_CHECK_FAILED', 'Could not check whether your email domain signs in with SSO.', { domain, status: response.status });
|
|
18
|
+
}
|
|
19
|
+
const body = await response.text();
|
|
20
|
+
if (!body) {
|
|
21
|
+
return { kind: 'none' };
|
|
22
|
+
}
|
|
23
|
+
const { identityProvider } = JSON.parse(body);
|
|
24
|
+
return identityProvider ? { kind: 'cognito', identityProvider } : { kind: 'legacy' };
|
|
25
|
+
}
|
|
26
|
+
exports.fetchSsoDomainCheck = fetchSsoDomainCheck;
|
|
27
|
+
function createSignInAttempt() {
|
|
28
|
+
// RFC 7636 needs a 43-128 character verifier: 32 random bytes encode to 43.
|
|
29
|
+
const verifier = (0, node_crypto_1.randomBytes)(32).toString('base64url');
|
|
30
|
+
return {
|
|
31
|
+
verifier,
|
|
32
|
+
challenge: (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url'),
|
|
33
|
+
// RFC 6749 section 10.10 asks for at most a 2^-128 chance of guessing state.
|
|
34
|
+
state: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
exports.createSignInAttempt = createSignInAttempt;
|
|
38
|
+
function buildAuthorizeUrl(client, identityProvider, redirectUri, signInAttempt) {
|
|
39
|
+
const params = new URLSearchParams({
|
|
40
|
+
response_type: 'code',
|
|
41
|
+
client_id: client.clientId,
|
|
42
|
+
redirect_uri: redirectUri,
|
|
43
|
+
scope: OAUTH_SCOPES.join(' '),
|
|
44
|
+
identity_provider: identityProvider,
|
|
45
|
+
code_challenge: signInAttempt.challenge,
|
|
46
|
+
code_challenge_method: 'S256',
|
|
47
|
+
state: signInAttempt.state,
|
|
48
|
+
});
|
|
49
|
+
return `${client.domain}/oauth2/authorize?${params}`;
|
|
50
|
+
}
|
|
51
|
+
exports.buildAuthorizeUrl = buildAuthorizeUrl;
|
|
52
|
+
function parsePastedSignInCode(pasted, expectedState) {
|
|
53
|
+
const [code, state] = pasted.trim().split('#');
|
|
54
|
+
if (!code || state !== expectedState) {
|
|
55
|
+
throw new sign_in_error_1.SignInError('SSO_SIGN_IN_CODE_MISMATCH', 'That sign-in code is not from this login attempt. Run the command again.');
|
|
56
|
+
}
|
|
57
|
+
return code;
|
|
58
|
+
}
|
|
59
|
+
exports.parsePastedSignInCode = parsePastedSignInCode;
|
|
60
|
+
function listenForLoopbackCode(expectedState) {
|
|
61
|
+
let resolveCode;
|
|
62
|
+
let rejectCode;
|
|
63
|
+
const code = new Promise((resolve, reject) => {
|
|
64
|
+
resolveCode = resolve;
|
|
65
|
+
rejectCode = reject;
|
|
66
|
+
});
|
|
67
|
+
const server = (0, node_http_1.createServer)((request, response) => {
|
|
68
|
+
const url = new URL(request.url, exports.LOOPBACK_CALLBACK_URL);
|
|
69
|
+
if (url.pathname !== '/callback') {
|
|
70
|
+
response.writeHead(404).end();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (url.searchParams.get('state') !== expectedState) {
|
|
74
|
+
response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Unknown sign-in attempt.');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const error = url.searchParams.get('error_description') ?? url.searchParams.get('error');
|
|
78
|
+
const receivedCode = url.searchParams.get('code');
|
|
79
|
+
const signedIn = !error && Boolean(receivedCode);
|
|
80
|
+
const page = signedIn
|
|
81
|
+
? 'Sign-in received. Return to your terminal.'
|
|
82
|
+
: 'Sign-in failed. Return to your terminal.';
|
|
83
|
+
response
|
|
84
|
+
.writeHead(signedIn ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' })
|
|
85
|
+
.end(page, () => stopListening(request.socket, () => {
|
|
86
|
+
if (error) {
|
|
87
|
+
rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_REJECTED', 'Your identity provider did not complete the sign-in. Run the command again.', { oauthError: error }));
|
|
88
|
+
}
|
|
89
|
+
else if (!signedIn) {
|
|
90
|
+
rejectCode(new sign_in_error_1.SignInError('SSO_UNEXPECTED_CALLBACK', 'SSO sign-in returned an unexpected response. Run the command again.'));
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
resolveCode(receivedCode);
|
|
94
|
+
}
|
|
95
|
+
}));
|
|
96
|
+
});
|
|
97
|
+
const openSockets = new Set();
|
|
98
|
+
server.on('connection', (socket) => {
|
|
99
|
+
openSockets.add(socket);
|
|
100
|
+
socket.once('close', () => openSockets.delete(socket));
|
|
101
|
+
});
|
|
102
|
+
const timeout = setTimeout(() => stopListening(undefined, () => rejectCode(new sign_in_error_1.SignInError('SSO_SIGN_IN_TIMED_OUT', 'Timed out waiting for the browser sign-in.'))), BROWSER_SIGN_IN_TIMEOUT_MS);
|
|
103
|
+
function stopListening(respondingSocket, settle) {
|
|
104
|
+
clearTimeout(timeout);
|
|
105
|
+
server.close();
|
|
106
|
+
openSockets.forEach((socket) => socket !== respondingSocket && socket.destroy());
|
|
107
|
+
settle();
|
|
108
|
+
}
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
server.once('error', (error) => {
|
|
111
|
+
clearTimeout(timeout);
|
|
112
|
+
if (error.code !== 'EADDRINUSE') {
|
|
113
|
+
reject(error);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
reject(new sign_in_error_1.SignInError('SSO_LOOPBACK_PORT_IN_USE', 'The sign-in port is in use. Run contrail login --no-browser instead.', { port: exports.LOOPBACK_PORT }));
|
|
117
|
+
});
|
|
118
|
+
server.listen(exports.LOOPBACK_PORT, 'localhost', () => resolve({ code, stop: () => stopListening(undefined, () => undefined) }));
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
exports.listenForLoopbackCode = listenForLoopbackCode;
|
|
122
|
+
function canOpenBrowser(env = process.env, platform = process.platform) {
|
|
123
|
+
const isRemoteShell = Boolean(env.SSH_CONNECTION || env.SSH_TTY);
|
|
124
|
+
const hasLinuxDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
|
|
125
|
+
return !isRemoteShell && (platform !== 'linux' || hasLinuxDisplay);
|
|
126
|
+
}
|
|
127
|
+
exports.canOpenBrowser = canOpenBrowser;
|
|
128
|
+
function openBrowser(url) {
|
|
129
|
+
const [command, args] = buildOpenBrowserCommand(url, process.platform);
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const browserProcess = (0, node_child_process_1.spawn)(command, args, { stdio: 'ignore', detached: true });
|
|
132
|
+
browserProcess.once('spawn', () => {
|
|
133
|
+
browserProcess.unref();
|
|
134
|
+
resolve();
|
|
135
|
+
});
|
|
136
|
+
browserProcess.once('error', reject);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
exports.openBrowser = openBrowser;
|
|
140
|
+
function buildOpenBrowserCommand(url, platform) {
|
|
141
|
+
if (platform === 'darwin') {
|
|
142
|
+
return ['open', [url]];
|
|
143
|
+
}
|
|
144
|
+
if (platform === 'win32') {
|
|
145
|
+
return ['rundll32', ['url.dll,FileProtocolHandler', url]];
|
|
146
|
+
}
|
|
147
|
+
return ['xdg-open', [url]];
|
|
148
|
+
}
|
|
149
|
+
exports.buildOpenBrowserCommand = buildOpenBrowserCommand;
|
|
150
|
+
async function exchangeCodeForTokens(client, code, redirectUri, verifier) {
|
|
151
|
+
const tokens = await postToTokenEndpoint(client, {
|
|
152
|
+
grant_type: 'authorization_code',
|
|
153
|
+
client_id: client.clientId,
|
|
154
|
+
code,
|
|
155
|
+
redirect_uri: redirectUri,
|
|
156
|
+
code_verifier: verifier,
|
|
157
|
+
});
|
|
158
|
+
return { accessToken: tokens.access_token, refreshToken: tokens.refresh_token };
|
|
159
|
+
}
|
|
160
|
+
exports.exchangeCodeForTokens = exchangeCodeForTokens;
|
|
161
|
+
async function refreshSsoAccessToken(client, refreshToken) {
|
|
162
|
+
const tokens = await postToTokenEndpoint(client, {
|
|
163
|
+
grant_type: 'refresh_token',
|
|
164
|
+
client_id: client.clientId,
|
|
165
|
+
refresh_token: refreshToken,
|
|
166
|
+
});
|
|
167
|
+
return tokens.access_token;
|
|
168
|
+
}
|
|
169
|
+
exports.refreshSsoAccessToken = refreshSsoAccessToken;
|
|
170
|
+
async function postToTokenEndpoint(client, form) {
|
|
171
|
+
const response = await fetch(`${client.domain}/oauth2/token`, {
|
|
172
|
+
method: 'POST',
|
|
173
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
174
|
+
body: new URLSearchParams(form),
|
|
175
|
+
});
|
|
176
|
+
const body = await response.json();
|
|
177
|
+
if (!response.ok) {
|
|
178
|
+
throw new sign_in_error_1.SignInError('SSO_TOKEN_REQUEST_FAILED', 'Cognito rejected the token request.', {
|
|
179
|
+
status: response.status,
|
|
180
|
+
oauthError: body.error,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return body;
|
|
184
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const node_crypto_1 = require("node:crypto");
|
|
4
|
+
const node_net_1 = require("node:net");
|
|
5
|
+
const sso_1 = require("./sso");
|
|
6
|
+
const ssoClient = {
|
|
7
|
+
domain: 'https://dev-vibeiq.auth.us-east-1.amazoncognito.com',
|
|
8
|
+
clientId: 'cli-client',
|
|
9
|
+
};
|
|
10
|
+
describe('createSignInAttempt', () => {
|
|
11
|
+
it('should derive the challenge as the base64url SHA-256 of the verifier', () => {
|
|
12
|
+
const signInAttempt = (0, sso_1.createSignInAttempt)();
|
|
13
|
+
expect(signInAttempt.challenge).toBe((0, node_crypto_1.createHash)('sha256').update(signInAttempt.verifier).digest('base64url'));
|
|
14
|
+
});
|
|
15
|
+
it('should make a verifier of at least the 43 characters PKCE requires', () => {
|
|
16
|
+
expect((0, sso_1.createSignInAttempt)().verifier.length).toBeGreaterThanOrEqual(43);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
describe('buildAuthorizeUrl', () => {
|
|
20
|
+
it('should send the user straight to their identity provider with a PKCE challenge', () => {
|
|
21
|
+
const url = new URL((0, sso_1.buildAuthorizeUrl)(ssoClient, 'sso-vibeiq-com', sso_1.LOOPBACK_CALLBACK_URL, {
|
|
22
|
+
verifier: 'verifier',
|
|
23
|
+
challenge: 'challenge',
|
|
24
|
+
state: 'state',
|
|
25
|
+
}));
|
|
26
|
+
expect(url.origin + url.pathname).toBe(`${ssoClient.domain}/oauth2/authorize`);
|
|
27
|
+
expect(Object.fromEntries(url.searchParams)).toEqual({
|
|
28
|
+
response_type: 'code',
|
|
29
|
+
client_id: 'cli-client',
|
|
30
|
+
redirect_uri: 'http://localhost:7731/callback',
|
|
31
|
+
scope: 'openid email api.vibeiq.default/read api.vibeiq.default/write',
|
|
32
|
+
identity_provider: 'sso-vibeiq-com',
|
|
33
|
+
code_challenge: 'challenge',
|
|
34
|
+
code_challenge_method: 'S256',
|
|
35
|
+
state: 'state',
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
describe('parsePastedSignInCode', () => {
|
|
40
|
+
it('should return the code when the pasted state matches this attempt', () => {
|
|
41
|
+
expect((0, sso_1.parsePastedSignInCode)(' the-code#the-state \n', 'the-state')).toBe('the-code');
|
|
42
|
+
});
|
|
43
|
+
it('should reject a code from another attempt', () => {
|
|
44
|
+
expect(() => (0, sso_1.parsePastedSignInCode)('the-code#other-state', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
|
|
45
|
+
});
|
|
46
|
+
it('should reject a code pasted without its state', () => {
|
|
47
|
+
expect(() => (0, sso_1.parsePastedSignInCode)('the-code', 'the-state')).toThrow(expect.objectContaining({ code: 'SSO_SIGN_IN_CODE_MISMATCH' }));
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
describe('canOpenBrowser', () => {
|
|
51
|
+
it('should open a browser on a local Mac', () => {
|
|
52
|
+
expect((0, sso_1.canOpenBrowser)({}, 'darwin')).toBe(true);
|
|
53
|
+
});
|
|
54
|
+
it('should not open a browser over SSH', () => {
|
|
55
|
+
expect((0, sso_1.canOpenBrowser)({ SSH_CONNECTION: '10.0.0.1 22 10.0.0.2 22' }, 'darwin')).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
it('should not open a browser on Linux without a display', () => {
|
|
58
|
+
expect((0, sso_1.canOpenBrowser)({}, 'linux')).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
it('should open a browser on a Linux desktop', () => {
|
|
61
|
+
expect((0, sso_1.canOpenBrowser)({ WAYLAND_DISPLAY: 'wayland-0' }, 'linux')).toBe(true);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
describe('fetchSsoDomainCheck', () => {
|
|
65
|
+
const originalFetch = global.fetch;
|
|
66
|
+
afterEach(() => {
|
|
67
|
+
global.fetch = originalFetch;
|
|
68
|
+
});
|
|
69
|
+
function stubDomainCheckFetch(body, status = 200) {
|
|
70
|
+
global.fetch = jest.fn().mockResolvedValue(new Response(body, { status }));
|
|
71
|
+
}
|
|
72
|
+
it('should name the Cognito identity provider for an SSO domain', async () => {
|
|
73
|
+
stubDomainCheckFetch(JSON.stringify({ identityProvider: 'sso-vibeiq-com' }));
|
|
74
|
+
await expect((0, sso_1.fetchSsoDomainCheck)('Dev@VibeIQ.com', 'https://api')).resolves.toEqual({
|
|
75
|
+
kind: 'cognito',
|
|
76
|
+
identityProvider: 'sso-vibeiq-com',
|
|
77
|
+
});
|
|
78
|
+
expect(global.fetch).toHaveBeenCalledWith('https://api/sso-login/domain-check/vibeiq.com');
|
|
79
|
+
});
|
|
80
|
+
it('should report a legacy SSO domain', async () => {
|
|
81
|
+
stubDomainCheckFetch(JSON.stringify({ identityProvider: '', url: 'https://api/sso-login/login/acme.com' }));
|
|
82
|
+
await expect((0, sso_1.fetchSsoDomainCheck)('dev@acme.com', 'https://api')).resolves.toEqual({
|
|
83
|
+
kind: 'legacy',
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
it('should report no SSO for an empty response', async () => {
|
|
87
|
+
stubDomainCheckFetch('');
|
|
88
|
+
await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).resolves.toEqual({
|
|
89
|
+
kind: 'none',
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
it('should fail when the lookup fails', async () => {
|
|
93
|
+
stubDomainCheckFetch('{}', 502);
|
|
94
|
+
await expect((0, sso_1.fetchSsoDomainCheck)('dev@example.com', 'https://api')).rejects.toMatchObject({
|
|
95
|
+
code: 'SSO_DOMAIN_CHECK_FAILED',
|
|
96
|
+
details: { domain: 'example.com', status: 502 },
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
describe('listenForLoopbackCode', () => {
|
|
101
|
+
it('should resolve with the code the browser redirects back with', async () => {
|
|
102
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
103
|
+
const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
|
|
104
|
+
expect(response.status).toBe(200);
|
|
105
|
+
await expect(listener.code).resolves.toBe('the-code');
|
|
106
|
+
});
|
|
107
|
+
it('should keep waiting for this attempt after a redirect from another attempt', async () => {
|
|
108
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
109
|
+
const staleResponse = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=old-code&state=old-state`);
|
|
110
|
+
await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
|
|
111
|
+
expect(staleResponse.status).toBe(400);
|
|
112
|
+
await expect(listener.code).resolves.toBe('the-code');
|
|
113
|
+
});
|
|
114
|
+
it('should reject a redirect for this attempt that carries no code', async () => {
|
|
115
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
116
|
+
const rejection = expect(listener.code).rejects.toMatchObject({
|
|
117
|
+
code: 'SSO_UNEXPECTED_CALLBACK',
|
|
118
|
+
});
|
|
119
|
+
const response = await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?state=the-state`);
|
|
120
|
+
expect(response.status).toBe(400);
|
|
121
|
+
await rejection;
|
|
122
|
+
});
|
|
123
|
+
it('should reject when the identity provider reports an error', async () => {
|
|
124
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
125
|
+
const rejection = expect(listener.code).rejects.toMatchObject({
|
|
126
|
+
code: 'SSO_SIGN_IN_REJECTED',
|
|
127
|
+
details: { oauthError: 'User cancelled' },
|
|
128
|
+
});
|
|
129
|
+
await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?error=access_denied&error_description=User%20cancelled&state=the-state`);
|
|
130
|
+
await rejection;
|
|
131
|
+
});
|
|
132
|
+
it('should close idle browser connections once the code arrives', async () => {
|
|
133
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
134
|
+
const idleConnection = (0, node_net_1.connect)(sso_1.LOOPBACK_PORT, 'localhost');
|
|
135
|
+
await new Promise((resolve) => idleConnection.once('connect', resolve));
|
|
136
|
+
const idleConnectionClosed = new Promise((resolve) => idleConnection.once('close', resolve));
|
|
137
|
+
await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
|
|
138
|
+
await expect(listener.code).resolves.toBe('the-code');
|
|
139
|
+
await expect(idleConnectionClosed).resolves.toBe(false);
|
|
140
|
+
});
|
|
141
|
+
it('should tell the user to paste a code instead when the port is taken', async () => {
|
|
142
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
143
|
+
await expect((0, sso_1.listenForLoopbackCode)('another-state')).rejects.toMatchObject({
|
|
144
|
+
code: 'SSO_LOOPBACK_PORT_IN_USE',
|
|
145
|
+
details: { port: sso_1.LOOPBACK_PORT },
|
|
146
|
+
});
|
|
147
|
+
await fetch(`${sso_1.LOOPBACK_CALLBACK_URL}?code=the-code&state=the-state`);
|
|
148
|
+
await listener.code;
|
|
149
|
+
});
|
|
150
|
+
it('should free the port when stopped', async () => {
|
|
151
|
+
const listener = await (0, sso_1.listenForLoopbackCode)('the-state');
|
|
152
|
+
listener.stop();
|
|
153
|
+
const nextListener = await (0, sso_1.listenForLoopbackCode)('next-state');
|
|
154
|
+
nextListener.stop();
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
describe('buildOpenBrowserCommand', () => {
|
|
158
|
+
it('should use open on a Mac', () => {
|
|
159
|
+
expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'darwin')).toEqual([
|
|
160
|
+
'open',
|
|
161
|
+
['https://sign.in'],
|
|
162
|
+
]);
|
|
163
|
+
});
|
|
164
|
+
it('should pass the URL through rundll32 on Windows so the shell cannot split it', () => {
|
|
165
|
+
expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in?a=1&b=2', 'win32')).toEqual([
|
|
166
|
+
'rundll32',
|
|
167
|
+
['url.dll,FileProtocolHandler', 'https://sign.in?a=1&b=2'],
|
|
168
|
+
]);
|
|
169
|
+
});
|
|
170
|
+
it('should use xdg-open on Linux', () => {
|
|
171
|
+
expect((0, sso_1.buildOpenBrowserCommand)('https://sign.in', 'linux')).toEqual([
|
|
172
|
+
'xdg-open',
|
|
173
|
+
['https://sign.in'],
|
|
174
|
+
]);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
describe('exchangeCodeForTokens', () => {
|
|
178
|
+
const originalFetch = global.fetch;
|
|
179
|
+
afterEach(() => {
|
|
180
|
+
global.fetch = originalFetch;
|
|
181
|
+
});
|
|
182
|
+
it('should name the Cognito error when the exchange is refused', async () => {
|
|
183
|
+
global.fetch = jest
|
|
184
|
+
.fn()
|
|
185
|
+
.mockResolvedValue(new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }));
|
|
186
|
+
await expect((0, sso_1.exchangeCodeForTokens)(ssoClient, 'the-code', sso_1.LOOPBACK_CALLBACK_URL, 'verifier')).rejects.toMatchObject({
|
|
187
|
+
code: 'SSO_TOKEN_REQUEST_FAILED',
|
|
188
|
+
details: { status: 400, oauthError: 'invalid_grant' },
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
});
|
package/dist/basecommand.d.ts
CHANGED
|
@@ -11,5 +11,8 @@ export declare abstract class BaseCommand extends Command {
|
|
|
11
11
|
protected args: any;
|
|
12
12
|
init(): Promise<void>;
|
|
13
13
|
setLogLevel(logLevel: string, config?: any): void;
|
|
14
|
+
protected catch(error: Error & {
|
|
15
|
+
exitCode?: number;
|
|
16
|
+
}): Promise<unknown>;
|
|
14
17
|
private confirmEnv;
|
|
15
18
|
}
|
package/dist/basecommand.js
CHANGED
|
@@ -8,6 +8,7 @@ const logger_1 = tslib_1.__importDefault(require("./logger"));
|
|
|
8
8
|
const config_1 = require("./helpers/config/config");
|
|
9
9
|
const lodash_1 = require("lodash");
|
|
10
10
|
const login_1 = require("./auth/login");
|
|
11
|
+
const sign_in_error_1 = require("./auth/sign-in-error");
|
|
11
12
|
const baseFlags_1 = require("./baseFlags");
|
|
12
13
|
class BaseCommand extends core_1.Command {
|
|
13
14
|
static description = 'Global Flags';
|
|
@@ -48,11 +49,17 @@ class BaseCommand extends core_1.Command {
|
|
|
48
49
|
logger_1.default.level = config.logLevel;
|
|
49
50
|
}
|
|
50
51
|
}
|
|
52
|
+
async catch(error) {
|
|
53
|
+
if (error instanceof sign_in_error_1.SignInError) {
|
|
54
|
+
this.error((0, sign_in_error_1.formatErrorForTerminal)(error), { exit: 1 });
|
|
55
|
+
}
|
|
56
|
+
return super.catch(error);
|
|
57
|
+
}
|
|
51
58
|
async confirmEnv() {
|
|
52
59
|
let config = await (0, config_1.getConfig)();
|
|
53
60
|
if ((0, lodash_1.keys)(config).length === 0) {
|
|
54
61
|
await (0, login_1.authUser)().catch((e) => {
|
|
55
|
-
console.log(`Error: ${e
|
|
62
|
+
console.log(`Error: ${(0, sign_in_error_1.formatErrorForTerminal)(e)}\n\nCheck if you are using the correct environment configuration and credentials.`);
|
|
56
63
|
this.exit(1);
|
|
57
64
|
});
|
|
58
65
|
config = await (0, config_1.getConfig)();
|
|
@@ -11,7 +11,7 @@ const upgrade_1 = require("./upgrade");
|
|
|
11
11
|
const basecommand_1 = require("../../basecommand");
|
|
12
12
|
const logger_1 = tslib_1.__importDefault(require("../../logger"));
|
|
13
13
|
class PublishApp extends basecommand_1.BaseCommand {
|
|
14
|
-
static description = 'Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property)';
|
|
14
|
+
static description = 'Publish the app to the marketplace. This visibility of your app depends on the app.yml configuration ("visibility" property). A pre-release version (e.g. "1.4.0-alpha.1") is published without becoming the latest version of the app.';
|
|
15
15
|
static examples = [
|
|
16
16
|
`$ contrail app publish
|
|
17
17
|
`,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { BaseCommand } from '../../../basecommand';
|
|
2
|
+
export default class AppPrereleaseVersionUpgrade extends BaseCommand {
|
|
3
|
+
skipConfirmEnv: boolean;
|
|
4
|
+
static description: string;
|
|
5
|
+
static examples: string[];
|
|
6
|
+
static flags: {
|
|
7
|
+
alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
|
|
8
|
+
logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
|
|
9
|
+
};
|
|
10
|
+
run(): Promise<void>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
const load_app_config_1 = require("../../../helpers/app/load-app-config");
|
|
5
|
+
const basecommand_1 = require("../../../basecommand");
|
|
6
|
+
const logger_1 = tslib_1.__importDefault(require("../../../logger"));
|
|
7
|
+
const update_app_config_1 = require("../../../helpers/app/update-app-config");
|
|
8
|
+
const upgrade_version_1 = require("../../../helpers/app/upgrade-version");
|
|
9
|
+
class AppPrereleaseVersionUpgrade extends basecommand_1.BaseCommand {
|
|
10
|
+
skipConfirmEnv = true;
|
|
11
|
+
static description = 'Upgrade the Pre-release app version. A stable version becomes the first alpha of the next patch (1.2.3 to 1.2.4-alpha.0). A pre-release version gets its number bumped (1.2.4-alpha.0 to 1.2.4-alpha.1).';
|
|
12
|
+
static examples = [
|
|
13
|
+
`$ contrail app version prerelease
|
|
14
|
+
`,
|
|
15
|
+
];
|
|
16
|
+
static flags = {
|
|
17
|
+
...basecommand_1.BaseCommand.baseFlags,
|
|
18
|
+
};
|
|
19
|
+
async run() {
|
|
20
|
+
try {
|
|
21
|
+
const appDeclaration = (0, load_app_config_1.loadAppConfig)({ skipValidation: true });
|
|
22
|
+
logger_1.default.info(`Upgrading Pre-release Version for ${appDeclaration.version}`);
|
|
23
|
+
const version = (0, upgrade_version_1.upgradeVersion)(appDeclaration.version, 'prerelease');
|
|
24
|
+
(0, update_app_config_1.updateAppConfig)({ ...appDeclaration, version });
|
|
25
|
+
logger_1.default.info(`Pre-release Version Upgraded to ${version}`);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
logger_1.default.error(`Application Pre-release Version Upgrade Failed: ${e}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.default = AppPrereleaseVersionUpgrade;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { BaseCommand } from '../basecommand';
|
|
2
|
+
export default class Login extends BaseCommand {
|
|
3
|
+
static description: string;
|
|
4
|
+
skipConfirmEnv: boolean;
|
|
5
|
+
static examples: string[];
|
|
6
|
+
static flags: {
|
|
7
|
+
browser: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
|
|
8
|
+
alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
|
|
9
|
+
logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
|
|
10
|
+
};
|
|
11
|
+
run(): Promise<void>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
const core_1 = require("@oclif/core");
|
|
5
|
+
const basecommand_1 = require("../basecommand");
|
|
6
|
+
const login_1 = require("../auth/login");
|
|
7
|
+
const logger_1 = tslib_1.__importDefault(require("../logger"));
|
|
8
|
+
class Login extends basecommand_1.BaseCommand {
|
|
9
|
+
static description = 'Sign in to VibeIQ with SSO or your email and password';
|
|
10
|
+
skipConfirmEnv = true;
|
|
11
|
+
static examples = ['$ contrail login', '$ contrail login --no-browser'];
|
|
12
|
+
static flags = {
|
|
13
|
+
...basecommand_1.BaseCommand.baseFlags,
|
|
14
|
+
browser: core_1.Flags.boolean({
|
|
15
|
+
description: 'Open a browser for SSO. Use --no-browser to paste a sign-in code instead.',
|
|
16
|
+
default: true,
|
|
17
|
+
allowNo: true,
|
|
18
|
+
}),
|
|
19
|
+
};
|
|
20
|
+
async run() {
|
|
21
|
+
const context = await (0, login_1.signIn)({ shouldOpenBrowser: this.flags.browser });
|
|
22
|
+
logger_1.default.info(`Signed in to ${context.orgSlug}.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.default = Login;
|
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.validateAccessGrants = exports.visibilityValidator = exports.appVersionValidator = exports.validateAppConfig = exports.ERROR_MESSAGES = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
+
const semver_1 = tslib_1.__importDefault(require("semver"));
|
|
5
6
|
const interfaces_1 = require("../../interfaces");
|
|
6
7
|
const logger_1 = tslib_1.__importDefault(require("../../logger"));
|
|
7
8
|
const VALIDATORS = [appVersionValidator, visibilityValidator, validateAccessGrants];
|
|
8
9
|
exports.ERROR_MESSAGES = {
|
|
9
|
-
missingVersionField: 'Missing "version" field". Semantic App Version looks like "1.0.0". Use "contrail app version [patch|minor|major]" to update the app version.',
|
|
10
|
+
missingVersionField: 'Missing "version" field". Semantic App Version looks like "1.0.0". Use "contrail app version [patch|minor|major|prerelease]" to update the app version.',
|
|
10
11
|
invalidVersionField: '"version" field is not a string. Expecting a version like "1.0.0". Manually update the "version" field to be a string in the app.yml file.',
|
|
11
|
-
invalidAppVersion: 'Invalid app version. Semantic App Version looks like "1.0.0". Use "contrail app version [patch|minor|major]" to update the app version.',
|
|
12
|
+
invalidAppVersion: 'Invalid app version. Semantic App Version looks like "1.0.0", or "1.0.0-alpha.1" for a pre-release. Use "contrail app version [patch|minor|major|prerelease]" to update the app version.',
|
|
12
13
|
accessGrantsArray: 'accessGrants must be an array.',
|
|
13
14
|
invalidOrgSlug: 'Invalid or missing orgSlug in one of the accessGrants objects.',
|
|
14
15
|
emptyPermissionsArray: 'Permissions must be a non-empty array in one of the accessGrants objects.',
|
|
@@ -45,8 +46,7 @@ function appVersionValidator(appDeclaration) {
|
|
|
45
46
|
errors.push(exports.ERROR_MESSAGES.invalidVersionField);
|
|
46
47
|
return { errors, warnings };
|
|
47
48
|
}
|
|
48
|
-
|
|
49
|
-
if (parts.length !== 3) {
|
|
49
|
+
if (semver_1.default.valid(appDeclaration.version) !== appDeclaration.version.split('+')[0]) {
|
|
50
50
|
errors.push(exports.ERROR_MESSAGES.invalidAppVersion);
|
|
51
51
|
}
|
|
52
52
|
return { errors, warnings };
|
|
@@ -33,6 +33,42 @@ describe('appVersionValidator', () => {
|
|
|
33
33
|
const validationResult = (0, app_config_validators_1.appVersionValidator)(appDeclaration);
|
|
34
34
|
expect(validationResult).toEqual(validResult);
|
|
35
35
|
});
|
|
36
|
+
it('should not return an error if app version is a pre-release', () => {
|
|
37
|
+
const appDeclaration = {
|
|
38
|
+
version: '1.4.0-alpha.1',
|
|
39
|
+
};
|
|
40
|
+
const validationResult = (0, app_config_validators_1.appVersionValidator)(appDeclaration);
|
|
41
|
+
expect(validationResult).toEqual(validResult);
|
|
42
|
+
});
|
|
43
|
+
it('should not return an error if app version has build metadata', () => {
|
|
44
|
+
const appDeclaration = {
|
|
45
|
+
version: '1.4.0+build123',
|
|
46
|
+
};
|
|
47
|
+
const validationResult = (0, app_config_validators_1.appVersionValidator)(appDeclaration);
|
|
48
|
+
expect(validationResult).toEqual(validResult);
|
|
49
|
+
});
|
|
50
|
+
it('should return an error if app version has a leading v', () => {
|
|
51
|
+
const appDeclaration = {
|
|
52
|
+
version: 'v1.4.0',
|
|
53
|
+
};
|
|
54
|
+
const expectedError = {
|
|
55
|
+
errors: [app_config_validators_1.ERROR_MESSAGES.invalidAppVersion],
|
|
56
|
+
warnings: [],
|
|
57
|
+
};
|
|
58
|
+
const validationResult = (0, app_config_validators_1.appVersionValidator)(appDeclaration);
|
|
59
|
+
expect(validationResult).toEqual(expectedError);
|
|
60
|
+
});
|
|
61
|
+
it('should return an error if a version part is not a number', () => {
|
|
62
|
+
const appDeclaration = {
|
|
63
|
+
version: '1.0.x',
|
|
64
|
+
};
|
|
65
|
+
const expectedError = {
|
|
66
|
+
errors: [app_config_validators_1.ERROR_MESSAGES.invalidAppVersion],
|
|
67
|
+
warnings: [],
|
|
68
|
+
};
|
|
69
|
+
const validationResult = (0, app_config_validators_1.appVersionValidator)(appDeclaration);
|
|
70
|
+
expect(validationResult).toEqual(expectedError);
|
|
71
|
+
});
|
|
36
72
|
it('should gracefully handle bad versions', () => {
|
|
37
73
|
const appDeclaration = {
|
|
38
74
|
version: '1',
|
|
@@ -7,6 +7,7 @@ export declare class AppDeployer {
|
|
|
7
7
|
getExistingApp(appDeclaration: AppDeclaration): Promise<App>;
|
|
8
8
|
private createNewApp;
|
|
9
9
|
updateExistingApp(appDeclaration: AppDeclaration, existingApp: any): Promise<App>;
|
|
10
|
+
private publishPrereleaseVersion;
|
|
10
11
|
remove(appDeclaration: AppDeclaration): Promise<void>;
|
|
11
12
|
}
|
|
12
13
|
export declare function createNodePackage(appIdentifier: string, debug: boolean, dryRun: boolean): Promise<AppCodePackage>;
|
|
@@ -15,6 +15,7 @@ const child_process_1 = tslib_1.__importDefault(require("child_process"));
|
|
|
15
15
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
16
16
|
const extensions_deployer_1 = require("./extensions-deployer");
|
|
17
17
|
const metadata_extractor_1 = require("./metadata-extractor");
|
|
18
|
+
const semver_1 = tslib_1.__importDefault(require("semver"));
|
|
18
19
|
class AppDeployer {
|
|
19
20
|
debug;
|
|
20
21
|
dryRun;
|
|
@@ -29,6 +30,10 @@ class AppDeployer {
|
|
|
29
30
|
logger_1.default.info(`${chalk_1.default.yellow.bold('APP')} Creating new app.`);
|
|
30
31
|
app = await this.createNewApp(appDeclaration);
|
|
31
32
|
}
|
|
33
|
+
else if (semver_1.default.prerelease(appDeclaration.version)) {
|
|
34
|
+
logger_1.default.info(`${chalk_1.default.yellow.bold('APP')} Publishing pre-release version.`);
|
|
35
|
+
app = await this.publishPrereleaseVersion(appDeclaration, app);
|
|
36
|
+
}
|
|
32
37
|
else {
|
|
33
38
|
logger_1.default.info(`${chalk_1.default.yellow.bold('APP')} Updating existing app.`);
|
|
34
39
|
app = await this.updateExistingApp(appDeclaration, app);
|
|
@@ -146,6 +151,35 @@ class AppDeployer {
|
|
|
146
151
|
logger_1.default.info(`${chalk_1.default.yellow.bold('APP')} Updated app: ${app.name}`);
|
|
147
152
|
return app;
|
|
148
153
|
}
|
|
154
|
+
async publishPrereleaseVersion(appDeclaration, existingApp) {
|
|
155
|
+
const appCodePackage = await createNodePackage(appDeclaration.appIdentifier, this.debug, this.dryRun);
|
|
156
|
+
if (this.dryRun) {
|
|
157
|
+
logger_1.default.info('Dry run, not creating app version');
|
|
158
|
+
return {};
|
|
159
|
+
}
|
|
160
|
+
const appVersion = await new sdk_1.Entities().create({
|
|
161
|
+
entityName: 'app-version',
|
|
162
|
+
object: {
|
|
163
|
+
appId: existingApp.id,
|
|
164
|
+
semver: appDeclaration.version,
|
|
165
|
+
eventWorkflowTriggerKeyMapping: appDeclaration.eventWorkflowTriggerKeyMapping,
|
|
166
|
+
configProperties: appDeclaration.appConfiguration
|
|
167
|
+
? app_template_parsers_1.ConfigPropertiesParser.getConfigProperties(appDeclaration.appConfiguration)
|
|
168
|
+
: undefined,
|
|
169
|
+
triggerKeyDefinitions: appDeclaration.triggers
|
|
170
|
+
? app_template_parsers_1.TriggerKeyDefinitionParser.buildTriggersArray(appDeclaration)
|
|
171
|
+
: undefined,
|
|
172
|
+
externalLinks: appDeclaration.externalLinks
|
|
173
|
+
? app_template_parsers_1.ExternalLinkParser.validateAndGetExternalLinks(appDeclaration.externalLinks)
|
|
174
|
+
: [],
|
|
175
|
+
appCodePackageId: appCodePackage.id,
|
|
176
|
+
frameworkVersion: 2,
|
|
177
|
+
nodeRuntime: appDeclaration.nodeRuntime ?? existingApp.nodeRuntime,
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
logger_1.default.info(`${chalk_1.default.yellow.bold('APP')} Published pre-release version: ${appVersion.semver}`);
|
|
181
|
+
return { ...existingApp, latestAppVersionId: appVersion.id };
|
|
182
|
+
}
|
|
149
183
|
async remove(appDeclaration) {
|
|
150
184
|
let app = await this.getExistingApp(appDeclaration);
|
|
151
185
|
if (app) {
|
|
@@ -3,7 +3,9 @@ import semver from 'semver';
|
|
|
3
3
|
* Upgrades a semantic version based on a specified release type.
|
|
4
4
|
*
|
|
5
5
|
* @param {string} currentVersion - The current semantic version string.
|
|
6
|
-
* @param {semver.ReleaseType} type - The type of release ('major', 'minor', 'patch').
|
|
6
|
+
* @param {semver.ReleaseType} type - The type of release ('major', 'minor', 'patch', 'prerelease').
|
|
7
|
+
* 'prerelease' starts an alpha (1.2.3 becomes 1.2.4-alpha.0) or bumps the existing pre-release tag
|
|
8
|
+
* (1.2.4-alpha.0 becomes 1.2.4-alpha.1).
|
|
7
9
|
* @returns {string} The upgraded semantic version.
|
|
8
10
|
* @throws {Error} If the provided currentVersion is not a valid semantic version.
|
|
9
11
|
*
|