@sitecore-content-sdk/cli 0.2.0-beta.10 → 0.2.0-beta.12
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/dist/cjs/scripts/auth/index.js +26 -0
- package/dist/cjs/scripts/auth/list.js +36 -0
- package/dist/cjs/scripts/auth/login.js +112 -0
- package/dist/cjs/scripts/auth/logout.js +28 -0
- package/dist/cjs/scripts/auth/models.js +2 -0
- package/dist/cjs/scripts/auth/status.js +34 -0
- package/dist/cjs/scripts/index.js +3 -1
- package/dist/cjs/utils/auth/flow.js +72 -0
- package/dist/cjs/utils/auth/renewal.js +95 -0
- package/dist/cjs/utils/auth/tenant-state.js +91 -0
- package/dist/cjs/utils/auth/tenant-store.js +212 -0
- package/dist/esm/scripts/auth/index.js +23 -0
- package/dist/esm/scripts/auth/list.js +33 -0
- package/dist/esm/scripts/auth/login.js +109 -0
- package/dist/esm/scripts/auth/logout.js +25 -0
- package/dist/esm/scripts/auth/models.js +1 -0
- package/dist/esm/scripts/auth/status.js +31 -0
- package/dist/esm/scripts/index.js +2 -0
- package/dist/esm/utils/auth/flow.js +68 -0
- package/dist/esm/utils/auth/renewal.js +90 -0
- package/dist/esm/utils/auth/tenant-state.js +53 -0
- package/dist/esm/utils/auth/tenant-store.js +170 -0
- package/package.json +3 -3
- package/types/scripts/auth/index.d.ts +7 -0
- package/types/scripts/auth/list.d.ts +2 -0
- package/types/scripts/auth/login.d.ts +3 -0
- package/types/scripts/auth/logout.d.ts +2 -0
- package/types/scripts/auth/models.d.ts +94 -0
- package/types/scripts/auth/status.d.ts +2 -0
- package/types/scripts/index.d.ts +2 -0
- package/types/utils/auth/flow.d.ts +24 -0
- package/types/utils/auth/renewal.d.ts +22 -0
- package/types/utils/auth/tenant-state.d.ts +14 -0
- package/types/utils/auth/tenant-store.d.ts +40 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
36
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
37
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
38
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
39
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
40
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
41
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
45
|
+
exports.writeTenantAuthInfo = writeTenantAuthInfo;
|
|
46
|
+
exports.readTenantAuthInfo = readTenantAuthInfo;
|
|
47
|
+
exports.writeTenantInfo = writeTenantInfo;
|
|
48
|
+
exports.readTenantInfo = readTenantInfo;
|
|
49
|
+
exports.deleteTenantAuthInfo = deleteTenantAuthInfo;
|
|
50
|
+
exports.getAllTenantsInfo = getAllTenantsInfo;
|
|
51
|
+
exports.decodeJwtPayload = decodeJwtPayload;
|
|
52
|
+
const fs = __importStar(require("fs"));
|
|
53
|
+
const path = __importStar(require("path"));
|
|
54
|
+
const os = __importStar(require("os"));
|
|
55
|
+
const CLAIMS = 'https://auth.sitecorecloud.io/claims';
|
|
56
|
+
const rootDir = path.join(os.homedir(), '.sitecore', 'sitecore-tools');
|
|
57
|
+
/**
|
|
58
|
+
* Get the full path to the tenant-specific folder.
|
|
59
|
+
* @param {string} tenantId - The tenant ID.
|
|
60
|
+
* @returns The absolute path to the tenant directory.
|
|
61
|
+
*/
|
|
62
|
+
function getTenantPath(tenantId) {
|
|
63
|
+
return path.join(rootDir, tenantId);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Write the authentication configuration for a tenant.
|
|
67
|
+
* @param {string} tenantId - The tenant ID.
|
|
68
|
+
* @param {TenantAuth} authInfo - The tenant's auth data.
|
|
69
|
+
*/
|
|
70
|
+
function writeTenantAuthInfo(tenantId, authInfo) {
|
|
71
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
try {
|
|
73
|
+
const dir = getTenantPath(tenantId);
|
|
74
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
75
|
+
fs.writeFileSync(path.join(dir, 'auth.json'), JSON.stringify(authInfo, null, 2));
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
console.error(`\n Failed to write auth.json for tenant '${tenantId}': ${error.message}`);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Read the authentication configuration for a tenant.
|
|
84
|
+
* @param {string} tenantId - The tenant ID.
|
|
85
|
+
* @returns Parsed auth config or null if not found or failed to read.
|
|
86
|
+
*/
|
|
87
|
+
function readTenantAuthInfo(tenantId) {
|
|
88
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
89
|
+
const filePath = path.join(getTenantPath(tenantId), 'auth.json');
|
|
90
|
+
if (!fs.existsSync(filePath))
|
|
91
|
+
return null;
|
|
92
|
+
try {
|
|
93
|
+
const raw = fs.readFileSync(filePath, 'utf-8');
|
|
94
|
+
return JSON.parse(raw);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
console.error(`\n Failed to read auth.json for tenant '${tenantId}': ${error.message}`);
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Write the public metadata information for a tenant.
|
|
104
|
+
* @param {TenantInfo} info - The tenant info object.
|
|
105
|
+
*/
|
|
106
|
+
function writeTenantInfo(info) {
|
|
107
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
108
|
+
try {
|
|
109
|
+
const dir = getTenantPath(info.tenantId);
|
|
110
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
111
|
+
fs.writeFileSync(path.join(dir, 'info.json'), JSON.stringify(info, null, 2));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
console.error(`\n Failed to write info.json for tenant '${info.tenantId}': ${error.message}`);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Read the public metadata information for a tenant.
|
|
120
|
+
* @param {string} tenantId - The tenant ID.
|
|
121
|
+
* @returns Parsed tenant info or null if not found or failed to read.
|
|
122
|
+
*/
|
|
123
|
+
function readTenantInfo(tenantId) {
|
|
124
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
125
|
+
const infoFilePath = path.join(getTenantPath(tenantId), 'info.json');
|
|
126
|
+
if (!fs.existsSync(infoFilePath)) {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const content = fs.readFileSync(infoFilePath, 'utf-8');
|
|
131
|
+
return JSON.parse(content);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
console.error(`\n Failed to read info.json for tenant '${tenantId}': ${error.message}`);
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Deletes the stored auth.json file for the given tenant.
|
|
141
|
+
* @param {string} tenantId - The tenant ID.
|
|
142
|
+
*/
|
|
143
|
+
function deleteTenantAuthInfo(tenantId) {
|
|
144
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
145
|
+
const filePath = path.join(getTenantPath(tenantId), 'auth.json');
|
|
146
|
+
try {
|
|
147
|
+
if (fs.existsSync(filePath)) {
|
|
148
|
+
fs.unlinkSync(filePath);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
console.error(`\n Failed to delete auth.json for tenant '${tenantId}': ${error.message}`);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Scans the CLI root directory and returns all valid tenant infos.
|
|
158
|
+
* @returns A list of TenantInfo objects found in {tenant-id}/info.json files.
|
|
159
|
+
*/
|
|
160
|
+
function getAllTenantsInfo() {
|
|
161
|
+
if (!fs.existsSync(rootDir))
|
|
162
|
+
return [];
|
|
163
|
+
const subDirs = fs
|
|
164
|
+
.readdirSync(rootDir)
|
|
165
|
+
.filter((entry) => fs.statSync(path.join(rootDir, entry)).isDirectory());
|
|
166
|
+
const tenants = [];
|
|
167
|
+
for (const dir of subDirs) {
|
|
168
|
+
const infoPath = path.join(rootDir, dir, 'info.json');
|
|
169
|
+
if (fs.existsSync(infoPath)) {
|
|
170
|
+
try {
|
|
171
|
+
const content = fs.readFileSync(infoPath, 'utf-8');
|
|
172
|
+
const data = JSON.parse(content);
|
|
173
|
+
if (data.tenantId && data.tenantName && data.organizationId && data.clientId) {
|
|
174
|
+
tenants.push({
|
|
175
|
+
tenantId: data.tenantId,
|
|
176
|
+
tenantName: data.tenantName,
|
|
177
|
+
organizationId: data.organizationId,
|
|
178
|
+
clientId: data.clientId,
|
|
179
|
+
authority: data.authority,
|
|
180
|
+
audience: data.audience,
|
|
181
|
+
baseUrl: data.baseUrl,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
console.error('\n Failed to read tenant info file', error.message);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return tenants;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Decodes a JWT without verifying its signature.
|
|
194
|
+
* @param {string} token - The access token string.
|
|
195
|
+
* @returns Decoded payload object or null if invalid.
|
|
196
|
+
*/
|
|
197
|
+
function decodeJwtPayload(token) {
|
|
198
|
+
try {
|
|
199
|
+
const base64Payload = token.split('.')[1];
|
|
200
|
+
const payload = Buffer.from(base64Payload, 'base64').toString('utf-8');
|
|
201
|
+
const decoded = JSON.parse(payload);
|
|
202
|
+
return {
|
|
203
|
+
tokenTenantId: decoded === null || decoded === void 0 ? void 0 : decoded[`${CLAIMS}/tenant_id`],
|
|
204
|
+
tokenOrgId: decoded === null || decoded === void 0 ? void 0 : decoded[`${CLAIMS}/org_id`],
|
|
205
|
+
tokenTenantName: decoded === null || decoded === void 0 ? void 0 : decoded[`${CLAIMS}/tenant_name`],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
console.error('\n Failed to decode access token:', error.message);
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { login } from './login';
|
|
2
|
+
import { logout } from './logout';
|
|
3
|
+
import { status } from './status';
|
|
4
|
+
import { list } from './list';
|
|
5
|
+
/**
|
|
6
|
+
* Registers the `auth` command group and its subcommands (`login`, `logout`, `status`, `list`) with Yargs.
|
|
7
|
+
* @param {Argv} yargs - The Yargs instance used to define CLI commands.
|
|
8
|
+
* @returns The configured Yargs command group for authentication operations.
|
|
9
|
+
*/
|
|
10
|
+
export function builder(yargs) {
|
|
11
|
+
return yargs.command({
|
|
12
|
+
command: 'auth',
|
|
13
|
+
describe: 'Performs authentication for content services',
|
|
14
|
+
builder: (_yargs) => {
|
|
15
|
+
return _yargs
|
|
16
|
+
.command([login, logout, status, list])
|
|
17
|
+
.strict()
|
|
18
|
+
.demandCommand(1, 'You need to specify a command to run')
|
|
19
|
+
.help();
|
|
20
|
+
},
|
|
21
|
+
handler: () => { },
|
|
22
|
+
});
|
|
23
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { getAllTenantsInfo } from '../../utils/auth/tenant-store';
|
|
11
|
+
export const list = {
|
|
12
|
+
command: 'list',
|
|
13
|
+
describe: 'List all known tenants',
|
|
14
|
+
handler: () => __awaiter(void 0, void 0, void 0, function* () {
|
|
15
|
+
const tenants = getAllTenantsInfo();
|
|
16
|
+
if (tenants.length === 0) {
|
|
17
|
+
console.log('\n No tenant information found.');
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
console.log('\n Known tenants:\n');
|
|
21
|
+
tenants.forEach((tenant, index) => {
|
|
22
|
+
console.log(`Tenant ${index + 1}:`);
|
|
23
|
+
console.log(` Tenant ID : ${tenant.tenantId}`);
|
|
24
|
+
console.log(` Tenant Name : ${tenant.tenantName || 'N/A'}`);
|
|
25
|
+
console.log(` Organization ID : ${tenant.organizationId}`);
|
|
26
|
+
console.log(` Client ID : ${tenant.clientId}`);
|
|
27
|
+
console.log(` Authority : ${tenant.authority || 'N/A'}`);
|
|
28
|
+
console.log(` Audience : ${tenant.audience || 'N/A'}`);
|
|
29
|
+
console.log(` Base URL : ${tenant.baseUrl || 'N/A'}`);
|
|
30
|
+
console.log();
|
|
31
|
+
});
|
|
32
|
+
}),
|
|
33
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { clientCredentialsFlow, AUTH0_DOMAIN, AUDIENCE, BASE_URL } from '../../utils/auth/flow';
|
|
11
|
+
import { writeTenantAuthInfo, writeTenantInfo } from '../../utils/auth/tenant-store';
|
|
12
|
+
import { setActiveTenant } from '../../utils/auth/tenant-state';
|
|
13
|
+
export const login = {
|
|
14
|
+
command: 'login',
|
|
15
|
+
describe: 'Login into a tenant',
|
|
16
|
+
builder: (yargs) => yargs
|
|
17
|
+
.option('clientId', {
|
|
18
|
+
type: 'string',
|
|
19
|
+
requiresArg: true,
|
|
20
|
+
demandOption: true,
|
|
21
|
+
describe: 'Client ID for authentication',
|
|
22
|
+
})
|
|
23
|
+
.option('clientSecret', {
|
|
24
|
+
type: 'string',
|
|
25
|
+
demandOption: false,
|
|
26
|
+
describe: 'Client secret for authentication',
|
|
27
|
+
})
|
|
28
|
+
.option('tenantId', {
|
|
29
|
+
type: 'string',
|
|
30
|
+
demandOption: false,
|
|
31
|
+
describe: 'Tenant ID to login into.',
|
|
32
|
+
})
|
|
33
|
+
.option('organizationId', {
|
|
34
|
+
type: 'string',
|
|
35
|
+
demandOption: false,
|
|
36
|
+
describe: 'Organization ID to authenticate against.',
|
|
37
|
+
})
|
|
38
|
+
.option('authority', {
|
|
39
|
+
type: 'string',
|
|
40
|
+
demandOption: false,
|
|
41
|
+
describe: 'OAuth 2.0 authority URL for authentication.',
|
|
42
|
+
})
|
|
43
|
+
.option('audience', {
|
|
44
|
+
type: 'string',
|
|
45
|
+
demandOption: false,
|
|
46
|
+
describe: 'Intended recipient of the token, usually the API base URL.',
|
|
47
|
+
})
|
|
48
|
+
.option('baseUrl', {
|
|
49
|
+
type: 'string',
|
|
50
|
+
demandOption: false,
|
|
51
|
+
describe: 'Base URL for the API, used to construct the audience.',
|
|
52
|
+
})
|
|
53
|
+
.group([
|
|
54
|
+
'clientId',
|
|
55
|
+
'clientSecret',
|
|
56
|
+
'tenantId',
|
|
57
|
+
'organizationId',
|
|
58
|
+
'authority',
|
|
59
|
+
'audience',
|
|
60
|
+
'baseUrl',
|
|
61
|
+
], 'Login Options:'),
|
|
62
|
+
handler: (argv) => __awaiter(void 0, void 0, void 0, function* () {
|
|
63
|
+
const { clientId } = argv;
|
|
64
|
+
let authResult, tenantId, organizationId, tenantName;
|
|
65
|
+
if (argv.clientSecret) {
|
|
66
|
+
try {
|
|
67
|
+
const authData = yield clientCredentialsFlow({
|
|
68
|
+
clientId,
|
|
69
|
+
clientSecret: argv.clientSecret,
|
|
70
|
+
organizationId: argv.organizationId,
|
|
71
|
+
tenantId: argv.tenantId,
|
|
72
|
+
audience: argv.audience,
|
|
73
|
+
authority: argv.authority,
|
|
74
|
+
baseUrl: argv.baseUrl,
|
|
75
|
+
});
|
|
76
|
+
authResult = authData.data;
|
|
77
|
+
tenantId = authData.tokenTenantId;
|
|
78
|
+
organizationId = authData.tokenOrgId;
|
|
79
|
+
tenantName = authData.tokenTenantName;
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
console.error(`\n Login failed: ${err.message}`);
|
|
83
|
+
process.exit(1);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
// TODO: Implement Device Authorization Flow when clientSecret is not provided.
|
|
88
|
+
console.log('\n Please provide client secret for authentication.');
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
yield writeTenantAuthInfo(tenantId, {
|
|
92
|
+
clientSecret: argv.clientSecret,
|
|
93
|
+
access_token: authResult.access_token,
|
|
94
|
+
expires_in: authResult.expires_in,
|
|
95
|
+
expires_at: new Date(Date.now() + authResult.expires_in * 1000).toISOString(),
|
|
96
|
+
});
|
|
97
|
+
yield writeTenantInfo({
|
|
98
|
+
tenantId,
|
|
99
|
+
organizationId,
|
|
100
|
+
clientId,
|
|
101
|
+
tenantName,
|
|
102
|
+
authority: argv.authority || AUTH0_DOMAIN,
|
|
103
|
+
audience: argv.audience || AUDIENCE,
|
|
104
|
+
baseUrl: argv.baseUrl || BASE_URL,
|
|
105
|
+
});
|
|
106
|
+
setActiveTenant(tenantId);
|
|
107
|
+
console.info(`\n Logged in successfully to tenant ${tenantId}.`);
|
|
108
|
+
}),
|
|
109
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { getActiveTenant, clearActiveTenant } from '../../utils/auth/tenant-state';
|
|
11
|
+
import { deleteTenantAuthInfo } from '../../utils/auth/tenant-store';
|
|
12
|
+
export const logout = {
|
|
13
|
+
command: 'logout',
|
|
14
|
+
describe: 'Logout from the active tenant',
|
|
15
|
+
handler: () => __awaiter(void 0, void 0, void 0, function* () {
|
|
16
|
+
const tenantId = getActiveTenant();
|
|
17
|
+
if (!tenantId) {
|
|
18
|
+
console.error('\n No active tenant found. Please login first.');
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
clearActiveTenant();
|
|
22
|
+
deleteTenantAuthInfo(tenantId);
|
|
23
|
+
console.info(`\n Logged out from tenant ${tenantId}`);
|
|
24
|
+
}),
|
|
25
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { readTenantInfo } from '../../utils/auth/tenant-store';
|
|
11
|
+
import { renewAuthIfExpired } from '../../utils/auth/renewal';
|
|
12
|
+
export const status = {
|
|
13
|
+
command: 'status',
|
|
14
|
+
describe: 'Show current status of active tenant',
|
|
15
|
+
handler: () => __awaiter(void 0, void 0, void 0, function* () {
|
|
16
|
+
const context = yield renewAuthIfExpired();
|
|
17
|
+
if (!context) {
|
|
18
|
+
console.log('\n No valid authentication found. Please login.');
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const tenantInfo = yield readTenantInfo(context.tenantId);
|
|
22
|
+
console.log('\n Active tenant:');
|
|
23
|
+
console.log(` Tenant ID : ${context.tenantId}`);
|
|
24
|
+
console.log(` Tenant Name : ${(tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.tenantName) || 'N/A'}`);
|
|
25
|
+
console.log(` Organization ID : ${tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.organizationId}`);
|
|
26
|
+
console.log(` Client ID : ${tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.clientId}`);
|
|
27
|
+
console.log(` Authority : ${(tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.authority) || 'N/A'}`);
|
|
28
|
+
console.log(` Audience : ${(tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.audience) || 'N/A'}`);
|
|
29
|
+
console.log(` Base URL : ${(tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.baseUrl) || 'N/A'}`);
|
|
30
|
+
}),
|
|
31
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { decodeJwtPayload } from './tenant-store';
|
|
11
|
+
export const AUTH0_DOMAIN = 'https://auth.sitecorecloud.io';
|
|
12
|
+
export const AUDIENCE = 'https://api.sitecorecloud.io';
|
|
13
|
+
export const BASE_URL = 'https://edge-platform.sitecorecloud.io/cs/api';
|
|
14
|
+
const GRANT_TYPE = 'client_credentials';
|
|
15
|
+
/**
|
|
16
|
+
* Performs the OAuth 2.0 client credentials flow to obtain a JWT access token
|
|
17
|
+
* from the Sitecore Identity Provider using the provided client credentials.
|
|
18
|
+
* @param {object} [args] - The arguments for client credentials flow
|
|
19
|
+
* @param {string} [args.clientId] - The client ID registered with Sitecore Identity
|
|
20
|
+
* @param {string} [args.clientSecret] - The client secret associated with the client ID
|
|
21
|
+
* @param {string} [args.organizationId] - The ID of the organization the client belongs to
|
|
22
|
+
* @param {string} [args.tenantId] - The tenant ID representing the specific Sitecore environment
|
|
23
|
+
* @param {string} [args.audience] - The API audience the token is intended for. Defaults to `AUDIENCE`
|
|
24
|
+
* @param {string} [args.authority] - The auth server base URL. Defaults to `AUTH0_DOMAIN`
|
|
25
|
+
* @param {string} [args.baseUrl] - The base URL for the API, used to construct the audience
|
|
26
|
+
* @returns A Promise that resolves to the access token response (including access token, token type, expiry, etc.)
|
|
27
|
+
* @throws Will log and exit the process if the request fails or returns a non-OK status
|
|
28
|
+
*/
|
|
29
|
+
export function clientCredentialsFlow(_a) {
|
|
30
|
+
return __awaiter(this, arguments, void 0, function* ({ clientId, clientSecret, organizationId, tenantId, audience = AUDIENCE, authority = AUTH0_DOMAIN, baseUrl = BASE_URL, }) {
|
|
31
|
+
const params = new URLSearchParams({
|
|
32
|
+
client_id: clientId,
|
|
33
|
+
client_secret: clientSecret !== null && clientSecret !== void 0 ? clientSecret : '',
|
|
34
|
+
organization_id: organizationId !== null && organizationId !== void 0 ? organizationId : '',
|
|
35
|
+
tenant_id: tenantId !== null && tenantId !== void 0 ? tenantId : '',
|
|
36
|
+
audience,
|
|
37
|
+
grant_type: GRANT_TYPE,
|
|
38
|
+
baseUrl: baseUrl !== null && baseUrl !== void 0 ? baseUrl : '',
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
const response = yield fetch(`${authority}/oauth/token`, {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
44
|
+
body: params.toString(),
|
|
45
|
+
});
|
|
46
|
+
const data = yield response.json();
|
|
47
|
+
if (!response.ok) {
|
|
48
|
+
throw new Error(data.error_description || data.error || 'Error during client credentials flow');
|
|
49
|
+
}
|
|
50
|
+
const decodedPayload = decodeJwtPayload(data.access_token) || {};
|
|
51
|
+
if (!(decodedPayload === null || decodedPayload === void 0 ? void 0 : decodedPayload.tokenTenantId) || !decodedPayload.tokenOrgId) {
|
|
52
|
+
throw new Error('\n Token is missing required claims tenant_id or org_id.');
|
|
53
|
+
}
|
|
54
|
+
const { tokenTenantId, tokenOrgId, tokenTenantName } = decodedPayload;
|
|
55
|
+
if (tenantId && tenantId !== tokenTenantId) {
|
|
56
|
+
throw new Error('\n Mismatch: Provided tenant ID does not match claims tenant ID.');
|
|
57
|
+
}
|
|
58
|
+
if (organizationId && organizationId !== tokenOrgId) {
|
|
59
|
+
throw new Error('\n Mismatch: Provided organization ID does not match claims organization ID.');
|
|
60
|
+
}
|
|
61
|
+
return { data, tokenOrgId, tokenTenantId, tokenTenantName };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
console.error('\n Error during client credentials flow:', error instanceof Error ? error.message : error);
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { getActiveTenant, clearActiveTenant } from './tenant-state';
|
|
11
|
+
import { clientCredentialsFlow } from './flow';
|
|
12
|
+
import { writeTenantAuthInfo, readTenantAuthInfo, deleteTenantAuthInfo, readTenantInfo, } from './tenant-store';
|
|
13
|
+
/**
|
|
14
|
+
* Validates whether a given auth config is still valid (i.e., not expired).
|
|
15
|
+
* @param {TenantAuth} authInfo - The tenant auth configuration.
|
|
16
|
+
* @returns True if the token is still valid, false if expired.
|
|
17
|
+
*/
|
|
18
|
+
export function validateAuthInfo(authInfo) {
|
|
19
|
+
const now = new Date();
|
|
20
|
+
const expiry = new Date(authInfo.expires_at);
|
|
21
|
+
return now < expiry;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Renews the token for a given tenant using stored credentials.
|
|
25
|
+
* @param {TenantAuth} authInfo - Current authentication info for the tenant.
|
|
26
|
+
* @param {TenantInfo} tenantInfo - Public metadata about the tenant (e.g., clientId).
|
|
27
|
+
* @returns Promise<void>
|
|
28
|
+
* @throws If credentials are missing or renewal fails.
|
|
29
|
+
*/
|
|
30
|
+
export function renewClientToken(authInfo, tenantInfo) {
|
|
31
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
32
|
+
const result = yield clientCredentialsFlow({
|
|
33
|
+
clientId: tenantInfo.clientId,
|
|
34
|
+
clientSecret: authInfo.clientSecret,
|
|
35
|
+
organizationId: tenantInfo.organizationId,
|
|
36
|
+
tenantId: tenantInfo.tenantId,
|
|
37
|
+
audience: tenantInfo.audience,
|
|
38
|
+
authority: tenantInfo.authority,
|
|
39
|
+
baseUrl: tenantInfo.baseUrl,
|
|
40
|
+
});
|
|
41
|
+
const tenantId = tenantInfo.tenantId;
|
|
42
|
+
yield writeTenantAuthInfo(tenantId, {
|
|
43
|
+
clientSecret: authInfo.clientSecret,
|
|
44
|
+
access_token: result.data.access_token,
|
|
45
|
+
expires_in: result.data.expires_in,
|
|
46
|
+
expires_at: new Date(Date.now() + result.data.expires_in * 1000).toISOString(),
|
|
47
|
+
});
|
|
48
|
+
console.info(`\n Token for tenant ${tenantId} renewed.`);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Ensures a valid token exists, renews it if expired.
|
|
53
|
+
* Returns tenant context if successful, otherwise null.
|
|
54
|
+
*/
|
|
55
|
+
export function renewAuthIfExpired() {
|
|
56
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
57
|
+
const tenantId = getActiveTenant();
|
|
58
|
+
if (!tenantId)
|
|
59
|
+
return null;
|
|
60
|
+
const authInfo = yield readTenantAuthInfo(tenantId);
|
|
61
|
+
if (!authInfo)
|
|
62
|
+
return null;
|
|
63
|
+
const isValid = validateAuthInfo(authInfo);
|
|
64
|
+
if (isValid) {
|
|
65
|
+
return { tenantId };
|
|
66
|
+
}
|
|
67
|
+
const tenantInfo = yield readTenantInfo(tenantId);
|
|
68
|
+
if (!tenantInfo)
|
|
69
|
+
return null;
|
|
70
|
+
console.info(`\n Token for tenant ${tenantId} is expired. Renewing...`);
|
|
71
|
+
try {
|
|
72
|
+
if (authInfo.clientSecret) {
|
|
73
|
+
yield renewClientToken(authInfo, tenantInfo);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
// <TODO>: Implement Device auth token renewal.
|
|
77
|
+
throw new Error('\n Please use clientSecret for authentication.');
|
|
78
|
+
}
|
|
79
|
+
return { tenantId };
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
console.error(`\n Failed to renew token for tenant '${tenantId}'`);
|
|
83
|
+
console.warn(`\n Cleaning up stale authentication data for tenant '${tenantId}'...`);
|
|
84
|
+
yield deleteTenantAuthInfo(tenantId);
|
|
85
|
+
clearActiveTenant();
|
|
86
|
+
console.info('\n You will need to login again to re-authenticate.');
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as os from 'os';
|
|
4
|
+
const configDir = path.join(os.homedir(), '.sitecore', 'sitecore-tools');
|
|
5
|
+
const settingsFile = path.join(configDir, 'settings.json');
|
|
6
|
+
/**
|
|
7
|
+
* Gets the ID of the currently active tenant from settings.json.
|
|
8
|
+
* @returns The active tenant ID if present, otherwise null.
|
|
9
|
+
*/
|
|
10
|
+
export function getActiveTenant() {
|
|
11
|
+
var _a;
|
|
12
|
+
if (!fs.existsSync(settingsFile)) {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
const content = fs.readFileSync(settingsFile, 'utf-8');
|
|
17
|
+
const data = JSON.parse(content);
|
|
18
|
+
return (_a = data.activeTenant) !== null && _a !== void 0 ? _a : null;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
console.error(`\n Failed to read active tenant: ${error.message}`);
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Sets the currently active tenant by writing to settings.json.
|
|
27
|
+
* @param {string} tenantId - The tenant ID to set as active.
|
|
28
|
+
*/
|
|
29
|
+
export function setActiveTenant(tenantId) {
|
|
30
|
+
try {
|
|
31
|
+
if (!fs.existsSync(configDir)) {
|
|
32
|
+
fs.mkdirSync(configDir, { recursive: true });
|
|
33
|
+
}
|
|
34
|
+
const data = { activeTenant: tenantId };
|
|
35
|
+
fs.writeFileSync(settingsFile, JSON.stringify(data, null, 2));
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
console.error(`\n Failed to set active tenant '${tenantId}': ${error.message}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Clears the currently active tenant from settings.json by deleting the file.
|
|
43
|
+
*/
|
|
44
|
+
export function clearActiveTenant() {
|
|
45
|
+
try {
|
|
46
|
+
if (fs.existsSync(settingsFile)) {
|
|
47
|
+
fs.unlinkSync(settingsFile);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
console.error(`\n Failed to clear active tenant: ${error.message}`);
|
|
52
|
+
}
|
|
53
|
+
}
|