-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathensure-pipelines-host-detect.js
More file actions
352 lines (321 loc) · 13.2 KB
/
Copy pathensure-pipelines-host-detect.js
File metadata and controls
352 lines (321 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#!/usr/bin/env node
// Detection-only wrapper around the ensure-pipelines-host workflow.
// Runs Phases 1.0 (cache fast-path) + 2 (resolution order: org-setting → BAP env GET
// → tenant default custom → tenant-wide enumeration) + 5 (verify if host found).
// NEVER enters Phase 3 (decision tree) or Phase 4 (provisioning). Always exits with
// actionTaken: "none". Used by plan-alm Phase 1 step 12 and other orchestrators that
// want to inspect host state without inviting user prompts.
//
// Resolution order (mirrors ProjectHostProvider.tsx):
// 1. Check docs/alm/last-host-check.json cache → probe finalHostEnvUrl → reuse if reachable.
// 2. GetOrgDbOrgSetting('ProjectHostEnvironmentId') on source env.
// - If bound → BAP env GET to resolve URL/sku.
// - If sku === 'Platform' → check tenant default custom host (discover-pipelines-host).
// - default !== orgSettingHostEnvId → CannotRedirect.
// - else → AvailableUsing(PlatformHost|CustomHostByAdminDefault).
// - else → AvailableUsingCustomHost.
// 3. If unbound → tenant-wide list-tenant-envs with --firstHitWins.
// - 1 custom host found → AvailableUnboundCustomHost.
// - >1 → MultipleUnboundCustomHosts.
// - 0 + PE found → PlatformHostExistsUnbound.
// - none → NoHost.
// 4. Verify host (verify-host-readiness) if any final URL is set.
//
// Usage:
// node ensure-pipelines-host-detect.js
// --envUrl <url> --token <dvToken> --userId <guid>
// --bapToken <bapToken>
// [--projectRoot <path>] [--cacheMaxAgeHours 24] [--no-cache]
// [--includeName <substring>] [--maxEnvsToProbe N] [--skus Production,Sandbox]
// [--minPipelinesVersion 9.0.0.0]
//
// Output (JSON to stdout): matches docs/alm/last-host-check.json schemaVersion 2.
'use strict';
const fs = require('fs');
const path = require('path');
const helpers = require('./validation-helpers');
const { almPath } = require('./alm-paths');
const { checkEnvHostBinding } = require('./check-env-host-binding');
const { resolveEnvById } = require('./resolve-env-by-id');
const { discoverPipelinesHost } = require('./discover-pipelines-host');
const { listTenantEnvs } = require('./list-tenant-envs');
const { verifyHostReadiness } = require('./verify-host-readiness');
const DEFAULT_CACHE_MAX_AGE_HOURS = 24;
function parseArgs(argv) {
const args = argv.slice(2);
const opts = {
envUrl: null,
token: null,
userId: null,
bapToken: null,
projectRoot: process.cwd(),
cacheMaxAgeHours: DEFAULT_CACHE_MAX_AGE_HOURS,
noCache: false,
includeName: null,
maxEnvsToProbe: null,
skus: null,
minPipelinesVersion: null,
source: 'auto',
};
for (let i = 0; i < args.length; i++) {
const a = args[i];
const next = args[i + 1];
if (a === '--envUrl' && next) opts.envUrl = args[++i];
else if (a === '--token' && next) opts.token = args[++i];
else if (a === '--userId' && next) opts.userId = args[++i];
else if (a === '--bapToken' && next) opts.bapToken = args[++i];
else if (a === '--projectRoot' && next) opts.projectRoot = args[++i];
else if (a === '--cacheMaxAgeHours' && next) opts.cacheMaxAgeHours = Number(args[++i]) || DEFAULT_CACHE_MAX_AGE_HOURS;
else if (a === '--no-cache') opts.noCache = true;
else if (a === '--includeName' && next) opts.includeName = args[++i];
else if (a === '--maxEnvsToProbe' && next) opts.maxEnvsToProbe = Number(args[++i]);
else if (a === '--skus' && next) opts.skus = args[++i].split(',').map((s) => s.trim()).filter(Boolean);
else if (a === '--minPipelinesVersion' && next) opts.minPipelinesVersion = args[++i];
else if (a === '--source' && next) opts.source = args[++i];
}
return opts;
}
function originOf(url) {
try {
const trustedUrl = helpers.validateAuthenticatedRequestUrl(url);
const u = new URL(trustedUrl);
helpers.validateDataverseEnvironmentUrl(u.origin);
return `${u.protocol}//${u.host}`;
} catch {
return null;
}
}
function getDataverseToken(originUrl, getTokenImpl) {
const trustedOrigin = helpers.validateDataverseEnvironmentUrl(originUrl);
if (typeof getTokenImpl === 'function') return getTokenImpl(trustedOrigin);
const token = helpers.getAuthToken(trustedOrigin);
if (!token) throw new Error(`az token acquisition failed for ${trustedOrigin}`);
return token;
}
async function tryCacheFastPath({ projectRoot, cacheMaxAgeHours, getTokenImpl }) {
const cachePath = almPath(projectRoot, 'lastHostCheck');
if (!fs.existsSync(cachePath)) return null;
let cached;
try {
cached = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
} catch {
return null;
}
if (!cached.checkedAt || !cached.finalHostEnvUrl || cached.ready !== true) return null;
const ageMs = Date.now() - Date.parse(cached.checkedAt);
if (!isFinite(ageMs) || ageMs < 0) return null;
if (ageMs > cacheMaxAgeHours * 3600 * 1000) return null;
// Probe with a fresh token.
let token;
try {
token = getDataverseToken(originOf(cached.finalHostEnvUrl), getTokenImpl);
} catch {
return null;
}
const verify = await verifyHostReadiness({
hostEnvUrl: cached.finalHostEnvUrl,
hostToken: token,
skipWhoAmI: false,
});
if (!verify.ready) return null;
return {
...cached,
schemaVersion: 2,
cacheHit: true,
cacheAgeMs: ageMs,
pipelinesSolutionVersion: verify.pipelinesSolutionVersion || cached.pipelinesSolutionVersion,
warnings: verify.warnings || [],
};
}
async function detect(opts = {}) {
const {
envUrl,
token,
userId,
bapToken,
projectRoot = process.cwd(),
cacheMaxAgeHours = DEFAULT_CACHE_MAX_AGE_HOURS,
noCache = false,
includeName = null,
maxEnvsToProbe = null,
skus = null,
minPipelinesVersion = null,
source = 'auto',
// Test injection points:
getTokenImpl = null,
listImpl = null,
verifyImpl = null,
pacExecImpl = null,
} = opts;
if (!envUrl) throw new Error('--envUrl is required');
if (!token) throw new Error('--token (dev env Dataverse token) is required');
if (!userId) throw new Error('--userId is required');
// BAP token is only required for source=bap. In source=pac or source=auto-with-PAC-fallback,
// detection works without BAP — the shim uses PAC CLI for env list/get.
if (source === 'bap' && !bapToken) throw new Error('--bapToken is required when --source bap');
const trustedEnvUrl = helpers.validateDataverseEnvironmentUrl(envUrl);
const startedAt = Date.now();
const baseOut = {
schemaVersion: 2,
checkedAt: new Date().toISOString(),
sourceEnvUrl: trustedEnvUrl,
sourceEnvId: null,
actionTaken: 'none',
finalHostEnvUrl: null,
finalHostEnvId: null,
finalHostEnvName: null, // BAP env displayName — surfaces in plan-alm host card so reviewers see "Supplier Portal Host" instead of just the GUID-y instance URL
finalHostInstanceApiUrl: null,
isPlatformHost: false,
tenantDefaultCustomHostEnvId: null,
pipelinesSolutionVersion: null,
ready: false,
warnings: [],
candidates: {
existingCustomHosts: [],
existingPlatformHost: null,
eligibleForAppInstall: [],
inaccessibleEnvs: [],
},
telemetry: { correlationId: null },
detectionDurationMs: 0,
cacheHit: false,
};
// Phase 1.0 — cache fast-path
if (!noCache) {
const hit = await tryCacheFastPath({ projectRoot, cacheMaxAgeHours, getTokenImpl });
if (hit) {
hit.detectionDurationMs = Date.now() - startedAt;
hit.checkedAt = new Date().toISOString();
return hit;
}
}
// Phase 2.1 — org-setting probe
const binding = await checkEnvHostBinding({ envUrl: trustedEnvUrl, token });
if (binding.bound) {
baseOut.sourceEnvId = binding.hostEnvId; // hostEnvId here is the env GUID stored in the org setting
// Phase 2.2 — resolve via BAP (or PAC fallback)
const env = await resolveEnvById({ bapToken, envId: binding.hostEnvId, source, pacExecImpl });
if (!env.found) {
// 404-ambiguous: source env's binding points at an env we can't see.
baseOut.resolutionStatus = 'OrgSettingStale';
baseOut.warnings.push(`ProjectHostEnvironmentId points at env ${binding.hostEnvId} which is not visible — may be deleted, disabled, or the caller lacks access.`);
baseOut.detectionDurationMs = Date.now() - startedAt;
return baseOut;
}
baseOut.finalHostEnvId = env.envId;
helpers.validateDataverseEnvironmentUrl(env.instanceUrl, 'Resolved host environment URL');
helpers.validateDataverseEnvironmentUrl(env.instanceApiUrl, 'Resolved host API URL');
baseOut.finalHostEnvUrl = env.instanceUrl;
baseOut.finalHostEnvName = env.displayName || null;
baseOut.finalHostInstanceApiUrl = env.instanceApiUrl;
baseOut.isPlatformHost = env.environmentSku === 'Platform';
// Phase 2.3 — if PE, check tenant default custom host (CannotRedirect detection)
if (baseOut.isPlatformHost) {
const def = await discoverPipelinesHost({ envUrl: trustedEnvUrl, token, userId });
if (def.found && def.hostEnvUrl) {
baseOut.tenantDefaultCustomHostEnvId = def.hostEnvUrl;
// The org setting and tenant default are both env GUIDs. Compare them.
const orgSettingValue = binding.hostEnvId.toLowerCase();
const tenantDefaultValue = String(def.hostEnvUrl).toLowerCase();
if (orgSettingValue !== tenantDefaultValue) {
baseOut.resolutionStatus = 'CannotRedirect';
baseOut.warnings.push(
`CannotRedirect: source env's ProjectHostEnvironmentId (${binding.hostEnvId}) points at PE, but tenant DefaultCustomPipelinesHostEnvForTenant (${def.hostEnvUrl}) points elsewhere. Resolution requires Power Platform admin.`,
);
baseOut.detectionDurationMs = Date.now() - startedAt;
return baseOut;
}
baseOut.resolutionStatus = 'AvailableUsingCustomHostByAdminDefault';
} else {
baseOut.resolutionStatus = 'AvailableUsingPlatformHost';
}
} else {
baseOut.resolutionStatus = 'AvailableUsingCustomHost';
}
} else {
// Phase 2.5 — no org binding. Tenant-wide enumeration.
const list = await listTenantEnvs({
bapToken,
// Default to Production+Sandbox so trial-license tenants (Sandbox-only)
// still see eligible existing envs in the env-first menu. See
// list-tenant-envs.js DEFAULT_SKUS for rationale.
skus: skus || ['Production', 'Sandbox'],
maxEnvsToProbe: maxEnvsToProbe || undefined,
firstHitWins: true,
includeName,
source,
listImpl,
getTokenImpl,
verifyImpl,
pacExecImpl,
});
baseOut.candidates = {
existingCustomHosts: list.existingCustomHosts,
existingPlatformHost: list.existingPlatformHost,
eligibleForAppInstall: list.eligibleForAppInstall,
inaccessibleEnvs: list.inaccessibleEnvs,
};
if (list.existingCustomHosts.length === 1) {
const h = list.existingCustomHosts[0];
baseOut.resolutionStatus = 'AvailableUnboundCustomHost';
baseOut.finalHostEnvId = h.envId;
baseOut.finalHostEnvUrl = h.instanceUrl;
baseOut.finalHostEnvName = h.displayName || null;
baseOut.finalHostInstanceApiUrl = h.instanceApiUrl;
baseOut.isPlatformHost = false;
baseOut.pipelinesSolutionVersion = h.pipelinesSolutionVersion || null;
} else if (list.existingCustomHosts.length > 1) {
baseOut.resolutionStatus = 'MultipleUnboundCustomHosts';
// No finalHostEnvUrl — orchestrator decides which to pick at execution time.
} else if (list.existingPlatformHost) {
const h = list.existingPlatformHost;
baseOut.resolutionStatus = 'PlatformHostExistsUnbound';
baseOut.finalHostEnvId = h.envId;
baseOut.finalHostEnvUrl = h.instanceUrl;
baseOut.finalHostEnvName = h.displayName || null;
baseOut.finalHostInstanceApiUrl = h.instanceApiUrl;
baseOut.isPlatformHost = true;
baseOut.pipelinesSolutionVersion = h.pipelinesSolutionVersion || null;
} else {
baseOut.resolutionStatus = 'NoHost';
}
}
// Phase 5 — verify host (only if finalHostEnvUrl was set)
if (baseOut.finalHostEnvUrl) {
let hostToken;
try {
hostToken = getDataverseToken(originOf(baseOut.finalHostEnvUrl), getTokenImpl);
} catch (e) {
baseOut.warnings.push(`Token acquisition failed for host: ${e.message}`);
baseOut.detectionDurationMs = Date.now() - startedAt;
return baseOut;
}
const verify = await verifyHostReadiness({
hostEnvUrl: baseOut.finalHostEnvUrl,
hostToken,
skipWhoAmI: false,
minPipelinesVersion,
});
baseOut.ready = verify.ready;
baseOut.pipelinesSolutionVersion = verify.pipelinesSolutionVersion || baseOut.pipelinesSolutionVersion;
baseOut.warnings = baseOut.warnings.concat(verify.warnings || []);
if (!verify.ready) {
baseOut.warnings.push('Verification failed — host did not pass deploymentpipelines / solutions check.');
}
}
baseOut.detectionDurationMs = Date.now() - startedAt;
return baseOut;
}
if (require.main === module) {
const opts = parseArgs(process.argv);
detect(opts)
.then((result) => {
console.log(JSON.stringify(result));
process.exit(0);
})
.catch((err) => {
process.stderr.write(`${err.message}\n`);
process.exit(1);
});
}
module.exports = { detect, tryCacheFastPath };