Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

model-apps 2.20.5, pcf 1.0.1: skill_completed telemetry for app builds, page uploads and control pushes (#784)

Akshay Malooad5576ff64c6
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index 1f87ecac4..35e44e507 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -40,6 +40,7 @@ on:
- "plugins/pcf/scripts/lib/nearest-name.js"
- "plugins/pcf/scripts/lib/utf8-stream.js"
- "plugins/pcf/scripts/lib/cli-failure.js"
+ - "plugins/pcf/scripts/lib/telemetry/skill-completed.js"
- "plugins/pcf/scripts/lib/telemetry/ikey.json"
- "plugins/pcf/scripts/lib/dataverse-auth.js"
- "plugins/pcf/scripts/check-auth.js"
diff --git a/.github/workflows/pcf-script-tests.yml b/.github/workflows/pcf-script-tests.yml
index acdb4062f..182fc586c 100644
--- a/.github/workflows/pcf-script-tests.yml
+++ b/.github/workflows/pcf-script-tests.yml
@@ -23,6 +23,7 @@ on:
- "plugins/model-apps/scripts/lib/nearest-name.js"
- "plugins/model-apps/scripts/lib/utf8-stream.js"
- "plugins/model-apps/scripts/lib/cli-failure.js"
+ - "plugins/model-apps/scripts/lib/telemetry/skill-completed.js"
- "plugins/model-apps/scripts/lib/telemetry/ikey.json"
- "plugins/model-apps/scripts/lib/dataverse-auth.js"
- "plugins/model-apps/scripts/check-auth.js"
diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 383bc2e14..30f36f4b3 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.20.4",
+ "version": "2.20.5",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 383bc2e14..30f36f4b3 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.20.4",
+ "version": "2.20.5",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 1da1e4ce0..ae8849004 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -2910,7 +2910,7 @@ scripts/
detect-browser.js ← System Chromium/Edge/Chrome detection (used by the launcher)
modelapps-hook-utils.js ← Tracked-skill discovery + validator lookup for the hooks
utf8-stream.js ← reads a hook's stdin as UTF-8 without splitting a multibyte character across pipe chunks
- telemetry/ ← Bundled 1DS telemetry: ikey.json (this plugin's per-region keys) + resolver.js + region/ (copy of power-pages' router) + lib/ (copy of shared/telemetry/lib)
+ telemetry/ ← Bundled 1DS telemetry: ikey.json (this plugin's per-region keys) + resolver.js + region/ (copy of power-pages' router) + lib/ (copy of shared/telemetry/lib) + skill-completed.js (skill_completed for the build and page upload; pcf copies it)
vendor/cds-maker-sdk.cjs ← headless vendored SDK bundle (rebuilt via _vendor-build/)
vendor/typescript/ ← the TypeScript 5.8.3 compiler the SDK compiles generative pages with (brotli; PROVENANCE.json; licenses)
_vendor-build/ ← esbuild vendoring tooling (build.js + build-typescript.js + pinned deps)
@@ -4031,7 +4031,18 @@ repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a **physical copy*
deliberately has no top-level static key, so a `null` resolution really does mean no
transmission.
- **Emission:** `hooks/run-skill-pretool-telemetry.js` (PreToolUse Skill) and
- `hooks/run-user-prompt-telemetry.js` (UserPromptSubmit `/model-apps:<skill>`).
+ `hooks/run-user-prompt-telemetry.js` (UserPromptSubmit `/model-apps:<skill>`) send `skill_started`.
+ `skill_completed` comes from the scripts that change an environment, when they finish:
+ `build-model-app.js` on an `--apply` (`app-builder`; per-phase `{ ok, skip, error }` step counts fed by
+ `createStepTally` from the engine's progress events, outcome mapped by `completionFor`) and
+ `genpage-upload.js` once an upload was attempted (`genpage`; `uploadCompletion`). Both go through
+ `scripts/lib/telemetry/skill-completed.js`, which owns the approved `eventInfo` allowlist
+ (`shared/telemetry/README.md`, "Model Apps and PCF"), routes by the TARGET environment's host and reads
+ its `orgId` with one `WhoAmI` and its `tenantId` from the Azure CLI token's `tid` — never from PAC's
+ profile, never for an opted-out user. pcf carries a verbatim copy (`scripts/validate-plugin-copies.js`).
+ It sends nothing from inside a `node:test` run unless the test sets
+ `POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT=1`, so the suites that drive these scripts with stand-ins never
+ emit; a new emitting script must go through this module rather than call the dispatcher itself.
- **Privacy:** telemetry is default-on: events can include Dataverse organization and Entra tenant GUIDs
when PAC is signed in, never the signed-in user's Entra object ID, and the local diagnostic mirror
(`~/.power-platform-skills/telemetry/model-apps/sessions/<id>/events.jsonl`) retains the same
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 85388411d..55757add7 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -253,6 +253,11 @@ DoD, China); an unrecognized cloud sends nothing. Then:
- **What's collected:** skill name, plugin/PAC/agent versions, OS/Node versions,
session/correlation IDs, and Dataverse organization and Entra tenant GUIDs when
PAC is signed in. Model Apps excludes the signed-in user's Entra object ID.
+ When an app build (`--apply`) or a page upload finishes, a `skill_completed`
+ event also records its outcome, duration, a fixed error class, and how many
+ steps of each build phase were created, already present or failed (or, for a
+ page, whether it was created, updated or unchanged) — with the organization
+ and tenant GUIDs of the environment it targeted, read with one `WhoAmI`.
Events do not include file paths, prompts, tool inputs, entity/table names, URLs,
credentials, usernames, or hostnames.
- **Local diagnostic mirror:** every event is also written to
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index b6365298d..a25db2a51 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -52,6 +52,7 @@ const { makeTempWorkspace } = require('./lib/temp-workspace.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
// The lease one apply of an app holds for the whole of its work in the workspace (lib/app-operation-lease.js).
const { withAppBuildLease, applyWorkspaceOf } = require('./lib/app-operation-lease.js');
+const { emitSkillCompleted, createStepTally } = require('./lib/telemetry/skill-completed.js');
// The folder an app's workspace lives in, checked before anything is built on it. An APPLY makes the folder if it is
// missing and re-checks it (mkdir on an existing junction succeeds, so the re-check is what refuses one). A DRY RUN
@@ -438,7 +439,11 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {
const journal = deps.journal;
// Tee the engine's progress events into the durable journal without touching the pure engine.
const baseEmit = deps.emit || cliEmit(log, { apply: opts.apply, counts });
- const emit = journal ? (e) => { baseEmit(e); journal.record(e); } : baseEmit;
+ // skill_completed telemetry counts an apply's steps per phase from the same events (lib/telemetry/skill-completed.js).
+ const stepTally = opts.apply ? deps.stepTally : null;
+ const emit = journal || stepTally
+ ? (e) => { baseEmit(e); if (journal) journal.record(e); if (stepTally) stepTally.record(e); }
+ : baseEmit;
const sleep = deps.sleep || ((ms) => new Promise((res) => setTimeout(res, ms)));
// One budget for all the waiting a run does when a service throttles — the HTTP client's waits before it sends a throttled read, publish, delete or column create again, the page backend's waits between the sends of a page write (a `$batch` the
// client never re-sends) and this loop's own waits before it runs a phase again — so the run can neither wait twenty silent minutes for one page nor forget, where one layer hands over to the other, what the service asked (lib/throttle-budget.js).
@@ -676,6 +681,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {
const declinedCount = () => (typeof throttle.declined === 'function' ? throttle.declined().count : 0);
for (let attempt = 1; ; attempt++) {
counts.ok = counts.skip = counts.error = 0; // summary reflects the final (successful) attempt
+ if (stepTally) stepTally.reset();
const declinedBefore = declinedCount();
try {
r = await runBuild(spec, {
@@ -1048,6 +1054,7 @@ function persistAppliedBaseline(r, { spec, opts, workspaceDir, appDirAbs, baseli
}
async function main() {
+ const startedAt = Date.now();
const argv = process.argv.slice(2);
const { positional, flags } = parseArgs(argv);
const USAGE =
@@ -1161,17 +1168,72 @@ async function main() {
// printed: emitResult ends the process, and a `finally` around it would never run. So the command's body ANSWERS its result, and it is printed
// here, after the release; an error it throws goes on to main().catch the same way. A dry run reads only, and takes no lease.
const command = { env, spec, languageCode, changedOnly, workspaceDir };
+ // skill_completed telemetry, for an APPLY only: a dry run changes nothing in the environment. Set before the run so a halt thrown out of
+ // it (main().catch) is reported too; reportCompletion awaits at most a short WhoAmI and never throws.
+ if (opts.apply) {
+ completionRun = {
+ startedAt, env, changedOnly, opts,
+ staged: !!(flags.stage || flags.only || flags.skip || flags.from || flags.to),
+ tally: createStepTally(),
+ };
+ }
const outcome = opts.apply
? await withAppBuildLease({ workspaceDir, appUniqueName: appUniqueName(spec), warn: (m) => process.stderr.write(`⚠ ${m}\n`) },
- (buildLease) => runBuildCommand({ ...command, opts: { ...opts, buildLease } }))
+ (buildLease) => runBuildCommand({ ...command, opts: { ...opts, buildLease }, stepTally: completionRun.tally }))
: await runBuildCommand({ ...command, opts });
+ await reportCompletion(completionRun, { ok: outcome.ok, payload: outcome.payload });
emitResult(outcome.ok, outcome.payload);
}
+// The apply this process is running, for skill_completed telemetry; null for a dry run or before an apply starts.
+let completionRun = null;
+
+// What an apply's result says, in the closed vocabulary of lib/telemetry/skill-completed.js — never its messages.
+// ok → success
+// thrown build-locked/pages-locked → locked (another build holds the app; nothing was sent)
+// thrown BuildHalt with a phase → halted, haltPhase
+// { ok: false, error } → auth (the identity preflight refused; runBuildCommand)
+// { ok: true, verify.ok: false } → verify-failed (applied, but the auto-verify found it incomplete)
+// { ok: false, errors } after a step failed → deploy-failed; before any step → halted at preflight (spec checks, approvals)
+function completionFor(run, { ok, payload, error }) {
+ const steps = run.tally.snapshot();
+ const stepErrors = Object.values(steps).some((row) => row.error > 0);
+ const eventInfo = {
+ operation: 'app-build',
+ scope: run.changedOnly ? 'changed-only' : run.staged ? 'staged' : 'full',
+ publish: !!run.opts.publish,
+ steps,
+ };
+ const verify = payload && payload.verify;
+ if (verify) eventInfo.verify = verify.ok ? 'passed' : 'failed';
+ else if (payload && !error) eventInfo.verify = 'not-run';
+ if (ok) return { outcome: 'success', eventInfo };
+ if (error) {
+ const code = error && error.code;
+ if (code === 'build-locked' || code === 'pages-locked' || code === 'build-lease-invalid') return { outcome: 'failure', errorClass: 'locked', eventInfo };
+ const phase = error && typeof error.phase === 'string' ? error.phase : undefined;
+ return phase
+ ? { outcome: 'failure', errorClass: 'halted', eventInfo: { ...eventInfo, haltPhase: phase } }
+ : { outcome: 'failure', errorClass: 'unexpected', eventInfo };
+ }
+ if (payload && payload.ok && verify && !verify.ok) return { outcome: 'failure', errorClass: 'verify-failed', eventInfo };
+ if (payload && typeof payload.error === 'string' && !Array.isArray(payload.errors)) return { outcome: 'failure', errorClass: 'auth', eventInfo: { ...eventInfo, haltPhase: 'preflight' } };
+ if (stepErrors) return { outcome: 'failure', errorClass: 'deploy-failed', eventInfo };
+ return { outcome: 'failure', errorClass: 'halted', eventInfo: { ...eventInfo, haltPhase: 'preflight' } };
+}
+
+async function reportCompletion(run, result, emit = emitSkillCompleted) {
+ if (!run) return;
+ try {
+ const { outcome, errorClass, eventInfo } = completionFor(run, result);
+ await emit({ skillName: 'app-builder', outcome, errorClass, eventInfo, envUrl: run.env, durationMs: Date.now() - run.startedAt });
+ } catch { /* telemetry never changes the build's result */ }
+}
+
// Everything main() does once the command line has been checked: auth, the authoring language, the SDK, the journal, the build and the baseline.
// Answers { ok, payload } for main() to print: a refusal of the identity as the `{ ok: false, error }` it has always printed, and otherwise the
// build's result, `ok` only when the build and its verify succeeded.
-async function runBuildCommand({ env, spec, languageCode, changedOnly, workspaceDir, opts }) {
+async function runBuildCommand({ env, spec, languageCode, changedOnly, workspaceDir, opts, stepTally }) {
// #455: the App, Form and Dashboard adapters bake the authoring LCID in at CONSTRUCTION, so it
// has to be resolved before the SDK exists — which is why this reads over the transport hatch
// rather than through `provision.queryRecords`. Resolving here also means the provisioned-language
@@ -1270,7 +1332,7 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
const deps = {
log: (m) => process.stderr.write(m + '\n'),
warn: (m) => process.stderr.write(`⚠ ${m}\n`),
- sdk, provisionSdk, journal, throttle,
+ sdk, provisionSdk, journal, throttle, stepTally,
// The role-privileges check must actually RUN here. verify-spec skips it unless BOTH
// `rolePrivileges` and `entityPrivileges` readers are present, and `entityPrivileges` used to
// need the raw client plus the org URL — omitting them degraded silently, so `--apply --verify`
@@ -1340,6 +1402,9 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
}
if (require.main === module) {
- main().catch((err) => emitResult(false, err));
+ main().catch(async (err) => {
+ await reportCompletion(completionRun, { ok: false, error: err });
+ emitResult(false, err);
+ });
}
-module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated, persistAppliedBaseline };
+module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated, persistAppliedBaseline, completionFor, reportCompletion };
diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.js
index 557adb6f1..7d7a20398 100644
--- a/plugins/model-apps/scripts/genpage-upload.js
+++ b/plugins/model-apps/scripts/genpage-upload.js
@@ -65,6 +65,7 @@ const { commandArgOrPlaceholder } = require('./lib/cli-failure.js');
const genpageBase = require('./lib/genpage-base.js');
const { writeFileSafe } = require('./lib/safe-fs.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
+const { emitSkillCompleted } = require('./lib/telemetry/skill-completed.js');
const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file',
'data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message', 'agent-message-file',
@@ -256,6 +257,7 @@ function completionMarker(flags, base) {
}
async function main(argv = process.argv.slice(2), deps = {}) {
+ const startedAt = Date.now();
const emit = deps.emit || emitResult;
const readFile = deps.readFile || fs.readFileSync;
const makeBackend = deps.makeGenpageSdk || makeGenpageSdk;
@@ -415,20 +417,51 @@ async function main(argv = process.argv.slice(2), deps = {}) {
// the page's source in the temp directory says so.
let outcome;
let leftOnDisk = null;
+ // skill_completed telemetry covers an upload that was ATTEMPTED — from here on — not a refusal of the command line or its files above.
+ const report = deps.reportCompletion || emitSkillCompleted;
try {
outcome = await deploy({
flags, genpage, base, completing, checkedText, styleProblems, griffelWords, stylesRefusal,
prompt, agentMessage, pageName, bindings, clearDataSources, overwriteDeployed, addToSitemap,
});
+ } catch (e) {
+ await reportUpload(report, flags, startedAt, { error: e });
+ throw e;
} finally {
try { leftOnDisk = leftOnDiskWarning(await genpage.dispose()); } catch { /* the backend's own folder; nothing to say when it cannot even answer */ }
// A deploy that threw has no result to carry it: that failure reaches the caller as it is, so the warning goes to stderr beside it.
if (leftOnDisk && !outcome) process.stderr.write(`WARNING: ${leftOnDisk}\n`);
}
if (leftOnDisk) outcome.payload = { ...outcome.payload, warnings: [...(outcome.payload.warnings || []), leftOnDisk] };
+ await reportUpload(report, flags, startedAt, outcome);
return emit(outcome.ok, outcome.payload);
}
+// What an upload's result says, in the closed vocabulary of lib/telemetry/skill-completed.js — never a message, a name or an id.
+// ok → success; page created | updated | unchanged, placedInApp, addedToSolution
+// code griffel-shorthand → invalid-input (the page was refused before anything was written)
+// any other failed result → deploy-failed; a throw → unexpected
+function uploadCompletion({ ok, payload, error } = {}) {
+ const eventInfo = { operation: 'page-upload' };
+ if (error) return { outcome: 'failure', errorClass: 'unexpected', eventInfo };
+ const p = payload || {};
+ if (ok) {
+ eventInfo.page = p.unchanged ? 'unchanged' : p.updated ? 'updated' : 'created';
+ eventInfo.placedInApp = p.addedToSitemap === true;
+ if (typeof p.addedToSolution === 'boolean') eventInfo.addedToSolution = p.addedToSolution;
+ return { outcome: 'success', eventInfo };
+ }
+ if (typeof p.addedToSolution === 'boolean') eventInfo.addedToSolution = p.addedToSolution;
+ return { outcome: 'failure', errorClass: p.code === 'griffel-shorthand' ? 'invalid-input' : 'deploy-failed', eventInfo };
+}
+
+async function reportUpload(report, flags, startedAt, result) {
+ try {
+ const { outcome, errorClass, eventInfo } = uploadCompletion(result);
+ await report({ skillName: 'genpage', outcome, errorClass, eventInfo, envUrl: flags.env, durationMs: Date.now() - startedAt });
+ } catch { /* telemetry never changes the upload's result */ }
+}
+
// Everything after the flags and the files have been read and checked: an update's guards, the write, the base marker and the placement in an
// app. It RETURNS what to report — { ok, payload } — instead of reporting it, so that main can remove the backend's workspace first.
async function deploy(context) {
@@ -760,4 +793,4 @@ if (require.main === module) {
process.exit(1);
});
}
-module.exports = { main, resolveText, notPlainFile };
+module.exports = { main, resolveText, notPlainFile, uploadCompletion };
diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.js
index 35eddcdb3..a370809cb 100644
--- a/plugins/model-apps/scripts/lib/dataverse-auth.js
+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js
@@ -122,6 +122,14 @@ function getAuthToken(envUrl, opts = {}) {
return readAzToken(resource, opts);
}
+// The token this process has ALREADY read for the environment (the memo getAuthToken fills), or null. It never starts the Azure CLI:
+// for work that must not cost the user a CLI start of seconds — usage telemetry after a script's real work is done
+// (lib/telemetry/skill-completed.js) — and for which "no token yet" simply means "do without".
+function peekAuthToken(envUrl) {
+ const resource = dataverseOrigin(envUrl);
+ return resource && authTokenMemo.has(resource) ? authTokenMemo.get(resource) : null;
+}
+
// The Azure CLI read behind every token this plugin uses — a Dataverse environment's (getAuthToken, above) and the Power Apps
// service's (getPowerAppsToken, below) — so both share one memo, one failure record and one budget. `resource` is the `--resource` of
// `az account get-access-token`; the callers decide which resources are allowed (a Dataverse origin is checked by dataverseOrigin, the
@@ -957,6 +965,7 @@ module.exports = {
preflightAuth,
azIdentity,
getAuthToken,
+ peekAuthToken,
getAuthTokenAsync,
getPowerAppsToken,
getPowerAppsTokenAsync,
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/plugins/model-apps/scripts/lib/telemetry/skill-completed.js b/plugins/model-apps/scripts/lib/telemetry/skill-completed.js
new file mode 100644
index 000000000..fafd02735
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/skill-completed.js
@@ -0,0 +1,325 @@
+"use strict";
+
+// `skill_completed` usage telemetry for the scripts that change a Power Platform environment: the
+// model-apps app build (build-model-app.js), the generative-page upload (genpage-upload.js) and the pcf
+// control push (pcf-push.js). The skill_started hooks only say a skill BEGAN; this event says what the
+// run did to the environment — its outcome, how long it took, and how many artifacts of each kind it
+// created, reused or failed on — so usage can be tied to the apps, pages and controls it produced.
+//
+// plugins/pcf/scripts/lib/telemetry/skill-completed.js is a VERBATIM copy of this file
+// (scripts/validate-plugin-copies.js fails on drift): edit this one, then copy it over. That is why it
+// reads its plugin's name and version from the manifest beside it instead of naming a plugin.
+//
+// Privacy contract (shared/telemetry/README.md, "Model Apps and PCF"): every nested `eventInfo` value is
+// a fixed enum, a boolean or a bounded count — sanitizeEventInfo() drops anything else, so no table,
+// app, page, control, solution or environment NAME, no URL and no error text can reach the wire. The
+// only identifiers are the Dataverse organization GUID and the Entra tenant GUID of the environment the
+// run targeted, as skill_started already carries; never the signed-in user's object ID.
+//
+// Fail closed throughout: telemetry must never change a script's result or exit code, so every path
+// here swallows its own errors and the caller's `await` resolves either way.
+
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const events = require("./lib/events");
+const emitSpawn = require("./lib/emit-spawn");
+const agentInfo = require("./lib/agent-info");
+const resolverLoader = require("./lib/resolver-loader");
+const { isTransmissionOptedOut } = require("./lib/user-config");
+
+const TELEMETRY_DIR = __dirname;
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..", "..");
+const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";
+const DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".power-platform-skills");
+// The WhoAmI that names the target organization runs while the user waits for the script's result, so it
+// gets a short budget; a slow or failing read only drops the IDs from the event.
+const IDENTITY_TIMEOUT_MS = 3000;
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+// Not a PAC cloud token, so resolver.js routes it nowhere; see the emit below.
+const UNROUTABLE_CLOUD = "Unrecognized";
+
+// ---- The approved eventInfo schema --------------------------------------------------------------------
+// Keep in step with shared/telemetry/README.md. Adding a key or a value needs the privacy review that
+// file describes, plus its disclosure and the tests in scripts/tests/skill-completed.test.js.
+const OPERATIONS = new Set(["app-build", "page-upload", "control-push"]);
+// The app build's engine phases (scripts/lib/stages.js PHASES, pinned by a test) and the two the build
+// reports outside them: `preflight` (checks before any write) and `push` (the pcf deploy).
+const PHASES = new Set([
+ "preflight", "solution", "data-model", "sample-data", "web-resources", "views", "charts", "forms",
+ "business-rules", "business-process-flows", "commands", "dashboards", "app-shell", "pages",
+ "ai-features", "security", "publish", "push",
+]);
+const SCOPES = new Set(["full", "staged", "changed-only"]);
+const VERIFY_RESULTS = new Set(["passed", "failed", "not-run"]);
+const PAGE_ACTIONS = new Set(["created", "updated", "unchanged"]);
+const REGISTRATION = new Set(["verified", "not-verified", "skipped"]);
+const STEP_STATUSES = ["ok", "skip", "error"];
+// Top-level `errorClass` on a failure. Stable class names, never an error message.
+const ERROR_CLASSES = new Set([
+ "auth", "invalid-input", "locked", "halted", "verify-failed", "deploy-failed", "timeout", "unexpected",
+]);
+// A step count above this is not a real run; clamp rather than send an implausible number.
+const MAX_COUNT = 100000;
+
+function count(value) {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < 0) return 0;
+ return Math.min(Math.floor(n), MAX_COUNT);
+}
+
+function enumOf(value, allowed) {
+ return typeof value === "string" && allowed.has(value) ? value : undefined;
+}
+
+function bool(value) {
+ return typeof value === "boolean" ? value : undefined;
+}
+
+// Allowlist-only: what is not named here is dropped. `steps` is { <phase>: { ok, skip, error } }.
+function sanitizeEventInfo(input) {
+ const src = input && typeof input === "object" && !Array.isArray(input) ? input : {};
+ const out = { schemaVersion: 1 };
+ const set = (key, value) => { if (value !== undefined) out[key] = value; };
+ set("operation", enumOf(src.operation, OPERATIONS));
+ set("scope", enumOf(src.scope, SCOPES));
+ set("publish", bool(src.publish));
+ set("verify", enumOf(src.verify, VERIFY_RESULTS));
+ set("haltPhase", enumOf(src.haltPhase, PHASES));
+ set("page", enumOf(src.page, PAGE_ACTIONS));
+ set("placedInApp", bool(src.placedInApp));
+ set("addedToSolution", bool(src.addedToSolution));
+ set("incremental", bool(src.incremental));
+ set("registration", enumOf(src.registration, REGISTRATION));
+ if (src.steps && typeof src.steps === "object" && !Array.isArray(src.steps)) {
+ const steps = {};
+ for (const [phase, tally] of Object.entries(src.steps)) {
+ if (!PHASES.has(phase) || !tally || typeof tally !== "object") continue;
+ const row = {};
+ for (const status of STEP_STATUSES) row[status] = count(tally[status]);
+ if (row.ok + row.skip + row.error > 0) steps[phase] = row;
+ }
+ if (Object.keys(steps).length) out.steps = steps;
+ }
+ return out;
+}
+
+// ---- Step tally ---------------------------------------------------------------------------------------
+// Fed the build engine's progress events ({ phase, status, replaces? }). A step the engine takes up again
+// names the outcome it replaces (build-model-app.js cliEmit), so each step is counted once, by its final
+// outcome — the same rule as the build's closing "N created, N skipped, N failed" line.
+function createStepTally() {
+ const byPhase = {};
+ return {
+ record(e) {
+ if (!e || typeof e.phase !== "string" || !STEP_STATUSES.includes(e.status)) return;
+ const row = byPhase[e.phase] || (byPhase[e.phase] = { ok: 0, skip: 0, error: 0 });
+ if (STEP_STATUSES.includes(e.replaces) && row[e.replaces] > 0) row[e.replaces] -= 1;
+ row[e.status] += 1;
+ },
+ // The engine restarts every phase on an automatic retry; the summary reflects the final attempt.
+ reset() { for (const key of Object.keys(byPhase)) delete byPhase[key]; },
+ snapshot() { return JSON.parse(JSON.stringify(byPhase)); },
+ };
+}
+
+// ---- Routing context ----------------------------------------------------------------------------------
+// The cloud of the TARGET environment, from its host, as the PAC cloud token the plugin's resolver.js
+// routes on. Hooks read `pac auth who`, whose active profile can be a different environment from the
+// `--env` a script was given; the host is the target's own. Host families as lib/dataverse-auth.js
+// DATAVERSE_HOST accepts them (GCC is the `crm9` region of the commercial family):
+// https://learn.microsoft.com/power-platform/admin/new-datacenter-regions
+// https://learn.microsoft.com/power-platform/admin/powerapps-us-government#power-apps-us-government-service-urls
+// lib/sdk-first.js connectivityCloudOf reads hosts too, but answers a different question (which route
+// the SDK can take, so GCC is "Unsupported" there); this one must name every cloud a key exists for.
+// An unknown host returns "". The emitter never hands "" to the resolver for a run that had a target: with
+// no organization ID, "" reads as a signed-out PAC and routes to the public US default (resolver.js).
+function cloudOfEnvironment(envUrl) {
+ let host = "";
+ try { host = new URL(String(envUrl)).host.toLowerCase(); } catch { return ""; }
+ if (/\.(?:api\.)?crmtest\.dynamics\.com$/.test(host)) return "Test";
+ if (/\.(?:api\.)?crm9\.dynamics\.com$/.test(host)) return "UsGov";
+ if (/\.(?:api\.)?crm\d*\.dynamics\.com$/.test(host)) return "Public";
+ if (/\.(?:api\.)?crm\.microsoftdynamics\.us$/.test(host)) return "UsGovHigh";
+ if (/\.(?:api\.)?crm\.appsplatform\.us$/.test(host)) return "UsGovDod";
+ if (/\.(?:api\.)?crm\.dynamics\.cn$/.test(host)) return "China";
+ return "";
+}
+
+// The Entra tenant GUID from an access token's `tid` claim. Only `tid` is read — never `oid`, `upn` or any
+// other user claim — and nothing is verified: the token was just issued to this process by the Azure CLI,
+// and a wrong value only mislabels a usage event.
+// JWT layout (RFC 7519): base64url(header).base64url(payload).signature, payload e.g. {"tid":"<guid>",...}
+function tenantIdFromToken(token) {
+ try {
+ const payload = String(token).split(".")[1];
+ if (!payload) return undefined;
+ const claims = JSON.parse(Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
+ return typeof claims.tid === "string" && GUID.test(claims.tid) ? claims.tid.toLowerCase() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+// { orgId, tenantId } of the target environment, or {} — never throws, and never starts the Azure CLI: the
+// token is read from dataverse-auth's per-process memo (peekAuthToken), which the script filled when it
+// talked to the environment. A script that never got that far — a refused sign-in, a lock refusal, a failed
+// push — has no token there, and its event simply goes without the IDs; reading one would cost the user a
+// CLI start of seconds (up to the Azure CLI budget) for telemetry. The one request is a WhoAmI.
+// Both IDs come from an ACCEPTED WhoAmI, or neither is sent: the token's `tid` names the tenant the Azure
+// CLI signed in to, which is the environment's only if the environment accepted the token. (Observed live:
+// a CLI signed in to another tenant gets a token, and the environment answers 401.)
+// WhoAmI: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoami
+async function resolveEnvironmentIdentity(envUrl, deps = {}) {
+ try {
+ const auth = deps.auth || require("../dataverse-auth.js");
+ if (typeof auth.peekAuthToken !== "function") return {};
+ const origin = auth.dataverseOrigin(envUrl);
+ if (!origin) return {};
+ const token = auth.peekAuthToken(origin);
+ if (!token) return {};
+ let timer;
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), deps.timeoutMs || IDENTITY_TIMEOUT_MS); });
+ const who = auth.dataverseRequest(origin, "GET", "WhoAmI", null, { token, timeout: deps.timeoutMs || IDENTITY_TIMEOUT_MS, refreshOn401: false })
+ .catch(() => null);
+ const res = await Promise.race([who, timeout]);
+ clearTimeout(timer);
+ const orgId = res && res.status >= 200 && res.status < 300 && res.data && res.data.OrganizationId;
+ if (typeof orgId !== "string" || !GUID.test(orgId)) return {};
+ const tenantId = tenantIdFromToken(token);
+ return { orgId: orgId.toLowerCase(), ...(tenantId ? { tenantId } : {}) };
+ } catch {
+ return {};
+ }
+}
+
+// ---- Gates --------------------------------------------------------------------------------------------
+function readIkey() {
+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ const ikeyPath = override && override.trim() ? override : path.join(TELEMETRY_DIR, "ikey.json");
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return { cfg, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };
+ } catch {
+ // Unreadable config is the repo kill switch, as in emit-dispatcher.js: fail closed.
+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };
+ }
+}
+
+function isProvisioned(cfg, ikeyPath) {
+ try {
+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));
+ if (resolver && typeof resolver.isProvisioned === "function") return !!resolver.isProvisioned(cfg);
+ return !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== PLACEHOLDER_IKEY);
+ } catch {
+ return false;
+ }
+}
+
+function readManifest() {
+ try {
+ const m = JSON.parse(fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8"));
+ return { name: typeof m.name === "string" ? m.name : "", version: m.version || "unknown" };
+ } catch {
+ return { name: "", version: "unknown" };
+ }
+}
+
+// node:test marks every process it runs (and their children inherit it) with NODE_TEST_CONTEXT. The
+// scripts this module serves are exercised by hundreds of tests with stand-in environments; without this
+// gate each of them would spawn a dispatcher, write a mirror in the developer's home and — on a machine
+// with no opt-out set — post an event about a fake build. A test that means to check emission sets
+// POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT=1 and routes it to a POWER_PLATFORM_SKILLS_FAKE_HTTPS probe.
+function suppressedUnderTest(env) {
+ return !!env.NODE_TEST_CONTEXT && env.POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT !== "1";
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+// ---- Emit ---------------------------------------------------------------------------------------------
+// input: { skillName, outcome: "success"|"failure", durationMs, errorClass?, eventInfo?, envUrl?,
+// orgId?, tenantId?, resolveIdentity? (default true) }
+// Resolves true when an event was handed to the dispatcher, false otherwise. Never rejects.
+async function emitSkillCompleted(input, deps = {}) {
+ try {
+ const env = deps.env || process.env;
+ if (suppressedUnderTest(env)) return false;
+ if (!input || typeof input.skillName !== "string" || !input.skillName) return false;
+ const outcome = input.outcome === "success" || input.outcome === "failure" ? input.outcome : null;
+ if (!outcome) return false;
+
+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();
+ if (disabled || !isProvisioned(cfg, ikeyPath)) return false;
+ const manifest = readManifest();
+ if (!manifest.name) return false;
+
+ const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";
+ // A user who opted out of transmission still gets the local mirror (the dispatcher writes it), but no
+ // network request is made on telemetry's behalf: the organization lookup is skipped, so their mirror
+ // records the event without the organization and tenant IDs.
+ const optedOut = isTransmissionOptedOut(configDir || DEFAULT_CONFIG_DIR, manifest.name, env);
+ let identity = {
+ ...(typeof input.orgId === "string" && GUID.test(input.orgId) ? { orgId: input.orgId.toLowerCase() } : {}),
+ ...(typeof input.tenantId === "string" && GUID.test(input.tenantId) ? { tenantId: input.tenantId.toLowerCase() } : {}),
+ };
+ if (!optedOut && input.resolveIdentity !== false && input.envUrl && !(identity.orgId && identity.tenantId)) {
+ const resolved = await (deps.resolveIdentity || resolveEnvironmentIdentity)(input.envUrl);
+ identity = { ...resolved, ...identity };
+ }
+
+ let agent = {};
+ try { agent = agentInfo.readAiAgent(env) || {}; } catch { agent = {}; }
+ const durationMs = Number.isFinite(input.durationMs) && input.durationMs >= 0 ? Math.round(input.durationMs) : undefined;
+ const errorClass = outcome === "failure" ? (enumOf(input.errorClass, ERROR_CLASSES) || "unexpected") : undefined;
+
+ const fields = {
+ pluginName: manifest.name,
+ pluginVersion: manifest.version,
+ // Scripts run outside the hooks that see the agent's session, so a completion carries its own random
+ // run ID; it is tied to the environment through orgId, not to the skill_started that preceded it.
+ sessionId: crypto.randomUUID(),
+ correlationId: crypto.randomUUID(),
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: "v" + String(process.versions.node).split(".")[0],
+ skillName: input.skillName,
+ outcome,
+ ...(durationMs !== undefined ? { durationMs } : {}),
+ ...(errorClass ? { errorClass } : {}),
+ ...identity,
+ eventInfo: sanitizeEventInfo(input.eventInfo),
+ ...(agent.aiAgentName ? { aiAgentName: agent.aiAgentName } : {}),
+ ...(agent.aiAgentVersion ? { aiAgentVersion: agent.aiAgentVersion } : {}),
+ };
+ (deps.fireAndForget || emitSpawn.fireAndForget)(events.buildSkillCompleted(eventStreamName, fields), {
+ // A host outside the known Dataverse families gets a cloud no resolver recognizes, so the event is mirrored locally and sent
+ // nowhere — never to the public default a blank cloud would select when the run has no organization ID (a lookup skipped,
+ // refused or timed out). resolver.js: an unrecognized non-empty cloud resolves to null.
+ cloud: cloudOfEnvironment(input.envUrl) || UNROUTABLE_CLOUD,
+ configDir,
+ fakeProbe: env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",
+ ikeyJsonPath: ikeyPath,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+module.exports = {
+ emitSkillCompleted,
+ createStepTally,
+ sanitizeEventInfo,
+ cloudOfEnvironment,
+ tenantIdFromToken,
+ resolveEnvironmentIdentity,
+ ERROR_CLASSES,
+ PHASES,
+};
diff --git a/plugins/model-apps/scripts/tests/dataverse-auth.test.js b/plugins/model-apps/scripts/tests/dataverse-auth.test.js
index ef1d42753..304679e60 100644
--- a/plugins/model-apps/scripts/tests/dataverse-auth.test.js
+++ b/plugins/model-apps/scripts/tests/dataverse-auth.test.js
@@ -1,1239 +1,1255 @@
-'use strict';
-const { test } = require('node:test');
-const assert = require('node:assert/strict');
-const http = require('node:http');
-
-const { parseArgs, readJsonArg, label, requiredLevel } = require('../lib/dataverse-auth');
-
-test('parseArgs: positional only', () => {
- const { positional, flags } = parseArgs(['a', 'b', 'c']);
- assert.deepEqual(positional, ['a', 'b', 'c']);
- assert.deepEqual(flags, {});
-});
-
-test('parseArgs: mix of positional and flags', () => {
- const { positional, flags } = parseArgs(['a', '--foo', 'bar', 'b', '--baz']);
- assert.deepEqual(positional, ['a', 'b']);
- assert.deepEqual(flags, { foo: 'bar', baz: true });
-});
-
-test('parseArgs: bool flag followed by another flag treats first as bool', () => {
- const { flags } = parseArgs(['--x', '--y', '1']);
- assert.deepEqual(flags, { x: true, y: '1' });
-});
-
-test('parseArgs: repeated flag overwrites', () => {
- const { flags } = parseArgs(['--foo', '1', '--foo', '2']);
- assert.equal(flags.foo, '2');
-});
-
-test('parseArgs: --key=value form', () => {
- const { positional, flags } = parseArgs(['x', '--foo=bar', '--baz=qux', 'y']);
- assert.deepEqual(positional, ['x', 'y']);
- assert.deepEqual(flags, { foo: 'bar', baz: 'qux' });
-});
-
-test('parseArgs: --key=value with empty value', () => {
- const { flags } = parseArgs(['--foo=']);
- assert.equal(flags.foo, '');
-});
-
-test('parseArgs: --key=value preserves additional = signs in value', () => {
- const { flags } = parseArgs(['--query=a=b=c']);
- assert.equal(flags.query, 'a=b=c');
-});
-
-test('parseArgs: mixed --key=value and --key value forms', () => {
- const { flags } = parseArgs(['--foo=bar', '--baz', 'qux']);
- assert.deepEqual(flags, { foo: 'bar', baz: 'qux' });
-});
-
-test('readJsonArg: inline JSON', () => {
- assert.deepEqual(readJsonArg('{"a":1}'), { a: 1 });
-});
-
-test('readJsonArg: file path with @ prefix', () => {
- const fs = require('node:fs');
- const path = require('node:path');
- const os = require('node:os');
- const tmp = path.join(os.tmpdir(), `dv-auth-test-${Date.now()}.json`);
- fs.writeFileSync(tmp, JSON.stringify({ from: 'file' }));
- try {
- assert.deepEqual(readJsonArg('@' + tmp), { from: 'file' });
- } finally {
- fs.unlinkSync(tmp);
- }
-});
-
-test('readJsonArg: null and undefined pass through', () => {
- assert.equal(readJsonArg(null), null);
- assert.equal(readJsonArg(undefined), null);
-});
-
-test('label: builds Dataverse verbose Label object', () => {
- const out = label('Hello');
- assert.equal(out['@odata.type'], 'Microsoft.Dynamics.CRM.Label');
- assert.equal(out.LocalizedLabels.length, 1);
- assert.equal(out.LocalizedLabels[0].Label, 'Hello');
- assert.equal(out.LocalizedLabels[0].LanguageCode, 1033);
-});
-
-test('label: respects custom language code', () => {
- const out = label('Bonjour', 1036);
- assert.equal(out.LocalizedLabels[0].LanguageCode, 1036);
-});
-
-test('requiredLevel: defaults to None and is mutable', () => {
- const out = requiredLevel();
- assert.equal(out.Value, 'None');
- assert.equal(out.CanBeChanged, true);
-});
-
-test('requiredLevel: respects argument', () => {
- assert.equal(requiredLevel('ApplicationRequired').Value, 'ApplicationRequired');
-});
-
-test('makeRequest preserves UTF-8 characters split across response chunks', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const body = JSON.stringify({ city: '東京', emoji: '😀', cafe: 'Café' });
- const bodyBytes = Buffer.from(body, 'utf8');
- const server = http.createServer((req, res) => {
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
- if (req.url === '/split') {
- for (let i = 0; i < bodyBytes.length; i += 1) {
- res.write(bodyBytes.subarray(i, i + 1));
- }
- res.end();
- return;
- }
- if (req.url === '/whole') {
- res.end(bodyBytes);
- return;
- }
- res.statusCode = 404;
- res.end('not found');
- });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- const { port } = server.address();
- try {
- const whole = await makeRequest({ url: `http://127.0.0.1:${port}/whole` });
- const split = await makeRequest({ url: `http://127.0.0.1:${port}/split` });
- assert.equal(whole.body, body);
- assert.equal(split.body, body);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-// A file's content is bytes: a generative page's row, an image. Decoded as UTF-8, bytes that are not valid UTF-8 come back changed (each bad byte becomes
-// U+FFFD), so `binary` hands back the Buffer as it arrived — split across chunks or not — and a request body that is a Buffer goes out verbatim.
-test('makeRequest with `binary` returns the body as the bytes that arrived, never decoded; a Buffer body is sent as it is', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0xfe, 0x00, 0xc3, 0x28, 0xe2, 0x82]);
- let received = null;
- const server = http.createServer((req, res) => {
- const chunks = [];
- req.on('data', (c) => chunks.push(c));
- req.on('end', () => {
- if (req.method === 'PATCH') received = Buffer.concat(chunks);
- res.setHeader('Content-Type', 'application/octet-stream');
- for (let i = 0; i < bytes.length; i += 1) res.write(bytes.subarray(i, i + 1));
- res.end();
- });
- });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- const { port } = server.address();
- try {
- const got = await makeRequest({ url: `http://127.0.0.1:${port}/x/$value`, binary: true });
- assert.ok(Buffer.isBuffer(got.body), 'a Buffer');
- assert.ok(got.body.equals(bytes), 'byte for byte');
- const decoded = await makeRequest({ url: `http://127.0.0.1:${port}/x/$value` });
- assert.strictEqual(typeof decoded.body, 'string', 'without `binary`, decoded as before');
- assert.notStrictEqual(Buffer.from(decoded.body, 'utf8').length, bytes.length, 'the control: decoding changes bytes that are not UTF-8');
- await makeRequest({ url: `http://127.0.0.1:${port}/x`, method: 'PATCH', body: bytes, headers: { 'Content-Length': String(bytes.length) }, binary: true });
- assert.ok(received && received.equals(bytes), 'the body went out byte for byte');
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-test('makeRequest settles with an error when the connection closes mid-response', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- // Headers and part of the body arrive, then the socket closes: no 'end', and the socket timeout
- // cannot fire on a closed socket. The promise must still settle through the { error } contract.
- const server = http.createServer((req, res) => {
- res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
- res.write('{"value":[');
- setTimeout(() => res.socket.destroy(), 20);
- });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- const { port } = server.address();
- try {
- const settled = await Promise.race([
- makeRequest({ url: `http://127.0.0.1:${port}/cut`, timeout: 60000 }),
- new Promise((resolve) => setTimeout(() => resolve('still pending'), 2000)),
- ]);
- assert.notEqual(settled, 'still pending', 'a truncated response must not leave the request pending');
- assert.match(settled.error, /before (it|the response) completed/);
- assert.strictEqual(settled.incompleteResponse, true, 'the server answered before the body was cut off');
- assert.strictEqual(settled.statusCode, 200);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-test('makeRequest marks a timeout after the headers arrived as an incomplete response', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- // The server answers, sends part of the body, then stalls. The request timeout fires on the
- // request, not the response, but the answer had arrived: a POST may already have been applied.
- const sockets = new Set();
- const server = http.createServer((req, res) => {
- res.writeHead(201, { 'Content-Type': 'application/json', 'Content-Length': '100' });
- res.write('{"id":');
- });
- server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- const { port } = server.address();
- try {
- const answered = await makeRequest({ url: `http://127.0.0.1:${port}/stall`, method: 'POST', body: '{}', timeout: 150 });
- assert.strictEqual(answered.incompleteResponse, true);
- assert.strictEqual(answered.statusCode, 201);
- assert.match(answered.error, /timed out before the response completed/);
- } finally {
- for (const s of sockets) s.destroy();
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-test('makeRequest keeps a timeout with no answer as a plain request failure', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const sockets = new Set();
- const server = http.createServer(() => { /* never answers */ });
- server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- const { port } = server.address();
- try {
- const silent = await makeRequest({ url: `http://127.0.0.1:${port}/silent`, method: 'POST', body: '{}', timeout: 150 });
- assert.deepStrictEqual(silent, { error: 'Request timed out' });
- } finally {
- for (const s of sockets) s.destroy();
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-// A request that fails comes with Node's own CODE beside the message. The message cannot say what the failure was — a certificate that does not verify quotes the host and the certificate's names, and a name can spell anything — so a
-// caller that decides whether the request is worth sending again (lib/sdk-http-client.js) reads the code. Only what Node raised for the request has one: the failures this module words itself have none.
-test('makeRequest reports Node\'s own error code beside the message of a request that failed — a refused connection, and a connection reset before any answer', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const probe = http.createServer();
- await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve));
- const { port: closedPort } = probe.address();
- await new Promise((resolve) => probe.close(resolve));
- const refused = await makeRequest({ url: `http://127.0.0.1:${closedPort}/x` });
- assert.strictEqual(refused.code, 'ECONNREFUSED');
- assert.match(refused.error, /ECONNREFUSED/);
- assert.deepStrictEqual(Object.keys(refused).sort(), ['code', 'error'], 'the message and the code, and nothing that says the server answered');
-
- const resetting = http.createServer((req) => req.socket.destroy());
- await new Promise((resolve) => resetting.listen(0, '127.0.0.1', resolve));
- try {
- const reset = await makeRequest({ url: `http://127.0.0.1:${resetting.address().port}/x`, method: 'POST', body: '{}' });
- assert.strictEqual(reset.code, 'ECONNRESET');
- assert.match(reset.error, /socket hang up|ECONNRESET/);
- assert.strictEqual(reset.incompleteResponse, undefined, 'no answer had arrived');
- } finally {
- await new Promise((resolve) => resetting.close(resolve));
- }
-});
-
-test('makeRequest reports the code of a certificate that does not verify — Node raises it for the request, whatever the message quotes', async (t) => {
- const https = require('node:https');
- const { EventEmitter } = require('node:events');
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const failure = Object.assign(
- new Error("Hostname/IP does not match certificate's altnames: Host: contoso.crm.dynamics.com. is not in the cert's altnames: DNS:ECONNRESET.example.com"),
- { code: 'ERR_TLS_CERT_ALTNAME_INVALID' },
- );
- let raised = failure;
- t.mock.method(https, 'request', () => {
- const req = new EventEmitter();
- req.write = () => {};
- req.end = () => setImmediate(() => req.emit('error', raised));
- req.destroy = () => {};
- return req;
- });
- assert.deepStrictEqual(await makeRequest({ url: 'https://contoso.crm.dynamics.com/api/data/v9.2/x' }), { error: failure.message, code: 'ERR_TLS_CERT_ALTNAME_INVALID' });
- // An error Node gave no code for is reported as it always was: the message alone.
- raised = new Error('something Node did not give a code for');
- assert.deepStrictEqual(await makeRequest({ url: 'https://contoso.crm.dynamics.com/api/data/v9.2/x' }), { error: 'something Node did not give a code for' });
-});
-
-test('the failures makeRequest words itself — a connection closed mid-response — carry no code: they are read by their words', async () => {
- const { makeRequest } = require('../lib/dataverse-auth.js');
- const server = http.createServer((req, res) => {
- res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
- res.write('{"value":[');
- setTimeout(() => res.socket.destroy(), 20);
- });
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
- try {
- const cut = await makeRequest({ url: `http://127.0.0.1:${server.address().port}/cut` });
- assert.match(cut.error, /before (it|the response) completed/);
- assert.strictEqual(cut.incompleteResponse, true);
- assert.ok(!('code' in cut), 'the words are this module\'s own, and no code is made up for them');
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-});
-
-test('dataverseRequest does not replay a POST whose response was cut off, but retries a GET', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- const cut = (statusCode) => ({ error: 'Connection closed before the response completed', incompleteResponse: true, statusCode });
- let posts = 0;
- await assert.rejects(
- dataverseRequest('https://contoso.crm.dynamics.com', 'POST', 'accounts', { name: 'A' }, {
- getToken: () => 'TOK', request: async () => { posts += 1; return cut(201); },
- }),
- /already answered 201, so this POST may have been applied; it was not re-sent/,
- );
- assert.strictEqual(posts, 1);
- let gets = 0;
- const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'accounts', null, {
- getToken: () => 'TOK',
- request: async () => { gets += 1; return gets === 1 ? cut(200) : { statusCode: 200, body: '{"value":[]}' }; },
- });
- assert.strictEqual(res.status, 200);
- assert.strictEqual(gets, 2);
-});
-
-// --- the access token is not in what a call that did not succeed reports ---------------------------------------------------------------------------
-// `dataverseRequest` hands back what the service answered — `{ status, data }` — and a caller that fails prints it (`ensureOk` quotes `data.error.message`; list-connections.js reads the connection
-// references with it, and prints what failed). An authorization layer, or a gateway, that rejects a token may repeat it — whole, or one part of it — in the body or in a header, and a transport failure's
-// text can repeat the request it was sending. So an answer that is not a success is handed back with the token taken out of it, and so is the text of a transport failure, by the scrubber the plugin's
-// Dataverse HttpClient uses (lib/sdk-http-client.js: one scrubber). A SUCCESS is the caller's data and is never touched, whatever it holds.
-const ECHOED = ['syntheticHeaderPartOfTheEchoedToken', 'syntheticPayloadPartOfTheEchoedToken', 'syntheticSignaturePartOfTheEchoedToken'].join('.');
-const ORG_URL = 'https://contoso.crm.dynamics.com';
-
-test('dataverseRequest takes the token out of the answer to a call that did not succeed — the body, whole or in a part, whatever its shape — and leaves the status and the typed code', async () => {
- const { dataverseRequest, ensureOk } = require('../lib/dataverse-auth.js');
- const [header, payload] = ECHOED.split('.');
- const answers = [
- [400, JSON.stringify({ error: { code: '0x80048d19', message: `Rejected bearer ${ECHOED}` } }), (res) => { assert.equal(res.data.error.message, 'Rejected bearer <token>'); assert.equal(res.data.error.code, '0x80048d19'); }],
- [403, JSON.stringify({ error: { message: `the claim ${payload} is not valid`, details: [`and ${header}`] } }), (res) => { assert.equal(res.data.error.message, 'the claim <token> is not valid'); assert.deepEqual(res.data.error.details, ['and <token>']); }],
- [410, `<html>Gone: Authorization: Bearer ${ECHOED}</html>`, (res) => assert.equal(res.data, '<html>Gone: Authorization: Bearer <token></html>')],
- [404, JSON.stringify({ [`key ${ECHOED}`]: 1 }), (res) => assert.deepEqual(res.data, { 'key <token>': 1 })],
- ];
- for (const [statusCode, body, check] of answers) {
- const res = await dataverseRequest(ORG_URL, 'GET', 'connectionreferences', null, { getToken: () => ECHOED, request: async () => ({ statusCode, body }) });
- assert.equal(res.status, statusCode);
- check(res);
- assert.ok(!JSON.stringify(res).includes(ECHOED) && !JSON.stringify(res).includes(payload), `${statusCode}: no part of the token is left`);
- }
- // What a caller prints is what it quotes of the answer: the message of the failure it raises holds no token either.
- const refused = await dataverseRequest(ORG_URL, 'GET', 'connectionreferences', null, { getToken: () => ECHOED, request: async () => ({ statusCode: 403, body: JSON.stringify({ error: { message: `Rejected bearer ${ECHOED}` } }) }) });
- assert.throws(() => ensureOk(refused, 'List connection references'), (error) => error.message === 'List connection references failed: HTTP 403 — Rejected bearer <token>');
-});
-
-test('dataverseRequest takes the token out of an answer\u2019s headers when it hands them back — and out of the answer to the request that was sent with the token a 401 replaced', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- const refreshed = 'syntheticRefreshedTokenOfTheSecondRequest0123456789';
- const reads = [];
- const sent = [];
- const answers = [
- { statusCode: 401, body: JSON.stringify({ error: { message: `token ${ECHOED} expired` } }), headers: {} },
- { statusCode: 403, body: JSON.stringify({ error: { message: `old ${ECHOED} new ${refreshed}` } }), headers: { 'www-authenticate': `Bearer error="invalid_token", error_description="${refreshed}"`, 'x-request-id': 'abc' } },
- ];
- const res = await dataverseRequest(ORG_URL, 'GET', 'WhoAmI', null, {
- includeHeaders: true,
- getToken: (url, options) => { reads.push(options); return options && options.fresh ? refreshed : ECHOED; },
- request: async (options) => { sent.push(options.headers.Authorization); return answers[sent.length - 1]; },
- });
- assert.deepEqual(sent, [`Bearer ${ECHOED}`, `Bearer ${refreshed}`], 'the first token, refused, and the one that replaced it');
- assert.equal(res.status, 403);
- assert.equal(res.data.error.message, 'old <token> new <token>', 'both tokens the call sent are taken out');
- assert.deepEqual(res.headers, { 'www-authenticate': 'Bearer error="invalid_token", error_description="<token>"', 'x-request-id': 'abc' });
-});
-
-test('dataverseRequest takes the token out of the text of a transport failure — a GET that never got an answer, and a POST whose answer was cut off', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- await assert.rejects(
- dataverseRequest(ORG_URL, 'GET', 'WhoAmI', null, { getToken: () => ECHOED, request: async () => ({ error: `socket hang up while sending Authorization: Bearer ${ECHOED}` }) }),
- (error) => error.message === 'Request failed: socket hang up while sending Authorization: Bearer <token>',
- );
- await assert.rejects(
- dataverseRequest(ORG_URL, 'POST', 'accounts', { name: 'A' }, { getToken: () => ECHOED, request: async () => ({ error: `reset (${ECHOED.split('.')[1]})`, incompleteResponse: true, statusCode: 201 }) }),
- (error) => error.message === 'Request failed: reset (<token>) — the server had already answered 201, so this POST may have been applied; it was not re-sent. Check the result before running it again.',
- );
-});
-
-test('dataverseRequest never alters a success — its data and its headers come back exactly as they arrived, token text and all — and a value too short to be a token is never taken out of anything', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- // A record whose field happens to hold the token, a text body, and a header that repeats it: successes are the caller's data.
- const record = JSON.stringify({ value: [{ name: ECHOED, note: ECHOED.split('.')[1] }] });
- const ok = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { includeHeaders: true, getToken: () => ECHOED, request: async () => ({ statusCode: 200, body: record, headers: { 'x-echo': ECHOED } }) });
- assert.deepEqual(ok.data, JSON.parse(record));
- assert.deepEqual(ok.headers, { 'x-echo': ECHOED });
- const text = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { getToken: () => ECHOED, request: async () => ({ statusCode: 200, body: `plain ${ECHOED}` }) });
- assert.equal(text.data, `plain ${ECHOED}`);
- // The floor is the Dataverse client's: a token shorter than 16 characters is no access token (the tests' own stand-ins are), and taking it out would blank every place a message has the same letters.
- const short = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { getToken: () => 'TOK', request: async () => ({ statusCode: 400, body: JSON.stringify({ error: { message: 'TOKEN TOK' } }) }) });
- assert.equal(short.data.error.message, 'TOKEN TOK');
-});
-
-test('getAuthToken reuses a non-empty token per normalized resource URL', () => {
- const { getAuthToken } = require('../lib/dataverse-auth.js');
- const calls = [];
- const exec = (_file, args) => {
- calls.push(args[args.indexOf('--resource') + 1]);
- return 'TOK\n';
- };
- const oldPath = process.env.PATH;
- process.env.PATH = '';
- try {
- assert.equal(getAuthToken('https://contoso.crm.dynamics.com/', { exec, fresh: true }), 'TOK');
- assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'TOK');
- assert.equal(getAuthToken('https://fabrikam.crm.dynamics.com', { exec, fresh: true }), 'TOK');
- } finally {
- process.env.PATH = oldPath;
- }
- assert.deepEqual(calls, ['https://contoso.crm.dynamics.com', 'https://fabrikam.crm.dynamics.com']);
-});
-
-test('a fresh acquire bypasses the memo and replaces the token it holds', () => {
- const { getAuthToken } = require('../lib/dataverse-auth.js');
- const tokens = ['OLD\n', 'NEW\n'];
- let calls = 0;
- const exec = () => tokens[Math.min(calls++, tokens.length - 1)];
- const url = 'https://fabrikam.crm4.dynamics.com';
- const oldPath = process.env.PATH;
- process.env.PATH = '';
- try {
- assert.equal(getAuthToken(url, { exec, fresh: true }), 'OLD');
- assert.equal(getAuthToken(url, { exec }), 'OLD', 'an ordinary repeat is served from the memo');
- // A 401 refresh must not be handed the token the server just rejected.
- assert.equal(getAuthToken(url, { exec, fresh: true }), 'NEW');
- assert.equal(getAuthToken(url, { exec }), 'NEW', 'the refreshed token replaces the memoized one');
- } finally {
- process.env.PATH = oldPath;
- }
- assert.equal(calls, 2);
-});
-test('getAuthToken does not cache a null token result', () => {
- const { getAuthToken } = require('../lib/dataverse-auth.js');
- let calls = 0;
- const exec = () => {
- calls += 1;
- if (calls === 1) return '\n';
- return 'TOK\n';
- };
- const oldPath = process.env.PATH;
- process.env.PATH = '';
- try {
- assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec, fresh: true }), null);
- assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec }), 'TOK');
- } finally {
- process.env.PATH = oldPath;
- }
- assert.equal(calls, 2);
-});
-
-test('getAuthTokenAsync is served from a memo that getAuthToken filled', async () => {
- // The other direction of sharing: check-auth warms the memo asynchronously, but a synchronous caller
- // may have filled it first, and the async path must then not start the CLI again.
- const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');
- let asyncCalls = 0;
- const exec = () => 'SYNC\n';
- const execFile = (_file, _args, _opts, cb) => { asyncCalls += 1; setImmediate(() => cb(null, 'ASYNC\n')); };
- const url = 'https://fabrikam.crm5.dynamics.com';
- const oldPath = process.env.PATH;
- process.env.PATH = '';
- try {
- assert.equal(getAuthToken(url, { exec, fresh: true }), 'SYNC');
- assert.equal(await getAuthTokenAsync(url, { execFile }), 'SYNC');
- } finally {
- process.env.PATH = oldPath;
- }
- assert.equal(asyncCalls, 0);
-});
-test('getAuthTokenAsync shares the token memo with getAuthToken and honors fresh replacement', async () => {
- const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');
- const calls = [];
- const exec = (_file, args) => {
- calls.push(`sync:${args[args.indexOf('--resource') + 1]}`);
- return 'SYNC\n';
- };
- const execFile = (_file, args, _opts, cb) => {
- calls.push(`async:${args[args.indexOf('--resource') + 1]}`);
- setImmediate(() => cb(null, calls.length === 1 ? 'ASYNC\n' : 'FRESH\n'));
- };
- const oldPath = process.env.PATH;
- process.env.PATH = '';
- try {
- assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com/', { execFile, fresh: true }), 'ASYNC');
- assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'ASYNC');
- assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com', { execFile, fresh: true }), 'FRESH');
- assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'FRESH');
- } finally {
- process.env.PATH = oldPath;
- }
- assert.deepEqual(calls, [
- 'async:https://contoso.crm.dynamics.com',
- 'async:https://contoso.crm.dynamics.com',
- ]);
-});
-
-test('cancelling a getAuthTokenAsync read ends the child\'s whole process tree, not just the wrapper Node starts, and is not a remembered failure', async () => {
- // check-auth starts this read beside `az account show`; when the account verdict ends the run, the token child is
- // cancelled. On Windows `az` is a batch shim under cmd.exe, so Node's own abort would end only that wrapper and leave az's
- // Python process running after this one exits — the abort is handled here, through killProcessTree, and the signal is not
- // handed to the child's start. The cancellation must also not be recorded as the Azure CLI failing: a later reader of
- // tokenFailureKind would be told the CLI "failed" when it was simply told to stop.
- const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
- const url = 'https://contoso-abort.crm.dynamics.com';
- const controller = new AbortController();
- const child = { pid: 4242 };
- const killed = [];
- let seen;
- let finish;
- const execFile = (_file, _args, options, cb) => { seen = options; finish = cb; return child; };
- const pending = getAuthTokenAsync(url, { execFile, signal: controller.signal, killTree: (c) => killed.push(c) });
- assert.ok(!('signal' in seen), 'the signal is not handed to Node, whose own kill would reach only the cmd.exe wrapper');
- assert.deepEqual(killed, [], 'nothing is ended before the abort');
- controller.abort();
- assert.deepEqual(killed, [child], 'the abort ends the child\'s process tree');
- finish(Object.assign(new Error('Command failed'), { code: 1 }), '', '');
- assert.equal(await pending, null);
- assert.equal(tokenFailureKind(url), null, 'a cancelled read leaves no failure behind');
-});
-
-test('a getAuthTokenAsync read that already finished is not ended by a later abort, and one cancelled before it starts runs nothing', async () => {
- const { getAuthTokenAsync } = require('../lib/dataverse-auth.js');
- const controller = new AbortController();
- const killed = [];
- const execFile = (_file, _args, _options, cb) => { setImmediate(() => cb(null, 'TOKEN\n', '')); return { pid: 7 }; };
- assert.equal(await getAuthTokenAsync('https://contoso-finished.crm.dynamics.com', { execFile, signal: controller.signal, killTree: (c) => killed.push(c) }), 'TOKEN');
- controller.abort();
- assert.deepEqual(killed, [], 'the child had finished: there is nothing to end');
- let started = 0;
- const cancelled = new AbortController();
- cancelled.abort();
- assert.equal(await getAuthTokenAsync('https://contoso-never.crm.dynamics.com', { execFile: () => { started += 1; return {}; }, signal: cancelled.signal }), null);
- assert.equal(started, 0, 'no process is started for a read that was already cancelled');
-});
-
-test('without a signal getAuthTokenAsync starts the CLI with exactly the options it always did, and a real failure is still remembered', async () => {
- const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
- const url = 'https://contoso-plain.crm.dynamics.com';
- let seen;
- const execFile = (_file, _args, options, cb) => { seen = options; setImmediate(() => cb(Object.assign(new Error('boom'), { killed: true, signal: 'SIGTERM' }), '', '')); return {}; };
- assert.equal(await getAuthTokenAsync(url, { execFile }), null);
- assert.deepEqual(Object.keys(seen).sort(), ['encoding', 'timeout', 'windowsHide'], 'no `signal` key unless the caller supplied one');
- assert.equal(tokenFailureKind(url), 'timeout');
-});
-
-test('dataverseRequest hands a 401 back without refreshing the token when refreshOn401 is false — the refresh is a synchronous CLI read', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- const run = async (options) => {
- const tokenCalls = [];
- let sends = 0;
- const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
- getToken: (_url, o) => { tokenCalls.push(Boolean(o && o.fresh)); return 'TOK'; },
- request: async () => { sends += 1; return { statusCode: 401, body: '' }; },
- ...options,
- });
- return { res, tokenCalls, sends };
- };
- const refreshing = await run({});
- assert.deepEqual(refreshing.tokenCalls, [false, true, true], 'by default each 401 is followed by a fresh token read, twice');
- assert.equal(refreshing.sends, 3);
- const handedBack = await run({ refreshOn401: false });
- assert.equal(handedBack.res.status, 401);
- assert.deepEqual(handedBack.tokenCalls, [false], 'only the memoized token was used: no synchronous read');
- assert.equal(handedBack.sends, 1, 'and the 401 was not sent again');
-});
-
-test('emitResult: partial-failure object writes JSON to stdout (not [object Object])', () => {
- // Spawn a tiny script that calls emitResult(false, {errors:[...]}) and
- // verify that stdout contains the JSON payload — not the literal string
- // "[object Object]". Regression guard for the bulk-insert failure path.
- const { spawnSync } = require('node:child_process');
- const path = require('node:path');
- const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
- const code = `
- const { emitResult } = require(${JSON.stringify(libPath)});
- emitResult(false, { ok: false, count: 0, ids: [], errors: [{ index: 0, status: 400, message: 'bad row' }] });
- `;
- const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
- assert.equal(res.status, 1, 'expected exit 1');
- assert.doesNotMatch(res.stdout, /\[object Object\]/, 'stdout must not be [object Object]');
- const parsed = JSON.parse(res.stdout.trim());
- assert.equal(parsed.ok, false);
- assert.equal(parsed.errors.length, 1);
- assert.equal(parsed.errors[0].index, 0);
- assert.equal(parsed.errors[0].status, 400);
- assert.equal(parsed.errors[0].message, 'bad row');
- assert.match(res.stderr, /Operation completed with 1 error/);
-});
-
-// --- AB#6686427: auth preflight — az tenant divergence from the selected PAC environment ---------
-//
-// The skill flow validates and selects a PAC profile, but every script authenticates through the
-// INDEPENDENTLY active Azure CLI account. In a normal multi-tenant workflow `pac auth` and
-// `az login` legitimately point at different tenants, and the result is an HTTP 401 that reads as a
-// Dataverse permission problem — so the user troubleshoots roles and PAC profiles while the actual
-// cause is the ambient az context. Worse, download's best-effort catches turn that 401 into a
-// silently EMPTY spec (AB#6686423), so the failure does not even surface as an error.
-//
-// The preflight names the identity that will actually supply the token, before any real work.
-
-const { preflightAuth } = require('../lib/dataverse-auth.js');
-
-test('AB#6686427: preflight passes and reports the identity when WhoAmI succeeds', async () => {
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 200, data: { UserId: '00000000-0000-0000-0000-000000000001' } }),
- azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),
- });
- assert.strictEqual(r.ok, true, JSON.stringify(r));
- assert.match(r.identity.user, /maker@contoso\.com/);
-});
-
-test('preflight: identityOnSuccess:false skips the identity read on success but keeps it for a 401', async () => {
- let reads = 0;
- const azIdentity = () => { reads += 1; return { user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }; };
- const ok = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 200, data: { UserId: '00000000-0000-0000-0000-000000000001' } }),
- azIdentity,
- identityOnSuccess: false,
- });
- assert.strictEqual(ok.ok, true);
- assert.strictEqual(ok.userId, '00000000-0000-0000-0000-000000000001');
- assert.strictEqual('identity' in ok, false, 'no identity on a verdict-only success');
- assert.strictEqual(reads, 0, 'no `az account show` for a value nobody reads');
- const denied = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 401, headers: {} }),
- azIdentity,
- identityOnSuccess: false,
- });
- assert.strictEqual(denied.ok, false);
- assert.strictEqual(reads, 1, 'a 401 still names the identity it rejected');
- assert.match(denied.error, /maker@contoso\.com/);
-});
-
-test('dataverseRequest USES a preset token and skips the CLI entirely', async () => {
- // The receiving half of the preflight optimisation. Passing the token is pointless if this side
- // fetches its own anyway, and that is invisible from the caller.
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- let cliCalls = 0;
- let sentAuth;
- const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
- token: 'tok-abc',
- getToken: () => { cliCalls += 1; return 'tok-from-cli'; },
- request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },
- });
- assert.strictEqual(cliCalls, 0, 'a preset token must skip `az account get-access-token` altogether');
- assert.strictEqual(sentAuth, 'Bearer tok-abc');
- assert.strictEqual(res.status, 200);
-
- // Counterfactual: with no preset token it still acquires one, or the seam would have broken the
- // normal path while looking green.
- cliCalls = 0;
- await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
- getToken: () => { cliCalls += 1; return 'tok-from-cli'; },
- request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },
- });
- assert.strictEqual(cliCalls, 1);
- assert.strictEqual(sentAuth, 'Bearer tok-from-cli');
-});
-
-
-test('dataverseRequest bypasses the token memo after a 401 before retrying', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- const tokenCalls = [];
- const sent = [];
- const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
- getToken: (_url, options) => {
- tokenCalls.push(Boolean(options && options.fresh));
- return tokenCalls.length === 1 ? 'OLD' : 'NEW';
- },
- request: async ({ headers }) => {
- sent.push(headers.Authorization);
- return sent.length === 1
- ? { statusCode: 401, body: '' }
- : { statusCode: 200, body: '{"ok":true}' };
- },
- });
- assert.strictEqual(res.status, 200);
- assert.deepStrictEqual(tokenCalls, [false, true]);
- assert.deepStrictEqual(sent, ['Bearer OLD', 'Bearer NEW']);
-});
-
-test('a path-bearing or query-bearing env is refused, not silently trimmed to its origin', async () => {
- // `dataverseRequest` appends `/api/data/...` to whatever it is given, so a trimmed
- // `https://org.crm.dynamics.com/some/path` would probe `.../some/path/api/data/...` and report a
- // result about a URL nobody asked for. This function decides where a bearer token may be sent, so
- // "close enough" is the wrong disposition.
- for (const bad of [
- 'https://contoso.crm.dynamics.com/some/path',
- 'https://contoso.crm.dynamics.com/?q=1',
- 'https://contoso.crm.dynamics.com/#frag',
- ]) {
- let tokenAsked = 0;
- let requested = 0;
- const r = await preflightAuth(bad, {
- getToken: () => { tokenAsked += 1; return 'token'; },
- request: async () => { requested += 1; return { status: 200, data: {} }; },
- azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),
- });
- assert.strictEqual(r.ok, false, `${bad} must be refused: ${JSON.stringify(r)}`);
- assert.match(r.error, /ORIGIN/, r.error);
- assert.strictEqual(tokenAsked, 0, `${bad}: no token may be acquired for a rejected target`);
- assert.strictEqual(requested, 0, `${bad}: and nothing may be sent`);
- }
- // Counterfactual: a bare origin, and an origin with only a trailing slash, are both fine.
- for (const good of ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com/']) {
- const r = await preflightAuth(good, {
- getToken: () => 'token',
- request: async () => ({ status: 200, data: { UserId: 'u' } }),
- azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),
- });
- assert.strictEqual(r.ok, true, `${good} must be accepted: ${JSON.stringify(r)}`);
- }
-});
-
-// --- emitResult: a single explained failure must not be dressed as a partial one -----------------
-test('both CLIs report an auth-preflight failure with the SAME payload shape', () => {
- // `emitResult` reserves `errors: [...]` for a genuine PARTIAL failure and summarises it as a COUNT.
- // `build-model-app.js` wrapped its single preflight message in that array while
- // `download-model-app.js` passed it as `error`, so the two sibling CLIs printed different things
- // for the identical failure — and the one users hit on an apply printed the count, replacing a
- // message written specifically to say which identity to sign in as.
- //
- // Asserted on the SOURCE because the alternative is spawning both CLIs against a live tenant. build-model-app.js answers the result
- // (`payload`) for main() to print once its build lease is let go (tests/build-lease-cli.test.js prints it through the real printer).
- const fs = require('node:fs');
- const path = require('node:path');
- for (const cli of ['build-model-app.js', 'download-model-app.js']) {
- const src = fs.readFileSync(path.join(__dirname, '..', cli), 'utf8');
- const line = src.split('\n').find((l) => /(?:emitResult\(false,|payload:\s*\{).*auth\.error/.test(l));
- assert.ok(line, `${cli}: expected an emitResult call carrying auth.error`);
- assert.match(line, /error:\s*auth\.error/, `${cli}: a single explained failure must use \`error\`: ${line.trim()}`);
- assert.doesNotMatch(line, /errors:\s*\[/, `${cli}: \`errors: [...]\` is for PARTIAL failures and prints only a count: ${line.trim()}`);
- }
-});
-
-test('emitResult prints a single error message instead of "unknown error(s)"', () => {
- // The auth preflight, the app-id resolver and friends all fail with { ok:false, error:"<what to
- // do>" } and no `errors` array. The old branch printed "Operation completed with unknown error(s)"
- // for every one of them — burying a message written specifically to tell the operator what to do,
- // under boilerplate that is also untrue: nothing completed, and it is not unknown.
- const { emitResult } = require('../lib/dataverse-auth.js');
- const run = (payload) => {
- const out = [];
- const err = [];
- const so = process.stdout.write;
- const se = process.stderr.write;
- const ex = process.exit;
- process.stdout.write = (s) => { out.push(String(s)); return true; };
- process.stderr.write = (s) => { err.push(String(s)); return true; };
- // `emitResult` ends the process by contract, so the exit is turned into a throw and swallowed.
- process.exit = () => { throw new Error('__exit__'); };
- try { emitResult(false, payload); } catch (e) { if (e.message !== '__exit__') throw e; } finally {
- process.stdout.write = so; process.stderr.write = se; process.exit = ex;
- }
- return { out: out.join(''), err: err.join('') };
- };
-
- const single = run({ ok: false, error: 'no Azure CLI access token could be obtained; run az login' });
- assert.match(single.err, /run az login/, 'the actionable message must reach stderr');
- assert.doesNotMatch(single.err, /unknown error/, 'and must not be replaced by boilerplate');
- assert.match(single.out, /"ok":false/, 'the structured payload still goes to stdout for callers');
-
- // The genuine PARTIAL-failure contract is unchanged: a count, with the detail on stdout.
- const partial = run({ ok: false, errors: [{ row: 1 }, { row: 2 }] });
- assert.match(partial.err, /completed with 2 error\(s\)/, partial.err);
-
- // Neither shape: say so honestly rather than claiming a count we do not have.
- const opaque = run({ ok: false });
- assert.match(opaque.err, /unstructured error/, opaque.err);
- assert.doesNotMatch(opaque.err, /completed with/, 'nothing completed');
-});
-
-test('AB#6686427: the preflight HANDS its token to the request instead of fetching a second one', async () => {
- // `preflightAuth` deliberately acquires a token itself so it can tell "not signed in" apart from
- // "signed in but rejected" — two different diagnoses with two different fixes. Without passing it
- // on, `dataverseRequest` shells out to `az account get-access-token` again for the same origin,
- // and that call cold-starts the Azure CLI's Python runtime: seconds, on a path a user waits on.
- let tokenCalls = 0;
- let sawToken;
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => { tokenCalls += 1; return 'tok-abc'; },
- request: async (_url, _m, _p, _b, opts) => { sawToken = opts && opts.token; return { status: 200, data: { UserId: 'u' } }; },
- azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),
- });
- assert.strictEqual(r.ok, true, JSON.stringify(r));
- assert.strictEqual(tokenCalls, 1, 'exactly one token acquisition');
- assert.strictEqual(sawToken, 'tok-abc', 'and the SAME token must reach the request');
-});
-
-test('AB#6686427: a 401 names the ACTIVE az identity, the target org, and the remediation', async () => {
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 401, data: {} }),
- azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbbbbbb-0000-0000-0000-000000000000' }),
- });
- assert.strictEqual(r.ok, false);
- // Naming only the status repeats the failure the user already saw; the point is to name the CAUSE.
- assert.match(r.error, /other@fabrikam\.onmicrosoft\.com/, 'must name the active az identity');
- assert.match(r.error, /bbbbbbbb-0000-0000-0000-000000000000/, 'must name the tenant supplying the token');
- assert.match(r.error, /contoso\.crm\.dynamics\.com/, 'must name the target org');
- assert.match(r.error, /az login/, 'must name the remediation');
-});
-
-test('AB#6686427: no token at all is reported as a sign-in problem, not a permission one', async () => {
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => null,
- request: async () => { throw new Error('should not be called'); },
- azIdentity: () => null,
- });
- assert.strictEqual(r.ok, false);
- assert.match(r.error, /az login/);
- // Assert the CLAIM, not the vocabulary: the message may legitimately use the word "permissions"
- // to rule it OUT, which an over-crude /permission/ ban would fail. What must not happen is the
- // failure being ATTRIBUTED to privileges, sending the user to security roles.
- assert.match(r.error, /sign-in problem/, 'must name the real cause');
- assert.doesNotMatch(r.error, /insufficient|lacks? (the )?privilege|missing privilege|security role/i,
- 'must not attribute a missing token to privileges');
-});
-
-test('AB#6686427: the preflight is a diagnostic and never throws', async () => {
- for (const opts of [
- { getToken: () => { throw new Error('az exploded'); }, request: async () => ({ status: 200, data: {} }), azIdentity: () => null },
- { getToken: () => 't', request: async () => { throw new Error('socket hang up'); }, azIdentity: () => null },
- { getToken: () => 't', request: async () => ({ status: 200, data: {} }), azIdentity: () => { throw new Error('az show failed'); } },
- ]) {
- let r;
- await assert.doesNotReject(async () => { r = await preflightAuth('https://contoso.crm.dynamics.com', opts); });
- assert.ok(typeof r.ok === 'boolean', 'always returns a structured verdict');
- }
-});
-
-test('AB#6686427: a non-401 failure is INCONCLUSIVE, not a block and not a tenant mismatch', async () => {
- // A 403 is a real privilege problem and a 500 is the service; blaming the az tenant for either
- // would send the user down exactly the wrong path — the mirror of the bug being fixed.
- //
- // They must also NOT BLOCK. This probe goes through `dataverseRequest`, which retries fewer
- // statuses and fewer times than the `createAzHttpClient` the real download uses (that one also
- // retries 504). A transient 5xx the download would have ridden out must not be turned into a hard
- // failure by a diagnostic sitting in front of it. Found in review.
- for (const status of [403, 429, 500, 504]) {
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status, data: { error: { message: 'upstream detail' } } }),
- azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),
- });
- assert.strictEqual(r.ok, false);
- assert.strictEqual(r.inconclusive, true, `${status} must be inconclusive, never blocking`);
- assert.doesNotMatch(r.error, /az login --tenant/, `${status} must not be blamed on the az tenant`);
- assert.match(r.error, /upstream detail/, 'the server message explains a 403 and must survive');
- }
-});
-
-test('AB#6686427: a non-HTTPS or malformed env is refused BEFORE any token is acquired', async () => {
- // The preflight runs ahead of createAzHttpClient's credential boundary and goes through
- // dataverseRequest, whose transport falls back to plain `http` for a non-HTTPS scheme. Without
- // this gate a malformed --env could put a bearer token on the wire in clear text. Found in review.
- for (const bad of ['http://contoso.crm.dynamics.com', 'not-a-url', 'ftp://x/y', '']) {
- let tokenAsked = 0;
- const r = await preflightAuth(bad, {
- getToken: () => { tokenAsked++; return 'token'; },
- request: async () => { throw new Error('must not reach the wire'); },
- azIdentity: () => null,
- });
- assert.strictEqual(r.ok, false, `${bad} must be refused`);
- assert.strictEqual(r.inconclusive, undefined, 'a bad target is definitive, not inconclusive');
- assert.strictEqual(tokenAsked, 0, `no token may be acquired for ${bad}`);
- assert.match(r.error, /https/i);
- }
-});
-
-test('AB#6686427: a CLAIMS CHALLENGE 401 is not blamed on the tenant', async () => {
- // Conditional Access / CAE answer 401 with `WWW-Authenticate: ... error="insufficient_claims"`,
- // and `az login --tenant` does not fix it. Asserting tenant divergence as a certainty would be the
- // same misattribution this bug is about, pointed somewhere new. Found in review.
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 401, data: null, headers: { 'www-authenticate': 'Bearer error="insufficient_claims", claims="eyJ..."' } }),
- azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),
- });
- assert.strictEqual(r.ok, false);
- assert.match(r.error, /claims/i);
- assert.doesNotMatch(r.error, /az login --tenant/, 'a claims challenge is not a tenant problem');
-});
-
-test('AB#6686427: the happy path does not shell out to az for an identity nobody asked for', async () => {
- // The caller only reads `auth.ok`; paying for an `az account show` subprocess on every successful
- // run is pure cost. Found in review.
- let idReads = 0;
- const r = await preflightAuth('https://contoso.crm.dynamics.com', {
- getToken: () => 'token',
- request: async () => ({ status: 200, data: { UserId: 'u' } }),
- azIdentity: () => { idReads++; return { user: '[email protected]', tenantId: 'aaaa' }; },
- });
- assert.strictEqual(r.ok, true);
- assert.ok(idReads <= 1, `identity read at most once on success, got ${idReads}`);
-});
-
-// --- AB#6686424: a terminal 401 must explain itself ----------------------------------------------
-//
-// Both auth paths already retry a 401 once (dataverse-auth's loop, and sdk-http-client.js:130). The
-// retry is not the gap: MEASURED, `az account get-access-token` serves from the MSAL cache, so an
-// immediate re-call returns a byte-identical token (same sha256). A retry therefore cannot fix a
-// token that is rejected for WHO it belongs to — only one that expired in a very narrow window.
-//
-// The reporter's own workaround was "refresh Azure CLI login and retry" — an `az login`, which is
-// AB#6686427's cause. So what a surviving 401 needs is not another attempt, it is to say whose
-// token was refused, so the reader stops looking at Dataverse roles.
-
-test('AB#6686424: a terminal 401 names the identity whose token was refused', () => {
- const { ensureOk } = require('../lib/dataverse-auth.js');
- assert.throws(
- () => ensureOk({ status: 401, data: { error: { message: 'Unauthorized' } } }, 'read EntityDefinitions',
- { azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbb-tenant' }) }),
- (e) => {
- assert.match(e.message, /other@fabrikam\.onmicrosoft\.com/, 'names the account');
- assert.match(e.message, /bbbb-tenant/, 'names the tenant');
- assert.match(e.message, /az login/, 'names the remediation');
- return true;
- }
- );
-});
-
-test('AB#6686424: a NON-401 error is left exactly as it was', () => {
- // A 403 is a real privilege problem and a 400 is a bad request; attaching identity advice to
- // either would send the reader to `az login` for something az cannot fix.
- const { ensureOk } = require('../lib/dataverse-auth.js');
- for (const status of [400, 403, 404, 500]) {
- assert.throws(
- () => ensureOk({ status, data: { error: { message: 'boom' } } }, 'ctx', { azIdentity: () => ({ user: 'x', tenantId: 'y' }) }),
- (e) => {
- assert.doesNotMatch(e.message, /az login/, `${status} must not be blamed on the az identity`);
- assert.match(e.message, /boom/);
- return true;
- }
- );
- }
-});
-
-test('AB#6686424: an unreadable identity still produces a useful 401, never a crash', () => {
- const { ensureOk } = require('../lib/dataverse-auth.js');
- assert.throws(
- () => ensureOk({ status: 401, data: {} }, 'ctx', { azIdentity: () => { throw new Error('az gone'); } }),
- (e) => {
- assert.match(e.message, /401/);
- assert.match(e.message, /az login/);
- return true;
- }
- );
-});
-
-test('AB#6686424: a 2xx is returned untouched (no identity read on the happy path)', () => {
- const { ensureOk } = require('../lib/dataverse-auth.js');
- let called = 0;
- const res = { status: 200, data: { ok: 1 } };
- assert.strictEqual(ensureOk(res, 'ctx', { azIdentity: () => { called++; return null; } }), res);
- assert.strictEqual(called, 0, 'must not shell out to az on every successful call');
-});
-
-test('AB#6686424: a bodyless error does not print "null" as the server message', () => {
- // Found by LIVE verification, not by the unit fixtures: a real Dataverse 401 often carries no body
- // at all, so `data` is null and the message read "HTTP 401 — null". Every unit fixture supplied a
- // message, so nothing caught it.
- const { ensureOk } = require('../lib/dataverse-auth.js');
- for (const [status, data] of [[401, null], [500, null], [404, undefined]]) {
- assert.throws(
- () => ensureOk({ status, data }, 'ctx', { azIdentity: () => null }),
- (e) => {
- assert.doesNotMatch(e.message, /— null|— undefined/, `${status} must not print a bare null: ${e.message}`);
- assert.match(e.message, /no response body/);
- return true;
- }
- );
- }
-});
-
-// --- environment URLs: only a Dataverse https origin is ever used -------------------------------
-// The origin is the `--resource` a token is requested for, the base of every request URL, and the
-// only place a token is sent. Anything else is refused before a process starts or a request is sent.
-test('dataverseOrigin accepts a Dataverse origin in any cloud and returns it canonically', () => {
- const { dataverseOrigin } = require('../lib/dataverse-auth.js');
- for (const [input, expected] of [
- ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com'],
- ['https://Contoso.CRM.Dynamics.com/', 'https://contoso.crm.dynamics.com'],
- [' https://contoso.crm4.dynamics.com// ', 'https://contoso.crm4.dynamics.com'],
- ['HTTPS://contoso.api.crm.dynamics.com', 'https://contoso.api.crm.dynamics.com'],
- ['https://contoso.crmtest.dynamics.com', 'https://contoso.crmtest.dynamics.com'],
- ['https://contoso.crm.microsoftdynamics.us', 'https://contoso.crm.microsoftdynamics.us'],
- ['https://contoso.crm.appsplatform.us', 'https://contoso.crm.appsplatform.us'],
- ['https://contoso.crm.dynamics.cn', 'https://contoso.crm.dynamics.cn'],
- ]) {
- assert.equal(dataverseOrigin(input), expected, input);
- }
-});
-
-test('dataverseOrigin refuses anything that is not exactly an https Dataverse origin', () => {
- const { dataverseOrigin } = require('../lib/dataverse-auth.js');
- for (const input of [
- 'http://contoso.crm.dynamics.com',
- 'https://contoso.crm.dynamics.com/main.aspx',
- 'https://contoso.crm.dynamics.com/?x=1',
- 'https://contoso.crm.dynamics.com/#x',
- 'https://contoso.crm.dynamics.com:443',
- 'https://[email protected]',
- 'https://contoso.crm.dynamics.com/&whoami',
- 'https://contoso.crm.dynamics.com&whoami',
- 'https://contoso.crm.dynamics.com\\x',
- 'https://contoso.crm.dynamics.com%20',
- 'https://contoso.crm.dynamics.com\nx',
- 'https://contoso.example.com',
- 'https://crm.dynamics.com',
- 'https://contoso.crm.dynamics.com.example.com',
- '',
- null,
- undefined,
- ]) {
- assert.equal(dataverseOrigin(input), null, JSON.stringify(input));
- }
-});
-
-test('a non-origin environment URL starts no Azure CLI process and sends no request', async () => {
- const { getAuthToken, getAuthTokenAsync, dataverseRequest } = require('../lib/dataverse-auth.js');
- let started = 0;
- const exec = () => { started += 1; return 'TOK\n'; };
- const execFile = (_f, _a, _o, cb) => { started += 1; cb(null, 'TOK\n'); };
- const bad = 'https://contoso.crm.dynamics.com/&whoami';
- assert.equal(getAuthToken(bad, { exec, fresh: true }), null);
- assert.equal(await getAuthTokenAsync(bad, { execFile, fresh: true }), null);
- let sent = 0;
- await assert.rejects(
- dataverseRequest(bad, 'GET', 'WhoAmI', null, { getToken: exec, request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; } }),
- /is not a Dataverse environment URL/
- );
- assert.equal(started, 0);
- assert.equal(sent, 0);
-});
-
-test('dataverseRequest builds the request on the validated origin and requests the token for it', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- let resource;
- let url;
- await dataverseRequest('https://Contoso.crm.dynamics.com/', 'GET', 'WhoAmI', null, {
- getToken: (r) => { resource = r; return 'TOK'; },
- request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },
- });
- assert.equal(resource, 'https://contoso.crm.dynamics.com');
- assert.equal(url, 'https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');
-});
-
-test('a path that leaves the Web API root is refused before a token is read or a request sent', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- // [path, where it resolves]. Each spelling reached an endpoint outside /api/data/v9.2/ on a live
- // environment with the released code. The client resolves the first seven itself; the server decodes
- // %2F / %5C and resolves the next three. The last one leaves the root as the client sends it, although
- // the server's further decoding would bring it back: the client reading is checked on its own too.
- const escapes = [
- ['../v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
- ['../../../XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
- ['%2e%2e/%2E%2e/%2e%2E/XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
- ['.%2e/v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
- ['..\\..\\..\\XRMServices\\2011\\Organization.svc\\web', '/XRMServices/2011/Organization.svc/web'],
- ['a%2Fb/../../x', '/api/data/x'],
- ['..', '/api/data/'],
- ['..%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
- ['..%5cv9.0%5cWhoAmI', '/api/data/v9.0/WhoAmI'],
- ['.%2e%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
- ['../x%2F..%2Fv9.2%2FWhoAmI', '/api/data/x%2F..%2Fv9.2%2FWhoAmI'],
- ];
- for (const [apiPath, resolved] of escapes) {
- let tokens = 0;
- let sent = 0;
- await assert.rejects(
- dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
- getToken: () => { tokens += 1; return 'TOK'; },
- request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; },
- }),
- (e) => /leaves the Dataverse Web API root \/api\/data\/v9\.2\//.test(e.message) && e.message.includes(`resolves to '${resolved}'`),
- apiPath
- );
- assert.equal(tokens, 0, apiPath);
- assert.equal(sent, 0, apiPath);
- }
- await assert.rejects(
- dataverseRequest('https://contoso.crm.dynamics.com', 'GET', undefined, null, { getToken: () => 'TOK', request: async () => ({ statusCode: 200, body: '{}' }) }),
- /must be text \(got undefined\)/
- );
-});
-
-test('a path inside the Web API root is sent exactly as before', async () => {
- const { dataverseRequest } = require('../lib/dataverse-auth.js');
- const accepted = [
- 'WhoAmI',
- "EntityDefinitions(LogicalName='account')/Attributes?$select=LogicalName",
- '$batch',
- // Dataverse answers /api/data/v9.2//WhoAmI and WhoAmI%2F like WhoAmI (measured).
- '/WhoAmI',
- 'WhoAmI%2F',
- // Decoded by the server, this resolves back inside the root.
- 'x/..%2F..%2Fv9.2%2FWhoAmI',
- // Dot segments inside a query are data, not a path.
- "accounts?$filter=name eq '../../x'",
- // An absolute URL is only text under the root: it cannot change where the request goes.
- 'https://example.com/x',
- ];
- for (const apiPath of accepted) {
- let url;
- await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
- getToken: () => 'TOK',
- request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },
- });
- assert.equal(url, `https://contoso.crm.dynamics.com/api/data/v9.2/${apiPath}`, apiPath);
- }
-});
-
-test('createAzHttpClient requests its token for the validated origin, never the text it was given', async () => {
- const { createAzHttpClient } = require('../lib/sdk-http-client.js');
- assert.throws(() => createAzHttpClient('https://contoso.crm.dynamics.com/&whoami', { getToken: () => 'TOK' }), /Invalid Dataverse org URL/);
- let resource;
- const http = createAzHttpClient('https://CONTOSO.crm.dynamics.com/', {
- getToken: (r) => { resource = r; return 'TOK'; },
- request: async () => ({ statusCode: 200, body: '{}' }),
- });
- await http.get('https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');
- assert.equal(resource, 'https://contoso.crm.dynamics.com');
-});
-
-test('azIdentity reads the identity through the process runner seam', () => {
- const { azIdentity } = require('../lib/dataverse-auth.js');
- const seen = [];
- const id = azIdentity({ exec: (cmd, args) => { seen.push([cmd, ...args].join(' ')); return '{"user":"[email protected]","tenantId":"t"}'; } });
- assert.deepEqual(id, { user: '[email protected]', tenantId: 't' });
- assert.deepEqual(seen, ['az account show --query {user:user.name,tenantId:tenantId} -o json']);
-});
-
-// End to end on Windows, where the Azure CLI is a batch shim: the entry-point CLIs refuse an
-// environment URL that is not an origin, and nothing but the (fake) Azure CLI ever runs.
-test('the Dataverse entry points refuse a non-origin URL before anything runs (real CLI, Windows)', { skip: process.platform !== 'win32' }, () => {
- const { spawnSync } = require('node:child_process');
- const fs = require('node:fs');
- const os = require('node:os');
- const path = require('node:path');
- const scripts = path.join(__dirname, '..');
- const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-origin-e2e-'));
- try {
- const bin = path.join(work, 'bin');
- fs.mkdirSync(bin);
- const azLog = path.join(work, 'az-calls.txt');
- fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo %*>>"${azLog}"\r\n@exit /b 1\r\n`, 'utf8');
- const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };
- const url = 'https://contoso.crm.dynamics.com/&md,MARKER';
- const runs = [
- spawnSync(process.execPath, [path.join(scripts, 'dataverse-request.js'), url, 'GET', 'WhoAmI'], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),
- spawnSync(process.execPath, [path.join(scripts, 'check-auth.js'), '--env', url], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),
- ];
- assert.equal(fs.existsSync(path.join(work, 'MARKER')), false, 'no second command ran');
- assert.match(runs[0].stderr, /is not a Dataverse environment URL/);
- const logged = fs.existsSync(azLog) ? fs.readFileSync(azLog, 'utf8') : '';
- assert.doesNotMatch(logged, /MARKER/, `the URL never reached the Azure CLI: ${logged}`);
- } finally {
- fs.rmSync(work, { recursive: true, force: true });
- }
-});
-
-// Cancelling the token read, end to end on a real cmd.exe. `az.cmd` runs the Azure CLI's program as cmd.exe's CHILD, so ending only
-// the cmd.exe Node started (what an AbortSignal handed to execFile does) leaves that program running after the process that
-// cancelled it has exited. Here the "CLI" is a node program that records its pid and idles.
-test('aborting a real getAuthTokenAsync read ends the program the az shim started too, so nothing is left running (real cmd.exe, Windows)', { skip: process.platform !== 'win32' }, () => {
- const { spawnSync } = require('node:child_process');
- const fs = require('node:fs');
- const os = require('node:os');
- const path = require('node:path');
- const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-abort-e2e-'));
- const pidFile = path.join(work, 'az-program.pid');
- const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
- let program = 0;
- try {
- const bin = path.join(work, 'bin');
- fs.mkdirSync(bin);
- // The timer is a backstop: whatever a failing run leaves behind ends by itself.
- fs.writeFileSync(path.join(bin, 'idle.js'), `require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setTimeout(() => process.exit(0), 120000);\n`, 'utf8');
- fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo off\r\n"${process.execPath}" "${path.join(bin, 'idle.js')}" %*\r\n`, 'utf8');
- const url = 'https://contoso.crm.dynamics.com';
- const driver = `
- const fs = require('fs');
- const { getAuthTokenAsync, tokenFailureKind } = require(${JSON.stringify(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'))});
- (async () => {
- const controller = new AbortController();
- const read = getAuthTokenAsync(${JSON.stringify(url)}, { signal: controller.signal });
- for (let i = 0; i < 150 && !fs.existsSync(${JSON.stringify(pidFile)}); i += 1) await new Promise((resolve) => setTimeout(resolve, 100));
- controller.abort();
- process.stdout.write(JSON.stringify({ token: await read, failure: tokenFailureKind(${JSON.stringify(url)}) }));
- })();`;
- const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };
- const run = spawnSync(process.execPath, ['-e', driver], { cwd: work, env, encoding: 'utf8', timeout: 60000 });
- assert.equal(run.status, 0, `${run.stdout}${run.stderr}`);
- assert.deepEqual(JSON.parse(run.stdout), { token: null, failure: null }, 'a cancelled read is null and leaves no failure behind');
- program = Number(fs.readFileSync(pidFile, 'utf8'));
- assert.ok(program > 0, 'the az shim started its program');
- // The tree was ended before the reader that cancelled it exited; allow the OS a moment to finish reaping it.
- const until = Date.now() + 5000;
- while (alive(program) && Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
- assert.equal(alive(program), false, 'the program the az shim started is no longer running');
- } finally {
- // Whatever the assertions above found, never leave the program the shim started running.
- if (!program && fs.existsSync(pidFile)) program = Number(fs.readFileSync(pidFile, 'utf8')) || 0;
- if (program && alive(program)) { try { process.kill(program); } catch { /* already gone */ } }
- fs.rmSync(work, { recursive: true, force: true });
- }
-});
-
-// --- emitResult: `ascii` keeps a script's stdout pure ASCII ----------------------------------------------------
-//
-// An agent reads a script's stdout off a console. Windows PowerShell 5.1 decodes a child's output with the OEM code
-// page, so UTF-8 bytes of an em dash arrive as three other characters; written as a \uXXXX escape the same JSON
-// survives any code page. Only a script that asks for it changes — every other caller keeps the raw text.
-test('emitResult with `ascii` writes every character above U+007E as a \\uXXXX escape, in either outcome, and leaves stderr as written', () => {
- const { spawnSync } = require('node:child_process');
- const path = require('node:path');
- const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
- // An em dash and an accented letter (BMP), an emoji (a surrogate pair, as JSON writes a character outside the BMP),
- // DEL, and the characters JSON.stringify already escapes.
- const message = 'Norwegian Bokm\u00e5l \u2014 \ud83d\ude00 \u007f "quoted" \\ back\nline';
- for (const [ok, status] of [[true, 0], [false, 1]]) {
- const payload = { ok, error: message, list: ['1025 ar-SA \u2014 RTL: Yes'] };
- const code = `
- const { emitResult } = require(${JSON.stringify(libPath)});
- emitResult(${ok}, ${JSON.stringify(payload)}, { ascii: true });
- `;
- const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
- assert.equal(res.status, status, `ok=${ok}: ${res.stderr}`);
- assert.match(res.stdout, /^[\x00-\x7e\r\n]*$/, `ok=${ok}: pure ASCII`);
- assert.ok(res.stdout.includes('\\u2014') && res.stdout.includes('\\u00e5') && res.stdout.includes('\\ud83d\\ude00') && res.stdout.includes('\\u007f'), res.stdout);
- assert.deepEqual(JSON.parse(res.stdout.trim()), payload, `ok=${ok}: the same document, decoded`);
- if (!ok) assert.equal(res.stderr.trim(), message.trim(), 'stderr is for people and is not escaped');
- }
-});
-
-test('emitResult without `ascii` still writes the raw text: no other script\u2019s output changes', () => {
- const { spawnSync } = require('node:child_process');
- const path = require('node:path');
- const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
- const code = `
- const { emitResult } = require(${JSON.stringify(libPath)});
- emitResult(true, { s: '1025 ar-SA \\u2014 RTL: Yes' });
- `;
- const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
- assert.equal(res.status, 0, res.stderr);
- assert.ok(res.stdout.includes('\u2014') && !res.stdout.includes('\\u2014'), res.stdout);
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const http = require('node:http');
+
+const { parseArgs, readJsonArg, label, requiredLevel } = require('../lib/dataverse-auth');
+
+test('parseArgs: positional only', () => {
+ const { positional, flags } = parseArgs(['a', 'b', 'c']);
+ assert.deepEqual(positional, ['a', 'b', 'c']);
+ assert.deepEqual(flags, {});
+});
+
+test('parseArgs: mix of positional and flags', () => {
+ const { positional, flags } = parseArgs(['a', '--foo', 'bar', 'b', '--baz']);
+ assert.deepEqual(positional, ['a', 'b']);
+ assert.deepEqual(flags, { foo: 'bar', baz: true });
+});
+
+test('parseArgs: bool flag followed by another flag treats first as bool', () => {
+ const { flags } = parseArgs(['--x', '--y', '1']);
+ assert.deepEqual(flags, { x: true, y: '1' });
+});
+
+test('parseArgs: repeated flag overwrites', () => {
+ const { flags } = parseArgs(['--foo', '1', '--foo', '2']);
+ assert.equal(flags.foo, '2');
+});
+
+test('parseArgs: --key=value form', () => {
+ const { positional, flags } = parseArgs(['x', '--foo=bar', '--baz=qux', 'y']);
+ assert.deepEqual(positional, ['x', 'y']);
+ assert.deepEqual(flags, { foo: 'bar', baz: 'qux' });
+});
+
+test('parseArgs: --key=value with empty value', () => {
+ const { flags } = parseArgs(['--foo=']);
+ assert.equal(flags.foo, '');
+});
+
+test('parseArgs: --key=value preserves additional = signs in value', () => {
+ const { flags } = parseArgs(['--query=a=b=c']);
+ assert.equal(flags.query, 'a=b=c');
+});
+
+test('parseArgs: mixed --key=value and --key value forms', () => {
+ const { flags } = parseArgs(['--foo=bar', '--baz', 'qux']);
+ assert.deepEqual(flags, { foo: 'bar', baz: 'qux' });
+});
+
+test('readJsonArg: inline JSON', () => {
+ assert.deepEqual(readJsonArg('{"a":1}'), { a: 1 });
+});
+
+test('readJsonArg: file path with @ prefix', () => {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const os = require('node:os');
+ const tmp = path.join(os.tmpdir(), `dv-auth-test-${Date.now()}.json`);
+ fs.writeFileSync(tmp, JSON.stringify({ from: 'file' }));
+ try {
+ assert.deepEqual(readJsonArg('@' + tmp), { from: 'file' });
+ } finally {
+ fs.unlinkSync(tmp);
+ }
+});
+
+test('readJsonArg: null and undefined pass through', () => {
+ assert.equal(readJsonArg(null), null);
+ assert.equal(readJsonArg(undefined), null);
+});
+
+test('label: builds Dataverse verbose Label object', () => {
+ const out = label('Hello');
+ assert.equal(out['@odata.type'], 'Microsoft.Dynamics.CRM.Label');
+ assert.equal(out.LocalizedLabels.length, 1);
+ assert.equal(out.LocalizedLabels[0].Label, 'Hello');
+ assert.equal(out.LocalizedLabels[0].LanguageCode, 1033);
+});
+
+test('label: respects custom language code', () => {
+ const out = label('Bonjour', 1036);
+ assert.equal(out.LocalizedLabels[0].LanguageCode, 1036);
+});
+
+test('requiredLevel: defaults to None and is mutable', () => {
+ const out = requiredLevel();
+ assert.equal(out.Value, 'None');
+ assert.equal(out.CanBeChanged, true);
+});
+
+test('requiredLevel: respects argument', () => {
+ assert.equal(requiredLevel('ApplicationRequired').Value, 'ApplicationRequired');
+});
+
+test('makeRequest preserves UTF-8 characters split across response chunks', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const body = JSON.stringify({ city: '東京', emoji: '😀', cafe: 'Café' });
+ const bodyBytes = Buffer.from(body, 'utf8');
+ const server = http.createServer((req, res) => {
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ if (req.url === '/split') {
+ for (let i = 0; i < bodyBytes.length; i += 1) {
+ res.write(bodyBytes.subarray(i, i + 1));
+ }
+ res.end();
+ return;
+ }
+ if (req.url === '/whole') {
+ res.end(bodyBytes);
+ return;
+ }
+ res.statusCode = 404;
+ res.end('not found');
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ try {
+ const whole = await makeRequest({ url: `http://127.0.0.1:${port}/whole` });
+ const split = await makeRequest({ url: `http://127.0.0.1:${port}/split` });
+ assert.equal(whole.body, body);
+ assert.equal(split.body, body);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+// A file's content is bytes: a generative page's row, an image. Decoded as UTF-8, bytes that are not valid UTF-8 come back changed (each bad byte becomes
+// U+FFFD), so `binary` hands back the Buffer as it arrived — split across chunks or not — and a request body that is a Buffer goes out verbatim.
+test('makeRequest with `binary` returns the body as the bytes that arrived, never decoded; a Buffer body is sent as it is', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0xfe, 0x00, 0xc3, 0x28, 0xe2, 0x82]);
+ let received = null;
+ const server = http.createServer((req, res) => {
+ const chunks = [];
+ req.on('data', (c) => chunks.push(c));
+ req.on('end', () => {
+ if (req.method === 'PATCH') received = Buffer.concat(chunks);
+ res.setHeader('Content-Type', 'application/octet-stream');
+ for (let i = 0; i < bytes.length; i += 1) res.write(bytes.subarray(i, i + 1));
+ res.end();
+ });
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ try {
+ const got = await makeRequest({ url: `http://127.0.0.1:${port}/x/$value`, binary: true });
+ assert.ok(Buffer.isBuffer(got.body), 'a Buffer');
+ assert.ok(got.body.equals(bytes), 'byte for byte');
+ const decoded = await makeRequest({ url: `http://127.0.0.1:${port}/x/$value` });
+ assert.strictEqual(typeof decoded.body, 'string', 'without `binary`, decoded as before');
+ assert.notStrictEqual(Buffer.from(decoded.body, 'utf8').length, bytes.length, 'the control: decoding changes bytes that are not UTF-8');
+ await makeRequest({ url: `http://127.0.0.1:${port}/x`, method: 'PATCH', body: bytes, headers: { 'Content-Length': String(bytes.length) }, binary: true });
+ assert.ok(received && received.equals(bytes), 'the body went out byte for byte');
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+test('makeRequest settles with an error when the connection closes mid-response', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ // Headers and part of the body arrive, then the socket closes: no 'end', and the socket timeout
+ // cannot fire on a closed socket. The promise must still settle through the { error } contract.
+ const server = http.createServer((req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
+ res.write('{"value":[');
+ setTimeout(() => res.socket.destroy(), 20);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ try {
+ const settled = await Promise.race([
+ makeRequest({ url: `http://127.0.0.1:${port}/cut`, timeout: 60000 }),
+ new Promise((resolve) => setTimeout(() => resolve('still pending'), 2000)),
+ ]);
+ assert.notEqual(settled, 'still pending', 'a truncated response must not leave the request pending');
+ assert.match(settled.error, /before (it|the response) completed/);
+ assert.strictEqual(settled.incompleteResponse, true, 'the server answered before the body was cut off');
+ assert.strictEqual(settled.statusCode, 200);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+test('makeRequest marks a timeout after the headers arrived as an incomplete response', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ // The server answers, sends part of the body, then stalls. The request timeout fires on the
+ // request, not the response, but the answer had arrived: a POST may already have been applied.
+ const sockets = new Set();
+ const server = http.createServer((req, res) => {
+ res.writeHead(201, { 'Content-Type': 'application/json', 'Content-Length': '100' });
+ res.write('{"id":');
+ });
+ server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ try {
+ const answered = await makeRequest({ url: `http://127.0.0.1:${port}/stall`, method: 'POST', body: '{}', timeout: 150 });
+ assert.strictEqual(answered.incompleteResponse, true);
+ assert.strictEqual(answered.statusCode, 201);
+ assert.match(answered.error, /timed out before the response completed/);
+ } finally {
+ for (const s of sockets) s.destroy();
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+test('makeRequest keeps a timeout with no answer as a plain request failure', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const sockets = new Set();
+ const server = http.createServer(() => { /* never answers */ });
+ server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ try {
+ const silent = await makeRequest({ url: `http://127.0.0.1:${port}/silent`, method: 'POST', body: '{}', timeout: 150 });
+ assert.deepStrictEqual(silent, { error: 'Request timed out' });
+ } finally {
+ for (const s of sockets) s.destroy();
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+// A request that fails comes with Node's own CODE beside the message. The message cannot say what the failure was — a certificate that does not verify quotes the host and the certificate's names, and a name can spell anything — so a
+// caller that decides whether the request is worth sending again (lib/sdk-http-client.js) reads the code. Only what Node raised for the request has one: the failures this module words itself have none.
+test('makeRequest reports Node\'s own error code beside the message of a request that failed — a refused connection, and a connection reset before any answer', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const probe = http.createServer();
+ await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve));
+ const { port: closedPort } = probe.address();
+ await new Promise((resolve) => probe.close(resolve));
+ const refused = await makeRequest({ url: `http://127.0.0.1:${closedPort}/x` });
+ assert.strictEqual(refused.code, 'ECONNREFUSED');
+ assert.match(refused.error, /ECONNREFUSED/);
+ assert.deepStrictEqual(Object.keys(refused).sort(), ['code', 'error'], 'the message and the code, and nothing that says the server answered');
+
+ const resetting = http.createServer((req) => req.socket.destroy());
+ await new Promise((resolve) => resetting.listen(0, '127.0.0.1', resolve));
+ try {
+ const reset = await makeRequest({ url: `http://127.0.0.1:${resetting.address().port}/x`, method: 'POST', body: '{}' });
+ assert.strictEqual(reset.code, 'ECONNRESET');
+ assert.match(reset.error, /socket hang up|ECONNRESET/);
+ assert.strictEqual(reset.incompleteResponse, undefined, 'no answer had arrived');
+ } finally {
+ await new Promise((resolve) => resetting.close(resolve));
+ }
+});
+
+test('makeRequest reports the code of a certificate that does not verify — Node raises it for the request, whatever the message quotes', async (t) => {
+ const https = require('node:https');
+ const { EventEmitter } = require('node:events');
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const failure = Object.assign(
+ new Error("Hostname/IP does not match certificate's altnames: Host: contoso.crm.dynamics.com. is not in the cert's altnames: DNS:ECONNRESET.example.com"),
+ { code: 'ERR_TLS_CERT_ALTNAME_INVALID' },
+ );
+ let raised = failure;
+ t.mock.method(https, 'request', () => {
+ const req = new EventEmitter();
+ req.write = () => {};
+ req.end = () => setImmediate(() => req.emit('error', raised));
+ req.destroy = () => {};
+ return req;
+ });
+ assert.deepStrictEqual(await makeRequest({ url: 'https://contoso.crm.dynamics.com/api/data/v9.2/x' }), { error: failure.message, code: 'ERR_TLS_CERT_ALTNAME_INVALID' });
+ // An error Node gave no code for is reported as it always was: the message alone.
+ raised = new Error('something Node did not give a code for');
+ assert.deepStrictEqual(await makeRequest({ url: 'https://contoso.crm.dynamics.com/api/data/v9.2/x' }), { error: 'something Node did not give a code for' });
+});
+
+test('the failures makeRequest words itself — a connection closed mid-response — carry no code: they are read by their words', async () => {
+ const { makeRequest } = require('../lib/dataverse-auth.js');
+ const server = http.createServer((req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
+ res.write('{"value":[');
+ setTimeout(() => res.socket.destroy(), 20);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const cut = await makeRequest({ url: `http://127.0.0.1:${server.address().port}/cut` });
+ assert.match(cut.error, /before (it|the response) completed/);
+ assert.strictEqual(cut.incompleteResponse, true);
+ assert.ok(!('code' in cut), 'the words are this module\'s own, and no code is made up for them');
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+test('dataverseRequest does not replay a POST whose response was cut off, but retries a GET', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const cut = (statusCode) => ({ error: 'Connection closed before the response completed', incompleteResponse: true, statusCode });
+ let posts = 0;
+ await assert.rejects(
+ dataverseRequest('https://contoso.crm.dynamics.com', 'POST', 'accounts', { name: 'A' }, {
+ getToken: () => 'TOK', request: async () => { posts += 1; return cut(201); },
+ }),
+ /already answered 201, so this POST may have been applied; it was not re-sent/,
+ );
+ assert.strictEqual(posts, 1);
+ let gets = 0;
+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'accounts', null, {
+ getToken: () => 'TOK',
+ request: async () => { gets += 1; return gets === 1 ? cut(200) : { statusCode: 200, body: '{"value":[]}' }; },
+ });
+ assert.strictEqual(res.status, 200);
+ assert.strictEqual(gets, 2);
+});
+
+// --- the access token is not in what a call that did not succeed reports ---------------------------------------------------------------------------
+// `dataverseRequest` hands back what the service answered — `{ status, data }` — and a caller that fails prints it (`ensureOk` quotes `data.error.message`; list-connections.js reads the connection
+// references with it, and prints what failed). An authorization layer, or a gateway, that rejects a token may repeat it — whole, or one part of it — in the body or in a header, and a transport failure's
+// text can repeat the request it was sending. So an answer that is not a success is handed back with the token taken out of it, and so is the text of a transport failure, by the scrubber the plugin's
+// Dataverse HttpClient uses (lib/sdk-http-client.js: one scrubber). A SUCCESS is the caller's data and is never touched, whatever it holds.
+const ECHOED = ['syntheticHeaderPartOfTheEchoedToken', 'syntheticPayloadPartOfTheEchoedToken', 'syntheticSignaturePartOfTheEchoedToken'].join('.');
+const ORG_URL = 'https://contoso.crm.dynamics.com';
+
+test('dataverseRequest takes the token out of the answer to a call that did not succeed — the body, whole or in a part, whatever its shape — and leaves the status and the typed code', async () => {
+ const { dataverseRequest, ensureOk } = require('../lib/dataverse-auth.js');
+ const [header, payload] = ECHOED.split('.');
+ const answers = [
+ [400, JSON.stringify({ error: { code: '0x80048d19', message: `Rejected bearer ${ECHOED}` } }), (res) => { assert.equal(res.data.error.message, 'Rejected bearer <token>'); assert.equal(res.data.error.code, '0x80048d19'); }],
+ [403, JSON.stringify({ error: { message: `the claim ${payload} is not valid`, details: [`and ${header}`] } }), (res) => { assert.equal(res.data.error.message, 'the claim <token> is not valid'); assert.deepEqual(res.data.error.details, ['and <token>']); }],
+ [410, `<html>Gone: Authorization: Bearer ${ECHOED}</html>`, (res) => assert.equal(res.data, '<html>Gone: Authorization: Bearer <token></html>')],
+ [404, JSON.stringify({ [`key ${ECHOED}`]: 1 }), (res) => assert.deepEqual(res.data, { 'key <token>': 1 })],
+ ];
+ for (const [statusCode, body, check] of answers) {
+ const res = await dataverseRequest(ORG_URL, 'GET', 'connectionreferences', null, { getToken: () => ECHOED, request: async () => ({ statusCode, body }) });
+ assert.equal(res.status, statusCode);
+ check(res);
+ assert.ok(!JSON.stringify(res).includes(ECHOED) && !JSON.stringify(res).includes(payload), `${statusCode}: no part of the token is left`);
+ }
+ // What a caller prints is what it quotes of the answer: the message of the failure it raises holds no token either.
+ const refused = await dataverseRequest(ORG_URL, 'GET', 'connectionreferences', null, { getToken: () => ECHOED, request: async () => ({ statusCode: 403, body: JSON.stringify({ error: { message: `Rejected bearer ${ECHOED}` } }) }) });
+ assert.throws(() => ensureOk(refused, 'List connection references'), (error) => error.message === 'List connection references failed: HTTP 403 — Rejected bearer <token>');
+});
+
+test('dataverseRequest takes the token out of an answer\u2019s headers when it hands them back — and out of the answer to the request that was sent with the token a 401 replaced', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const refreshed = 'syntheticRefreshedTokenOfTheSecondRequest0123456789';
+ const reads = [];
+ const sent = [];
+ const answers = [
+ { statusCode: 401, body: JSON.stringify({ error: { message: `token ${ECHOED} expired` } }), headers: {} },
+ { statusCode: 403, body: JSON.stringify({ error: { message: `old ${ECHOED} new ${refreshed}` } }), headers: { 'www-authenticate': `Bearer error="invalid_token", error_description="${refreshed}"`, 'x-request-id': 'abc' } },
+ ];
+ const res = await dataverseRequest(ORG_URL, 'GET', 'WhoAmI', null, {
+ includeHeaders: true,
+ getToken: (url, options) => { reads.push(options); return options && options.fresh ? refreshed : ECHOED; },
+ request: async (options) => { sent.push(options.headers.Authorization); return answers[sent.length - 1]; },
+ });
+ assert.deepEqual(sent, [`Bearer ${ECHOED}`, `Bearer ${refreshed}`], 'the first token, refused, and the one that replaced it');
+ assert.equal(res.status, 403);
+ assert.equal(res.data.error.message, 'old <token> new <token>', 'both tokens the call sent are taken out');
+ assert.deepEqual(res.headers, { 'www-authenticate': 'Bearer error="invalid_token", error_description="<token>"', 'x-request-id': 'abc' });
+});
+
+test('dataverseRequest takes the token out of the text of a transport failure — a GET that never got an answer, and a POST whose answer was cut off', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ await assert.rejects(
+ dataverseRequest(ORG_URL, 'GET', 'WhoAmI', null, { getToken: () => ECHOED, request: async () => ({ error: `socket hang up while sending Authorization: Bearer ${ECHOED}` }) }),
+ (error) => error.message === 'Request failed: socket hang up while sending Authorization: Bearer <token>',
+ );
+ await assert.rejects(
+ dataverseRequest(ORG_URL, 'POST', 'accounts', { name: 'A' }, { getToken: () => ECHOED, request: async () => ({ error: `reset (${ECHOED.split('.')[1]})`, incompleteResponse: true, statusCode: 201 }) }),
+ (error) => error.message === 'Request failed: reset (<token>) — the server had already answered 201, so this POST may have been applied; it was not re-sent. Check the result before running it again.',
+ );
+});
+
+test('dataverseRequest never alters a success — its data and its headers come back exactly as they arrived, token text and all — and a value too short to be a token is never taken out of anything', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ // A record whose field happens to hold the token, a text body, and a header that repeats it: successes are the caller's data.
+ const record = JSON.stringify({ value: [{ name: ECHOED, note: ECHOED.split('.')[1] }] });
+ const ok = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { includeHeaders: true, getToken: () => ECHOED, request: async () => ({ statusCode: 200, body: record, headers: { 'x-echo': ECHOED } }) });
+ assert.deepEqual(ok.data, JSON.parse(record));
+ assert.deepEqual(ok.headers, { 'x-echo': ECHOED });
+ const text = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { getToken: () => ECHOED, request: async () => ({ statusCode: 200, body: `plain ${ECHOED}` }) });
+ assert.equal(text.data, `plain ${ECHOED}`);
+ // The floor is the Dataverse client's: a token shorter than 16 characters is no access token (the tests' own stand-ins are), and taking it out would blank every place a message has the same letters.
+ const short = await dataverseRequest(ORG_URL, 'GET', 'accounts', null, { getToken: () => 'TOK', request: async () => ({ statusCode: 400, body: JSON.stringify({ error: { message: 'TOKEN TOK' } }) }) });
+ assert.equal(short.data.error.message, 'TOKEN TOK');
+});
+
+test('getAuthToken reuses a non-empty token per normalized resource URL', () => {
+ const { getAuthToken } = require('../lib/dataverse-auth.js');
+ const calls = [];
+ const exec = (_file, args) => {
+ calls.push(args[args.indexOf('--resource') + 1]);
+ return 'TOK\n';
+ };
+ const oldPath = process.env.PATH;
+ process.env.PATH = '';
+ try {
+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com/', { exec, fresh: true }), 'TOK');
+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'TOK');
+ assert.equal(getAuthToken('https://fabrikam.crm.dynamics.com', { exec, fresh: true }), 'TOK');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ assert.deepEqual(calls, ['https://contoso.crm.dynamics.com', 'https://fabrikam.crm.dynamics.com']);
+});
+
+test('peekAuthToken answers only what the memo holds, and never starts the Azure CLI', () => {
+ const { getAuthToken, peekAuthToken } = require('../lib/dataverse-auth.js');
+ // A host no other test in this process reads, so the memo cannot already hold it.
+ const env = 'https://contoso-peekprobe.crm.dynamics.com';
+ const oldPath = process.env.PATH;
+ process.env.PATH = ''; // an Azure CLI start here would fail the read, not succeed silently
+ try {
+ assert.equal(peekAuthToken(env), null, 'nothing read yet: null, and no process');
+ assert.equal(peekAuthToken('not a url'), null);
+ assert.equal(getAuthToken(env, { exec: () => 'PEEKED\n', fresh: true }), 'PEEKED');
+ assert.equal(peekAuthToken(`${env}/`), 'PEEKED', 'the memo, by normalized origin');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+});
+
+test('a fresh acquire bypasses the memo and replaces the token it holds', () => {
+ const { getAuthToken } = require('../lib/dataverse-auth.js');
+ const tokens = ['OLD\n', 'NEW\n'];
+ let calls = 0;
+ const exec = () => tokens[Math.min(calls++, tokens.length - 1)];
+ const url = 'https://fabrikam.crm4.dynamics.com';
+ const oldPath = process.env.PATH;
+ process.env.PATH = '';
+ try {
+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'OLD');
+ assert.equal(getAuthToken(url, { exec }), 'OLD', 'an ordinary repeat is served from the memo');
+ // A 401 refresh must not be handed the token the server just rejected.
+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'NEW');
+ assert.equal(getAuthToken(url, { exec }), 'NEW', 'the refreshed token replaces the memoized one');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ assert.equal(calls, 2);
+});
+test('getAuthToken does not cache a null token result', () => {
+ const { getAuthToken } = require('../lib/dataverse-auth.js');
+ let calls = 0;
+ const exec = () => {
+ calls += 1;
+ if (calls === 1) return '\n';
+ return 'TOK\n';
+ };
+ const oldPath = process.env.PATH;
+ process.env.PATH = '';
+ try {
+ assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec, fresh: true }), null);
+ assert.equal(getAuthToken('https://example.crm.dynamics.com', { exec }), 'TOK');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ assert.equal(calls, 2);
+});
+
+test('getAuthTokenAsync is served from a memo that getAuthToken filled', async () => {
+ // The other direction of sharing: check-auth warms the memo asynchronously, but a synchronous caller
+ // may have filled it first, and the async path must then not start the CLI again.
+ const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');
+ let asyncCalls = 0;
+ const exec = () => 'SYNC\n';
+ const execFile = (_file, _args, _opts, cb) => { asyncCalls += 1; setImmediate(() => cb(null, 'ASYNC\n')); };
+ const url = 'https://fabrikam.crm5.dynamics.com';
+ const oldPath = process.env.PATH;
+ process.env.PATH = '';
+ try {
+ assert.equal(getAuthToken(url, { exec, fresh: true }), 'SYNC');
+ assert.equal(await getAuthTokenAsync(url, { execFile }), 'SYNC');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ assert.equal(asyncCalls, 0);
+});
+test('getAuthTokenAsync shares the token memo with getAuthToken and honors fresh replacement', async () => {
+ const { getAuthToken, getAuthTokenAsync } = require('../lib/dataverse-auth.js');
+ const calls = [];
+ const exec = (_file, args) => {
+ calls.push(`sync:${args[args.indexOf('--resource') + 1]}`);
+ return 'SYNC\n';
+ };
+ const execFile = (_file, args, _opts, cb) => {
+ calls.push(`async:${args[args.indexOf('--resource') + 1]}`);
+ setImmediate(() => cb(null, calls.length === 1 ? 'ASYNC\n' : 'FRESH\n'));
+ };
+ const oldPath = process.env.PATH;
+ process.env.PATH = '';
+ try {
+ assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com/', { execFile, fresh: true }), 'ASYNC');
+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'ASYNC');
+ assert.equal(await getAuthTokenAsync('https://contoso.crm.dynamics.com', { execFile, fresh: true }), 'FRESH');
+ assert.equal(getAuthToken('https://contoso.crm.dynamics.com', { exec }), 'FRESH');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ assert.deepEqual(calls, [
+ 'async:https://contoso.crm.dynamics.com',
+ 'async:https://contoso.crm.dynamics.com',
+ ]);
+});
+
+test('cancelling a getAuthTokenAsync read ends the child\'s whole process tree, not just the wrapper Node starts, and is not a remembered failure', async () => {
+ // check-auth starts this read beside `az account show`; when the account verdict ends the run, the token child is
+ // cancelled. On Windows `az` is a batch shim under cmd.exe, so Node's own abort would end only that wrapper and leave az's
+ // Python process running after this one exits — the abort is handled here, through killProcessTree, and the signal is not
+ // handed to the child's start. The cancellation must also not be recorded as the Azure CLI failing: a later reader of
+ // tokenFailureKind would be told the CLI "failed" when it was simply told to stop.
+ const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
+ const url = 'https://contoso-abort.crm.dynamics.com';
+ const controller = new AbortController();
+ const child = { pid: 4242 };
+ const killed = [];
+ let seen;
+ let finish;
+ const execFile = (_file, _args, options, cb) => { seen = options; finish = cb; return child; };
+ const pending = getAuthTokenAsync(url, { execFile, signal: controller.signal, killTree: (c) => killed.push(c) });
+ assert.ok(!('signal' in seen), 'the signal is not handed to Node, whose own kill would reach only the cmd.exe wrapper');
+ assert.deepEqual(killed, [], 'nothing is ended before the abort');
+ controller.abort();
+ assert.deepEqual(killed, [child], 'the abort ends the child\'s process tree');
+ finish(Object.assign(new Error('Command failed'), { code: 1 }), '', '');
+ assert.equal(await pending, null);
+ assert.equal(tokenFailureKind(url), null, 'a cancelled read leaves no failure behind');
+});
+
+test('a getAuthTokenAsync read that already finished is not ended by a later abort, and one cancelled before it starts runs nothing', async () => {
+ const { getAuthTokenAsync } = require('../lib/dataverse-auth.js');
+ const controller = new AbortController();
+ const killed = [];
+ const execFile = (_file, _args, _options, cb) => { setImmediate(() => cb(null, 'TOKEN\n', '')); return { pid: 7 }; };
+ assert.equal(await getAuthTokenAsync('https://contoso-finished.crm.dynamics.com', { execFile, signal: controller.signal, killTree: (c) => killed.push(c) }), 'TOKEN');
+ controller.abort();
+ assert.deepEqual(killed, [], 'the child had finished: there is nothing to end');
+ let started = 0;
+ const cancelled = new AbortController();
+ cancelled.abort();
+ assert.equal(await getAuthTokenAsync('https://contoso-never.crm.dynamics.com', { execFile: () => { started += 1; return {}; }, signal: cancelled.signal }), null);
+ assert.equal(started, 0, 'no process is started for a read that was already cancelled');
+});
+
+test('without a signal getAuthTokenAsync starts the CLI with exactly the options it always did, and a real failure is still remembered', async () => {
+ const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
+ const url = 'https://contoso-plain.crm.dynamics.com';
+ let seen;
+ const execFile = (_file, _args, options, cb) => { seen = options; setImmediate(() => cb(Object.assign(new Error('boom'), { killed: true, signal: 'SIGTERM' }), '', '')); return {}; };
+ assert.equal(await getAuthTokenAsync(url, { execFile }), null);
+ assert.deepEqual(Object.keys(seen).sort(), ['encoding', 'timeout', 'windowsHide'], 'no `signal` key unless the caller supplied one');
+ assert.equal(tokenFailureKind(url), 'timeout');
+});
+
+test('dataverseRequest hands a 401 back without refreshing the token when refreshOn401 is false — the refresh is a synchronous CLI read', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const run = async (options) => {
+ const tokenCalls = [];
+ let sends = 0;
+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
+ getToken: (_url, o) => { tokenCalls.push(Boolean(o && o.fresh)); return 'TOK'; },
+ request: async () => { sends += 1; return { statusCode: 401, body: '' }; },
+ ...options,
+ });
+ return { res, tokenCalls, sends };
+ };
+ const refreshing = await run({});
+ assert.deepEqual(refreshing.tokenCalls, [false, true, true], 'by default each 401 is followed by a fresh token read, twice');
+ assert.equal(refreshing.sends, 3);
+ const handedBack = await run({ refreshOn401: false });
+ assert.equal(handedBack.res.status, 401);
+ assert.deepEqual(handedBack.tokenCalls, [false], 'only the memoized token was used: no synchronous read');
+ assert.equal(handedBack.sends, 1, 'and the 401 was not sent again');
+});
+
+test('emitResult: partial-failure object writes JSON to stdout (not [object Object])', () => {
+ // Spawn a tiny script that calls emitResult(false, {errors:[...]}) and
+ // verify that stdout contains the JSON payload — not the literal string
+ // "[object Object]". Regression guard for the bulk-insert failure path.
+ const { spawnSync } = require('node:child_process');
+ const path = require('node:path');
+ const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
+ const code = `
+ const { emitResult } = require(${JSON.stringify(libPath)});
+ emitResult(false, { ok: false, count: 0, ids: [], errors: [{ index: 0, status: 400, message: 'bad row' }] });
+ `;
+ const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
+ assert.equal(res.status, 1, 'expected exit 1');
+ assert.doesNotMatch(res.stdout, /\[object Object\]/, 'stdout must not be [object Object]');
+ const parsed = JSON.parse(res.stdout.trim());
+ assert.equal(parsed.ok, false);
+ assert.equal(parsed.errors.length, 1);
+ assert.equal(parsed.errors[0].index, 0);
+ assert.equal(parsed.errors[0].status, 400);
+ assert.equal(parsed.errors[0].message, 'bad row');
+ assert.match(res.stderr, /Operation completed with 1 error/);
+});
+
+// --- AB#6686427: auth preflight — az tenant divergence from the selected PAC environment ---------
+//
+// The skill flow validates and selects a PAC profile, but every script authenticates through the
+// INDEPENDENTLY active Azure CLI account. In a normal multi-tenant workflow `pac auth` and
+// `az login` legitimately point at different tenants, and the result is an HTTP 401 that reads as a
+// Dataverse permission problem — so the user troubleshoots roles and PAC profiles while the actual
+// cause is the ambient az context. Worse, download's best-effort catches turn that 401 into a
+// silently EMPTY spec (AB#6686423), so the failure does not even surface as an error.
+//
+// The preflight names the identity that will actually supply the token, before any real work.
+
+const { preflightAuth } = require('../lib/dataverse-auth.js');
+
+test('AB#6686427: preflight passes and reports the identity when WhoAmI succeeds', async () => {
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 200, data: { UserId: '00000000-0000-0000-0000-000000000001' } }),
+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),
+ });
+ assert.strictEqual(r.ok, true, JSON.stringify(r));
+ assert.match(r.identity.user, /maker@contoso\.com/);
+});
+
+test('preflight: identityOnSuccess:false skips the identity read on success but keeps it for a 401', async () => {
+ let reads = 0;
+ const azIdentity = () => { reads += 1; return { user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }; };
+ const ok = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 200, data: { UserId: '00000000-0000-0000-0000-000000000001' } }),
+ azIdentity,
+ identityOnSuccess: false,
+ });
+ assert.strictEqual(ok.ok, true);
+ assert.strictEqual(ok.userId, '00000000-0000-0000-0000-000000000001');
+ assert.strictEqual('identity' in ok, false, 'no identity on a verdict-only success');
+ assert.strictEqual(reads, 0, 'no `az account show` for a value nobody reads');
+ const denied = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 401, headers: {} }),
+ azIdentity,
+ identityOnSuccess: false,
+ });
+ assert.strictEqual(denied.ok, false);
+ assert.strictEqual(reads, 1, 'a 401 still names the identity it rejected');
+ assert.match(denied.error, /maker@contoso\.com/);
+});
+
+test('dataverseRequest USES a preset token and skips the CLI entirely', async () => {
+ // The receiving half of the preflight optimisation. Passing the token is pointless if this side
+ // fetches its own anyway, and that is invisible from the caller.
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ let cliCalls = 0;
+ let sentAuth;
+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
+ token: 'tok-abc',
+ getToken: () => { cliCalls += 1; return 'tok-from-cli'; },
+ request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },
+ });
+ assert.strictEqual(cliCalls, 0, 'a preset token must skip `az account get-access-token` altogether');
+ assert.strictEqual(sentAuth, 'Bearer tok-abc');
+ assert.strictEqual(res.status, 200);
+
+ // Counterfactual: with no preset token it still acquires one, or the seam would have broken the
+ // normal path while looking green.
+ cliCalls = 0;
+ await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
+ getToken: () => { cliCalls += 1; return 'tok-from-cli'; },
+ request: async ({ headers }) => { sentAuth = headers.Authorization; return { statusCode: 200, body: '{}' }; },
+ });
+ assert.strictEqual(cliCalls, 1);
+ assert.strictEqual(sentAuth, 'Bearer tok-from-cli');
+});
+
+
+test('dataverseRequest bypasses the token memo after a 401 before retrying', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const tokenCalls = [];
+ const sent = [];
+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
+ getToken: (_url, options) => {
+ tokenCalls.push(Boolean(options && options.fresh));
+ return tokenCalls.length === 1 ? 'OLD' : 'NEW';
+ },
+ request: async ({ headers }) => {
+ sent.push(headers.Authorization);
+ return sent.length === 1
+ ? { statusCode: 401, body: '' }
+ : { statusCode: 200, body: '{"ok":true}' };
+ },
+ });
+ assert.strictEqual(res.status, 200);
+ assert.deepStrictEqual(tokenCalls, [false, true]);
+ assert.deepStrictEqual(sent, ['Bearer OLD', 'Bearer NEW']);
+});
+
+test('a path-bearing or query-bearing env is refused, not silently trimmed to its origin', async () => {
+ // `dataverseRequest` appends `/api/data/...` to whatever it is given, so a trimmed
+ // `https://org.crm.dynamics.com/some/path` would probe `.../some/path/api/data/...` and report a
+ // result about a URL nobody asked for. This function decides where a bearer token may be sent, so
+ // "close enough" is the wrong disposition.
+ for (const bad of [
+ 'https://contoso.crm.dynamics.com/some/path',
+ 'https://contoso.crm.dynamics.com/?q=1',
+ 'https://contoso.crm.dynamics.com/#frag',
+ ]) {
+ let tokenAsked = 0;
+ let requested = 0;
+ const r = await preflightAuth(bad, {
+ getToken: () => { tokenAsked += 1; return 'token'; },
+ request: async () => { requested += 1; return { status: 200, data: {} }; },
+ azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),
+ });
+ assert.strictEqual(r.ok, false, `${bad} must be refused: ${JSON.stringify(r)}`);
+ assert.match(r.error, /ORIGIN/, r.error);
+ assert.strictEqual(tokenAsked, 0, `${bad}: no token may be acquired for a rejected target`);
+ assert.strictEqual(requested, 0, `${bad}: and nothing may be sent`);
+ }
+ // Counterfactual: a bare origin, and an origin with only a trailing slash, are both fine.
+ for (const good of ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com/']) {
+ const r = await preflightAuth(good, {
+ getToken: () => 'token',
+ request: async () => ({ status: 200, data: { UserId: 'u' } }),
+ azIdentity: () => ({ user: '[email protected]', tenantId: 't' }),
+ });
+ assert.strictEqual(r.ok, true, `${good} must be accepted: ${JSON.stringify(r)}`);
+ }
+});
+
+// --- emitResult: a single explained failure must not be dressed as a partial one -----------------
+test('both CLIs report an auth-preflight failure with the SAME payload shape', () => {
+ // `emitResult` reserves `errors: [...]` for a genuine PARTIAL failure and summarises it as a COUNT.
+ // `build-model-app.js` wrapped its single preflight message in that array while
+ // `download-model-app.js` passed it as `error`, so the two sibling CLIs printed different things
+ // for the identical failure — and the one users hit on an apply printed the count, replacing a
+ // message written specifically to say which identity to sign in as.
+ //
+ // Asserted on the SOURCE because the alternative is spawning both CLIs against a live tenant. build-model-app.js answers the result
+ // (`payload`) for main() to print once its build lease is let go (tests/build-lease-cli.test.js prints it through the real printer).
+ const fs = require('node:fs');
+ const path = require('node:path');
+ for (const cli of ['build-model-app.js', 'download-model-app.js']) {
+ const src = fs.readFileSync(path.join(__dirname, '..', cli), 'utf8');
+ const line = src.split('\n').find((l) => /(?:emitResult\(false,|payload:\s*\{).*auth\.error/.test(l));
+ assert.ok(line, `${cli}: expected an emitResult call carrying auth.error`);
+ assert.match(line, /error:\s*auth\.error/, `${cli}: a single explained failure must use \`error\`: ${line.trim()}`);
+ assert.doesNotMatch(line, /errors:\s*\[/, `${cli}: \`errors: [...]\` is for PARTIAL failures and prints only a count: ${line.trim()}`);
+ }
+});
+
+test('emitResult prints a single error message instead of "unknown error(s)"', () => {
+ // The auth preflight, the app-id resolver and friends all fail with { ok:false, error:"<what to
+ // do>" } and no `errors` array. The old branch printed "Operation completed with unknown error(s)"
+ // for every one of them — burying a message written specifically to tell the operator what to do,
+ // under boilerplate that is also untrue: nothing completed, and it is not unknown.
+ const { emitResult } = require('../lib/dataverse-auth.js');
+ const run = (payload) => {
+ const out = [];
+ const err = [];
+ const so = process.stdout.write;
+ const se = process.stderr.write;
+ const ex = process.exit;
+ process.stdout.write = (s) => { out.push(String(s)); return true; };
+ process.stderr.write = (s) => { err.push(String(s)); return true; };
+ // `emitResult` ends the process by contract, so the exit is turned into a throw and swallowed.
+ process.exit = () => { throw new Error('__exit__'); };
+ try { emitResult(false, payload); } catch (e) { if (e.message !== '__exit__') throw e; } finally {
+ process.stdout.write = so; process.stderr.write = se; process.exit = ex;
+ }
+ return { out: out.join(''), err: err.join('') };
+ };
+
+ const single = run({ ok: false, error: 'no Azure CLI access token could be obtained; run az login' });
+ assert.match(single.err, /run az login/, 'the actionable message must reach stderr');
+ assert.doesNotMatch(single.err, /unknown error/, 'and must not be replaced by boilerplate');
+ assert.match(single.out, /"ok":false/, 'the structured payload still goes to stdout for callers');
+
+ // The genuine PARTIAL-failure contract is unchanged: a count, with the detail on stdout.
+ const partial = run({ ok: false, errors: [{ row: 1 }, { row: 2 }] });
+ assert.match(partial.err, /completed with 2 error\(s\)/, partial.err);
+
+ // Neither shape: say so honestly rather than claiming a count we do not have.
+ const opaque = run({ ok: false });
+ assert.match(opaque.err, /unstructured error/, opaque.err);
+ assert.doesNotMatch(opaque.err, /completed with/, 'nothing completed');
+});
+
+test('AB#6686427: the preflight HANDS its token to the request instead of fetching a second one', async () => {
+ // `preflightAuth` deliberately acquires a token itself so it can tell "not signed in" apart from
+ // "signed in but rejected" — two different diagnoses with two different fixes. Without passing it
+ // on, `dataverseRequest` shells out to `az account get-access-token` again for the same origin,
+ // and that call cold-starts the Azure CLI's Python runtime: seconds, on a path a user waits on.
+ let tokenCalls = 0;
+ let sawToken;
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => { tokenCalls += 1; return 'tok-abc'; },
+ request: async (_url, _m, _p, _b, opts) => { sawToken = opts && opts.token; return { status: 200, data: { UserId: 'u' } }; },
+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaaaaaa-0000-0000-0000-000000000000' }),
+ });
+ assert.strictEqual(r.ok, true, JSON.stringify(r));
+ assert.strictEqual(tokenCalls, 1, 'exactly one token acquisition');
+ assert.strictEqual(sawToken, 'tok-abc', 'and the SAME token must reach the request');
+});
+
+test('AB#6686427: a 401 names the ACTIVE az identity, the target org, and the remediation', async () => {
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 401, data: {} }),
+ azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbbbbbb-0000-0000-0000-000000000000' }),
+ });
+ assert.strictEqual(r.ok, false);
+ // Naming only the status repeats the failure the user already saw; the point is to name the CAUSE.
+ assert.match(r.error, /other@fabrikam\.onmicrosoft\.com/, 'must name the active az identity');
+ assert.match(r.error, /bbbbbbbb-0000-0000-0000-000000000000/, 'must name the tenant supplying the token');
+ assert.match(r.error, /contoso\.crm\.dynamics\.com/, 'must name the target org');
+ assert.match(r.error, /az login/, 'must name the remediation');
+});
+
+test('AB#6686427: no token at all is reported as a sign-in problem, not a permission one', async () => {
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => null,
+ request: async () => { throw new Error('should not be called'); },
+ azIdentity: () => null,
+ });
+ assert.strictEqual(r.ok, false);
+ assert.match(r.error, /az login/);
+ // Assert the CLAIM, not the vocabulary: the message may legitimately use the word "permissions"
+ // to rule it OUT, which an over-crude /permission/ ban would fail. What must not happen is the
+ // failure being ATTRIBUTED to privileges, sending the user to security roles.
+ assert.match(r.error, /sign-in problem/, 'must name the real cause');
+ assert.doesNotMatch(r.error, /insufficient|lacks? (the )?privilege|missing privilege|security role/i,
+ 'must not attribute a missing token to privileges');
+});
+
+test('AB#6686427: the preflight is a diagnostic and never throws', async () => {
+ for (const opts of [
+ { getToken: () => { throw new Error('az exploded'); }, request: async () => ({ status: 200, data: {} }), azIdentity: () => null },
+ { getToken: () => 't', request: async () => { throw new Error('socket hang up'); }, azIdentity: () => null },
+ { getToken: () => 't', request: async () => ({ status: 200, data: {} }), azIdentity: () => { throw new Error('az show failed'); } },
+ ]) {
+ let r;
+ await assert.doesNotReject(async () => { r = await preflightAuth('https://contoso.crm.dynamics.com', opts); });
+ assert.ok(typeof r.ok === 'boolean', 'always returns a structured verdict');
+ }
+});
+
+test('AB#6686427: a non-401 failure is INCONCLUSIVE, not a block and not a tenant mismatch', async () => {
+ // A 403 is a real privilege problem and a 500 is the service; blaming the az tenant for either
+ // would send the user down exactly the wrong path — the mirror of the bug being fixed.
+ //
+ // They must also NOT BLOCK. This probe goes through `dataverseRequest`, which retries fewer
+ // statuses and fewer times than the `createAzHttpClient` the real download uses (that one also
+ // retries 504). A transient 5xx the download would have ridden out must not be turned into a hard
+ // failure by a diagnostic sitting in front of it. Found in review.
+ for (const status of [403, 429, 500, 504]) {
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status, data: { error: { message: 'upstream detail' } } }),
+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),
+ });
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(r.inconclusive, true, `${status} must be inconclusive, never blocking`);
+ assert.doesNotMatch(r.error, /az login --tenant/, `${status} must not be blamed on the az tenant`);
+ assert.match(r.error, /upstream detail/, 'the server message explains a 403 and must survive');
+ }
+});
+
+test('AB#6686427: a non-HTTPS or malformed env is refused BEFORE any token is acquired', async () => {
+ // The preflight runs ahead of createAzHttpClient's credential boundary and goes through
+ // dataverseRequest, whose transport falls back to plain `http` for a non-HTTPS scheme. Without
+ // this gate a malformed --env could put a bearer token on the wire in clear text. Found in review.
+ for (const bad of ['http://contoso.crm.dynamics.com', 'not-a-url', 'ftp://x/y', '']) {
+ let tokenAsked = 0;
+ const r = await preflightAuth(bad, {
+ getToken: () => { tokenAsked++; return 'token'; },
+ request: async () => { throw new Error('must not reach the wire'); },
+ azIdentity: () => null,
+ });
+ assert.strictEqual(r.ok, false, `${bad} must be refused`);
+ assert.strictEqual(r.inconclusive, undefined, 'a bad target is definitive, not inconclusive');
+ assert.strictEqual(tokenAsked, 0, `no token may be acquired for ${bad}`);
+ assert.match(r.error, /https/i);
+ }
+});
+
+test('AB#6686427: a CLAIMS CHALLENGE 401 is not blamed on the tenant', async () => {
+ // Conditional Access / CAE answer 401 with `WWW-Authenticate: ... error="insufficient_claims"`,
+ // and `az login --tenant` does not fix it. Asserting tenant divergence as a certainty would be the
+ // same misattribution this bug is about, pointed somewhere new. Found in review.
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 401, data: null, headers: { 'www-authenticate': 'Bearer error="insufficient_claims", claims="eyJ..."' } }),
+ azIdentity: () => ({ user: '[email protected]', tenantId: 'aaaa' }),
+ });
+ assert.strictEqual(r.ok, false);
+ assert.match(r.error, /claims/i);
+ assert.doesNotMatch(r.error, /az login --tenant/, 'a claims challenge is not a tenant problem');
+});
+
+test('AB#6686427: the happy path does not shell out to az for an identity nobody asked for', async () => {
+ // The caller only reads `auth.ok`; paying for an `az account show` subprocess on every successful
+ // run is pure cost. Found in review.
+ let idReads = 0;
+ const r = await preflightAuth('https://contoso.crm.dynamics.com', {
+ getToken: () => 'token',
+ request: async () => ({ status: 200, data: { UserId: 'u' } }),
+ azIdentity: () => { idReads++; return { user: '[email protected]', tenantId: 'aaaa' }; },
+ });
+ assert.strictEqual(r.ok, true);
+ assert.ok(idReads <= 1, `identity read at most once on success, got ${idReads}`);
+});
+
+// --- AB#6686424: a terminal 401 must explain itself ----------------------------------------------
+//
+// Both auth paths already retry a 401 once (dataverse-auth's loop, and sdk-http-client.js:130). The
+// retry is not the gap: MEASURED, `az account get-access-token` serves from the MSAL cache, so an
+// immediate re-call returns a byte-identical token (same sha256). A retry therefore cannot fix a
+// token that is rejected for WHO it belongs to — only one that expired in a very narrow window.
+//
+// The reporter's own workaround was "refresh Azure CLI login and retry" — an `az login`, which is
+// AB#6686427's cause. So what a surviving 401 needs is not another attempt, it is to say whose
+// token was refused, so the reader stops looking at Dataverse roles.
+
+test('AB#6686424: a terminal 401 names the identity whose token was refused', () => {
+ const { ensureOk } = require('../lib/dataverse-auth.js');
+ assert.throws(
+ () => ensureOk({ status: 401, data: { error: { message: 'Unauthorized' } } }, 'read EntityDefinitions',
+ { azIdentity: () => ({ user: '[email protected]', tenantId: 'bbbb-tenant' }) }),
+ (e) => {
+ assert.match(e.message, /other@fabrikam\.onmicrosoft\.com/, 'names the account');
+ assert.match(e.message, /bbbb-tenant/, 'names the tenant');
+ assert.match(e.message, /az login/, 'names the remediation');
+ return true;
+ }
+ );
+});
+
+test('AB#6686424: a NON-401 error is left exactly as it was', () => {
+ // A 403 is a real privilege problem and a 400 is a bad request; attaching identity advice to
+ // either would send the reader to `az login` for something az cannot fix.
+ const { ensureOk } = require('../lib/dataverse-auth.js');
+ for (const status of [400, 403, 404, 500]) {
+ assert.throws(
+ () => ensureOk({ status, data: { error: { message: 'boom' } } }, 'ctx', { azIdentity: () => ({ user: 'x', tenantId: 'y' }) }),
+ (e) => {
+ assert.doesNotMatch(e.message, /az login/, `${status} must not be blamed on the az identity`);
+ assert.match(e.message, /boom/);
+ return true;
+ }
+ );
+ }
+});
+
+test('AB#6686424: an unreadable identity still produces a useful 401, never a crash', () => {
+ const { ensureOk } = require('../lib/dataverse-auth.js');
+ assert.throws(
+ () => ensureOk({ status: 401, data: {} }, 'ctx', { azIdentity: () => { throw new Error('az gone'); } }),
+ (e) => {
+ assert.match(e.message, /401/);
+ assert.match(e.message, /az login/);
+ return true;
+ }
+ );
+});
+
+test('AB#6686424: a 2xx is returned untouched (no identity read on the happy path)', () => {
+ const { ensureOk } = require('../lib/dataverse-auth.js');
+ let called = 0;
+ const res = { status: 200, data: { ok: 1 } };
+ assert.strictEqual(ensureOk(res, 'ctx', { azIdentity: () => { called++; return null; } }), res);
+ assert.strictEqual(called, 0, 'must not shell out to az on every successful call');
+});
+
+test('AB#6686424: a bodyless error does not print "null" as the server message', () => {
+ // Found by LIVE verification, not by the unit fixtures: a real Dataverse 401 often carries no body
+ // at all, so `data` is null and the message read "HTTP 401 — null". Every unit fixture supplied a
+ // message, so nothing caught it.
+ const { ensureOk } = require('../lib/dataverse-auth.js');
+ for (const [status, data] of [[401, null], [500, null], [404, undefined]]) {
+ assert.throws(
+ () => ensureOk({ status, data }, 'ctx', { azIdentity: () => null }),
+ (e) => {
+ assert.doesNotMatch(e.message, /— null|— undefined/, `${status} must not print a bare null: ${e.message}`);
+ assert.match(e.message, /no response body/);
+ return true;
+ }
+ );
+ }
+});
+
+// --- environment URLs: only a Dataverse https origin is ever used -------------------------------
+// The origin is the `--resource` a token is requested for, the base of every request URL, and the
+// only place a token is sent. Anything else is refused before a process starts or a request is sent.
+test('dataverseOrigin accepts a Dataverse origin in any cloud and returns it canonically', () => {
+ const { dataverseOrigin } = require('../lib/dataverse-auth.js');
+ for (const [input, expected] of [
+ ['https://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com'],
+ ['https://Contoso.CRM.Dynamics.com/', 'https://contoso.crm.dynamics.com'],
+ [' https://contoso.crm4.dynamics.com// ', 'https://contoso.crm4.dynamics.com'],
+ ['HTTPS://contoso.api.crm.dynamics.com', 'https://contoso.api.crm.dynamics.com'],
+ ['https://contoso.crmtest.dynamics.com', 'https://contoso.crmtest.dynamics.com'],
+ ['https://contoso.crm.microsoftdynamics.us', 'https://contoso.crm.microsoftdynamics.us'],
+ ['https://contoso.crm.appsplatform.us', 'https://contoso.crm.appsplatform.us'],
+ ['https://contoso.crm.dynamics.cn', 'https://contoso.crm.dynamics.cn'],
+ ]) {
+ assert.equal(dataverseOrigin(input), expected, input);
+ }
+});
+
+test('dataverseOrigin refuses anything that is not exactly an https Dataverse origin', () => {
+ const { dataverseOrigin } = require('../lib/dataverse-auth.js');
+ for (const input of [
+ 'http://contoso.crm.dynamics.com',
+ 'https://contoso.crm.dynamics.com/main.aspx',
+ 'https://contoso.crm.dynamics.com/?x=1',
+ 'https://contoso.crm.dynamics.com/#x',
+ 'https://contoso.crm.dynamics.com:443',
+ 'https://[email protected]',
+ 'https://contoso.crm.dynamics.com/&whoami',
+ 'https://contoso.crm.dynamics.com&whoami',
+ 'https://contoso.crm.dynamics.com\\x',
+ 'https://contoso.crm.dynamics.com%20',
+ 'https://contoso.crm.dynamics.com\nx',
+ 'https://contoso.example.com',
+ 'https://crm.dynamics.com',
+ 'https://contoso.crm.dynamics.com.example.com',
+ '',
+ null,
+ undefined,
+ ]) {
+ assert.equal(dataverseOrigin(input), null, JSON.stringify(input));
+ }
+});
+
+test('a non-origin environment URL starts no Azure CLI process and sends no request', async () => {
+ const { getAuthToken, getAuthTokenAsync, dataverseRequest } = require('../lib/dataverse-auth.js');
+ let started = 0;
+ const exec = () => { started += 1; return 'TOK\n'; };
+ const execFile = (_f, _a, _o, cb) => { started += 1; cb(null, 'TOK\n'); };
+ const bad = 'https://contoso.crm.dynamics.com/&whoami';
+ assert.equal(getAuthToken(bad, { exec, fresh: true }), null);
+ assert.equal(await getAuthTokenAsync(bad, { execFile, fresh: true }), null);
+ let sent = 0;
+ await assert.rejects(
+ dataverseRequest(bad, 'GET', 'WhoAmI', null, { getToken: exec, request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; } }),
+ /is not a Dataverse environment URL/
+ );
+ assert.equal(started, 0);
+ assert.equal(sent, 0);
+});
+
+test('dataverseRequest builds the request on the validated origin and requests the token for it', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ let resource;
+ let url;
+ await dataverseRequest('https://Contoso.crm.dynamics.com/', 'GET', 'WhoAmI', null, {
+ getToken: (r) => { resource = r; return 'TOK'; },
+ request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },
+ });
+ assert.equal(resource, 'https://contoso.crm.dynamics.com');
+ assert.equal(url, 'https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');
+});
+
+test('a path that leaves the Web API root is refused before a token is read or a request sent', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ // [path, where it resolves]. Each spelling reached an endpoint outside /api/data/v9.2/ on a live
+ // environment with the released code. The client resolves the first seven itself; the server decodes
+ // %2F / %5C and resolves the next three. The last one leaves the root as the client sends it, although
+ // the server's further decoding would bring it back: the client reading is checked on its own too.
+ const escapes = [
+ ['../v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['../../../XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
+ ['%2e%2e/%2E%2e/%2e%2E/XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
+ ['.%2e/v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['..\\..\\..\\XRMServices\\2011\\Organization.svc\\web', '/XRMServices/2011/Organization.svc/web'],
+ ['a%2Fb/../../x', '/api/data/x'],
+ ['..', '/api/data/'],
+ ['..%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['..%5cv9.0%5cWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['.%2e%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['../x%2F..%2Fv9.2%2FWhoAmI', '/api/data/x%2F..%2Fv9.2%2FWhoAmI'],
+ ];
+ for (const [apiPath, resolved] of escapes) {
+ let tokens = 0;
+ let sent = 0;
+ await assert.rejects(
+ dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
+ getToken: () => { tokens += 1; return 'TOK'; },
+ request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; },
+ }),
+ (e) => /leaves the Dataverse Web API root \/api\/data\/v9\.2\//.test(e.message) && e.message.includes(`resolves to '${resolved}'`),
+ apiPath
+ );
+ assert.equal(tokens, 0, apiPath);
+ assert.equal(sent, 0, apiPath);
+ }
+ await assert.rejects(
+ dataverseRequest('https://contoso.crm.dynamics.com', 'GET', undefined, null, { getToken: () => 'TOK', request: async () => ({ statusCode: 200, body: '{}' }) }),
+ /must be text \(got undefined\)/
+ );
+});
+
+test('a path inside the Web API root is sent exactly as before', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const accepted = [
+ 'WhoAmI',
+ "EntityDefinitions(LogicalName='account')/Attributes?$select=LogicalName",
+ '$batch',
+ // Dataverse answers /api/data/v9.2//WhoAmI and WhoAmI%2F like WhoAmI (measured).
+ '/WhoAmI',
+ 'WhoAmI%2F',
+ // Decoded by the server, this resolves back inside the root.
+ 'x/..%2F..%2Fv9.2%2FWhoAmI',
+ // Dot segments inside a query are data, not a path.
+ "accounts?$filter=name eq '../../x'",
+ // An absolute URL is only text under the root: it cannot change where the request goes.
+ 'https://example.com/x',
+ ];
+ for (const apiPath of accepted) {
+ let url;
+ await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
+ getToken: () => 'TOK',
+ request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },
+ });
+ assert.equal(url, `https://contoso.crm.dynamics.com/api/data/v9.2/${apiPath}`, apiPath);
+ }
+});
+
+test('createAzHttpClient requests its token for the validated origin, never the text it was given', async () => {
+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+ assert.throws(() => createAzHttpClient('https://contoso.crm.dynamics.com/&whoami', { getToken: () => 'TOK' }), /Invalid Dataverse org URL/);
+ let resource;
+ const http = createAzHttpClient('https://CONTOSO.crm.dynamics.com/', {
+ getToken: (r) => { resource = r; return 'TOK'; },
+ request: async () => ({ statusCode: 200, body: '{}' }),
+ });
+ await http.get('https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');
+ assert.equal(resource, 'https://contoso.crm.dynamics.com');
+});
+
+test('azIdentity reads the identity through the process runner seam', () => {
+ const { azIdentity } = require('../lib/dataverse-auth.js');
+ const seen = [];
+ const id = azIdentity({ exec: (cmd, args) => { seen.push([cmd, ...args].join(' ')); return '{"user":"[email protected]","tenantId":"t"}'; } });
+ assert.deepEqual(id, { user: '[email protected]', tenantId: 't' });
+ assert.deepEqual(seen, ['az account show --query {user:user.name,tenantId:tenantId} -o json']);
+});
+
+// End to end on Windows, where the Azure CLI is a batch shim: the entry-point CLIs refuse an
+// environment URL that is not an origin, and nothing but the (fake) Azure CLI ever runs.
+test('the Dataverse entry points refuse a non-origin URL before anything runs (real CLI, Windows)', { skip: process.platform !== 'win32' }, () => {
+ const { spawnSync } = require('node:child_process');
+ const fs = require('node:fs');
+ const os = require('node:os');
+ const path = require('node:path');
+ const scripts = path.join(__dirname, '..');
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-origin-e2e-'));
+ try {
+ const bin = path.join(work, 'bin');
+ fs.mkdirSync(bin);
+ const azLog = path.join(work, 'az-calls.txt');
+ fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo %*>>"${azLog}"\r\n@exit /b 1\r\n`, 'utf8');
+ const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };
+ const url = 'https://contoso.crm.dynamics.com/&md,MARKER';
+ const runs = [
+ spawnSync(process.execPath, [path.join(scripts, 'dataverse-request.js'), url, 'GET', 'WhoAmI'], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),
+ spawnSync(process.execPath, [path.join(scripts, 'check-auth.js'), '--env', url], { cwd: work, env, encoding: 'utf8', timeout: 60000 }),
+ ];
+ assert.equal(fs.existsSync(path.join(work, 'MARKER')), false, 'no second command ran');
+ assert.match(runs[0].stderr, /is not a Dataverse environment URL/);
+ const logged = fs.existsSync(azLog) ? fs.readFileSync(azLog, 'utf8') : '';
+ assert.doesNotMatch(logged, /MARKER/, `the URL never reached the Azure CLI: ${logged}`);
+ } finally {
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+});
+
+// Cancelling the token read, end to end on a real cmd.exe. `az.cmd` runs the Azure CLI's program as cmd.exe's CHILD, so ending only
+// the cmd.exe Node started (what an AbortSignal handed to execFile does) leaves that program running after the process that
+// cancelled it has exited. Here the "CLI" is a node program that records its pid and idles.
+test('aborting a real getAuthTokenAsync read ends the program the az shim started too, so nothing is left running (real cmd.exe, Windows)', { skip: process.platform !== 'win32' }, () => {
+ const { spawnSync } = require('node:child_process');
+ const fs = require('node:fs');
+ const os = require('node:os');
+ const path = require('node:path');
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-abort-e2e-'));
+ const pidFile = path.join(work, 'az-program.pid');
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
+ let program = 0;
+ try {
+ const bin = path.join(work, 'bin');
+ fs.mkdirSync(bin);
+ // The timer is a backstop: whatever a failing run leaves behind ends by itself.
+ fs.writeFileSync(path.join(bin, 'idle.js'), `require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setTimeout(() => process.exit(0), 120000);\n`, 'utf8');
+ fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo off\r\n"${process.execPath}" "${path.join(bin, 'idle.js')}" %*\r\n`, 'utf8');
+ const url = 'https://contoso.crm.dynamics.com';
+ const driver = `
+ const fs = require('fs');
+ const { getAuthTokenAsync, tokenFailureKind } = require(${JSON.stringify(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'))});
+ (async () => {
+ const controller = new AbortController();
+ const read = getAuthTokenAsync(${JSON.stringify(url)}, { signal: controller.signal });
+ for (let i = 0; i < 150 && !fs.existsSync(${JSON.stringify(pidFile)}); i += 1) await new Promise((resolve) => setTimeout(resolve, 100));
+ controller.abort();
+ process.stdout.write(JSON.stringify({ token: await read, failure: tokenFailureKind(${JSON.stringify(url)}) }));
+ })();`;
+ const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };
+ const run = spawnSync(process.execPath, ['-e', driver], { cwd: work, env, encoding: 'utf8', timeout: 60000 });
+ assert.equal(run.status, 0, `${run.stdout}${run.stderr}`);
+ assert.deepEqual(JSON.parse(run.stdout), { token: null, failure: null }, 'a cancelled read is null and leaves no failure behind');
+ program = Number(fs.readFileSync(pidFile, 'utf8'));
+ assert.ok(program > 0, 'the az shim started its program');
+ // The tree was ended before the reader that cancelled it exited; allow the OS a moment to finish reaping it.
+ const until = Date.now() + 5000;
+ while (alive(program) && Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
+ assert.equal(alive(program), false, 'the program the az shim started is no longer running');
+ } finally {
+ // Whatever the assertions above found, never leave the program the shim started running.
+ if (!program && fs.existsSync(pidFile)) program = Number(fs.readFileSync(pidFile, 'utf8')) || 0;
+ if (program && alive(program)) { try { process.kill(program); } catch { /* already gone */ } }
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+});
+
+// --- emitResult: `ascii` keeps a script's stdout pure ASCII ----------------------------------------------------
+//
+// An agent reads a script's stdout off a console. Windows PowerShell 5.1 decodes a child's output with the OEM code
+// page, so UTF-8 bytes of an em dash arrive as three other characters; written as a \uXXXX escape the same JSON
+// survives any code page. Only a script that asks for it changes — every other caller keeps the raw text.
+test('emitResult with `ascii` writes every character above U+007E as a \\uXXXX escape, in either outcome, and leaves stderr as written', () => {
+ const { spawnSync } = require('node:child_process');
+ const path = require('node:path');
+ const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
+ // An em dash and an accented letter (BMP), an emoji (a surrogate pair, as JSON writes a character outside the BMP),
+ // DEL, and the characters JSON.stringify already escapes.
+ const message = 'Norwegian Bokm\u00e5l \u2014 \ud83d\ude00 \u007f "quoted" \\ back\nline';
+ for (const [ok, status] of [[true, 0], [false, 1]]) {
+ const payload = { ok, error: message, list: ['1025 ar-SA \u2014 RTL: Yes'] };
+ const code = `
+ const { emitResult } = require(${JSON.stringify(libPath)});
+ emitResult(${ok}, ${JSON.stringify(payload)}, { ascii: true });
+ `;
+ const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
+ assert.equal(res.status, status, `ok=${ok}: ${res.stderr}`);
+ assert.match(res.stdout, /^[\x00-\x7e\r\n]*$/, `ok=${ok}: pure ASCII`);
+ assert.ok(res.stdout.includes('\\u2014') && res.stdout.includes('\\u00e5') && res.stdout.includes('\\ud83d\\ude00') && res.stdout.includes('\\u007f'), res.stdout);
+ assert.deepEqual(JSON.parse(res.stdout.trim()), payload, `ok=${ok}: the same document, decoded`);
+ if (!ok) assert.equal(res.stderr.trim(), message.trim(), 'stderr is for people and is not escaped');
+ }
+});
+
+test('emitResult without `ascii` still writes the raw text: no other script\u2019s output changes', () => {
+ const { spawnSync } = require('node:child_process');
+ const path = require('node:path');
+ const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
+ const code = `
+ const { emitResult } = require(${JSON.stringify(libPath)});
+ emitResult(true, { s: '1025 ar-SA \\u2014 RTL: Yes' });
+ `;
+ const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
+ assert.equal(res.status, 0, res.stderr);
+ assert.ok(res.stdout.includes('\u2014') && !res.stdout.includes('\\u2014'), res.stdout);
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.js
index 6dc673e61..7f61f917a 100644
--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js
@@ -2378,3 +2378,52 @@ test('a file that starts with two byte order marks reaches the backend as the te
assert.strictEqual(only(updating, 'update')[1].source, text);
assert.strictEqual(pageHash(only(updating, 'update')[1].source), readMarker(file).localSha256, 'and the recorded hash is of that same text');
});
+
+// ── skill_completed telemetry (lib/telemetry/skill-completed.js) ───────────────────────────────────────────────────────────────
+// An upload that was ATTEMPTED reports once, before its result is printed, in the closed vocabulary: what happened to the page, never its
+// name, id, prompt or the environment's URL. A refusal of the command line or its files sends nothing.
+function reporter() {
+ const sent = [];
+ return { sent, reportCompletion: async (input) => { sent.push(input); return true; } };
+}
+
+test('skill_completed: a create reports success with page "created", the target environment and a duration', async () => {
+ const spy = reporter();
+ const r = await run(createArgs(codeFile()), environment(), spy);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.strictEqual(spy.sent.length, 1);
+ const [sent] = spy.sent;
+ assert.deepStrictEqual({ ...sent, durationMs: typeof sent.durationMs }, {
+ skillName: 'genpage', outcome: 'success', errorClass: undefined, envUrl: ENV, durationMs: 'number',
+ eventInfo: { operation: 'page-upload', page: 'created', placedInApp: false },
+ });
+});
+
+test('skill_completed: an update reports page "updated"', async () => {
+ const file = codeFile('export const n = 2;\n'); // an edit of the deployed TEXT: the same bytes would be "unchanged"
+ seedBase(file);
+ const spy = reporter();
+ const r = await run(updateArgs(file), environment(), spy);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.deepStrictEqual(spy.sent.map((s) => [s.outcome, s.eventInfo.page]), [['success', 'updated']]);
+});
+
+test('skill_completed: a command the script refuses before any upload reports nothing', async () => {
+ const spy = reporter();
+ const { factory } = untouchable();
+ const r = await run(['--env', ENV, '--app-id', APP, ...NAMED], factory, spy);
+ assert.strictEqual(r.ok, false);
+ assert.deepStrictEqual(spy.sent, []);
+});
+
+test('skill_completed: uploadCompletion maps each result to its outcome and error class', () => {
+ const { uploadCompletion } = uploadMod;
+ assert.deepStrictEqual(uploadCompletion({ ok: true, payload: { ok: true, updated: true, unchanged: true, addedToSitemap: true, addedToSolution: true } }),
+ { outcome: 'success', eventInfo: { operation: 'page-upload', page: 'unchanged', placedInApp: true, addedToSolution: true } });
+ assert.deepStrictEqual(uploadCompletion({ ok: false, payload: { ok: false, code: 'griffel-shorthand', error: 'x' } }),
+ { outcome: 'failure', errorClass: 'invalid-input', eventInfo: { operation: 'page-upload' } });
+ assert.deepStrictEqual(uploadCompletion({ ok: false, payload: { code: 'solution-add-failed', addedToSolution: false } }),
+ { outcome: 'failure', errorClass: 'deploy-failed', eventInfo: { operation: 'page-upload', addedToSolution: false } });
+ assert.deepStrictEqual(uploadCompletion({ error: new Error('boom') }),
+ { outcome: 'failure', errorClass: 'unexpected', eventInfo: { operation: 'page-upload' } });
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.js
index c947cf29e..91c1a3c26 100644
--- a/plugins/model-apps/scripts/tests/run-tests.test.js
+++ b/plugins/model-apps/scripts/tests/run-tests.test.js
@@ -276,6 +276,7 @@ const PCF_COPY_SYNC_PATHS = new Set([
'plugins/pcf/scripts/lib/nearest-name.js',
'plugins/pcf/scripts/lib/utf8-stream.js',
'plugins/pcf/scripts/lib/cli-failure.js',
+ 'plugins/pcf/scripts/lib/telemetry/skill-completed.js',
'plugins/pcf/scripts/lib/telemetry/ikey.json',
'plugins/pcf/scripts/lib/dataverse-auth.js',
'plugins/pcf/scripts/check-auth.js',
diff --git a/plugins/model-apps/scripts/tests/skill-completed.test.js b/plugins/model-apps/scripts/tests/skill-completed.test.js
new file mode 100644
index 000000000..e15cf5d20
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/skill-completed.test.js
@@ -0,0 +1,385 @@
+'use strict';
+// skill_completed telemetry (lib/telemetry/skill-completed.js): the event the environment-changing scripts send when they finish — the app
+// build, the generative-page upload, and (through pcf's verbatim copy) the control push. What these hold:
+// - the privacy contract: eventInfo carries only the approved keys, enum values, booleans and bounded counts; anything else is dropped;
+// - the routing context: the target environment's cloud is read from its host, the tenant from the token's `tid` alone, the organization
+// from one WhoAmI with a short budget — and an opted-out user incurs no lookup;
+// - the gates: the repo kill switch, an unprovisioned key, and a node:test run that did not ask for emission all send nothing;
+// - the build's mapping from its result to outcome / errorClass / per-phase step counts, and the engine wiring that feeds the counts.
+// The end-to-end cases spawn a real dispatcher and read the POWER_PLATFORM_SKILLS_FAKE_HTTPS probe: nothing reaches a collector.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const sc = require('../lib/telemetry/skill-completed.js');
+const { PHASES } = require('../lib/stages.js');
+const { buildModelApp, completionFor, reportCompletion } = require('../build-model-app.js');
+const { ConnectionError } = require('../lib/maker-sdk.js');
+// Removes every folder these tests make once the file is done; the suite fails on anything left in its temp folder.
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+
+const MODULE = path.resolve(__dirname, '..', 'lib', 'telemetry', 'skill-completed.js');
+const SHIPPED_IKEY = path.resolve(__dirname, '..', 'lib', 'telemetry', 'ikey.json');
+const ORG = '11111111-2222-4333-8444-555555555555';
+const TENANT = '66666666-7777-4888-9999-aaaaaaaaaaaa';
+
+function mkTemp() {
+ return makeTempDir('modelapps-skillcompleted-');
+}
+
+// The detached dispatcher writes the local mirror before it decides where (or whether) to send. A case that expects NO probe waits for
+// the mirror, so the child has finished with the folder before the file's cleanup removes it.
+function waitForMirror(configDir, timeoutMs = 5000) {
+ const root = path.join(configDir, 'telemetry', 'model-apps', 'sessions');
+ const has = () => fs.existsSync(root) && fs.readdirSync(root).some((d) => fs.existsSync(path.join(root, d, 'events.jsonl')));
+ const deadline = Date.now() + timeoutMs;
+ while (!has() && Date.now() < deadline) sleep(25);
+ return has();
+}
+
+function sleep(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+function waitForFile(file, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (!fs.existsSync(file) && Date.now() < deadline) sleep(25);
+ return fs.existsSync(file);
+}
+
+// A JWT-shaped token whose payload is `claims` (unsigned: tenantIdFromToken reads, never verifies).
+function token(claims) {
+ const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+ return `${b64({ alg: 'none' })}.${b64(claims)}.sig`;
+}
+
+// ── The privacy contract ───────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('sanitizeEventInfo keeps only the approved keys and values, and stamps the schema version', () => {
+ const out = sc.sanitizeEventInfo({
+ operation: 'app-build', scope: 'changed-only', publish: true, verify: 'failed', haltPhase: 'forms',
+ page: 'created', placedInApp: false, addedToSolution: true, incremental: false, registration: 'verified',
+ steps: { forms: { ok: 3, skip: 1, error: 1 } },
+ // Not in the schema, or not an allowed value: every one is dropped.
+ appName: 'Contoso Sales', envUrl: 'https://contoso.crm.dynamics.com', message: 'boom', tables: ['contoso_order'],
+ });
+ assert.deepEqual(out, {
+ schemaVersion: 1, operation: 'app-build', scope: 'changed-only', publish: true, verify: 'failed', haltPhase: 'forms',
+ page: 'created', placedInApp: false, addedToSolution: true, incremental: false, registration: 'verified',
+ steps: { forms: { ok: 3, skip: 1, error: 1 } },
+ });
+});
+
+test('sanitizeEventInfo drops values outside each enum, non-booleans, unknown phases and empty rows, and clamps counts', () => {
+ const out = sc.sanitizeEventInfo({
+ operation: 'drop-table', scope: 'everything', publish: 'yes', verify: 'maybe', haltPhase: 'contoso_order', page: 'deleted',
+ steps: {
+ contoso_order: { ok: 1 }, // a table name is not a phase
+ views: { ok: -4, skip: 2.9, error: 'x' },
+ charts: { ok: 0, skip: 0, error: 0 }, // an empty row says nothing
+ forms: { ok: 1e12 },
+ },
+ });
+ assert.deepEqual(out, { schemaVersion: 1, steps: { views: { ok: 0, skip: 2, error: 0 }, forms: { ok: 100000, skip: 0, error: 0 } } });
+ assert.deepEqual(sc.sanitizeEventInfo('not an object'), { schemaVersion: 1 });
+ assert.deepEqual(sc.sanitizeEventInfo({ steps: ['views'] }), { schemaVersion: 1 });
+});
+
+test('every engine phase the build can report is an allowed step key (pinned to lib/stages.js)', () => {
+ for (const phase of [...PHASES, 'preflight']) assert.ok(sc.PHASES.has(phase), `${phase} is missing from the telemetry schema`);
+});
+
+// ── The step tally ──────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('the step tally counts each step once, by its final outcome, per phase', () => {
+ const tally = sc.createStepTally();
+ for (const e of [
+ { phase: 'data-model', status: 'start' }, // a header, not a step
+ { phase: 'data-model', status: 'ok' },
+ { phase: 'data-model', status: 'skip' },
+ { phase: 'views', status: 'error' },
+ { phase: 'views', status: 'ok', replaces: 'error' }, // a deferred step taken up again: its earlier outcome is replaced
+ { phase: 'forms', status: 'warn' },
+ null,
+ ]) tally.record(e);
+ assert.deepEqual(tally.snapshot(), { 'data-model': { ok: 1, skip: 1, error: 0 }, views: { ok: 1, skip: 0, error: 0 } });
+ tally.reset();
+ assert.deepEqual(tally.snapshot(), {});
+});
+
+test('an apply feeds its engine events to the tally, and an automatic re-run starts it over', async () => {
+ const tally = sc.createStepTally();
+ let attempt = 0;
+ const r = await buildModelApp(
+ { schemaVersion: 2, solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' }, app: { name: 'Tally Probe' },
+ entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] } },
+ { apply: true, workspaceDir: mkTemp(), maxRetries: 1, retryDelayMs: 0 },
+ {
+ log: () => {},
+ stepTally: tally,
+ runBuild: async (s, o) => {
+ attempt += 1;
+ o.emit({ phase: 'solution', status: 'ok', n: 1, total: 2, label: 's' });
+ if (attempt === 1) {
+ o.emit({ phase: 'data-model', status: 'error', n: 2, total: 2, label: 't' });
+ // A 503: transient, so the build runs again (as app-build-lease.test.js drives it).
+ throw new ConnectionError('https://contoso.crm.dynamics.com/api/data/v9.2/solutions', 503, 'Service Unavailable');
+ }
+ o.emit({ phase: 'data-model', status: 'ok', n: 2, total: 2, label: 't' });
+ return { ok: true, dryRun: false, created: {} };
+ },
+ sleep: async () => {},
+ }
+ );
+ assert.equal(r.ok, true);
+ assert.equal(attempt, 2, 'the transient halt was retried');
+ assert.deepEqual(tally.snapshot(), { solution: { ok: 1, skip: 0, error: 0 }, 'data-model': { ok: 1, skip: 0, error: 0 } });
+});
+
+// ── The build's result, in the closed vocabulary ────────────────────────────────────────────────────────────────────────────
+
+function run(over = {}) {
+ const tally = sc.createStepTally();
+ for (const e of over.events || []) tally.record(e);
+ return { startedAt: Date.now() - 1000, env: 'https://contoso.crm.dynamics.com', changedOnly: false, staged: false, opts: { publish: true }, tally, ...over };
+}
+
+test('completionFor maps each kind of build result to its outcome, error class and phase', () => {
+ const ok = completionFor(run({ events: [{ phase: 'forms', status: 'ok' }] }), { ok: true, payload: { ok: true, verify: { ok: true } } });
+ assert.deepEqual(ok, { outcome: 'success', eventInfo: { operation: 'app-build', scope: 'full', publish: true, steps: { forms: { ok: 1, skip: 0, error: 0 } }, verify: 'passed' } });
+
+ assert.equal(completionFor(run(), { ok: true, payload: { ok: true } }).eventInfo.verify, 'not-run');
+ assert.equal(completionFor(run({ staged: true }), { ok: true, payload: { ok: true } }).eventInfo.scope, 'staged');
+ assert.equal(completionFor(run({ changedOnly: true, staged: true }), { ok: true, payload: { ok: true } }).eventInfo.scope, 'changed-only');
+
+ const verify = completionFor(run(), { ok: false, payload: { ok: true, verify: { ok: false } } });
+ assert.equal(verify.errorClass, 'verify-failed');
+ assert.equal(verify.eventInfo.verify, 'failed');
+
+ const auth = completionFor(run(), { ok: false, payload: { ok: false, error: 'the token was issued to someone else' } });
+ assert.deepEqual([auth.errorClass, auth.eventInfo.haltPhase], ['auth', 'preflight']);
+
+ const refused = completionFor(run(), { ok: false, payload: { ok: false, errors: ['destructive ops need approval'] } });
+ assert.deepEqual([refused.errorClass, refused.eventInfo.haltPhase], ['halted', 'preflight']);
+
+ const partial = completionFor(run({ events: [{ phase: 'views', status: 'error' }] }), { ok: false, payload: { ok: false, errors: ['1 step failed'] } });
+ assert.equal(partial.errorClass, 'deploy-failed');
+
+ const halt = completionFor(run(), { ok: false, error: Object.assign(new Error('forms stopped'), { phase: 'forms', code: 'whatever' }) });
+ assert.deepEqual([halt.outcome, halt.errorClass, halt.eventInfo.haltPhase, halt.eventInfo.verify], ['failure', 'halted', 'forms', undefined]);
+
+ for (const code of ['build-locked', 'pages-locked', 'build-lease-invalid']) {
+ assert.equal(completionFor(run(), { ok: false, error: Object.assign(new Error('x'), { code, phase: 'preflight' }) }).errorClass, 'locked', code);
+ }
+ assert.equal(completionFor(run(), { ok: false, error: new Error('unexpected') }).errorClass, 'unexpected');
+});
+
+test('reportCompletion sends app-builder with the target environment and a duration, and never throws', async () => {
+ const sent = [];
+ await reportCompletion(run(), { ok: true, payload: { ok: true } }, async (input) => { sent.push(input); return true; });
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0].skillName, 'app-builder');
+ assert.equal(sent[0].outcome, 'success');
+ assert.equal(sent[0].envUrl, 'https://contoso.crm.dynamics.com');
+ assert.ok(sent[0].durationMs >= 1000);
+ await reportCompletion(null, { ok: true }, async () => { throw new Error('a dry run reports nothing'); });
+ await reportCompletion(run(), { ok: true, payload: {} }, async () => { throw new Error('telemetry failed'); });
+});
+
+// ── Routing context ─────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('cloudOfEnvironment names the PAC cloud of a Dataverse host, and nothing for any other', () => {
+ const cases = [
+ ['https://contoso.crm.dynamics.com', 'Public'],
+ ['https://contoso.crm4.dynamics.com', 'Public'],
+ ['https://contoso.api.crm11.dynamics.com', 'Public'],
+ ['https://contoso.crm9.dynamics.com', 'UsGov'],
+ ['https://contoso.crm.microsoftdynamics.us', 'UsGovHigh'],
+ ['https://contoso.crm.appsplatform.us', 'UsGovDod'],
+ ['https://contoso.crm.dynamics.cn', 'China'],
+ ['https://contoso.crmtest.dynamics.com', 'Test'],
+ ['https://contoso.example.com', ''],
+ ['https://contoso.crm.dynamics.com.evil.example', ''],
+ ['not a url', ''],
+ [undefined, ''],
+ ];
+ for (const [url, cloud] of cases) assert.equal(sc.cloudOfEnvironment(url), cloud, String(url));
+});
+
+test('tenantIdFromToken reads the tid claim and nothing else', () => {
+ assert.equal(sc.tenantIdFromToken(token({ tid: TENANT.toUpperCase(), oid: ORG, upn: '[email protected]' })), TENANT);
+ assert.equal(sc.tenantIdFromToken(token({ oid: ORG })), undefined);
+ assert.equal(sc.tenantIdFromToken(token({ tid: 'not-a-guid' })), undefined);
+ assert.equal(sc.tenantIdFromToken('garbage'), undefined);
+});
+
+function fakeAuth({ whoAmI, peek = () => token({ tid: TENANT }) } = {}) {
+ const calls = [];
+ return {
+ calls,
+ dataverseOrigin: (u) => (/^https:\/\/[a-z0-9.-]+$/.test(u) ? u : null),
+ peekAuthToken: (origin) => { calls.push(['peek', origin]); return peek(); },
+ getAuthToken: () => { throw new Error('telemetry must never start the Azure CLI'); },
+ dataverseRequest: async (origin, method, apiPath, body, opts) => { calls.push(['request', method, apiPath, opts.refreshOn401]); return whoAmI(); },
+ };
+}
+
+test('resolveEnvironmentIdentity: the tenant from the memoized token, the organization from one WhoAmI', async () => {
+ const auth = fakeAuth({ whoAmI: async () => ({ status: 200, data: { OrganizationId: ORG.toUpperCase(), UserId: 'u' } }) });
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth }), { orgId: ORG, tenantId: TENANT });
+ assert.deepEqual(auth.calls[0], ['peek', 'https://contoso.crm.dynamics.com'], 'the memo only');
+ assert.deepEqual(auth.calls[1], ['request', 'GET', 'WhoAmI', false], 'a 401 is not refreshed for telemetry');
+});
+
+test('resolveEnvironmentIdentity sends no request when the script never read a token (a refused sign-in, a lock refusal, a failed push)', async () => {
+ const auth = fakeAuth({ peek: () => null, whoAmI: async () => { throw new Error('no request without a token'); } });
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth }), {});
+ assert.deepEqual(auth.calls, [['peek', 'https://contoso.crm.dynamics.com']]);
+ // An auth module without the memo read (an older copy) is the same: no IDs, and no Azure CLI.
+ const { peekAuthToken, ...older } = fakeAuth({ whoAmI: async () => ({ status: 200, data: { OrganizationId: ORG } }) });
+ assert.equal(typeof peekAuthToken, 'function');
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth: older }), {});
+});
+
+test('resolveEnvironmentIdentity degrades to nothing — a slow, failed or refused WhoAmI sends neither ID, since the token\'s tenant is the environment\'s only once it accepted the token', async () => {
+ const slow = fakeAuth({ whoAmI: () => new Promise(() => {}) });
+ const t0 = Date.now();
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth: slow, timeoutMs: 50 }), {});
+ assert.ok(Date.now() - t0 < 2000, 'the budget bounds the wait');
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth: fakeAuth({ whoAmI: async () => { throw new Error('ECONNRESET'); } }) }), {});
+ // Observed live: an Azure CLI signed in to another tenant gets a token, and the environment answers 401. Its `tid` is not this environment's.
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('https://contoso.crm.dynamics.com', { auth: fakeAuth({ whoAmI: async () => ({ status: 401, data: {} }) }) }), {});
+ assert.deepEqual(await sc.resolveEnvironmentIdentity('ftp://contoso', { auth: fakeAuth({ whoAmI: async () => ({}) }) }), {});
+});
+
+// ── Gates ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+const OK_INPUT = { skillName: 'app-builder', outcome: 'success', durationMs: 5, envUrl: 'https://contoso.crm.dynamics.com' };
+
+test('nothing is sent from inside a node:test run unless the test asks for it', async () => {
+ const fired = [];
+ const sent = await sc.emitSkillCompleted(OK_INPUT, { env: { NODE_TEST_CONTEXT: 'child' }, fireAndForget: (e) => fired.push(e) });
+ assert.equal(sent, false);
+ assert.deepEqual(fired, []);
+});
+
+test('an invalid input sends nothing', async () => {
+ const env = { POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT: '1', NODE_TEST_CONTEXT: 'child' };
+ for (const input of [null, { outcome: 'success' }, { skillName: 'app-builder', outcome: 'done' }]) {
+ const fired = [];
+ assert.equal(await sc.emitSkillCompleted(input, { env, fireAndForget: (e) => fired.push(e) }), false);
+ assert.deepEqual(fired, []);
+ }
+});
+
+test('a user who opted out gets no organization lookup, and the event still goes to the dispatcher for the local mirror', async () => {
+ const configDir = mkTemp();
+ fs.writeFileSync(path.join(configDir, 'config.json'), JSON.stringify({ telemetry: { 'model-apps': 'off' } }));
+ const fired = [];
+ let looked = 0;
+ const sent = await sc.emitSkillCompleted(OK_INPUT, {
+ env: { NODE_TEST_CONTEXT: 'child', POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT: '1', POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir },
+ resolveIdentity: async () => { looked += 1; return { orgId: ORG }; },
+ fireAndForget: (e) => fired.push(e),
+ });
+ assert.equal(sent, true);
+ assert.equal(looked, 0);
+ assert.equal(fired[0].data.orgId, undefined);
+});
+
+// Spawns a process that calls emitSkillCompleted with `input`, the way a script does, and returns the probe the dispatcher writes.
+// `identity` is what the organization lookup answers ({} for a lookup that was skipped, refused or timed out).
+function emitInChild({ input, ikeyPath, configDir, extraEnv = {}, identity = { orgId: ORG, tenantId: TENANT } }) {
+ const probe = path.join(configDir, 'probe.json');
+ const code = `require(${JSON.stringify(MODULE)}).emitSkillCompleted(${JSON.stringify(input)}, ` +
+ `{ resolveIdentity: async () => (${JSON.stringify(identity)}) }).then((r) => process.stdout.write(String(r)));`;
+ const res = spawnSync(process.execPath, ['-e', code], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT: '1',
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || '',
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probe,
+ // CI opts out of transmission; this case asserts what WOULD be sent, so it clears that for its own child only.
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '',
+ ...extraEnv,
+ },
+ timeout: 15000,
+ });
+ return { res, probe };
+}
+
+test('the repo kill switch and an unprovisioned key send nothing', () => {
+ for (const cfg of [
+ { instrumentationKey: 'k-1', collector_url: 'https://example.invalid/', event_stream_name: 'S', disabled: true },
+ { instrumentationKey: 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING', collector_url: 'https://example.invalid/', event_stream_name: 'S', disabled: false },
+ ]) {
+ const configDir = mkTemp();
+ const ikeyPath = path.join(configDir, 'ikey.json');
+ fs.writeFileSync(ikeyPath, JSON.stringify(cfg));
+ const { res, probe } = emitInChild({ input: OK_INPUT, ikeyPath, configDir });
+ assert.equal(res.stdout, 'false', res.stderr);
+ assert.equal(waitForFile(probe, 1000), false);
+ }
+});
+
+test('end to end with the shipped config: the Power Apps client event carries the outcome, counts and target identity — and nothing else', () => {
+ const configDir = mkTemp();
+ // Seed the shared org→region cache so the public-cloud route resolves without the Artemis gateway: the test stays offline.
+ fs.mkdirSync(path.join(configDir, 'region-cache'), { recursive: true });
+ fs.writeFileSync(path.join(configDir, 'region-cache', `${ORG}.json`), JSON.stringify({ region: 'eu', expiresAt: Date.now() + 3600000 }));
+ const input = {
+ ...OK_INPUT,
+ outcome: 'failure',
+ errorClass: 'halted',
+ eventInfo: { operation: 'app-build', scope: 'full', publish: true, haltPhase: 'forms', steps: { forms: { ok: 2, error: 1 } }, appName: 'Contoso Sales' },
+ };
+ const { res, probe } = emitInChild({ input, configDir });
+ assert.equal(res.stdout, 'true', res.stderr);
+ assert.ok(waitForFile(probe, 5000), 'the dispatcher wrote the probe');
+ const shipped = JSON.parse(fs.readFileSync(SHIPPED_IKEY, 'utf8'));
+ const { headers, body } = JSON.parse(fs.readFileSync(probe, 'utf8'));
+ assert.equal(headers['x-apikey'], shipped.regions.eu.instrumentation_key, 'a public-cloud org is routed by its geo');
+ const wire = JSON.parse(body);
+ assert.equal(wire.name, 'event');
+ assert.equal(wire.data.clientType, 'ModelAppsAIPlugin');
+ assert.equal(wire.data.event_Name, 'skill_completed');
+ assert.equal(wire.data.severity, 'Error');
+ assert.equal(wire.data.tenantId, TENANT);
+ const dims = JSON.parse(wire.data.customDimensions);
+ assert.equal(dims.pluginName, 'model-apps');
+ assert.equal(dims.skillName, 'app-builder');
+ assert.equal(dims.outcome, 'failure');
+ assert.equal(dims.errorClass, 'halted');
+ assert.equal(dims.durationMs, 5);
+ assert.equal(dims.orgId, ORG);
+ assert.deepEqual(dims.eventInfo, {
+ schemaVersion: 1, operation: 'app-build', scope: 'full', publish: true, haltPhase: 'forms', steps: { forms: { ok: 2, skip: 0, error: 1 } },
+ });
+ assert.ok(!body.includes('Contoso Sales'), 'an app name never reaches the wire');
+ assert.ok(!body.includes('contoso.crm.dynamics.com'), 'the environment URL never reaches the wire');
+});
+
+test('an environment in an unrecognized cloud is not sent anywhere — with an organization ID, and without one', () => {
+ for (const identity of [{ orgId: ORG, tenantId: TENANT }, {}]) {
+ const configDir = mkTemp();
+ const { res, probe } = emitInChild({ input: { ...OK_INPUT, envUrl: 'https://contoso.example.com' }, configDir, identity });
+ assert.equal(res.stdout, 'true', res.stderr);
+ // Without an ID a blank cloud would read as a signed-out PAC and take the public US default; the emitter names it unroutable instead.
+ assert.ok(waitForMirror(configDir), 'the dispatcher ran (it mirrors every event it is handed)');
+ assert.equal(waitForFile(probe, 1500), false, `routed somewhere with ${JSON.stringify(identity)}`);
+ }
+});
+
+test('a recognized public host with no organization ID (the lookup was skipped) still sends, to the configured default', () => {
+ const configDir = mkTemp();
+ const { res, probe } = emitInChild({ input: OK_INPUT, configDir, identity: {} });
+ assert.equal(res.stdout, 'true', res.stderr);
+ assert.ok(waitForFile(probe, 5000), 'the dispatcher wrote the probe');
+ const shipped = JSON.parse(fs.readFileSync(SHIPPED_IKEY, 'utf8'));
+ assert.equal(JSON.parse(fs.readFileSync(probe, 'utf8')).headers['x-apikey'], shipped.regions[shipped.default_region].instrumentation_key);
+});
diff --git a/plugins/model-apps/skills/telemetry/telemetry-workflow.md b/plugins/model-apps/skills/telemetry/telemetry-workflow.md
index f8eadef00..165568488 100644
--- a/plugins/model-apps/skills/telemetry/telemetry-workflow.md
+++ b/plugins/model-apps/skills/telemetry/telemetry-workflow.md
@@ -47,6 +47,11 @@ telemetry for this plugin. Default to `status` when no argument is given.
revision/common context and outcome markers even when transmission is off.
Old receipts are pruned best-effort after 14 days on a later selection; hard-off
writes none. No additional question, catalog fetch, or per-poll event is needed.
+- Model Apps app builds (`--apply`) and page uploads record `skill_completed`
+ when they finish: the outcome, duration, a fixed error class and per-phase
+ step counts (or whether a page was created, updated or unchanged), with the
+ organization and tenant GUIDs of the environment they targeted. App, table,
+ page and environment names are never included.
- Events do not include file paths, prompts, tool inputs, site names, Dataverse
URLs, credentials, usernames, or hostnames.
- **Automation/CI** can disable telemetry by setting the opt-out env var
diff --git a/plugins/pcf/.claude-plugin/plugin.json b/plugins/pcf/.claude-plugin/plugin.json
index 1ca65ca30..d364d4213 100644
--- a/plugins/pcf/.claude-plugin/plugin.json
+++ b/plugins/pcf/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "pcf",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Preview. Build, test, diagnose, upgrade, deploy, verify and inventory Power Apps component framework (PCF) code components for model-driven apps, with guided setup for Power Pages standard field controls and canvas apps, from Microsoft-maintained templates and recipes pinned to a tested version matrix. Requires Node.js 20+; PAC CLI and the .NET SDK to deploy; Azure CLI (az) to verify and inventory.",
"author": {
"name": "Microsoft",
diff --git a/plugins/pcf/.plugin/plugin.json b/plugins/pcf/.plugin/plugin.json
index 1ca65ca30..d364d4213 100644
--- a/plugins/pcf/.plugin/plugin.json
+++ b/plugins/pcf/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "pcf",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Preview. Build, test, diagnose, upgrade, deploy, verify and inventory Power Apps component framework (PCF) code components for model-driven apps, with guided setup for Power Pages standard field controls and canvas apps, from Microsoft-maintained templates and recipes pinned to a tested version matrix. Requires Node.js 20+; PAC CLI and the .NET SDK to deploy; Azure CLI (az) to verify and inventory.",
"author": {
"name": "Microsoft",
diff --git a/plugins/pcf/AGENTS.md b/plugins/pcf/AGENTS.md
index dcf569f72..b3dfddd9d 100644
--- a/plugins/pcf/AGENTS.md
+++ b/plugins/pcf/AGENTS.md
@@ -112,7 +112,7 @@ PCF telemetry is **live on the shared model-apps tenant** and default-on for tra
- **Shared tenant and rotation:** change model-apps' `ikey.json`, then copy it into pcf in the same PR. `scripts/validate-plugin-copies.js` enforces this byte-identical config pair; `SHARED_KEY_GROUPS` in the key validator permits only model-apps + pcf, never an outsider.
- **Copies:** `scripts/lib/telemetry/lib/` is byte-identical to `shared/telemetry/lib/`; `region/` is byte-identical to Power Pages' telemetry region router. Refresh by copying source bytes, never editing a bundled file. `scripts/tests/telemetry-lib-copy.test.js` guards both, and PCF script CI watches both source paths.
-- **Identity and schema:** `clientType: "PcfAIPlugin"`, `pluginName: "pcf"` in the Power Apps client `event` envelope. Emit `skill_started` with base fields only, including `orgId`/`tenantId` when available, never the signed-in user's object ID or any `eventInfo` payload. PCF-specific `eventInfo` fields or new event types require privacy review first.
+- **Identity and schema:** `clientType: "PcfAIPlugin"`, `pluginName: "pcf"` in the Power Apps client `event` envelope. `skill_started` carries base fields only, including `orgId`/`tenantId` when available, never the signed-in user's object ID. `skill_completed` from `pcf-push.js` adds the approved control-push `eventInfo` (`shared/telemetry/README.md`, "Model Apps and PCF"), built by `scripts/lib/telemetry/skill-completed.js` — a verbatim copy of model-apps' (refresh it with `Copy-Item`; `scripts/validate-plugin-copies.js` fails on drift). Any other `eventInfo` field or event type requires privacy review first.
- **Routing:** PCF owns `resolver.js`. Sovereign/internal clouds route by PAC stamp alone; unknown clouds and signed-in organizations without a cloud stamp send nothing. A public organization routes by Artemis geo through the region-only shared cache, with no public-default fallback when its geo is unknown. Only signed-out PAC uses the configured default.
- **Hooks:** `run-skill-pretool-telemetry.js` and `run-user-prompt-telemetry.js` share `pcf-hook-utils.js`, which discovers installed `skills/*/SKILL.md` and excludes the telemetry control skill. No validator discovery is needed. Emission failures exit 0 and never block authoring.
- **Controls:** `scripts/telemetry-config.js` reuses the bundled user-config and local-log helpers without changing the shared library. `/pcf:telemetry on|off|status` merge-writes `telemetry["pcf"]` or reports the actual build state. The `POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT=1` environment opt-out has highest precedence. Opt-outs suppress transmission only; the local diagnostic mirror remains.
diff --git a/plugins/pcf/README.md b/plugins/pcf/README.md
index 0293f2f6a..0b97ba8af 100644
--- a/plugins/pcf/README.md
+++ b/plugins/pcf/README.md
@@ -129,7 +129,7 @@ export PCF_DISABLE_HOOKS=1
Usage telemetry is **enabled and default-on** for transmission, with **no first-run prompt**. PCF shares model-apps' 1DS tenant and instrumentation keys; its bundled `ikey.json` is a byte-identical copy.
-The hooks send **`skill_started` only**, with these approved base fields:
+The hooks send **`skill_started`**, with these approved base fields:
- `pluginName`, `pluginVersion`, `skillName` - plugin and invoked skill identity.
- `sessionId`, `correlationId` - session and per-invocation correlation.
@@ -137,7 +137,9 @@ The hooks send **`skill_started` only**, with these approved base fields:
- `pacCliVersion`, `aiAgentName`, `aiAgentVersion` - PAC and host agent metadata when available.
- `orgId`, `tenantId` - Dataverse organization and Entra tenant GUIDs when PAC is signed in.
-There is **no user object ID** and **no `eventInfo` payload**. The Power Apps client `event` envelope uses `clientType: "PcfAIPlugin"` and `pluginName: "pcf"` so PCF usage stays separate from other plugins and native-client traffic.
+When `pcf-push.js` finishes a push, it sends **`skill_completed`** with the same base fields (its own random `sessionId`, no PAC version), plus `outcome`, `durationMs`, a fixed `errorClass` on failure, and an `eventInfo` of enums and booleans only: `operation: "control-push"`, `incremental`, `registration` (`verified`, `not-verified`, `skipped`) and `steps.push`. Its `orgId`/`tenantId` are those of the environment pushed to, read with one `WhoAmI` using the token the registration read already holds; a push that did not read its registration back sends neither. The approved schema is in `shared/telemetry/README.md`.
+
+There is **no user object ID**. The Power Apps client `event` envelope uses `clientType: "PcfAIPlugin"` and `pluginName: "pcf"` so PCF usage stays separate from other plugins and native-client traffic.
**Routing matches model-apps:** a public-cloud organization routes by its geo to the US or EU collector, with no public-default fallback when its geo is unknown. Only signed-out PAC uses the configured US default. Sovereign or internal clouds route from the PAC cloud stamp alone, never to a public collector; unknown clouds and signed-in organizations without a cloud stamp send nothing.
diff --git a/plugins/pcf/scripts/lib/dataverse-auth.js b/plugins/pcf/scripts/lib/dataverse-auth.js
index b53aa626a..2f456281a 100644
--- a/plugins/pcf/scripts/lib/dataverse-auth.js
+++ b/plugins/pcf/scripts/lib/dataverse-auth.js
@@ -120,6 +120,14 @@ function getAuthToken(envUrl, opts = {}) {
return readAzToken(resource, opts);
}
+// The token this process has ALREADY read for the environment (the memo getAuthToken fills), or null. It never starts the Azure CLI:
+// for work that must not cost the user a CLI start of seconds — usage telemetry after a script's real work is done
+// (lib/telemetry/skill-completed.js) — and for which "no token yet" simply means "do without".
+function peekAuthToken(envUrl) {
+ const resource = dataverseOrigin(envUrl);
+ return resource && authTokenMemo.has(resource) ? authTokenMemo.get(resource) : null;
+}
+
// The Azure CLI read behind getAuthToken (above), with one memo, one failure record and one budget. In model-apps the same
// function also reads that plugin's Power Apps service token; this copy keeps only what getAuthToken needs. `resource` is the
// `--resource` of `az account get-access-token`, and getAuthToken passes only a checked Dataverse origin, so nothing here accepts
@@ -774,6 +782,7 @@ module.exports = {
requireDataverseOrigin,
webApiUrl,
getAuthToken,
+ peekAuthToken,
getAuthTokenAsync,
tokenFailureKind,
tokenFailureMessage,
diff --git a/plugins/pcf/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/pcf/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/pcf/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/pcf/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/plugins/pcf/scripts/lib/telemetry/skill-completed.js b/plugins/pcf/scripts/lib/telemetry/skill-completed.js
new file mode 100644
index 000000000..fafd02735
--- /dev/null
+++ b/plugins/pcf/scripts/lib/telemetry/skill-completed.js
@@ -0,0 +1,325 @@
+"use strict";
+
+// `skill_completed` usage telemetry for the scripts that change a Power Platform environment: the
+// model-apps app build (build-model-app.js), the generative-page upload (genpage-upload.js) and the pcf
+// control push (pcf-push.js). The skill_started hooks only say a skill BEGAN; this event says what the
+// run did to the environment — its outcome, how long it took, and how many artifacts of each kind it
+// created, reused or failed on — so usage can be tied to the apps, pages and controls it produced.
+//
+// plugins/pcf/scripts/lib/telemetry/skill-completed.js is a VERBATIM copy of this file
+// (scripts/validate-plugin-copies.js fails on drift): edit this one, then copy it over. That is why it
+// reads its plugin's name and version from the manifest beside it instead of naming a plugin.
+//
+// Privacy contract (shared/telemetry/README.md, "Model Apps and PCF"): every nested `eventInfo` value is
+// a fixed enum, a boolean or a bounded count — sanitizeEventInfo() drops anything else, so no table,
+// app, page, control, solution or environment NAME, no URL and no error text can reach the wire. The
+// only identifiers are the Dataverse organization GUID and the Entra tenant GUID of the environment the
+// run targeted, as skill_started already carries; never the signed-in user's object ID.
+//
+// Fail closed throughout: telemetry must never change a script's result or exit code, so every path
+// here swallows its own errors and the caller's `await` resolves either way.
+
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const events = require("./lib/events");
+const emitSpawn = require("./lib/emit-spawn");
+const agentInfo = require("./lib/agent-info");
+const resolverLoader = require("./lib/resolver-loader");
+const { isTransmissionOptedOut } = require("./lib/user-config");
+
+const TELEMETRY_DIR = __dirname;
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..", "..");
+const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";
+const DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".power-platform-skills");
+// The WhoAmI that names the target organization runs while the user waits for the script's result, so it
+// gets a short budget; a slow or failing read only drops the IDs from the event.
+const IDENTITY_TIMEOUT_MS = 3000;
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+// Not a PAC cloud token, so resolver.js routes it nowhere; see the emit below.
+const UNROUTABLE_CLOUD = "Unrecognized";
+
+// ---- The approved eventInfo schema --------------------------------------------------------------------
+// Keep in step with shared/telemetry/README.md. Adding a key or a value needs the privacy review that
+// file describes, plus its disclosure and the tests in scripts/tests/skill-completed.test.js.
+const OPERATIONS = new Set(["app-build", "page-upload", "control-push"]);
+// The app build's engine phases (scripts/lib/stages.js PHASES, pinned by a test) and the two the build
+// reports outside them: `preflight` (checks before any write) and `push` (the pcf deploy).
+const PHASES = new Set([
+ "preflight", "solution", "data-model", "sample-data", "web-resources", "views", "charts", "forms",
+ "business-rules", "business-process-flows", "commands", "dashboards", "app-shell", "pages",
+ "ai-features", "security", "publish", "push",
+]);
+const SCOPES = new Set(["full", "staged", "changed-only"]);
+const VERIFY_RESULTS = new Set(["passed", "failed", "not-run"]);
+const PAGE_ACTIONS = new Set(["created", "updated", "unchanged"]);
+const REGISTRATION = new Set(["verified", "not-verified", "skipped"]);
+const STEP_STATUSES = ["ok", "skip", "error"];
+// Top-level `errorClass` on a failure. Stable class names, never an error message.
+const ERROR_CLASSES = new Set([
+ "auth", "invalid-input", "locked", "halted", "verify-failed", "deploy-failed", "timeout", "unexpected",
+]);
+// A step count above this is not a real run; clamp rather than send an implausible number.
+const MAX_COUNT = 100000;
+
+function count(value) {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < 0) return 0;
+ return Math.min(Math.floor(n), MAX_COUNT);
+}
+
+function enumOf(value, allowed) {
+ return typeof value === "string" && allowed.has(value) ? value : undefined;
+}
+
+function bool(value) {
+ return typeof value === "boolean" ? value : undefined;
+}
+
+// Allowlist-only: what is not named here is dropped. `steps` is { <phase>: { ok, skip, error } }.
+function sanitizeEventInfo(input) {
+ const src = input && typeof input === "object" && !Array.isArray(input) ? input : {};
+ const out = { schemaVersion: 1 };
+ const set = (key, value) => { if (value !== undefined) out[key] = value; };
+ set("operation", enumOf(src.operation, OPERATIONS));
+ set("scope", enumOf(src.scope, SCOPES));
+ set("publish", bool(src.publish));
+ set("verify", enumOf(src.verify, VERIFY_RESULTS));
+ set("haltPhase", enumOf(src.haltPhase, PHASES));
+ set("page", enumOf(src.page, PAGE_ACTIONS));
+ set("placedInApp", bool(src.placedInApp));
+ set("addedToSolution", bool(src.addedToSolution));
+ set("incremental", bool(src.incremental));
+ set("registration", enumOf(src.registration, REGISTRATION));
+ if (src.steps && typeof src.steps === "object" && !Array.isArray(src.steps)) {
+ const steps = {};
+ for (const [phase, tally] of Object.entries(src.steps)) {
+ if (!PHASES.has(phase) || !tally || typeof tally !== "object") continue;
+ const row = {};
+ for (const status of STEP_STATUSES) row[status] = count(tally[status]);
+ if (row.ok + row.skip + row.error > 0) steps[phase] = row;
+ }
+ if (Object.keys(steps).length) out.steps = steps;
+ }
+ return out;
+}
+
+// ---- Step tally ---------------------------------------------------------------------------------------
+// Fed the build engine's progress events ({ phase, status, replaces? }). A step the engine takes up again
+// names the outcome it replaces (build-model-app.js cliEmit), so each step is counted once, by its final
+// outcome — the same rule as the build's closing "N created, N skipped, N failed" line.
+function createStepTally() {
+ const byPhase = {};
+ return {
+ record(e) {
+ if (!e || typeof e.phase !== "string" || !STEP_STATUSES.includes(e.status)) return;
+ const row = byPhase[e.phase] || (byPhase[e.phase] = { ok: 0, skip: 0, error: 0 });
+ if (STEP_STATUSES.includes(e.replaces) && row[e.replaces] > 0) row[e.replaces] -= 1;
+ row[e.status] += 1;
+ },
+ // The engine restarts every phase on an automatic retry; the summary reflects the final attempt.
+ reset() { for (const key of Object.keys(byPhase)) delete byPhase[key]; },
+ snapshot() { return JSON.parse(JSON.stringify(byPhase)); },
+ };
+}
+
+// ---- Routing context ----------------------------------------------------------------------------------
+// The cloud of the TARGET environment, from its host, as the PAC cloud token the plugin's resolver.js
+// routes on. Hooks read `pac auth who`, whose active profile can be a different environment from the
+// `--env` a script was given; the host is the target's own. Host families as lib/dataverse-auth.js
+// DATAVERSE_HOST accepts them (GCC is the `crm9` region of the commercial family):
+// https://learn.microsoft.com/power-platform/admin/new-datacenter-regions
+// https://learn.microsoft.com/power-platform/admin/powerapps-us-government#power-apps-us-government-service-urls
+// lib/sdk-first.js connectivityCloudOf reads hosts too, but answers a different question (which route
+// the SDK can take, so GCC is "Unsupported" there); this one must name every cloud a key exists for.
+// An unknown host returns "". The emitter never hands "" to the resolver for a run that had a target: with
+// no organization ID, "" reads as a signed-out PAC and routes to the public US default (resolver.js).
+function cloudOfEnvironment(envUrl) {
+ let host = "";
+ try { host = new URL(String(envUrl)).host.toLowerCase(); } catch { return ""; }
+ if (/\.(?:api\.)?crmtest\.dynamics\.com$/.test(host)) return "Test";
+ if (/\.(?:api\.)?crm9\.dynamics\.com$/.test(host)) return "UsGov";
+ if (/\.(?:api\.)?crm\d*\.dynamics\.com$/.test(host)) return "Public";
+ if (/\.(?:api\.)?crm\.microsoftdynamics\.us$/.test(host)) return "UsGovHigh";
+ if (/\.(?:api\.)?crm\.appsplatform\.us$/.test(host)) return "UsGovDod";
+ if (/\.(?:api\.)?crm\.dynamics\.cn$/.test(host)) return "China";
+ return "";
+}
+
+// The Entra tenant GUID from an access token's `tid` claim. Only `tid` is read — never `oid`, `upn` or any
+// other user claim — and nothing is verified: the token was just issued to this process by the Azure CLI,
+// and a wrong value only mislabels a usage event.
+// JWT layout (RFC 7519): base64url(header).base64url(payload).signature, payload e.g. {"tid":"<guid>",...}
+function tenantIdFromToken(token) {
+ try {
+ const payload = String(token).split(".")[1];
+ if (!payload) return undefined;
+ const claims = JSON.parse(Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
+ return typeof claims.tid === "string" && GUID.test(claims.tid) ? claims.tid.toLowerCase() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+// { orgId, tenantId } of the target environment, or {} — never throws, and never starts the Azure CLI: the
+// token is read from dataverse-auth's per-process memo (peekAuthToken), which the script filled when it
+// talked to the environment. A script that never got that far — a refused sign-in, a lock refusal, a failed
+// push — has no token there, and its event simply goes without the IDs; reading one would cost the user a
+// CLI start of seconds (up to the Azure CLI budget) for telemetry. The one request is a WhoAmI.
+// Both IDs come from an ACCEPTED WhoAmI, or neither is sent: the token's `tid` names the tenant the Azure
+// CLI signed in to, which is the environment's only if the environment accepted the token. (Observed live:
+// a CLI signed in to another tenant gets a token, and the environment answers 401.)
+// WhoAmI: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/whoami
+async function resolveEnvironmentIdentity(envUrl, deps = {}) {
+ try {
+ const auth = deps.auth || require("../dataverse-auth.js");
+ if (typeof auth.peekAuthToken !== "function") return {};
+ const origin = auth.dataverseOrigin(envUrl);
+ if (!origin) return {};
+ const token = auth.peekAuthToken(origin);
+ if (!token) return {};
+ let timer;
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), deps.timeoutMs || IDENTITY_TIMEOUT_MS); });
+ const who = auth.dataverseRequest(origin, "GET", "WhoAmI", null, { token, timeout: deps.timeoutMs || IDENTITY_TIMEOUT_MS, refreshOn401: false })
+ .catch(() => null);
+ const res = await Promise.race([who, timeout]);
+ clearTimeout(timer);
+ const orgId = res && res.status >= 200 && res.status < 300 && res.data && res.data.OrganizationId;
+ if (typeof orgId !== "string" || !GUID.test(orgId)) return {};
+ const tenantId = tenantIdFromToken(token);
+ return { orgId: orgId.toLowerCase(), ...(tenantId ? { tenantId } : {}) };
+ } catch {
+ return {};
+ }
+}
+
+// ---- Gates --------------------------------------------------------------------------------------------
+function readIkey() {
+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ const ikeyPath = override && override.trim() ? override : path.join(TELEMETRY_DIR, "ikey.json");
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return { cfg, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };
+ } catch {
+ // Unreadable config is the repo kill switch, as in emit-dispatcher.js: fail closed.
+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };
+ }
+}
+
+function isProvisioned(cfg, ikeyPath) {
+ try {
+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));
+ if (resolver && typeof resolver.isProvisioned === "function") return !!resolver.isProvisioned(cfg);
+ return !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== PLACEHOLDER_IKEY);
+ } catch {
+ return false;
+ }
+}
+
+function readManifest() {
+ try {
+ const m = JSON.parse(fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8"));
+ return { name: typeof m.name === "string" ? m.name : "", version: m.version || "unknown" };
+ } catch {
+ return { name: "", version: "unknown" };
+ }
+}
+
+// node:test marks every process it runs (and their children inherit it) with NODE_TEST_CONTEXT. The
+// scripts this module serves are exercised by hundreds of tests with stand-in environments; without this
+// gate each of them would spawn a dispatcher, write a mirror in the developer's home and — on a machine
+// with no opt-out set — post an event about a fake build. A test that means to check emission sets
+// POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT=1 and routes it to a POWER_PLATFORM_SKILLS_FAKE_HTTPS probe.
+function suppressedUnderTest(env) {
+ return !!env.NODE_TEST_CONTEXT && env.POWER_PLATFORM_SKILLS_TELEMETRY_TEST_EMIT !== "1";
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+// ---- Emit ---------------------------------------------------------------------------------------------
+// input: { skillName, outcome: "success"|"failure", durationMs, errorClass?, eventInfo?, envUrl?,
+// orgId?, tenantId?, resolveIdentity? (default true) }
+// Resolves true when an event was handed to the dispatcher, false otherwise. Never rejects.
+async function emitSkillCompleted(input, deps = {}) {
+ try {
+ const env = deps.env || process.env;
+ if (suppressedUnderTest(env)) return false;
+ if (!input || typeof input.skillName !== "string" || !input.skillName) return false;
+ const outcome = input.outcome === "success" || input.outcome === "failure" ? input.outcome : null;
+ if (!outcome) return false;
+
+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();
+ if (disabled || !isProvisioned(cfg, ikeyPath)) return false;
+ const manifest = readManifest();
+ if (!manifest.name) return false;
+
+ const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";
+ // A user who opted out of transmission still gets the local mirror (the dispatcher writes it), but no
+ // network request is made on telemetry's behalf: the organization lookup is skipped, so their mirror
+ // records the event without the organization and tenant IDs.
+ const optedOut = isTransmissionOptedOut(configDir || DEFAULT_CONFIG_DIR, manifest.name, env);
+ let identity = {
+ ...(typeof input.orgId === "string" && GUID.test(input.orgId) ? { orgId: input.orgId.toLowerCase() } : {}),
+ ...(typeof input.tenantId === "string" && GUID.test(input.tenantId) ? { tenantId: input.tenantId.toLowerCase() } : {}),
+ };
+ if (!optedOut && input.resolveIdentity !== false && input.envUrl && !(identity.orgId && identity.tenantId)) {
+ const resolved = await (deps.resolveIdentity || resolveEnvironmentIdentity)(input.envUrl);
+ identity = { ...resolved, ...identity };
+ }
+
+ let agent = {};
+ try { agent = agentInfo.readAiAgent(env) || {}; } catch { agent = {}; }
+ const durationMs = Number.isFinite(input.durationMs) && input.durationMs >= 0 ? Math.round(input.durationMs) : undefined;
+ const errorClass = outcome === "failure" ? (enumOf(input.errorClass, ERROR_CLASSES) || "unexpected") : undefined;
+
+ const fields = {
+ pluginName: manifest.name,
+ pluginVersion: manifest.version,
+ // Scripts run outside the hooks that see the agent's session, so a completion carries its own random
+ // run ID; it is tied to the environment through orgId, not to the skill_started that preceded it.
+ sessionId: crypto.randomUUID(),
+ correlationId: crypto.randomUUID(),
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: "v" + String(process.versions.node).split(".")[0],
+ skillName: input.skillName,
+ outcome,
+ ...(durationMs !== undefined ? { durationMs } : {}),
+ ...(errorClass ? { errorClass } : {}),
+ ...identity,
+ eventInfo: sanitizeEventInfo(input.eventInfo),
+ ...(agent.aiAgentName ? { aiAgentName: agent.aiAgentName } : {}),
+ ...(agent.aiAgentVersion ? { aiAgentVersion: agent.aiAgentVersion } : {}),
+ };
+ (deps.fireAndForget || emitSpawn.fireAndForget)(events.buildSkillCompleted(eventStreamName, fields), {
+ // A host outside the known Dataverse families gets a cloud no resolver recognizes, so the event is mirrored locally and sent
+ // nowhere — never to the public default a blank cloud would select when the run has no organization ID (a lookup skipped,
+ // refused or timed out). resolver.js: an unrecognized non-empty cloud resolves to null.
+ cloud: cloudOfEnvironment(input.envUrl) || UNROUTABLE_CLOUD,
+ configDir,
+ fakeProbe: env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",
+ ikeyJsonPath: ikeyPath,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+module.exports = {
+ emitSkillCompleted,
+ createStepTally,
+ sanitizeEventInfo,
+ cloudOfEnvironment,
+ tenantIdFromToken,
+ resolveEnvironmentIdentity,
+ ERROR_CLASSES,
+ PHASES,
+};
diff --git a/plugins/pcf/scripts/pcf-push.js b/plugins/pcf/scripts/pcf-push.js
index c0cd99aab..281aaf4a3 100644
--- a/plugins/pcf/scripts/pcf-push.js
+++ b/plugins/pcf/scripts/pcf-push.js
@@ -13,6 +13,7 @@ const { pcfprojBuildMode } = require('./lib/pcf-doctor.js');
const { makePcfSdk, findCustomControl, solutionPrefix } = require('./lib/pcf-dataverse.js');
const { parseManifest } = require('./lib/pcf-manifest.js');
const { booleanFlagError } = require('./lib/pcf-cli-flags.js');
+const { emitSkillCompleted } = require('./lib/telemetry/skill-completed.js');
const USAGE = `Usage:
node scripts/pcf-push.js --project <dir> --env <url> (--solution <uniqueName> | --publisher-prefix <p>) [--incremental] [--verbosity minimal|normal|detailed|diagnostic] [--allow-dev-bundle] [--no-verify]
@@ -75,6 +76,7 @@ function usageError(message) {
}
async function main(argv = process.argv.slice(2)) {
+ const startedAt = Date.now();
const parsed = parseArgs(argv);
const flagError = validateFlags(argv, {
known: KNOWN,
@@ -137,21 +139,26 @@ async function main(argv = process.argv.slice(2)) {
];
const push = runPac(pacArgs, { cwd: projectDir, timeoutMs: PUSH_TIMEOUT_MS });
+ // From here the push has run, so every exit reports skill_completed before the result is printed (emitResult exits the process).
+ const finish = async (ok, payload, facts) => {
+ await reportPush({ envOrigin, startedAt, incremental: !!flags.incremental, noVerify: !!flags['no-verify'], ...facts });
+ return emitResult(ok, payload);
+ };
if (timedOut(push)) {
// On Windows, process-runner starts a pac.cmd batch shim under checked cmd.exe arguments. Killing
// that wrapper on timeout is best-effort and may leave the MSBuild child running, so report the
// diagnostic log path and never claim the push was aborted.
- return emitResult(false, {
+ return finish(false, {
ok: false,
stage: 'push',
timedOut: true,
log: buildLogPath(projectDir),
message: 'pac pcf push timed out; the push or its MSBuild child may still be running. Inspect the build log before retrying.',
- });
+ }, { stage: 'push', timedOut: true });
}
if ((push.status || 0) !== 0) {
- return emitResult(false, {
+ return finish(false, {
ok: false,
stage: 'push',
status: push.status,
@@ -160,7 +167,7 @@ async function main(argv = process.argv.slice(2)) {
logTail: readBuildLogTail(projectDir),
stdout: scrubbedTail(push.stdout, 60),
stderr: scrubbedTail(push.stderr, 60),
- });
+ }, { stage: 'push' });
}
const expectedVersion = manifest.model.control.version || null;
@@ -185,23 +192,50 @@ async function main(argv = process.argv.slice(2)) {
registered,
});
} catch (err) {
- return emitResult(false, {
+ return finish(false, {
ok: false,
stage: 'receipt',
reason: errorReason(err),
registered: stripPrivateRegistration(registered),
- });
+ }, { stage: 'receipt', registered: !!registered.ok });
}
const ok = !!registered.ok || !!flags['no-verify'];
- return emitResult(ok, {
+ return finish(ok, {
ok,
stage: 'done',
control: controlName,
version: expectedVersion,
registered: stripPrivateRegistration(registered),
receipt,
- });
+ }, { stage: 'done', ok, registered: !!registered.ok });
+}
+
+// What a push's result says, in the closed vocabulary of lib/telemetry/skill-completed.js — never a control, solution or environment name.
+// done, ok → success; registration verified | skipped (--no-verify)
+// done, registration not read back → verify-failed push timed out → timeout
+// pac pcf push failed → deploy-failed the receipt could not be written → unexpected
+function pushCompletion({ stage, ok, timedOut: timedOutPush, registered, incremental, noVerify } = {}) {
+ const pushed = stage === 'done' || stage === 'receipt';
+ const eventInfo = {
+ operation: 'control-push',
+ incremental: !!incremental,
+ registration: noVerify ? 'skipped' : registered ? 'verified' : 'not-verified',
+ steps: { push: pushed ? { ok: 1 } : { error: 1 } },
+ };
+ if (stage === 'done' && ok) return { outcome: 'success', eventInfo };
+ if (stage === 'done') return { outcome: 'failure', errorClass: 'verify-failed', eventInfo };
+ if (stage === 'receipt') return { outcome: 'failure', errorClass: 'unexpected', eventInfo };
+ return { outcome: 'failure', errorClass: timedOutPush ? 'timeout' : 'deploy-failed', eventInfo: { ...eventInfo, haltPhase: 'push' } };
+}
+
+async function reportPush(facts, emit = emitSkillCompleted) {
+ try {
+ const { outcome, errorClass, eventInfo } = pushCompletion(facts);
+ await emit({
+ skillName: 'pcf', outcome, errorClass, eventInfo, envUrl: facts.envOrigin, durationMs: Date.now() - facts.startedAt,
+ });
+ } catch { /* telemetry never changes the push's result */ }
}
function normalizeEnvOrigin(value) {
@@ -387,4 +421,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { main };
+module.exports = { main, pushCompletion };
diff --git a/plugins/pcf/scripts/telemetry-config.js b/plugins/pcf/scripts/telemetry-config.js
index f3f9597ab..6b15495f4 100644
--- a/plugins/pcf/scripts/telemetry-config.js
+++ b/plugins/pcf/scripts/telemetry-config.js
@@ -55,7 +55,8 @@ function main(argv = process.argv.slice(2)) {
const latest = latestSessionLog(configDir, 'pcf');
if (latest) console.log(`Most recent session: ${latest}`);
}
- console.log('An enabled, provisioned release records only skill_started base fields: skill, plugin, PAC, agent, OS and Node versions, session and correlation IDs, plus orgId and tenantId when PAC is signed in; no user object ID or eventInfo fields.');
+ console.log('An enabled, provisioned release records skill_started base fields: skill, plugin, PAC, agent, OS and Node versions, session and correlation IDs, plus orgId and tenantId when PAC is signed in; no user object ID.');
+ console.log('When a control push finishes, skill_completed also records its outcome, duration, a fixed error class and whether the registration was verified, with the orgId and tenantId of the environment it targeted; never control, solution or environment names.');
console.log('Never sent: file paths, cwd, environment variables, prompts, arguments, tool inputs, site names, Dataverse URLs, stack traces, error messages, credentials, usernames or hostnames.');
console.log('Opt out: /pcf:telemetry off or POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT=1 (highest precedence).');
}
diff --git a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js b/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
index cf4b1caf0..120c2bdb2 100644
--- a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
+++ b/plugins/pcf/scripts/tests/pcf-pages-guard.test.js
@@ -840,10 +840,20 @@ test('Pages proof keeps lexical this in arrows but not rebinding functions or cl
const NESTED_SCAN_LIMIT_MS = 1500;
const CONTROL_SCAN_LIMIT_MS = 500;
+// A wall-clock limit on ONE cold run is noise-bound, not a test of the scanner: the first run pays the JIT's warm-up, and a
+// shared CI runner adds GC and scheduler pauses on top (observed: 501 ms against the 500 ms limit on a Windows runner, while
+// local single runs vary 125–253 ms for the same input). So the scan runs once untimed to warm up, then three times, and the
+// FASTEST run is compared: noise only ever adds time, while the regression these limits exist for — a quadratic rescan —
+// slows every run alike, by seconds, and still fails.
function timedScan(text) {
- const started = performance.now();
- const findings = [...scanSource(FILE, text), ...findingsFor(text)];
- return { elapsed: performance.now() - started, findings };
+ let findings = [...scanSource(FILE, text), ...findingsFor(text)];
+ let elapsed = Infinity;
+ for (let i = 0; i < 3; i += 1) {
+ const started = performance.now();
+ findings = [...scanSource(FILE, text), ...findingsFor(text)];
+ elapsed = Math.min(elapsed, performance.now() - started);
+ }
+ return { elapsed, findings };
}
test('Pages proof indexes the 5000-line nested fixture without quadratic rescans', (t) => {
diff --git a/plugins/pcf/scripts/tests/pcf-push.test.js b/plugins/pcf/scripts/tests/pcf-push.test.js
index 7ebb36af8..0d50e7e2c 100644
--- a/plugins/pcf/scripts/tests/pcf-push.test.js
+++ b/plugins/pcf/scripts/tests/pcf-push.test.js
@@ -597,3 +597,20 @@ test('failed receipt write emits receipt-stage JSON and leaves no partial receip
assert.equal(realFs.existsSync(path.join(projectDir, 'pcf-receipt.json')), false);
assert.deepEqual(realFs.readdirSync(projectDir).filter((entry) => entry.startsWith('.pcf-receipt-')), []);
});
+
+// skill_completed telemetry: what a push's result says, in the closed vocabulary of lib/telemetry/skill-completed.js (a verbatim copy of
+// model-apps', whose own suite holds the privacy contract) — never a control, solution or environment name.
+test('pushCompletion maps each push result to its outcome, error class and registration', () => {
+ const { pushCompletion } = require('../pcf-push.js');
+ const info = (over) => ({ operation: 'control-push', incremental: false, registration: 'verified', steps: { push: { ok: 1 } }, ...over });
+ assert.deepEqual(pushCompletion({ stage: 'done', ok: true, registered: true }), { outcome: 'success', eventInfo: info() });
+ assert.deepEqual(pushCompletion({ stage: 'done', ok: true, registered: false, noVerify: true, incremental: true }),
+ { outcome: 'success', eventInfo: info({ registration: 'skipped', incremental: true }) });
+ assert.deepEqual(pushCompletion({ stage: 'done', ok: false, registered: false }),
+ { outcome: 'failure', errorClass: 'verify-failed', eventInfo: info({ registration: 'not-verified' }) });
+ assert.deepEqual(pushCompletion({ stage: 'receipt', registered: true }), { outcome: 'failure', errorClass: 'unexpected', eventInfo: info() });
+ assert.deepEqual(pushCompletion({ stage: 'push', timedOut: true }),
+ { outcome: 'failure', errorClass: 'timeout', eventInfo: info({ registration: 'not-verified', steps: { push: { error: 1 } }, haltPhase: 'push' }) });
+ assert.deepEqual(pushCompletion({ stage: 'push' }),
+ { outcome: 'failure', errorClass: 'deploy-failed', eventInfo: info({ registration: 'not-verified', steps: { push: { error: 1 } }, haltPhase: 'push' }) });
+});
\ No newline at end of file
diff --git a/plugins/pcf/scripts/tests/telemetry-docs.test.js b/plugins/pcf/scripts/tests/telemetry-docs.test.js
index f2c4efd50..c6ca1a3e3 100644
--- a/plugins/pcf/scripts/tests/telemetry-docs.test.js
+++ b/plugins/pcf/scripts/tests/telemetry-docs.test.js
@@ -16,7 +16,7 @@ function telemetrySection(file) {
return section[1];
}
-test('PCF README discloses default-on shared-tenant telemetry and only approved base fields', () => {
+test('PCF README discloses default-on shared-tenant telemetry and only approved fields', () => {
const section = telemetrySection('README.md');
assert.match(section, /enabled.*default-on/i);
assert.match(section, /no first-run prompt/i);
@@ -31,7 +31,12 @@ test('PCF README discloses default-on shared-tenant telemetry and only approved
]) assert.ok(section.includes(field), `approved field missing from disclosure: ${field}`);
assert.match(section, /PAC is signed in/i);
assert.match(section, /no (?:signed-in )?user object (?:ID|identifier)/i);
- assert.match(section, /no `?eventInfo`?/i);
+ // The push's completion event and its closed eventInfo (shared/telemetry/README.md "Model Apps and PCF").
+ for (const field of ['skill_completed', 'outcome', 'durationMs', 'errorClass', 'eventInfo', '"control-push"', 'incremental', 'registration', 'steps.push']) {
+ assert.ok(section.includes(field), `completion field missing from disclosure: ${field}`);
+ }
+ assert.match(section, /enums and booleans only/i);
+ assert.match(section, /environment pushed to/i);
for (const forbidden of ['paths', 'prompts', 'tool inputs', 'Dataverse URLs', 'credentials', 'usernames', 'hostnames']) {
assert.ok(section.includes(forbidden), `never-sent category missing: ${forbidden}`);
}
@@ -85,6 +90,7 @@ test('the shared adopter table pins enabled PCF and its separable base-only shar
assert.match(row, /base fields only/i);
assert.match(row, /orgId.*tenantId.*PAC is signed in/i);
assert.match(row, /no.*user object ID/i);
+ assert.match(row, /skill_completed.*control push.*outcome.*durationMs.*errorClass.*eventInfo/i);
});
test('Model Apps guidance keeps PCF shared-tenant key rotations synchronized', (t) => {
diff --git a/plugins/pcf/skills/telemetry/telemetry-workflow.md b/plugins/pcf/skills/telemetry/telemetry-workflow.md
index e1271e926..d2358d9ca 100644
--- a/plugins/pcf/skills/telemetry/telemetry-workflow.md
+++ b/plugins/pcf/skills/telemetry/telemetry-workflow.md
@@ -27,10 +27,13 @@ usage telemetry. Default to `status` when no argument is given.
are preserved. The preference takes effect on the next event.
- `POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT=1` (or `true`) takes precedence
over the saved preference and `on`. It disables transmission only.
-- Only `skill_started` base fields are sent: skill,
+- `skill_started` sends base fields: skill,
plugin/PAC/agent versions, OS/Node versions, session/correlation IDs, and
- `orgId`/`tenantId` when PAC is signed in. There is **no user object ID** and
- no `eventInfo` payload.
+ `orgId`/`tenantId` when PAC is signed in. There is **no user object ID**.
+- When a control push finishes, `skill_completed` also records its outcome,
+ duration, a fixed error class, whether the push was incremental and whether
+ the registration was verified, with the `orgId`/`tenantId` of the environment
+ it targeted. Control, solution and environment names are never sent.
- File paths, cwd, environment variables, prompts, arguments, tool inputs, site
names, Dataverse URLs, stack traces, error messages, credentials, usernames
and hostnames are never sent.
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/scripts/validate-plugin-copies.js b/scripts/validate-plugin-copies.js
index ec532d889..8c3c7c041 100644
--- a/scripts/validate-plugin-copies.js
+++ b/scripts/validate-plugin-copies.js
@@ -32,6 +32,7 @@ const COPY_SETS = [
['scripts/lib/nearest-name.js', 'scripts/lib/nearest-name.js'],
['scripts/lib/utf8-stream.js', 'scripts/lib/utf8-stream.js'],
['scripts/lib/cli-failure.js', 'scripts/lib/cli-failure.js'],
+ ['scripts/lib/telemetry/skill-completed.js', 'scripts/lib/telemetry/skill-completed.js'],
['scripts/check-auth.js', 'scripts/check-auth.js'],
['scripts/resolve-interaction-mode.js', 'scripts/resolve-interaction-mode.js'],
['scripts/vendor/cds-maker-sdk.cjs', 'scripts/vendor/cds-maker-sdk.cjs'],
@@ -69,6 +70,7 @@ const COPY_SETS = [
'requireDataverseOrigin',
'webApiUrl',
'getAuthToken',
+ 'peekAuthToken',
'getAuthTokenAsync',
'tokenFailureKind',
'tokenFailureMessage',
diff --git a/shared/skills/telemetry/telemetry-workflow.md b/shared/skills/telemetry/telemetry-workflow.md
index f8eadef00..165568488 100644
--- a/shared/skills/telemetry/telemetry-workflow.md
+++ b/shared/skills/telemetry/telemetry-workflow.md
@@ -47,6 +47,11 @@ telemetry for this plugin. Default to `status` when no argument is given.
revision/common context and outcome markers even when transmission is off.
Old receipts are pruned best-effort after 14 days on a later selection; hard-off
writes none. No additional question, catalog fetch, or per-poll event is needed.
+- Model Apps app builds (`--apply`) and page uploads record `skill_completed`
+ when they finish: the outcome, duration, a fixed error class and per-phase
+ step counts (or whether a page was created, updated or unchanged), with the
+ organization and tenant GUIDs of the environment they targeted. App, table,
+ page and environment names are never included.
- Events do not include file paths, prompts, tool inputs, site names, Dataverse
URLs, credentials, usernames, or hostnames.
- **Automation/CI** can disable telemetry by setting the opt-out env var
diff --git a/shared/telemetry/README.md b/shared/telemetry/README.md
index 210bed233..a8a3d2843 100644
--- a/shared/telemetry/README.md
+++ b/shared/telemetry/README.md
@@ -65,8 +65,8 @@ choice cannot override `disabled: true`.
|---|---|---|---|
| Power Pages | `disabled: false` | Enabled and default-on for transmission. Organization-based geo routing selects a regional collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID; `eventInfo.framework` when the Power Pages code-site framework can be determined; `eventInfo.auditPermissions` (aggregate, identity-free) on the `audit-permissions` completion event. |
| Mobile Apps | `disabled: false` | Enabled and default-on for transmission. Its project environment selects the regional collector. Until that cluster is resolved, events remain in the local mirror and are not transmitted. | `eventInfo.invocationSource`; random per-project `eventInfo.appInstanceId` (or `null` outside a prepared project); optional validated checkpoint `eventInfo.additionalInfo`; and `eventInfo.appInsightsSelection`. |
-| Model Apps | `disabled: false` | Enabled and default-on for transmission. A public-cloud organization is geo-routed to the US or EU collector (US default only without an organization ID; an organization whose geo cannot be determined is not transmitted); a sovereign or internal PAC cloud is routed from the cloud stamp alone, never to a public collector; an unrecognized cloud, or a signed-in organization with no cloud, is not transmitted. Events are written to the local mirror even after a user transmission opt-out. | No signed-in user object ID. The base event can include `orgId` and `tenantId` when PAC is signed in. |
-| PCF | `disabled: false` | Enabled and default-on for transmission. Shares Model Apps' tenant and keys through a byte-identical config; routes as model-apps does. Uses `clientType: "PcfAIPlugin"` with `pluginName: "pcf"` in the shared Power Apps client `event` stream; keeps its local mirror after transmission opt-out. | Base fields only (`skill_started`, including `orgId`/`tenantId` when PAC is signed in); no signed-in user object ID or `eventInfo` payload. |
+| Model Apps | `disabled: false` | Enabled and default-on for transmission. A public-cloud organization is geo-routed to the US or EU collector (US default only without an organization ID; an organization whose geo cannot be determined is not transmitted); a sovereign or internal PAC cloud is routed from the cloud stamp alone, never to a public collector; an unrecognized cloud, or a signed-in organization with no cloud, is not transmitted. Events are written to the local mirror even after a user transmission opt-out. | No signed-in user object ID. `skill_started` can include `orgId` and `tenantId` when PAC is signed in. `skill_completed` (app build and page upload) adds `outcome`, `durationMs`, `errorClass` and the approved `eventInfo` below, with the target environment's `orgId`/`tenantId`. |
+| PCF | `disabled: false` | Enabled and default-on for transmission. Shares Model Apps' tenant and keys through a byte-identical config; routes as model-apps does. Uses `clientType: "PcfAIPlugin"` with `pluginName: "pcf"` in the shared Power Apps client `event` stream; keeps its local mirror after transmission opt-out. | No signed-in user object ID. `skill_started` carries base fields only (including `orgId`/`tenantId` when PAC is signed in). `skill_completed` (control push) adds `outcome`, `durationMs`, `errorClass` and the approved `eventInfo` below. |
| Power Automate | `disabled: false` | Enabled and default-on for transmission. Its resolver returns a destination only for public cloud, so sovereign-cloud events stay in the local mirror. Organization-based geo routing selects the US or EU collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID. The plugin's bundled MCP server and CLI emit on the same stream and additionally record `outcome`, `durationMs`, `errorClass`, and `errorCode`, a random per-invocation `correlationId` and per-process `sessionId`, and `envId`/`envLocation`/`envRegion`. Error messages are never recorded. |
| Power Apps Mobile Extension | `disabled: false` | Enabled and default-on for transmission. Records starts for 12 workflow skills, not the telemetry control or generated native controls/PCFs. Public-cloud organizations resolve to US or EU; unknown authenticated regions and unsupported clouds remain local-only. Without usable PAC identity, the US default is used. User transmission opt-out retains the local mirror. | `eventInfo.aadObjectId` when available from PAC, with optional `orgId` and `tenantId`. No other nested `eventInfo` fields. Uses fixed `clientType: "power-apps-mobile-extension"` and `pluginName` in the shared `event` stream. |
@@ -162,9 +162,21 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m
Mobile Apps does not add Dataverse organization or tenant IDs, or an Entra user object ID.
+ **Model Apps and PCF** (`skill_completed` only)
+
+ Sent by the scripts that change an environment when they finish: the model-apps app build (`app-builder`) and page upload (`genpage`), and the pcf control push (`pcf`). Built by `scripts/lib/telemetry/skill-completed.js` (pcf carries a verbatim copy), whose allowlist drops every key and value not listed here:
+
+ - `schemaVersion` (`1`) and `operation` — `app-build`, `page-upload` or `control-push`.
+ - App build: `scope` (`full`, `staged` for a `--stage`/`--only`/`--skip`/`--from`/`--to` run, `changed-only`), `publish` (boolean), `verify` (`passed`, `failed`, `not-run`), and `steps` — for each build phase that ran, `{ ok, skip, error }` step counts (`ok` created or changed, `skip` already present). Phase names are the engine's fixed set (`solution`, `data-model`, `views`, `forms`, `app-shell`, `pages`, `publish`, …), never a table, form, view or app name.
+ - Page upload: `page` (`created`, `updated`, `unchanged`), `placedInApp` and `addedToSolution` (booleans).
+ - Control push: `incremental` (boolean), `registration` (`verified`, `not-verified`, `skipped`) and `steps.push`.
+ - On a failure, `haltPhase` (one of the phase names above, or `preflight`/`push`), with the top-level `errorClass` one of `auth`, `invalid-input`, `locked`, `halted`, `verify-failed`, `deploy-failed`, `timeout` or `unexpected`.
+
+ The completion event also carries the top-level `outcome` and `durationMs`. Its `orgId` and `tenantId` are those of the environment the script targeted — the organization from one `WhoAmI` request (three-second budget) and the tenant from the `tid` claim of the Azure CLI token that request was accepted with — not PAC's active profile; no user claim is read. If the `WhoAmI` is refused, fails or times out, neither ID is sent. A user who opted out of transmission gets no lookup, so their local mirror records the event without those two IDs. The event's routing cloud is read from the environment's host, and a host outside the known Dataverse families is not transmitted. Scripts run outside the hooks that see the agent's session, so each completion carries its own random `sessionId`.
+
The shared dispatcher used by Power Pages and Model Apps sends `eventInfo` as a JSON **string** (re-serialized by `emit-dispatcher.js`, not the local mirror) because the tenant-side field mapping flattens `data.<key>` to a single `data_<key>` leaf and does not recurse into nested objects. The Kusto side must `parse_json()` / `todynamic()` it back into a dynamic value. The Mobile Apps custom dispatcher serializes the sanitized event fields into the Power Apps `event` stream's `customDimensions`; its local mirror also keeps the structured object.
- `FIELD_TYPES` enforces only that `eventInfo` is a structured JSON value; it does **not** enforce nested keys. Callers **MUST** restrict it to the documented schemas above. Power Pages `framework` is restricted to its closed set and describes only the scaffold, not a user, project, or site. Mobile Apps `appInstanceId` is randomly generated and is not derived from an app name, environment, tenant, organization, or user. Callers **MUST NOT** add other personal data, prompts, project or site identifiers, paths, URLs, credentials, or arbitrary caller payloads. Any proposed expansion requires review and approval, plus updates to this privacy disclosure, the documented event schema, and tests before code emits the new field.
+ `FIELD_TYPES` enforces only that `eventInfo` is a structured JSON value; it does **not** enforce nested keys. Callers **MUST** restrict it to the documented schemas above. Power Pages `framework` is restricted to its closed set and describes only the scaffold, not a user, project, or site. Mobile Apps `appInstanceId` is randomly generated and is not derived from an app name, environment, tenant, organization, or user. Model Apps and PCF completion fields are enums, booleans and counts only. Callers **MUST NOT** add other personal data, prompts, project or site identifiers, paths, URLs, credentials, or arbitrary caller payloads. Any proposed expansion requires review and approval, plus updates to this privacy disclosure, the documented event schema, and tests before code emits the new field.
`emitSkillStartedFromPrompt(promptText, opts)` accepts an optional `opts.eventInfo` so a plugin can contribute its own approved keys from the `UserPromptSubmit` hook. It takes either a plain object or a **thunk** returning one; the thunk is preferred, and is invoked only *after* the slash-command, `disabled`, and `isProvisioned` gates pass — that hook fires on every user prompt, so any real work (filesystem probing, shellouts) must not run on untracked prompts. A thunk that throws contributes nothing and never blocks the event. Non-object values (including arrays) are ignored.
diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.js
index 8950e32c5..70ca3c807 100644
--- a/shared/telemetry/lib/telemetry-config.js
+++ b/shared/telemetry/lib/telemetry-config.js
@@ -19,7 +19,11 @@ function dataDisclosure(plugin) {
" choices, canonical locales, public package names/versions, stable\n" +
" validation outcomes, and localization completion.\n"
: plugin === "model-apps"
- ? " Model Apps excludes the signed-in user's Entra object ID.\n"
+ ? " Model Apps excludes the signed-in user's Entra object ID. When an app\n" +
+ " build or a page upload finishes, it records the outcome, duration, a\n" +
+ " fixed error class and per-phase step counts, with the organization and\n" +
+ " tenant IDs of the environment it targeted — never app, table, page or\n" +
+ " environment names.\n"
: "";
return (
"ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" +
diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.js
index a4f54f87b..79429e008 100644
--- a/shared/telemetry/tests/telemetry-config.test.js
+++ b/shared/telemetry/tests/telemetry-config.test.js
@@ -277,3 +277,14 @@ test("omitted --plugin fails closed when the manifest has no name", () => {
assert.match(stdout, /Usage:/);
});
});
+
+test("status discloses the Model Apps completion event, and that it carries no names", () => {
+ const { status, stdout } = run(["--action", "status", "--plugin", "model-apps"], mkTmp());
+ assert.equal(status, 0);
+ assert.match(stdout, /excludes the signed-in user's Entra object ID/);
+ assert.match(stdout, /an app\s+build or a page upload finishes/);
+ assert.match(stdout, /outcome, duration, a\s+fixed error class and per-phase step counts/);
+ assert.match(stdout, /tenant IDs of the environment it targeted/);
+ assert.match(stdout, /never app, table, page or\s+environment names/);
+ assert.doesNotMatch(stdout, /eventInfo\.aadObjectId|eventInfo\.framework/);
+});
\ No newline at end of file