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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.12.1: enable usage telemetry with per-cloud routing (#686)
Akshay Maloo8266b76abb34
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.ymlindex 7f111f254..b4bd144b8 100644--- a/.github/workflows/model-apps-script-tests.yml+++ b/.github/workflows/model-apps-script-tests.yml@@ -26,6 +26,8 @@ on:# source. That guard is only useful if a change to the SOURCE runs it too.- "shared/telemetry/**"- "shared/skills/**"+ # The telemetry region router is a verbatim copy of power-pages' (same drift test).+ - "plugins/power-pages/scripts/lib/telemetry/region/**"- ".github/workflows/model-apps-script-tests.yml"# The jobs only read the checkout; the token needs nothing more, whatever the repository default is.@@ -47,8 +49,8 @@ jobs:timeout-minutes: 20# Defense-in-depth: opt this CI job out of telemetry transmission so a test# that forgets to isolate emission can never POST to a real collector. The- # plugin's committed ikey.json currently ships `disabled: true`, but that is- # a value that can change; the guard must not depend on it. Suppresses+ # plugin's committed ikey.json ships live (`disabled: false`) with real+ # production keys, so without this a stray emission would reach Kusto. Suppresses# TRANSMISSION only — the local diagnostic mirror is still written, so this# cannot change what the tests actually assert.env:diff --git a/AGENTS.md b/AGENTS.mdindex 5a2f36595..08556f900 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -145,13 +145,13 @@ Edit `shared/telemetry/` first, then refresh every adopting plugin's copied `scr**Never reuse another plugin's instrumentation key or event stream.** When adopting telemetry in a new plugin, copy only the routing-agnostic library (`shared/telemetry/lib` → `plugins/<plugin>/scripts/lib/telemetry/lib`) — do **not** copy an existing adopter's real `ikey.json` (or its `resolver.js`). Each plugin's `ikey.json` carries that plugin's own instrumentation key(s), collector routing, and `event_stream_name`; start from the placeholder `shared/telemetry/ikey.json` (every region key is `PLACEHOLDER_REPLACE_BEFORE_SHIPPING` and it ships `disabled: true`) and provision a fresh, plugin-specific key before shipping. Copying a key already committed to another plugin (e.g. lifting `power-pages`'s `ikey.json` wholesale) mis-attributes the new plugin's events to the other plugin's Kusto stream and pollutes it — the copy step must bring over library code only, never another plugin's provisioned `ikey.json`/`resolver.js`.-This invariant is CI-enforced: `node scripts/validate-telemetry-ikeys.js` (wired into the `validate-repository-metadata` workflow) scans every `plugins/*/**/ikey.json`, ignores placeholder/empty values, and fails if the same instrumentation key or `event_stream_name` appears under two different plugins. A single plugin reusing one key across regions is allowed; only cross-plugin reuse fails. Run it locally after touching any plugin's `ikey.json`.+This invariant is CI-enforced: `node scripts/validate-telemetry-ikeys.js` (wired into the `validate-repository-metadata` workflow) scans every `plugins/*/**/ikey.json`, ignores placeholder/empty values, and fails if the same instrumentation key or `event_stream_name` appears under two different plugins. A single plugin reusing one key across regions is allowed; only cross-plugin reuse fails. The one exception is the stream name `event`: it is the shared Power Apps client telemetry table (the only stream the mobile-apps/model-apps tenants ingest), so several plugins may send to it, provided each makes its rows separable in the payload with its own `clientType` and its `pluginName` in `customDimensions`. Keys are never exempt. Run it locally after touching any plugin's `ikey.json`.Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next to the plugin's `ikey.json` (implementing the `resolve`/`isProvisioned` contract); the shared library ships only that contract plus a static-key fallback, not any routing logic. A per-plugin opt-out env var `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (derived as the uppercased plugin name with non-alphanumerics collapsed to `_`, suffixed `_OPTOUT`; the name is the manifest's `name`, not the directory — `plugins/mobile-apps` is `mobile-app`, so its variable ends `_MOBILE_APP_OPTOUT`) disables transmission for automation when set to `1`/`true` (dotnet `*_TELEMETRY_OPTOUT` convention); it has the **highest precedence**, overriding both the persisted `config.json` choice and `/<plugin>:telemetry on`.### CI must opt out of telemetry transmission-A transmitting adopter's committed `ikey.json` ships **enabled** (`disabled: false`) with a real production instrumentation key, so any process that runs a telemetry-emitting hook or script **without isolating emission** will POST a real (but fake-in-content) event to the production collector. CI runs are not real usage, and such events pollute the production telemetry stream. An adopter that still ships `disabled: true` (model-apps today) sets the opt-out too, so enabling it later cannot turn its CI into a leak.+A transmitting adopter's committed `ikey.json` ships **enabled** (`disabled: false`) with a real production instrumentation key, so any process that runs a telemetry-emitting hook or script **without isolating emission** will POST a real (but fake-in-content) event to the production collector. CI runs are not real usage, and such events pollute the production telemetry stream.**Therefore: every GitHub Actions job that runs the test suite — or any step that could execute a telemetry-emitting hook/script for an adopting plugin — MUST set the plugin's opt-out env var at the job (or workflow) level.** For `power-pages`:@@ -166,7 +166,7 @@ jobs:This opt-out suppresses **transmission only** (the local diagnostic mirror is still written), so it is safe and has no effect on what the job actually tests. Tests that need to assert that emission *happens* clear the var in their own spawned-process env and route the event to a local `POWER_PLATFORM_SKILLS_FAKE_HTTPS` probe instead of the real collector — so the job-level opt-out never breaks them. Existing reference: `.github/workflows/power-pages-script-tests.yml`. When you add a new such workflow (or a new emitting step to an existing one), add this env var in the same change; treat a CI job that runs the tests without it as a production-telemetry leak.-Current adopters: `power-pages` and `mobile-apps` (transmitting), and `model-apps` (bundled, with its committed `ikey.json` still `disabled: true`). Others adopt on demand. The library's own tests (`shared/telemetry/tests`) run in `.github/workflows/shared-telemetry-tests.yml` on a change to the source or to any bundled copy, and its `bundled-copies.test.js` fails when any adopter's `plugins/<plugin>/scripts/lib/telemetry/lib` differs from `shared/telemetry/lib`. The workflow sets every adopter's opt-out — add a new adopter's variable there too. power-pages and model-apps also keep a `scripts/tests/telemetry-lib-copy.test.js` that runs the same comparison in their own suites (model-apps also checks its shared skill copies, and lists `shared/telemetry/**` in its workflow's path filter so a source edit runs it too).+Current adopters: `power-pages`, `mobile-apps`, and `model-apps` (all transmitting). Others adopt on demand. The library's own tests (`shared/telemetry/tests`) run in `.github/workflows/shared-telemetry-tests.yml` on a change to the source or to any bundled copy, and its `bundled-copies.test.js` fails when any adopter's `plugins/<plugin>/scripts/lib/telemetry/lib` differs from `shared/telemetry/lib`. The workflow sets every adopter's opt-out — add a new adopter's variable there too. power-pages and model-apps also keep a `scripts/tests/telemetry-lib-copy.test.js` that runs the same comparison in their own suites (model-apps also checks its shared skill copies, and lists `shared/telemetry/**` in its workflow's path filter so a source edit runs it too).## Legacy Marketplace Compatibilitydiff --git a/README.md b/README.mdindex 0aa9de803..ed2354fdc 100644--- a/README.md+++ b/README.md@@ -337,6 +337,6 @@ Any use of third-party trademarks or logos are subject to those third-party's po## Telemetry-Power Pages, Mobile Apps, and Model Apps ship 1DS telemetry code, but their committed configurations and event schemas differ. Power Pages and Mobile Apps telemetry are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps ships hard-disabled (`disabled: true`), so it currently transmits no events and writes no local telemetry mirror; if enabled later, its events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID.+Power Pages, Mobile Apps, and Model Apps ship 1DS telemetry code, but their committed configurations and event schemas differ. All three are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID.For an enabled plugin, users opt out of transmission via `/<plugin>:telemetry off` (for example, `/power-pages:telemetry off`), stored in `~/.power-platform-skills/config.json`. The local diagnostic mirror is still written after this transmission-only opt-out. Each adopting plugin also honors `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` for automation and CI. The environment variable has highest precedence and disables transmission regardless of the saved command choice. See the [shared telemetry guide](shared/telemetry/README.md) for the full field list, current plugin states, geo-routing behavior, kill-switch semantics, and local-mirror behavior.diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.jsindex 1d0d14e2d..fc6571132 100644--- a/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.js+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -106,6 +106,26 @@ function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName};}+// The wire envelope is the shared shape above unless the plugin's resolver.js+// exports an optional `formatEnvelope({ eventName, time, data, iKey,+// eventStreamName })`. That lets a plugin whose tenant ingests a different+// schema (e.g. the Power Apps client `event` table) reshape the payload without+// forking this dispatcher. `data` is the already-sanitized allowlisted payload,+// so a formatter can only rearrange approved fields, never add new sources.+// A formatter that throws or returns nothing sends NOTHING (fail closed): the+// plugin opted into a specific shape, and the default one would not be+// ingested by its pipeline anyway. The local mirror was already written.+function formatEnvelope(resolver, { eventName, time, data, iKey, eventStreamName }) {+ if (resolver && typeof resolver.formatEnvelope === "function") {+ try {+ return resolver.formatEnvelope({ eventName, time, data, iKey, eventStreamName }) || null;+ } catch {+ return null;+ }+ }+ return buildEnvelope(eventName, time, data, iKey, eventStreamName);+}+function writeProbe(filePath, { headers, body }) {try {fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");@@ -209,7 +229,14 @@ process.stdin.on("end", async () => {// Real iKey → Common Schema envelope (reuses the same time + sanitized data// as the local mirror) → HTTPS POST.- const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ const envelope = formatEnvelope(resolver, {+ eventName: event.name,+ time,+ data: sanitized,+ iKey,+ eventStreamName: cfg.event_stream_name,+ });+ if (!envelope) return exitSilently();const body = JSON.stringify(envelope) + "\n";const headers = {"Content-Type": "application/x-json-stream; charset=utf-8",diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 5324a7ba1..f7c31ef25 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.12.0",+ "version": "2.12.1","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.jsonindex 5324a7ba1..f7c31ef25 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.12.0",+ "version": "2.12.1","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.mdindex d5d43d9c6..5869f9e95 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -809,7 +809,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 hooksutf8-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 config) + 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)vendor/cds-maker-sdk.cjs ← headless vendored SDK bundle (rebuilt via _vendor-build/)_vendor-build/ ← esbuild vendoring tooling (build.js + pinned deps)tests/ ← node --test coverage for the scripts + hooks@@ -819,7 +819,7 @@ hooks/ ← Lifecycle hooksrun-skill-posttool-validation.js ← Runs a skill's validate*.js after the Skill tool returnsvalidate-icon-imports.js ← PostToolUse: blocks unverified @fluentui/react-icons in generated .tsxvalidate-write-safety.js ← PreToolUse: flags (non-blocking) out-of-cwd writes in model-apps sessions- run-skill-pretool-telemetry.js ← PreToolUse(Skill): emits skill_started (ships disabled)+ run-skill-pretool-telemetry.js ← PreToolUse(Skill): emits skill_startedrun-user-prompt-telemetry.js ← UserPromptSubmit: emits skill_started for /model-apps:<skill>skills/app-builder/@@ -1053,18 +1053,40 @@ repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a **physical copy*(never a symlink) so installed plugins don't depend on symlink handling. Edit`shared/telemetry/lib/` first, then refresh this plugin's copy in the same change.-- **Posture:** the committed `ikey.json` ships **`disabled: true`** (Tier-1 static,- no resolver) — currently carrying the **provisioned model-apps key + collector +- `event_stream_name`, staged disabled**. It emits nothing — no POST, no local log —- while `disabled: true`; flip `disabled` to `false` only after the Geneva mapping- is validated in DGrep (see the ADE provisioning runbook). `disabled: true` is the- active guard; the placeholder-key gate is a secondary defense for un-provisioned- copies. **Provision a fresh key; never copy another plugin's `ikey.json`**+- **Posture:** the committed `ikey.json` ships **live** (`disabled: false`) with this+ plugin's own per-region keys (`internal`, `us`, `eu`, `gov`, `high`, `dod`, `mooncake`;+ US and EU share the public key and differ only by collector) and the Power Apps client+ `event` stream. `disabled: true` is the repo-wide hard-off (no POST,+ no local log). **Provision a fresh key; never copy another plugin's `ikey.json`**(CI-enforced: `node scripts/validate-telemetry-ikeys.js`).+- **Wire shape:** these tenants ingest **only** the `event` stream, into the Power Apps client+ `event` table; any other stream name is accepted by the collector and then dropped. So+ `resolver.js` also exports `formatEnvelope`, which mirrors mobile-apps' envelope:+ `app_Name: "powerappsclient"`, `event_Name`, `session_Id`, `tenantId`, and every other+ allowlisted field as a `customDimensions` JSON string. `clientType` is+ **`ModelAppsAIPlugin`** (never mobile's `PowerAppsNative`), so rows are separable from+ real client traffic. Query the tenant's `event` table (raw 1DS copies prefix columns with `data_`):+ `event | where clientType == "ModelAppsAIPlugin" | extend d = parse_json(customDimensions)+ | summarize count() by tostring(d.pluginName), tostring(d.skillName)`.+ The local mirror keeps the flat, readable shape.+- **Routing:** `scripts/lib/telemetry/resolver.js` picks the key + collector per event.+ `region/` beside it is a **verbatim copy** of power-pages' Artemis geo + cloud-stamp+ router — refresh it by copying, and keep model-apps logic in `resolver.js`+ (`telemetry-lib-copy.test.js` fails on drift, and the workflow runs on a power-pages+ `region/` change). A public-cloud+ org routes to `us`/`eu` by its geo (cached per org for 24 h under+ `~/.power-platform-skills/region-cache/`, shared with power-pages — it stores only the+ region, never a key); if its geo can't be determined (Artemis down, unknown geo) it sends+ nothing rather than defaulting to US, and only a signed-out PAC (no org) takes the `us`+ default. Unlike power-pages, a sovereign or internal PAC cloud (`UsGov`,+ `UsGovHigh`, `UsGovDod`, `China`, `Tip1`/`Tip2`/`Test`/`Preprod`) routes from the stamp+ alone, with no Artemis call and **never** a fallback to the public collector; an+ unrecognized cloud, or a signed-in org with no cloud line, sends nothing. `ikey.json`+ 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>`).-- **Privacy:** while `disabled: true` nothing is built, sent or mirrored (see Posture). Once- enabled, telemetry is default-on: events can include Dataverse organization and Entra tenant GUIDs+- **Privacy:** telemetry is default-on: events can include Dataverse organization and Entra tenant GUIDswhen 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 samefields — it is still written after a user opts out of transmission via@@ -1353,9 +1375,10 @@ skill (`/genpage` or `/app-builder`), and for genpage verify Playwright browser(navigate/snapshot/click/screenshot).**Hooks + telemetry:** the lifecycle hooks and telemetry hooks are covered by the plugin unit suite-(`node scripts/run-tests.js`). Keep `scripts/lib/telemetry/ikey.json` shipping `disabled: true` until a-key is provisioned (a test enforces this), and run `node scripts/validate-telemetry-ikeys.js` from the-repo root after touching `ikey.json`.+(`node scripts/run-tests.js`); `resolver.test.js` pins the shipped `ikey.json` (live, a real key and the+right collector per region) and the sovereign/unknown-cloud routing. A test also forbids shipping a+placeholder key enabled. Run `node scripts/validate-telemetry-ikeys.js` from the repo root after+touching `ikey.json`.## Eval Suitediff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.mdindex 7ce0791a5..8cf88a507 100644--- a/plugins/model-apps/README.md+++ b/plugins/model-apps/README.md@@ -223,11 +223,10 @@ export MODEL_APPS_DISABLE_HOOKS=1## Telemetry-model-apps ships opt-out usage telemetry (1DS). The committed config ships-**disabled** (`disabled: true`) — until go-live it builds, sends and mirrors nothing, even though it now-carries the provisioned model-apps key + stream (staged, not yet enabled). `disabled:-true` is the active guard; the placeholder-key check is only a secondary guard for-un-provisioned copies. Once enabled it is **on by default** (you opt out), and then:+model-apps ships opt-out usage telemetry (1DS). It is **on by default** (you opt+out). Events go to the collector for your environment's cloud — the US or EU data+boundary for a public-cloud org, or the matching sovereign collector (GCC, GCC High,+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 whendiff --git a/plugins/model-apps/hooks/README.md b/plugins/model-apps/hooks/README.mdindex b7b17c04e..7818a21c4 100644--- a/plugins/model-apps/hooks/README.md+++ b/plugins/model-apps/hooks/README.md@@ -13,7 +13,7 @@ back.| Matcher | Hook | Behaviour || --- | --- | --- || `Write\|Edit\|MultiEdit` | `validate-write-safety.js` | **Flags** (non-blocking, exit 1) a write outside the cwd, and only during an active model-apps authoring session — that is, when a `genpage-plan.md`, `app-spec.json`, or `model-app-plan.md` marker exists at or under the cwd, which covers both `/genpage` and `/app-builder`. |-| `Skill\|skill` | `run-skill-pretool-telemetry.js` | Emits the `skill_started` usage event. Ships disabled until an instrumentation key is provisioned. |+| `Skill\|skill` | `run-skill-pretool-telemetry.js` | Emits the `skill_started` usage event, routed by `scripts/lib/telemetry/resolver.js`. |## PostToolUsediff --git a/plugins/model-apps/hooks/run-skill-pretool-telemetry.js b/plugins/model-apps/hooks/run-skill-pretool-telemetry.jsindex 48fb8bf11..8c3d8cdb3 100644--- a/plugins/model-apps/hooks/run-skill-pretool-telemetry.js+++ b/plugins/model-apps/hooks/run-skill-pretool-telemetry.js@@ -10,14 +10,14 @@* plugin-specific bits are the pluginName ("model-apps"), the hook-utils import,* and this plugin's own ikey.json.*- * Posture: this plugin's committed ikey.json ships `disabled: true` (the primary- * gate — currently carrying the provisioned key + stream, staged disabled), so- * today the hook short-circuits at `if (disabled)` and emits nothing (no local- * log, no POST). When enabled (`disabled: false`), a secondary non-placeholder/- * provisioned check gates emission, and the same code path emits. Once the Kusto- * mapping is validated and disabled is flipped to false, telemetry flows. Every- * branch is fail-closed: a missing lib, unreadable config, thrown resolver, or- * bad stdin all exit 0 so the hook can never break a skill run.+ * Posture: this plugin's committed ikey.json ships live (`disabled: false`) with a+ * per-region key map; the resolver.js beside it picks the key + collector for the+ * signed-in org's cloud and data boundary. `disabled: true` (or an unreadable+ * config) is the hard-off gate — the hook then short-circuits before any work and+ * emits nothing (no local log, no POST). The resolver's isProvisioned() check is+ * the secondary gate, so a placeholder key can never emit. Every branch is+ * fail-closed: a missing lib, unreadable config, thrown resolver, or bad stdin all+ * exit 0 so the hook can never break a skill run.*/const path = require("node:path");diff --git a/plugins/model-apps/scripts/lib/telemetry/ikey.json b/plugins/model-apps/scripts/lib/telemetry/ikey.jsonindex 951fbd62a..02ea1649d 100644--- a/plugins/model-apps/scripts/lib/telemetry/ikey.json+++ b/plugins/model-apps/scripts/lib/telemetry/ikey.json@@ -1,6 +1,35 @@{- "instrumentationKey": "17d9aee1951341508c46b0aad2f3fcb5-a41425e0-9b67-482e-971f-ad83c3b467e3-6814",- "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/",- "event_stream_name": "ModelAppsAIPluginEvent",- "disabled": true+ "event_stream_name": "event",+ "disabled": false,+ "default_region": "us",+ "regions": {+ "internal": {+ "instrumentation_key": "3fb21f3df5c44380bf452fd710f4d50c-17e2cd1c-a046-4060-8b2a-73d6bf01da2e-7604",+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "us": {+ "instrumentation_key": "5c3a61f48d7c4522912765ae7465ab5c-2775e155-1343-4cc0-83a7-85f4045a3b64-6591",+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "eu": {+ "instrumentation_key": "5c3a61f48d7c4522912765ae7465ab5c-2775e155-1343-4cc0-83a7-85f4045a3b64-6591",+ "collector_url": "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "gov": {+ "instrumentation_key": "0d7685a948a140789ac92933d3dc2d87-4bcebc5d-76e8-402c-8570-4d177c226283-7136",+ "collector_url": "https://tb.events.data.microsoft.com/OneCollector/1.0/"+ },+ "high": {+ "instrumentation_key": "d31229fb23b0406790b9332e5f465dfc-8c249ffd-0fb2-4e76-8284-86f7bb09662d-7998",+ "collector_url": "https://tb.events.data.microsoft.com/OneCollector/1.0/"+ },+ "dod": {+ "instrumentation_key": "41cc10dad35043adbcdace2896484ab4-b07b9a09-6aa2-46ba-b922-e1475ec4d45a-7452",+ "collector_url": "https://pf.events.data.microsoft.com/OneCollector/1.0/"+ },+ "mooncake": {+ "instrumentation_key": "1c1d139788f74386bd95e752dd781371-2a869201-8cb8-44bc-8c25-87b87c9eab9d-6996",+ "collector_url": "https://collector.azure.cn/OneCollector/1.0/"+ }+ }}diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.jsindex 1d0d14e2d..fc6571132 100644--- a/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js+++ b/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -106,6 +106,26 @@ function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName};}+// The wire envelope is the shared shape above unless the plugin's resolver.js+// exports an optional `formatEnvelope({ eventName, time, data, iKey,+// eventStreamName })`. That lets a plugin whose tenant ingests a different+// schema (e.g. the Power Apps client `event` table) reshape the payload without+// forking this dispatcher. `data` is the already-sanitized allowlisted payload,+// so a formatter can only rearrange approved fields, never add new sources.+// A formatter that throws or returns nothing sends NOTHING (fail closed): the+// plugin opted into a specific shape, and the default one would not be+// ingested by its pipeline anyway. The local mirror was already written.+function formatEnvelope(resolver, { eventName, time, data, iKey, eventStreamName }) {+ if (resolver && typeof resolver.formatEnvelope === "function") {+ try {+ return resolver.formatEnvelope({ eventName, time, data, iKey, eventStreamName }) || null;+ } catch {+ return null;+ }+ }+ return buildEnvelope(eventName, time, data, iKey, eventStreamName);+}+function writeProbe(filePath, { headers, body }) {try {fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");@@ -209,7 +229,14 @@ process.stdin.on("end", async () => {// Real iKey → Common Schema envelope (reuses the same time + sanitized data// as the local mirror) → HTTPS POST.- const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ const envelope = formatEnvelope(resolver, {+ eventName: event.name,+ time,+ data: sanitized,+ iKey,+ eventStreamName: cfg.event_stream_name,+ });+ if (!envelope) return exitSilently();const body = JSON.stringify(envelope) + "\n";const headers = {"Content-Type": "application/x-json-stream; charset=utf-8",diff --git a/plugins/model-apps/scripts/lib/telemetry/region/artemis-service.js b/plugins/model-apps/scripts/lib/telemetry/region/artemis-service.jsnew file mode 100644index 000000000..29af804ce--- /dev/null+++ b/plugins/model-apps/scripts/lib/telemetry/region/artemis-service.js@@ -0,0 +1,98 @@+"use strict";++const https = require("node:https");++const TIMEOUT_MS = 5000;++function normalizeCloud(cloud) {+ const c = String(cloud || "").toLowerCase();+ // "usgov" is the token `pac auth who` actually emits for GCC (see+ // validation-helpers.js CLOUD_TO_API). The other spellings are defensive+ // aliases. Exact `===` matching means this can't shadow usgovhigh/usgovdod.+ if (c === "usgov" || c === "usgovgcc" || c === "gcc" || c === "gov") return "Gov";+ if (c === "usgovhigh" || c === "high") return "High";+ if (c === "usgovdod" || c === "dod") return "Dod";+ if (c === "china" || c === "mooncake" || c === "chinacloud") return "Mooncake";+ if (c === "tip1" || c === "tip2" || c === "test" || c === "preprod") return "Internal";+ return "Public";+}++function urlFor(orgId, cloud) {+ const noDashes = String(orgId || "").replace(/-/g, "");+ const stamp = normalizeCloud(cloud);+ if (stamp === "Public") {+ const domain = noDashes.slice(0, -2);+ const suffix = noDashes.slice(-2);+ return `https://${domain}.${suffix}.organization.api.powerplatform.com/gateway/cluster?api-version=1`;+ }+ const domain = noDashes.slice(0, -1);+ const suffix = noDashes.slice(-1);+ if (stamp === "Gov") {+ return `https://${domain}.${suffix}.organization.api.gov.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "High") {+ return `https://${domain}.${suffix}.organization.api.high.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Dod") {+ return `https://${domain}.${suffix}.organization.api.appsplatform.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Mooncake") {+ return `https://${domain}.${suffix}.organization.api.powerplatform.partner.microsoftonline.cn/gateway/cluster?api-version=1`;+ }+ // Internal+ return `https://${domain}.${suffix}.organization.api.test.powerplatform.com/gateway/cluster?api-version=1`;+}++function defaultHttpsGet(url) {+ return new Promise((resolve, reject) => {+ let u;+ try {+ u = new URL(url);+ } catch (e) {+ reject(e);+ return;+ }+ const req = https.request(+ {+ hostname: u.hostname,+ path: u.pathname + (u.search || ""),+ method: "GET",+ },+ (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (c) => (body += c));+ res.on("end", () => resolve({ statusCode: res.statusCode, body }));+ }+ );+ req.on("error", reject);+ req.setTimeout(TIMEOUT_MS, () => {+ req.destroy(new Error("timeout"));+ });+ req.end();+ });+}++async function fetchGeo(orgId, cloud, opts = {}) {+ if (!orgId) return null;+ const url = urlFor(orgId, cloud);+ const httpsGet = typeof opts._httpsGet === "function" ? opts._httpsGet : defaultHttpsGet;+ let resp;+ try {+ resp = await httpsGet(url);+ } catch {+ return null;+ }+ if (!resp || typeof resp.statusCode !== "number") return null;+ if (resp.statusCode < 200 || resp.statusCode >= 300) return null;+ let body;+ try {+ body = JSON.parse(resp.body || "");+ } catch {+ return null;+ }+ if (!body || typeof body.geoName !== "string" || !body.geoName) return null;+ return { geoName: body.geoName, stamp: normalizeCloud(cloud) };+}++module.exports = { fetchGeo, urlFor, normalizeCloud, TIMEOUT_MS };diff --git a/plugins/model-apps/scripts/lib/telemetry/region/region-cache.js b/plugins/model-apps/scripts/lib/telemetry/region/region-cache.jsnew file mode 100644index 000000000..df378941d--- /dev/null+++ b/plugins/model-apps/scripts/lib/telemetry/region/region-cache.js@@ -0,0 +1,87 @@+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const DIR_NAME = "region-cache";+const TTL_MS = 24 * 60 * 60 * 1000;++// orgId comes from `pac auth who` ("Organization Id") — a Dataverse org GUID.+// Validate the shape before using it as a filename: defensive against a+// malformed/spoofed value containing path separators (`/`, `\`, `..`), and it+// doubles as the falsy-orgId guard.+const ORG_ID_RE =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;++function defaultDir() {+ return path.join(os.homedir(), ".power-platform-skills");+}++function cacheDir(configDir) {+ return path.join(configDir || defaultDir(), DIR_NAME);+}++function entryFile(orgId, configDir) {+ return path.join(cacheDir(configDir), `${orgId}.json`);+}++// Returns the cached { region } for an org, or null when missing / unreadable /+// malformed / expired. Only the plugin-INDEPENDENT org→region mapping is cached;+// the caller maps region→iKey from its own regionsMap (so a cache shared across+// plugins can never hand one plugin another plugin's key).+function read(orgId, configDir) {+ if (!ORG_ID_RE.test(String(orgId || ""))) return null;+ let entry;+ try {+ entry = JSON.parse(fs.readFileSync(entryFile(orgId, configDir), "utf8"));+ } catch {+ return null;+ }+ if (+ !entry ||+ typeof entry.expiresAt !== "number" ||+ entry.expiresAt < Date.now()+ ) {+ return null;+ }+ return { region: entry.region };+}++// Per-process counter so concurrent writers never collide on the temp name.+let writeSeq = 0;++function write(orgId, entry, configDir) {+ if (!ORG_ID_RE.test(String(orgId || "")) || !entry || !entry.region) return;+ const dir = cacheDir(configDir);+ try {+ fs.mkdirSync(dir, { recursive: true });+ } catch {+ return;+ }+ const file = path.join(dir, `${orgId}.json`);+ const payload = JSON.stringify({+ region: entry.region,+ expiresAt: Date.now() + TTL_MS,+ });+ // Per-org file + atomic rename: each org owns its own file, so concurrent+ // detached dispatchers (one per skill invocation) writing DIFFERENT orgs can+ // never clobber each other — the shared read-modify-write is gone, and+ // same-org concurrent writes are idempotent (identical content). The temp name+ // is per-process so writers don't collide; rename is an atomic replace (incl.+ // Windows via MoveFileEx) so a reader never sees a torn/half-written file.+ const tmp = `${file}.tmp.${process.pid}.${writeSeq++}`;+ try {+ fs.writeFileSync(tmp, payload, "utf8");+ fs.renameSync(tmp, file);+ } catch {+ // fail closed: cache miss next time. Best-effort cleanup of the temp file.+ try {+ fs.unlinkSync(tmp);+ } catch {+ // temp may not have been created; ignore+ }+ }+}++module.exports = { read, write, TTL_MS };diff --git a/plugins/model-apps/scripts/lib/telemetry/region/region-resolver.js b/plugins/model-apps/scripts/lib/telemetry/region/region-resolver.jsnew file mode 100644index 000000000..81cdff74a--- /dev/null+++ b/plugins/model-apps/scripts/lib/telemetry/region/region-resolver.js@@ -0,0 +1,91 @@+"use strict";++const { fetchGeo: defaultFetchGeo, normalizeCloud } = require("./artemis-service");+const defaultCache = require("./region-cache");++// Public-cloud geoName values → routing region. Anything not listed falls+// through to defaultRegion. Sovereign clouds short-circuit via the stamp.+const PUBLIC_US_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr"]);+const PUBLIC_EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch"]);++// Derive the plugin-INDEPENDENT routing region from the org's cloud stamp + geo,+// or null when the public geo is unrecognized (caller falls back to its own+// defaultRegion). Only a non-null result is safe to cache: it's a property of+// the org, not of any plugin's config.+function deriveRegion(cloud, geoName) {+ const stamp = normalizeCloud(cloud);+ if (stamp === "Gov") return "gov";+ if (stamp === "High") return "high";+ if (stamp === "Dod") return "dod";+ if (stamp === "Mooncake") return "mooncake";+ if (stamp === "Internal") return "internal";+ // stamp === "Public"+ const g = String(geoName || "").toLowerCase();+ if (PUBLIC_US_GEOS.has(g)) return "us";+ if (PUBLIC_EU_GEOS.has(g)) return "eu";+ return null;+}++function mapToRegion(cloud, geoName, defaultRegion) {+ return deriveRegion(cloud, geoName) || defaultRegion;+}++function entryFromMap(regionsMap, region) {+ const e = regionsMap && regionsMap[region];+ if (!e || !e.instrumentation_key) return null;+ return {+ region,+ iKey: e.instrumentation_key,+ collectorUrl: e.collector_url || "",+ };+}++async function resolve({+ orgId,+ cloud,+ regionsMap,+ defaultRegion,+ configDir,+ _fetchGeo,+ _cache,+}) {+ const cache = _cache || defaultCache;+ const fetchGeo = typeof _fetchGeo === "function" ? _fetchGeo : defaultFetchGeo;+ const fallback = entryFromMap(regionsMap, defaultRegion);++ if (!orgId) return fallback;++ // Cache holds only the plugin-independent org→region mapping; map it to THIS+ // plugin's iKey/collector from regionsMap on every hit, so a cache shared+ // across plugins can never hand one plugin another plugin's key.+ const cached = cache.read(orgId, configDir);+ if (cached && cached.region) {+ return entryFromMap(regionsMap, cached.region) || fallback;+ }++ let artemis;+ try {+ artemis = await fetchGeo(orgId, cloud);+ } catch {+ artemis = null;+ }+ if (!artemis) return fallback;++ // Only a region DERIVED from a recognized geo/stamp is plugin-independent and+ // cacheable; an unrecognized geo falls back to this plugin's defaultRegion,+ // which must NOT be cached (another plugin's default may differ).+ const derived = deriveRegion(cloud, artemis.geoName);+ const region = derived || defaultRegion;+ const entry = entryFromMap(regionsMap, region) || fallback;+ if (!entry) return null;+ if (derived) {+ try {+ cache.write(orgId, { region: derived }, configDir);+ } catch {+ // swallow+ }+ }+ return entry;+}++module.exports = { resolve, mapToRegion };diff --git a/plugins/model-apps/scripts/lib/telemetry/resolver.js b/plugins/model-apps/scripts/lib/telemetry/resolver.jsnew file mode 100644index 000000000..ecf5e2626--- /dev/null+++ b/plugins/model-apps/scripts/lib/telemetry/resolver.js@@ -0,0 +1,143 @@+"use strict";++// model-apps telemetry resolver: picks THIS plugin's instrumentation key + OneCollector URL for an+// event. Implements the shared dispatcher's resolver contract (shared/telemetry/lib/resolver-loader.js):+// resolve({ event, cfg, cloud, configDir }) → { region, iKey, collectorUrl } | null+// isProvisioned(cfg) → boolean (sync gate before the pac shell-outs)+// formatEnvelope({ time, data, iKey, ... }) → the wire envelope (Power Apps client `event` shape)+//+// ./region/ is a VERBATIM copy of power-pages' Artemis geo + cloud-stamp router. Keep it byte-identical+// so a refresh is a plain copy; the model-apps-specific routing lives here instead. Its org→region cache+// (~/.power-platform-skills/region-cache/<orgId>.json) is shared with power-pages on purpose: it stores+// only the plugin-independent region, and each plugin maps that to its own key from its own ikey.json.+const { resolve: resolveRegion, mapToRegion } = require("./region/region-resolver");++// `cloud` is the "Cloud:" value from `pac auth who`. PAC documents Public, UsGov, UsGovHigh, UsGovDod and+// China (https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/auth#pac-auth-create);+// Microsoft-internal stamps surface as Tip1/Tip2/Test/Preprod. An empty value is public only when there+// is also no org (PAC signed out): nothing identifies a region then, so the event takes the public default+// like power-pages does. A signed-in org with no cloud line is handled in resolve() below.+const PUBLIC_CLOUDS = new Set(["", "public"]);+// Never a key in ikey.json `regions`; see the public-org branch of resolve().+const NO_FALLBACK_REGION = "__no_fallback__";+const STAMPED_CLOUDS = new Set([+ "usgov", "usgovgcc", "gcc", "gov",+ "usgovhigh", "high",+ "usgovdod", "dod",+ "china", "mooncake", "chinacloud",+ "tip1", "tip2", "test", "preprod",+]);++function entryFromMap(regionsMap, region) {+ const e = regionsMap && regionsMap[region];+ if (!e || !e.instrumentation_key || !e.collector_url) return null;+ return { region, iKey: e.instrumentation_key, collectorUrl: e.collector_url };+}++async function resolve({ event, cfg, cloud, configDir }) {+ const regionsMap = (cfg && cfg.regions) || {};+ const defaultRegion = (cfg && cfg.default_region) || "us";+ const c = String(cloud || "").trim().toLowerCase();+ const orgId = (event && event.data && event.data.orgId) || "";++ // Deliberate deviation from power-pages: a sovereign or internal cloud is routed from the PAC+ // stamp ALONE. The stamp already decides the region (the geo is ignored for these), and the region+ // router only falls back to the PUBLIC default when its Artemis lookup fails — so a GCC/High/DoD/+ // China org whose gateway call timed out would otherwise have its event sent to the US public+ // collector. Returning null when this plugin has no entry for the stamp leaves the dispatcher with+ // no key (ikey.json carries no top-level static key), so nothing is sent — fail closed.+ if (STAMPED_CLOUDS.has(c)) {+ return entryFromMap(regionsMap, mapToRegion(cloud, "", defaultRegion));+ }++ // An unrecognized stamp (a future PAC value, an air-gapped cloud) has no key here, and the shared+ // normalizer would treat it as Public. Send nothing rather than leak it to a public collector; the+ // local diagnostic mirror is still written by the dispatcher.+ if (!PUBLIC_CLOUDS.has(c)) return null;++ // A signed-in org whose `pac auth who` output had no "Cloud:" line (the parser returns "" then) could be+ // a sovereign org. Treating it as public would query the public Artemis gateway, fail, and fall back to+ // the US public collector — so send nothing instead.+ if (!c && orgId) return null;++ // PAC signed out: no org, so nothing places the event in a data boundary and nothing org-identifying+ // is in it — take the configured public default, like power-pages.+ if (!orgId) return entryFromMap(regionsMap, defaultRegion);++ // Public cloud with an org: the US vs EU data boundary comes ONLY from the org's geo (Artemis gateway,+ // cached per org). The shared router falls back to its defaultRegion when Artemis fails or reports a+ // geo it doesn't recognize, which would send an EU org's event to the US collector during an outage.+ // Passing a region name that has no entry makes every such fallback resolve to null — send nothing,+ // keep the local mirror — while a recognized geo (fresh or cached) still routes normally. The router+ // caches only a DERIVED region, so this sentinel is never written to the shared org→region cache.+ return resolveRegion({+ orgId,+ cloud,+ regionsMap,+ defaultRegion: NO_FALLBACK_REGION,+ configDir,+ });+}++// Sync fast-gate: is the default region's key configured? Lets the hooks skip the ~3-5s pac shell-out+// when the config is unprovisioned. A placeholder key counts as unprovisioned, matching the+// dispatcher's own PLACEHOLDER_IKEY guard, so flipping `disabled: false` early cannot emit.+function isProvisioned(cfg) {+ const dr = (cfg && cfg.default_region) || "us";+ const entry = cfg && cfg.regions && cfg.regions[dr];+ return !!(+ entry &&+ entry.instrumentation_key &&+ entry.instrumentation_key !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING" &&+ entry.collector_url+ );+}++// Reshape the shared skill_started payload into the Power Apps client `event` schema. model-apps' 1DS+// tenants (shared with the mobile-apps plugin) ingest ONLY the `event` stream, into the Power Apps+// client `event` table — a stream named anything else is accepted by the collector (HTTP 200) and then+// silently dropped, because no table is mapped for it. This mirrors mobile-apps'+// scripts/lib/mobile-telemetry-dispatcher.js buildEnvelope(), with one deliberate difference:+// clientType is "ModelAppsAIPlugin", not "PowerAppsNative", so these rows can never be counted as Power+// Apps native-client traffic by queries that filter on clientType.+//+// Wire shape (one line of the x-json-stream body):+// { ver: "4.0", name: "event", time, iKey: "o:<tenant token>",+// data: { app_Name: "powerappsclient", clientType: "ModelAppsAIPlugin", event_Name: "skill_started",+// session_Id, tenantId?, severity, timestamp,+// customDimensions: "{\"pluginName\":\"model-apps\",\"skillName\":\"genpage\",...}" },+// ext: { app: { sesId, ver }, os: { name, ver } } }+// `data` arrives already sanitized against the shared FIELD_TYPES allowlist, so this only rearranges+// approved fields. Query: event | where clientType == "ModelAppsAIPlugin"+// | extend d = parse_json(customDimensions) | where d.pluginName == "model-apps"+function formatEnvelope({ time, data, iKey, eventStreamName }) {+ const d = data || {};+ const dimensions = { ...d };+ delete dimensions.eventName;+ delete dimensions.eventType;+ delete dimensions.severity;+ return {+ ver: "4.0",+ name: eventStreamName || "event",+ time,+ iKey: "o:" + String(iKey || "").split("-")[0],+ data: {+ app_Name: "powerappsclient",+ clientType: "ModelAppsAIPlugin",+ event_Name: d.eventName || "",+ session_Id: d.sessionId || "",+ ...(d.tenantId ? { tenantId: d.tenantId } : {}),+ severity: d.severity || "Info",+ timestamp: time,+ customDimensions: JSON.stringify(dimensions),+ },+ // Common Schema Part A extensions, kept outside customDimensions so the ingestion mapping fills the+ // standard app/session/OS columns (same as mobile-apps).+ ext: {+ app: { sesId: d.sessionId || "", ver: d.pluginVersion || "" },+ os: { name: d.osName || "", ver: d.osVersion || "" },+ },+ };+}++module.exports = { resolve, isProvisioned, formatEnvelope };diff --git a/plugins/model-apps/scripts/tests/artemis-service.test.js b/plugins/model-apps/scripts/tests/artemis-service.test.jsnew file mode 100644index 000000000..d0bb1ba76--- /dev/null+++ b/plugins/model-apps/scripts/tests/artemis-service.test.js@@ -0,0 +1,118 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const { fetchGeo, urlFor } = require("../lib/telemetry/region/artemis-service");++const orgId = "c7809087-d9b8-4a00-a78a-a4b901caa23f";++test("urlFor builds the Public template (two-char suffix)", () => {+ const u = urlFor(orgId, "Public");+ assert.match(u, /^https:\/\/c7809087d9b84a00a78aa4b901caa2\.3f\.organization\.api\.powerplatform\.com\/gateway\/cluster\?api-version=1$/);+});++test("urlFor builds the Gov template (single-char suffix, gov host)", () => {+ const u = urlFor(orgId, "Gov");+ assert.match(u, /^https:\/\/c7809087d9b84a00a78aa4b901caa23\.f\.organization\.api\.gov\.powerplatform\.microsoft\.us\/gateway\/cluster\?api-version=1$/);+});++test("urlFor builds the Gov template for the real PAC token 'UsGov' (GCC)", () => {+ const u = urlFor(orgId, "UsGov");+ assert.match(u, /api\.gov\.powerplatform\.microsoft\.us/);+ assert.doesNotMatch(u, /api\.powerplatform\.com\b/);+});++test("urlFor builds the High template", () => {+ const u = urlFor(orgId, "High");+ assert.match(u, /api\.high\.powerplatform\.microsoft\.us/);+});++test("urlFor builds the Dod template", () => {+ const u = urlFor(orgId, "Dod");+ assert.match(u, /api\.appsplatform\.us/);+});++test("urlFor builds the Mooncake template", () => {+ const u = urlFor(orgId, "Mooncake");+ assert.match(u, /powerplatform\.partner\.microsoftonline\.cn/);+});++test("urlFor builds the Internal template", () => {+ const u = urlFor(orgId, "Tip1");+ assert.match(u, /api\.test\.powerplatform\.com/);+});++test("urlFor falls back to Public when cloud is unknown or empty", () => {+ const u = urlFor(orgId, "WhoKnows");+ assert.match(u, /api\.powerplatform\.com\b/);+ assert.doesNotMatch(u, /\.gov\.|\.high\.|\.appsplatform\.|\.cn\b|\.test\./);+});++test("fetchGeo returns null when _httpsGet rejects", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.reject(new Error("network down")),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null on non-2xx status", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.resolve({ statusCode: 404, body: "" }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null on malformed JSON", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () => Promise.resolve({ statusCode: 200, body: "<<<<<" }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns null when body has no geoName", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () =>+ Promise.resolve({ statusCode: 200, body: JSON.stringify({ environment: "x" }) }),+ });+ assert.equal(result, null);+});++test("fetchGeo returns { geoName, stamp } on success", async () => {+ const result = await fetchGeo(orgId, "Public", {+ _httpsGet: () =>+ Promise.resolve({+ statusCode: 200,+ body: JSON.stringify({+ geoName: "us",+ environment: "prod",+ clusterNumber: 7,+ }),+ }),+ });+ assert.equal(result.geoName, "us");+ assert.equal(result.stamp, "Public");+});++test("fetchGeo uses the cloud-specific URL", async () => {+ let capturedUrl;+ await fetchGeo(orgId, "Mooncake", {+ _httpsGet: (u) => {+ capturedUrl = u;+ return Promise.resolve({+ statusCode: 200,+ body: JSON.stringify({ geoName: "cn", environment: "prod" }),+ });+ },+ });+ assert.match(capturedUrl, /\.partner\.microsoftonline\.cn/);+});++test("fetchGeo returns null when orgId is falsy (no HTTP call made)", async () => {+ let called = false;+ const fakeGet = () => { called = true; return Promise.resolve({ statusCode: 200, body: "{}" }); };+ assert.equal(await fetchGeo("", "Public", { _httpsGet: fakeGet }), null);+ assert.equal(await fetchGeo(null, "Public", { _httpsGet: fakeGet }), null);+ assert.equal(await fetchGeo(undefined, "Public", { _httpsGet: fakeGet }), null);+ assert.equal(called, false);+});diff --git a/plugins/model-apps/scripts/tests/region-cache.test.js b/plugins/model-apps/scripts/tests/region-cache.test.jsnew file mode 100644index 000000000..db469efc2--- /dev/null+++ b/plugins/model-apps/scripts/tests/region-cache.test.js@@ -0,0 +1,134 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const { read, write, TTL_MS } = require("../lib/telemetry/region/region-cache");++function mkTmp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-rc-"));+}++// Path of an org's per-org cache file under a config dir.+function entryPath(tmp, orgId) {+ return path.join(tmp, "region-cache", `${orgId}.json`);+}++// Write a raw entry file directly (for malformed/expired fixtures).+function writeRaw(tmp, orgId, contents) {+ fs.mkdirSync(path.join(tmp, "region-cache"), { recursive: true });+ fs.writeFileSync(entryPath(tmp, orgId), contents);+}++const orgIdA = "11111111-1111-1111-1111-111111111111";+const orgIdB = "22222222-2222-2222-2222-222222222222";+const entryUS = { region: "us" };+const entryEU = { region: "eu" };++test("read returns null when file does not exist", () => {+ const tmp = mkTmp();+ assert.equal(read(orgIdA, tmp), null);+});++test("write then read returns the region for the same orgId", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read(orgIdA, tmp).region, "us");+});++test("cache stores only the region (no iKey/collectorUrl)", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ const onDisk = JSON.parse(fs.readFileSync(entryPath(tmp, orgIdA), "utf8"));+ assert.deepEqual(Object.keys(onDisk).sort(), ["expiresAt", "region"]);+});++test("read returns null for an orgId that was never written", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read(orgIdB, tmp), null);+});++test("multiple orgIds coexist as separate files", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ write(orgIdB, entryEU, tmp);+ assert.equal(read(orgIdA, tmp).region, "us");+ assert.equal(read(orgIdB, tmp).region, "eu");+ assert.ok(fs.existsSync(entryPath(tmp, orgIdA)));+ assert.ok(fs.existsSync(entryPath(tmp, orgIdB)));+});++test("read returns null when entry is expired", () => {+ const tmp = mkTmp();+ writeRaw(+ tmp,+ orgIdA,+ JSON.stringify({ region: "us", expiresAt: Date.now() - 1000 })+ );+ assert.equal(read(orgIdA, tmp), null);+});++test("read returns null when JSON is malformed", () => {+ const tmp = mkTmp();+ writeRaw(tmp, orgIdA, "not json {");+ assert.equal(read(orgIdA, tmp), null);+});++test("write swallows disk errors (target dir unwritable)", () => {+ const notADir = path.join(os.tmpdir(), "ppskills-not-a-dir-" + Date.now());+ fs.writeFileSync(notADir, "");+ assert.doesNotThrow(() => write(orgIdA, entryUS, notADir));+});++test("write is atomic: leaves no temp files and produces complete per-org files", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ write(orgIdB, entryEU, tmp);+ const leftover = fs+ .readdirSync(path.join(tmp, "region-cache"))+ .filter((f) => f.includes(".tmp."));+ assert.deepEqual(leftover, [], "atomic write must not leave .tmp files behind");+ assert.equal(+ JSON.parse(fs.readFileSync(entryPath(tmp, orgIdA), "utf8")).region,+ "us"+ );+ assert.equal(+ JSON.parse(fs.readFileSync(entryPath(tmp, orgIdB), "utf8")).region,+ "eu"+ );+});++test("read returns null when orgId is falsy", () => {+ const tmp = mkTmp();+ write(orgIdA, entryUS, tmp);+ assert.equal(read("", tmp), null);+ assert.equal(read(null, tmp), null);+ assert.equal(read(undefined, tmp), null);+});++test("non-GUID orgId is rejected (no read, no write, no path traversal)", () => {+ const tmp = mkTmp();+ // Write attempt with a traversal-style id must be a no-op.+ assert.doesNotThrow(() => write("../evil", entryUS, tmp));+ assert.equal(read("../evil", tmp), null);+ // Nothing should have been created outside the (uncreated) cache dir.+ assert.equal(fs.existsSync(path.join(tmp, "region-cache")), false);+});++test("write is a silent no-op when orgId or entry is falsy", () => {+ const tmp = mkTmp();+ assert.doesNotThrow(() => write("", entryUS, tmp));+ assert.doesNotThrow(() => write(orgIdA, null, tmp));+ assert.doesNotThrow(() => write(orgIdA, undefined, tmp));+ assert.doesNotThrow(() => write(orgIdA, {}, tmp)); // entry with no region+ // No cache dir/file should exist after no-op writes.+ assert.equal(fs.existsSync(path.join(tmp, "region-cache")), false);+});++test("TTL_MS is exported as 24 hours", () => {+ assert.equal(TTL_MS, 24 * 60 * 60 * 1000);+});diff --git a/plugins/model-apps/scripts/tests/region-resolver.test.js b/plugins/model-apps/scripts/tests/region-resolver.test.jsnew file mode 100644index 000000000..94a1fd74c--- /dev/null+++ b/plugins/model-apps/scripts/tests/region-resolver.test.js@@ -0,0 +1,220 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");++const { resolve, mapToRegion } = require("../lib/telemetry/region/region-resolver");++const REGIONS = {+ internal: { instrumentation_key: "ik-int", collector_url: "https://int/" },+ us: { instrumentation_key: "ik-us", collector_url: "https://us/" },+ eu: { instrumentation_key: "ik-eu", collector_url: "https://eu/" },+ gov: { instrumentation_key: "ik-gov", collector_url: "https://gov/" },+ high: { instrumentation_key: "ik-hi", collector_url: "https://hi/" },+ dod: { instrumentation_key: "ik-dod", collector_url: "https://dod/" },+ mooncake: { instrumentation_key: "ik-mc", collector_url: "https://mc/" },+};++const noopCache = {+ read: () => null,+ write: () => {},+};++test("mapToRegion: Public + us → us", () => {+ assert.equal(mapToRegion("Public", "us", "us"), "us");+});++test("mapToRegion: Public + eu → eu", () => {+ assert.equal(mapToRegion("Public", "eu", "us"), "eu");+});++test("mapToRegion: Public + in (Asia-Pacific) → us", () => {+ assert.equal(mapToRegion("Public", "in", "us"), "us");+});++test("mapToRegion: Public + uk → eu", () => {+ assert.equal(mapToRegion("Public", "uk", "us"), "eu");+});++test("mapToRegion: Public + unknown geo → default", () => {+ assert.equal(mapToRegion("Public", "mars", "us"), "us");+});++test("mapToRegion: Gov → gov (geo ignored)", () => {+ assert.equal(mapToRegion("Gov", "us", "us"), "gov");+});++test("mapToRegion: UsGov (real PAC GCC token) → gov (geo ignored)", () => {+ assert.equal(mapToRegion("UsGov", "us", "us"), "gov");+});++test("mapToRegion: UsGovHigh → high (geo ignored)", () => {+ assert.equal(mapToRegion("UsGovHigh", "anything", "us"), "high");+});++test("mapToRegion: Dod → dod", () => {+ assert.equal(mapToRegion("Dod", "us", "us"), "dod");+});++test("mapToRegion: China → mooncake", () => {+ assert.equal(mapToRegion("China", "cn", "us"), "mooncake");+});++test("mapToRegion: Tip1 → internal", () => {+ assert.equal(mapToRegion("Tip1", "us", "us"), "internal");+});++test("mapToRegion: empty cloud → treated as Public", () => {+ assert.equal(mapToRegion("", "eu", "us"), "eu");+});++test("resolve: no orgId → default region without calling Artemis or cache", async () => {+ let cacheReadCalled = false;+ let fetchCalled = false;+ const result = await resolve({+ orgId: "",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => { fetchCalled = true; return Promise.resolve({ geoName: "us", stamp: "Public" }); },+ _cache: { read: () => { cacheReadCalled = true; return null; }, write: () => {} },+ });+ assert.equal(result.region, "us");+ assert.equal(result.iKey, "ik-us");+ assert.equal(result.collectorUrl, "https://us/");+ assert.equal(fetchCalled, false);+ assert.equal(cacheReadCalled, false);+});++test("resolve: cache hit maps the cached region to THIS plugin's iKey (not a cached key)", async () => {+ let fetchCalled = false;+ // Cache holds region only. The iKey must come from regionsMap, never the cache —+ // this is what stops a shared cache from misrouting one plugin's events to+ // another plugin's collector.+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => { fetchCalled = true; return Promise.resolve(null); },+ _cache: { read: () => ({ region: "eu" }), write: () => {} },+ });+ assert.equal(result.region, "eu");+ assert.equal(result.iKey, "ik-eu");+ assert.equal(result.collectorUrl, "https://eu/");+ assert.equal(fetchCalled, false);+});++test("resolve: cache hit on a region missing from regionsMap → falls back to default", async () => {+ const partial = { us: REGIONS.us };+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: partial,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve(null),+ _cache: { read: () => ({ region: "eu" }), write: () => {} },+ });+ assert.equal(result.region, "us"); // default fallback, since partial has no eu+});++test("resolve: cache miss + Artemis success → region-only cache write", async () => {+ let written;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "eu", stamp: "Public" }),+ _cache: {+ read: () => null,+ write: (orgId, entry) => { written = { orgId, entry }; },+ },+ });+ assert.equal(result.region, "eu");+ assert.equal(result.iKey, "ik-eu");+ // Only the plugin-independent region is persisted — no iKey/collectorUrl.+ assert.deepEqual(written.entry, { region: "eu" });+});++test("resolve: unrecognized geo (falls back to defaultRegion) is NOT cached", async () => {+ let writeCalled = false;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "eu",+ _fetchGeo: () => Promise.resolve({ geoName: "mars", stamp: "Public" }),+ _cache: { read: () => null, write: () => { writeCalled = true; } },+ });+ assert.equal(result.region, "eu"); // defaultRegion+ assert.equal(writeCalled, false, "a per-plugin default fallback must not be cached");+});++test("resolve: cache miss + Artemis null → default region, no cache write", async () => {+ let writeCalled = false;+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve(null),+ _cache: {+ read: () => null,+ write: () => { writeCalled = true; },+ },+ });+ assert.equal(result.region, "us");+ assert.equal(result.iKey, "ik-us");+ assert.equal(writeCalled, false);+});++test("resolve: regions map missing the resolved key → falls back to default", async () => {+ const partial = { us: REGIONS.us };+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Gov",+ regionsMap: partial,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Gov" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "us");+});++test("resolve: regions map missing default too → returns null", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Public",+ regionsMap: {},+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Public" }),+ _cache: noopCache,+ });+ assert.equal(result, null);+});++test("resolve: empty cloud + Artemis returns us → us region", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "us", stamp: "Public" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "us");+});++test("resolve: Mooncake cloud + ignored geo → mooncake region", async () => {+ const result = await resolve({+ orgId: "11111111-1111-1111-1111-111111111111",+ cloud: "Mooncake",+ regionsMap: REGIONS,+ defaultRegion: "us",+ _fetchGeo: () => Promise.resolve({ geoName: "cn", stamp: "Mooncake" }),+ _cache: noopCache,+ });+ assert.equal(result.region, "mooncake");+ assert.equal(result.iKey, "ik-mc");+});diff --git a/plugins/model-apps/scripts/tests/resolver.test.js b/plugins/model-apps/scripts/tests/resolver.test.jsnew file mode 100644index 000000000..2f81cc31a--- /dev/null+++ b/plugins/model-apps/scripts/tests/resolver.test.js@@ -0,0 +1,247 @@+"use strict";++const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const https = require("node:https");+const { EventEmitter } = require("node:events");++const resolver = require("../lib/telemetry/resolver");++const SHIPPED_IKEY = path.join(__dirname, "..", "lib", "telemetry", "ikey.json");+const ORG_ID = "00000000-0000-0000-0000-0000000000aa";++const REGIONS = {+ internal: { instrumentation_key: "ik-int", collector_url: "https://int.invalid/" },+ us: { instrumentation_key: "ik-us", collector_url: "https://us.invalid/" },+ eu: { instrumentation_key: "ik-eu", collector_url: "https://eu.invalid/" },+ gov: { instrumentation_key: "ik-gov", collector_url: "https://gov.invalid/" },+ high: { instrumentation_key: "ik-hi", collector_url: "https://hi.invalid/" },+ dod: { instrumentation_key: "ik-dod", collector_url: "https://dod.invalid/" },+ mooncake: { instrumentation_key: "ik-mc", collector_url: "https://mc.invalid/" },+};+const CFG = { default_region: "us", regions: REGIONS };++function mkTemp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-resolver-"));+}++// Replace https.request (which artemis-service calls at request time) for the duration of `fn`, so a+// test can both answer the Artemis gateway call and prove whether it was made. Never touches the network.+async function withFakeHttps(geoName, fn) {+ const calls = [];+ const original = https.request;+ https.request = (opts, onResponse) => {+ calls.push(opts.hostname);+ const req = new EventEmitter();+ req.setTimeout = () => req;+ req.destroy = () => {};+ req.end = () => {+ const res = new EventEmitter();+ res.statusCode = 200;+ res.setEncoding = () => {};+ onResponse(res);+ res.emit("data", JSON.stringify({ geoName }));+ res.emit("end");+ };+ return req;+ };+ try {+ return { result: await fn(), calls };+ } finally {+ https.request = original;+ }+}++test("isProvisioned: true when the default region has a real key + collector", () => {+ assert.equal(resolver.isProvisioned(CFG), true);+});++test("isProvisioned: false when the default region is missing, keyless or a placeholder", () => {+ assert.equal(resolver.isProvisioned(null), false);+ assert.equal(resolver.isProvisioned({}), false);+ assert.equal(resolver.isProvisioned({ regions: { us: { collector_url: "https://x/" } } }), false);+ assert.equal(resolver.isProvisioned({ regions: { us: { instrumentation_key: "k" } } }), false);+ assert.equal(+ resolver.isProvisioned({+ regions: { us: { instrumentation_key: "PLACEHOLDER_REPLACE_BEFORE_SHIPPING", collector_url: "https://x/" } },+ }),+ false+ );+});++test("Public cloud without an org (PAC signed out) → default region, no gateway call", async () => {+ const { result, calls } = await withFakeHttps("eu", () =>+ resolver.resolve({ event: { data: {} }, cfg: CFG, cloud: "", configDir: mkTemp() })+ );+ assert.deepEqual(result, { region: "us", iKey: "ik-us", collectorUrl: "https://us.invalid/" });+ assert.deepEqual(calls, []);+});++test("Public cloud with an org → routed by the org's geo (EU data boundary)", async () => {+ const { result, calls } = await withFakeHttps("eu", () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud: "Public", configDir: mkTemp() })+ );+ assert.equal(result.iKey, "ik-eu");+ assert.equal(result.collectorUrl, "https://eu.invalid/");+ assert.equal(calls.length, 1, "public routing must consult the Artemis gateway once");+ assert.match(calls[0], /\.organization\.api\.powerplatform\.com$/);+});++// An org's data boundary must come from its geo; the router's US default is only for a signed-out PAC.+for (const [label, geo] of [["the Artemis lookup fails", ""], ["Artemis reports an unrecognized geo", "mars"]]) {+ test(`Public cloud with an org → null (never the US default) when ${label}`, async () => {+ const configDir = mkTemp();+ const { result, calls } = await withFakeHttps(geo, () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud: "Public", configDir })+ );+ assert.equal(result, null);+ assert.equal(calls.length, 1);+ // Nothing is cached: the next event retries the lookup instead of inheriting a non-derived region.+ assert.equal(fs.existsSync(path.join(configDir, "region-cache", `${ORG_ID}.json`)), false);+ });+}++test("Public cloud with an org → a cached geo routes without a gateway call", async () => {+ const configDir = mkTemp();+ fs.mkdirSync(path.join(configDir, "region-cache"), { recursive: true });+ fs.writeFileSync(+ path.join(configDir, "region-cache", `${ORG_ID}.json`),+ JSON.stringify({ region: "eu", expiresAt: Date.now() + 60_000 })+ );+ const { result, calls } = await withFakeHttps("us", () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud: "Public", configDir })+ );+ assert.equal(result.iKey, "ik-eu");+ assert.deepEqual(calls, []);+});++for (const [cloud, region] of [+ ["UsGov", "gov"],+ ["UsGovHigh", "high"],+ ["UsGovDod", "dod"],+ ["China", "mooncake"],+ ["Tip1", "internal"],+ ["Tip2", "internal"],+ ["Test", "internal"],+ ["Preprod", "internal"],+]) {+ test(`${cloud} → ${region} from the PAC stamp alone (no Artemis call, no public fallback)`, async () => {+ const { result, calls } = await withFakeHttps("us", () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud, configDir: mkTemp() })+ );+ assert.equal(result.region, region);+ assert.equal(result.iKey, REGIONS[region].instrumentation_key);+ assert.deepEqual(calls, []);+ });+}++test("sovereign cloud with no configured entry → null (never the public default)", async () => {+ const cfg = { default_region: "us", regions: { us: REGIONS.us, eu: REGIONS.eu } };+ const r = await resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg, cloud: "UsGovHigh", configDir: mkTemp() });+ assert.equal(r, null);+});++test("unrecognized cloud stamp → null (fail closed, no gateway call)", async () => {+ const { result, calls } = await withFakeHttps("us", () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud: "USNat", configDir: mkTemp() })+ );+ assert.equal(result, null);+ assert.deepEqual(calls, []);+});++test("signed-in org with no cloud stamp → null (could be sovereign; never the public default)", async () => {+ const { result, calls } = await withFakeHttps("us", () =>+ resolver.resolve({ event: { data: { orgId: ORG_ID } }, cfg: CFG, cloud: "", configDir: mkTemp() })+ );+ assert.equal(result, null);+ assert.deepEqual(calls, []);+});++// --- The wire envelope ---------------------------------------------------------------------------++test("formatEnvelope emits the Power Apps client `event` shape, separable by clientType + pluginName", () => {+ const time = "2026-10-06T00:00:00.000Z";+ const data = {+ eventName: "skill_started",+ eventType: "Trace",+ severity: "Info",+ pluginName: "model-apps",+ pluginVersion: "2.12.1",+ skillName: "genpage",+ sessionId: "s-1",+ correlationId: "c-1",+ osName: "Windows",+ osVersion: "10.0.26100",+ orgId: ORG_ID,+ tenantId: "00000000-0000-0000-0000-0000000000bb",+ };+ const env = resolver.formatEnvelope({+ eventName: "event",+ time,+ data,+ iKey: "abc123-0000-0000-0000-000000000000-1234",+ eventStreamName: "event",+ });+ assert.equal(env.ver, "4.0");+ assert.equal(env.name, "event");+ assert.equal(env.time, time);+ assert.equal(env.iKey, "o:abc123");+ assert.deepEqual(Object.keys(env.data).sort(), [+ "app_Name", "clientType", "customDimensions", "event_Name", "session_Id", "severity", "tenantId", "timestamp",+ ]);+ assert.equal(env.data.app_Name, "powerappsclient");+ // Must NOT be PowerAppsNative (mobile-apps / the real native client) — keeps these rows out of client metrics.+ assert.equal(env.data.clientType, "ModelAppsAIPlugin");+ assert.equal(env.data.event_Name, "skill_started");+ assert.equal(env.data.session_Id, "s-1");+ assert.equal(env.data.tenantId, data.tenantId);+ assert.equal(env.data.timestamp, time);+ const dims = JSON.parse(env.data.customDimensions);+ assert.equal(dims.pluginName, "model-apps");+ assert.equal(dims.skillName, "genpage");+ assert.equal(dims.orgId, ORG_ID);+ for (const meta of ["eventName", "eventType", "severity"]) assert.equal(dims[meta], undefined, meta);+ assert.deepEqual(env.ext, { app: { sesId: "s-1", ver: "2.12.1" }, os: { name: "Windows", ver: "10.0.26100" } });+});++test("formatEnvelope omits tenantId when PAC gave none", () => {+ const env = resolver.formatEnvelope({ time: "t", data: { eventName: "skill_started" }, iKey: "k-1", eventStreamName: "event" });+ assert.equal("tenantId" in env.data, false);+ assert.equal(env.data.session_Id, "");+});++// --- The committed config -----------------------------------------------------------------------++// Collector per region, matching the 1DS OneCollector endpoints for each cluster category.+const EXPECTED_COLLECTORS = {+ internal: "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/",+ us: "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/",+ eu: "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/",+ gov: "https://tb.events.data.microsoft.com/OneCollector/1.0/",+ high: "https://tb.events.data.microsoft.com/OneCollector/1.0/",+ dod: "https://pf.events.data.microsoft.com/OneCollector/1.0/",+ mooncake: "https://collector.azure.cn/OneCollector/1.0/",+};++test("shipped ikey.json is live, region-routed, and has a real key + the right collector per region", () => {+ const cfg = JSON.parse(fs.readFileSync(SHIPPED_IKEY, "utf8"));+ assert.equal(cfg.disabled, false);+ assert.equal(cfg.event_stream_name, "event");+ assert.equal(cfg.default_region, "us");+ // No top-level static key: the dispatcher's static fallback must have nothing to fall back TO, so a+ // resolver that returns null (sovereign gap, unknown cloud) really does send nothing.+ assert.equal(cfg.instrumentationKey, undefined);+ assert.equal(cfg.collector_url, undefined);+ assert.deepEqual(Object.keys(cfg.regions).sort(), Object.keys(EXPECTED_COLLECTORS).sort());+ for (const [region, entry] of Object.entries(cfg.regions)) {+ // 1DS tenant tokens are "<32 hex tenant id>-<guid>-<4 digits>".+ assert.match(entry.instrumentation_key, /^[0-9a-f]{32}-[0-9a-f-]{36}-\d{4}$/, `${region} key shape`);+ assert.equal(entry.collector_url, EXPECTED_COLLECTORS[region], `${region} collector`);+ }+ // US and EU are the same public tenant; only the data-boundary collector differs.+ assert.equal(cfg.regions.us.instrumentation_key, cfg.regions.eu.instrumentation_key);+ assert.equal(resolver.isProvisioned(cfg), true);+});diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.jsindex 4bd668425..1fd1f223f 100644--- a/plugins/model-apps/scripts/tests/run-tests.test.js+++ b/plugins/model-apps/scripts/tests/run-tests.test.js@@ -69,164 +69,168 @@ test('summarize fails the run when any non-skipped suite failed', () => {assert.strictEqual(exitCode, 1);assert.ok(lines.some((l) => /FAIL\s+plugin node:test/.test(l)));});--// --- CI workflow scoping ----------------------------------------------------------------------// The plugin's workflow must stay scoped to THIS plugin. A widened path filter would spend CI on-// every unrelated PR, and (worse) make an unrelated plugin's red build look like a model-apps-// failure. This is a text assertion rather than a YAML parse because the repo ships no YAML-// dependency and the properties that matter are all line-level.-const WORKFLOW = path.resolve(__dirname, '..', '..', '..', '..', '.github', 'workflows', 'model-apps-script-tests.yml');-// The one exception: the `shared/` sources this plugin ships physical copies of. A change to one is-// NOT unrelated — telemetry-lib-copy.test.js fails when a copy drifts from its source, and it should-// fail in the PR that edited the source, not in the next model-apps PR, whose author did not cause it.-const BUNDLED_SHARED_SOURCES = new Set(['shared/telemetry/**', 'shared/skills/**']);--test('the model-apps CI workflow triggers ONLY on model-apps paths and the shared sources it bundles', () => {- const wf = fs.readFileSync(WORKFLOW, 'utf8');- // The `paths:` block ends at the first non-list line (the blank line before `jobs:`).- // paths:- // - "plugins/model-apps/**"- // # a comment is allowed between entries- // - "evals/model-apps/**"- const block = wf.slice(wf.indexOf('paths:'));- const globs = [];- for (const line of block.split('\n').slice(1)) {- const m = /^\s+-\s+"?([^"\s]+)"?\s*$/.exec(line);- if (m) { globs.push(m[1]); continue; }- if (/^\s*#/.test(line) || /^\s*$/.test(line)) continue;- break; // reached `jobs:` or another key- }- assert.ok(globs.length > 0, 'the workflow must declare a paths filter, not run on every PR');- for (const g of globs) {- assert.ok(- g.startsWith('plugins/model-apps/') || g.startsWith('evals/model-apps/') || g.endsWith('model-apps-script-tests.yml')- || BUNDLED_SHARED_SOURCES.has(g),- `path filter "${g}" is not scoped to model-apps — this workflow must not run for other plugins`- );- }- // And it must not be scoped so tightly that the plugin's own code stops triggering it.- assert.ok(globs.some((g) => g.startsWith('plugins/model-apps/')), 'the plugin source must trigger the workflow');- // Every shared source the plugin copies from must trigger it, and each one must exist: a renamed- // or removed source would otherwise leave an allowed glob that matches nothing.- for (const source of BUNDLED_SHARED_SOURCES) {- assert.ok(globs.includes(source), `a change to ${source} must run the drift test`);- assert.ok(fs.existsSync(path.resolve(__dirname, '..', '..', '..', '..', source.replace(/\/\*\*$/, ''))), `${source} names no directory`);- }-});--test('the model-apps CI workflow opts out of telemetry transmission on every job', () => {- // Repo convention: any job that could execute a telemetry-emitting hook or script must set the- // plugin's opt-out var, so a test that forgets to isolate emission cannot reach a real collector.- const wf = fs.readFileSync(WORKFLOW, 'utf8');- const jobCount = (wf.match(/^ {4}[a-z0-9-]+:\s*$/gim) || []).length;- const optOuts = (wf.match(/POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT/g) || []).length;- assert.ok(jobCount >= 2, `expected at least 2 jobs, found ${jobCount}`);- assert.strictEqual(optOuts, jobCount, `every job must set the opt-out (${optOuts} set / ${jobCount} jobs)`);++// --- CI workflow scoping ---------------------------------------------------------------------+// The plugin's workflow must stay scoped to THIS plugin. A widened path filter would spend CI on+// every unrelated PR, and (worse) make an unrelated plugin's red build look like a model-apps+// failure. This is a text assertion rather than a YAML parse because the repo ships no YAML+// dependency and the properties that matter are all line-level.+const WORKFLOW = path.resolve(__dirname, '..', '..', '..', '..', '.github', 'workflows', 'model-apps-script-tests.yml');+// The one exception: the sources this plugin ships physical copies of. A change to one is NOT+// unrelated — telemetry-lib-copy.test.js fails when a copy drifts from its source, and it should+// fail in the PR that edited the source, not in the next model-apps PR, whose author did not cause it.+const BUNDLED_SHARED_SOURCES = new Set([+ 'shared/telemetry/**',+ 'shared/skills/**',+ 'plugins/power-pages/scripts/lib/telemetry/region/**',+]);++test('the model-apps CI workflow triggers ONLY on model-apps paths and the shared sources it bundles', () => {+ const wf = fs.readFileSync(WORKFLOW, 'utf8');+ // The `paths:` block ends at the first non-list line (the blank line before `jobs:`).+ // paths:+ // - "plugins/model-apps/**"+ // # a comment is allowed between entries+ // - "evals/model-apps/**"+ const block = wf.slice(wf.indexOf('paths:'));+ const globs = [];+ for (const line of block.split('\n').slice(1)) {+ const m = /^\s+-\s+"?([^"\s]+)"?\s*$/.exec(line);+ if (m) { globs.push(m[1]); continue; }+ if (/^\s*#/.test(line) || /^\s*$/.test(line)) continue;+ break; // reached `jobs:` or another key+ }+ assert.ok(globs.length > 0, 'the workflow must declare a paths filter, not run on every PR');+ for (const g of globs) {+ assert.ok(+ g.startsWith('plugins/model-apps/') || g.startsWith('evals/model-apps/') || g.endsWith('model-apps-script-tests.yml')+ || BUNDLED_SHARED_SOURCES.has(g),+ `path filter "${g}" is not scoped to model-apps — this workflow must not run for other plugins`+ );+ }+ // And it must not be scoped so tightly that the plugin's own code stops triggering it.+ assert.ok(globs.some((g) => g.startsWith('plugins/model-apps/')), 'the plugin source must trigger the workflow');+ // Every shared source the plugin copies from must trigger it, and each one must exist: a renamed+ // or removed source would otherwise leave an allowed glob that matches nothing.+ for (const source of BUNDLED_SHARED_SOURCES) {+ assert.ok(globs.includes(source), `a change to ${source} must run the drift test`);+ assert.ok(fs.existsSync(path.resolve(__dirname, '..', '..', '..', '..', source.replace(/\/\*\*$/, ''))), `${source} names no directory`);+ }+});++test('the model-apps CI workflow opts out of telemetry transmission on every job', () => {+ // Repo convention: any job that could execute a telemetry-emitting hook or script must set the+ // plugin's opt-out var, so a test that forgets to isolate emission cannot reach a real collector.+ const wf = fs.readFileSync(WORKFLOW, 'utf8');+ const jobCount = (wf.match(/^ {4}[a-z0-9-]+:\s*$/gim) || []).length;+ const optOuts = (wf.match(/POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT/g) || []).length;+ assert.ok(jobCount >= 2, `expected at least 2 jobs, found ${jobCount}`);+ assert.strictEqual(optOuts, jobCount, `every job must set the opt-out (${optOuts} set / ${jobCount} jobs)`);+});++test('the model-apps CI workflow has a read-only token, cancels superseded runs, and bounds every job', () => {+ const wf = fs.readFileSync(WORKFLOW, 'utf8');+ // Declared at the top level so no job inherits whatever the repository default grants, and no+ // job widens it again with a write scope of its own.+ assert.match(wf, /^permissions:[ \t]*\r?\n[ \t]+contents:[ \t]*read[ \t]*\r?$/m, 'the token must be read-only');+ assert.doesNotMatch(wf, /^\s+[a-z-]+:[ \t]*write[ \t]*\r?$/m, 'no scope may be write');+ assert.match(wf, /^concurrency:[ \t]*\r?\n(?:[ \t]+.*\r?\n)*?[ \t]+cancel-in-progress:[ \t]*true\b/m,+ 'a new push must cancel the run it supersedes');+ // Without a limit a hung test holds its runner for GitHub's six-hour default.+ const jobCount = (wf.match(/^ {4}[a-z0-9-]+:\s*$/gim) || []).length;+ const timeouts = (wf.match(/^ {8}timeout-minutes:[ \t]*\d+[ \t]*\r?$/gm) || []).length;+ assert.strictEqual(timeouts, jobCount, `every job must set timeout-minutes (${timeouts} set / ${jobCount} jobs)`);+});++// --- committed lock files must not carry a registry URL ---------------------------------------+// `resolved` records the exact feed a package came from. Public npm is blocked on some Microsoft+// networks, so a contributor installing through an internal Azure Artifacts feed would rewrite+// every `resolved` to that internal URL and leak it into this OSS repo on the next commit. The+// `.npmrc` (`omit-lockfile-registry-resolved=true`) stops npm writing the field; this test is the+// backstop that catches a lock regenerated without it, or committed from another machine.+const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');+const VENDOR_BUILD = path.join(REPO_ROOT, 'plugins', 'model-apps', 'scripts', '_vendor-build');++test('the vendor-build lock file carries no registry URL of any kind', () => {+ const lockPath = path.join(VENDOR_BUILD, 'package-lock.json');+ const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));+ const offenders = [];+ for (const [name, entry] of Object.entries(lock.packages || {})) {+ if (entry && entry.resolved !== undefined) offenders.push(`packages['${name}'] -> ${entry.resolved}`);+ }+ for (const [name, entry] of Object.entries(lock.dependencies || {})) {+ if (entry && entry.resolved !== undefined) offenders.push(`dependencies['${name}'] -> ${entry.resolved}`);+ }+ assert.deepStrictEqual(+ offenders,+ [],+ `package-lock.json must not record a feed URL (an internal Azure Artifacts URL would leak into this OSS repo).\n` ++ `Re-run \`npm install\` in ${VENDOR_BUILD} with its .npmrc present, or delete the "resolved" keys.\nFound:\n ${offenders.join('\n ')}`+ );});--test('the model-apps CI workflow has a read-only token, cancels superseded runs, and bounds every job', () => {- const wf = fs.readFileSync(WORKFLOW, 'utf8');- // Declared at the top level so no job inherits whatever the repository default grants, and no- // job widens it again with a write scope of its own.- assert.match(wf, /^permissions:[ \t]*\r?\n[ \t]+contents:[ \t]*read[ \t]*\r?$/m, 'the token must be read-only');- assert.doesNotMatch(wf, /^\s+[a-z-]+:[ \t]*write[ \t]*\r?$/m, 'no scope may be write');- assert.match(wf, /^concurrency:[ \t]*\r?\n(?:[ \t]+.*\r?\n)*?[ \t]+cancel-in-progress:[ \t]*true\b/m,- 'a new push must cancel the run it supersedes');- // Without a limit a hung test holds its runner for GitHub's six-hour default.- const jobCount = (wf.match(/^ {4}[a-z0-9-]+:\s*$/gim) || []).length;- const timeouts = (wf.match(/^ {8}timeout-minutes:[ \t]*\d+[ \t]*\r?$/gm) || []).length;- assert.strictEqual(timeouts, jobCount, `every job must set timeout-minutes (${timeouts} set / ${jobCount} jobs)`);-});--// --- committed lock files must not carry a registry URL ----------------------------------------// `resolved` records the exact feed a package came from. Public npm is blocked on some Microsoft-// networks, so a contributor installing through an internal Azure Artifacts feed would rewrite-// every `resolved` to that internal URL and leak it into this OSS repo on the next commit. The-// `.npmrc` (`omit-lockfile-registry-resolved=true`) stops npm writing the field; this test is the-// backstop that catches a lock regenerated without it, or committed from another machine.-const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');-const VENDOR_BUILD = path.join(REPO_ROOT, 'plugins', 'model-apps', 'scripts', '_vendor-build');--test('the vendor-build lock file carries no registry URL of any kind', () => {- const lockPath = path.join(VENDOR_BUILD, 'package-lock.json');- const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));- const offenders = [];- for (const [name, entry] of Object.entries(lock.packages || {})) {- if (entry && entry.resolved !== undefined) offenders.push(`packages['${name}'] -> ${entry.resolved}`);- }- for (const [name, entry] of Object.entries(lock.dependencies || {})) {- if (entry && entry.resolved !== undefined) offenders.push(`dependencies['${name}'] -> ${entry.resolved}`);- }- assert.deepStrictEqual(- offenders,- [],- `package-lock.json must not record a feed URL (an internal Azure Artifacts URL would leak into this OSS repo).\n` +- `Re-run \`npm install\` in ${VENDOR_BUILD} with its .npmrc present, or delete the "resolved" keys.\nFound:\n ${offenders.join('\n ')}`- );-});--test('the vendor-build lock still pins every platform binary WITH an integrity hash', () => {- // Stripping `resolved` must not cost supply-chain protection, and regenerating the lock on one- // OS can silently collapse the tree: a `npm install --package-lock-only` that reuses a Windows- // node_modules dropped 28 packages to 3, losing every non-Windows esbuild binary that CI needs.- const lock = JSON.parse(fs.readFileSync(path.join(VENDOR_BUILD, 'package-lock.json'), 'utf8'));- const pkgs = Object.entries(lock.packages || {}).filter(([name]) => name !== '');- const missingIntegrity = pkgs.filter(([, e]) => !e.link && e.integrity === undefined).map(([n]) => n);- assert.deepStrictEqual(missingIntegrity, [], 'every locked package keeps its integrity hash');- // esbuild ships one optional package per platform; a single-platform lock means the tree was- // regenerated on one OS and the others were lost.- const platforms = pkgs.filter(([name]) => name.startsWith('node_modules/@esbuild/'));- assert.ok(platforms.length >= 10, `expected the full cross-platform esbuild set, found ${platforms.length}: ${platforms.map(([n]) => n).join(', ')}`);-});--test('the .npmrc that prevents the leak sits next to the package.json it governs', () => {- // npm reads the per-project .npmrc from the directory that OWNS package.json and does NOT walk- // up, so a repo-root .npmrc alone would NOT cover this lock file — verified with `npm config- // get` from inside the directory. Deleting this file silently re-enables the leak.- const npmrc = path.join(VENDOR_BUILD, '.npmrc');- assert.ok(fs.existsSync(npmrc), `${npmrc} is required: without it npm rewrites "resolved" with the contributor's feed URL`);- assert.match(fs.readFileSync(npmrc, 'utf8'), /^\s*omit-lockfile-registry-resolved\s*=\s*true\s*$/m);++test('the vendor-build lock still pins every platform binary WITH an integrity hash', () => {+ // Stripping `resolved` must not cost supply-chain protection, and regenerating the lock on one+ // OS can silently collapse the tree: a `npm install --package-lock-only` that reuses a Windows+ // node_modules dropped 28 packages to 3, losing every non-Windows esbuild binary that CI needs.+ const lock = JSON.parse(fs.readFileSync(path.join(VENDOR_BUILD, 'package-lock.json'), 'utf8'));+ const pkgs = Object.entries(lock.packages || {}).filter(([name]) => name !== '');+ const missingIntegrity = pkgs.filter(([, e]) => !e.link && e.integrity === undefined).map(([n]) => n);+ assert.deepStrictEqual(missingIntegrity, [], 'every locked package keeps its integrity hash');+ // esbuild ships one optional package per platform; a single-platform lock means the tree was+ // regenerated on one OS and the others were lost.+ const platforms = pkgs.filter(([name]) => name.startsWith('node_modules/@esbuild/'));+ assert.ok(platforms.length >= 10, `expected the full cross-platform esbuild set, found ${platforms.length}: ${platforms.map(([n]) => n).join(', ')}`);});--// The `.npmrc` that strips `resolved` only governs the directory that OWNS package.json -- npm does-// NOT walk up -- so it protects _vendor-build and nothing else. Verified: `npm config get` reads-// false from plugins/mobile-apps/template and from the power-pages create-site asset packages,-// each of which has its own package.json. That is the DESIRED scope (those are templates scaffolded-// into user projects; forcing our lockfile policy on a user's project would be wrong), but it means-// a lock file added to any other plugin tomorrow would be unprotected. This sweep is the backstop-// for that: it does not demand the strip everywhere, only that no committed lock leaks a NON-PUBLIC-// feed URL, which is the actual security property.-function findLockFiles(dir, out = []) {- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- if (entry.name === 'node_modules' || entry.name === '.git') continue;- const full = path.join(dir, entry.name);- if (entry.isDirectory()) findLockFiles(full, out);- else if (entry.name === 'package-lock.json') out.push(full);- }- return out;-}--test('NO committed lock file anywhere in the repo records a non-public registry URL', () => {- const locks = findLockFiles(REPO_ROOT);- assert.ok(locks.length > 0, 'the sweep must actually find the lock file(s) it is guarding');- const offenders = [];- for (const lockPath of locks) {- const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));- for (const section of ['packages', 'dependencies']) {- for (const [name, entry] of Object.entries(lock[section] || {})) {- const url = entry && entry.resolved;- if (typeof url !== 'string' || !/^https?:/i.test(url)) continue;- // Public npm (and its official mirror) are fine in an OSS repo; an internal Azure Artifacts- // or on-prem feed URL is the leak this guards against.- const host = new URL(url).host.toLowerCase();- if (host === 'registry.npmjs.org' || host === 'registry.yarnpkg.com') continue;- offenders.push(`${path.relative(REPO_ROOT, lockPath)} :: ${section}['${name}'] -> ${url}`);- }- }- }- assert.deepStrictEqual(- offenders,- [],- `a committed package-lock.json records a non-public feed URL, which would leak an internal registry into this OSS repo:\n ${offenders.join('\n ')}`- );++test('the .npmrc that prevents the leak sits next to the package.json it governs', () => {+ // npm reads the per-project .npmrc from the directory that OWNS package.json and does NOT walk+ // up, so a repo-root .npmrc alone would NOT cover this lock file — verified with `npm config+ // get` from inside the directory. Deleting this file silently re-enables the leak.+ const npmrc = path.join(VENDOR_BUILD, '.npmrc');+ assert.ok(fs.existsSync(npmrc), `${npmrc} is required: without it npm rewrites "resolved" with the contributor's feed URL`);+ assert.match(fs.readFileSync(npmrc, 'utf8'), /^\s*omit-lockfile-registry-resolved\s*=\s*true\s*$/m);+});++// The `.npmrc` that strips `resolved` only governs the directory that OWNS package.json -- npm does+// NOT walk up -- so it protects _vendor-build and nothing else. Verified: `npm config get` reads+// false from plugins/mobile-apps/template and from the power-pages create-site asset packages,+// each of which has its own package.json. That is the DESIRED scope (those are templates scaffolded+// into user projects; forcing our lockfile policy on a user's project would be wrong), but it means+// a lock file added to any other plugin tomorrow would be unprotected. This sweep is the backstop+// for that: it does not demand the strip everywhere, only that no committed lock leaks a NON-PUBLIC+// feed URL, which is the actual security property.+function findLockFiles(dir, out = []) {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === '.git') continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) findLockFiles(full, out);+ else if (entry.name === 'package-lock.json') out.push(full);+ }+ return out;+}++test('NO committed lock file anywhere in the repo records a non-public registry URL', () => {+ const locks = findLockFiles(REPO_ROOT);+ assert.ok(locks.length > 0, 'the sweep must actually find the lock file(s) it is guarding');+ const offenders = [];+ for (const lockPath of locks) {+ const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));+ for (const section of ['packages', 'dependencies']) {+ for (const [name, entry] of Object.entries(lock[section] || {})) {+ const url = entry && entry.resolved;+ if (typeof url !== 'string' || !/^https?:/i.test(url)) continue;+ // Public npm (and its official mirror) are fine in an OSS repo; an internal Azure Artifacts+ // or on-prem feed URL is the leak this guards against.+ const host = new URL(url).host.toLowerCase();+ if (host === 'registry.npmjs.org' || host === 'registry.yarnpkg.com') continue;+ offenders.push(`${path.relative(REPO_ROOT, lockPath)} :: ${section}['${name}'] -> ${url}`);+ }+ }+ }+ assert.deepStrictEqual(+ offenders,+ [],+ `a committed package-lock.json records a non-public feed URL, which would leak an internal registry into this OSS repo:\n ${offenders.join('\n ')}`+ );});diff --git a/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.jsindex a023fb0df..b1d31ba8a 100644--- a/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js+++ b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js@@ -92,7 +92,8 @@ function writeProvisionedConfig(configDir) {test("ikey.json is never shipped enabled with the placeholder key", () => {const cfg = JSON.parse(fs.readFileSync(SHIPPED_IKEY, "utf8"));- if (cfg.instrumentationKey === "PLACEHOLDER_REPLACE_BEFORE_SHIPPING") {+ const keys = [cfg.instrumentationKey, ...Object.values(cfg.regions || {}).map((r) => r && r.instrumentation_key)];+ if (keys.includes("PLACEHOLDER_REPLACE_BEFORE_SHIPPING")) {// Unprovisioned placeholder must stay hard-off.assert.equal(cfg.disabled, true, "a placeholder key must ship disabled:true");}@@ -113,18 +114,44 @@ test("exits 0 on malformed stdin", () => {assert.equal(status, 0);});-test("shipped disabled config → tracked skill emits nothing (no probe, hard-off)", () => {+test("shipped config + resolver → tracked skill is region-routed to this plugin's key (no network)", () => {const configDir = mkTemp();const probePath = path.join(configDir, "probe.json");- // No ikey override → the hook reads the shipped ikey.json (disabled:true) and- // short-circuits before spawning the dispatcher.+ const shipped = JSON.parse(fs.readFileSync(SHIPPED_IKEY, "utf8"));+ // The stub pac reports a Public-cloud org. Seed the shared org→region cache with "eu" so the+ // resolver routes from the cache instead of calling the Artemis gateway — the test stays offline,+ // and an EU key (not the US default) in the probe proves the shipped resolver.js did the routing.+ const cacheDir = path.join(configDir, "region-cache");+ fs.mkdirSync(cacheDir, { recursive: true });+ fs.writeFileSync(+ path.join(cacheDir, `${STUB_BANNER.orgId}.json`),+ JSON.stringify({ region: "eu", expiresAt: Date.now() + 60 * 60 * 1000 })+ );++ // No ikey override → the hook and dispatcher read the shipped ikey.json and load the resolver.js+ // beside it. FAKE_HTTPS swaps the POST for the probe file, so nothing reaches a real collector.const { status } = runHook({input: JSON.stringify({ tool_input: { skill: "genpage" } }),configDir,fakeProbe: probePath,});assert.equal(status, 0);- assert.equal(waitForFile(probePath, 1500), false, "disabled config must not write a probe");+ assert.ok(waitForFile(probePath, 5000), "dispatcher should have written the probe");+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ const body = JSON.parse(probe.body);+ assert.equal(body.name, shipped.event_stream_name);+ // The shipped resolver's formatEnvelope reshapes the event into the Power Apps client `event` schema.+ assert.equal(body.data.clientType, "ModelAppsAIPlugin");+ assert.equal(body.data.event_Name, "skill_started");+ const dims = JSON.parse(body.data.customDimensions);+ assert.equal(dims.pluginName, "model-apps");+ assert.equal(dims.skillName, "genpage");+ assert.equal(dims.eventInfo, undefined, "model-apps must not send eventInfo/aadObjectId");+ // Without the native stub (no csc.exe on this Windows box) PAC is absent: no org, so the event+ // takes the US default instead of the cached EU route.+ const region = stubBuilt ? "eu" : "us";+ assert.equal(probe.headers["x-apikey"], shipped.regions[region].instrumentation_key);+ assert.equal(body.iKey, "o:" + shipped.regions[region].instrumentation_key.split("-")[0]);});test("provisioned Tier-1 config → tracked skill emits skill_started to the probe", () => {diff --git a/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.jsindex c8c523527..a5fee6fc7 100644--- a/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js+++ b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js@@ -44,6 +44,24 @@ test('bundled telemetry lib is identical to shared/telemetry/lib', (t) => {assert.deepEqual(drifted, [], 'bundled copy has drifted from shared/telemetry/lib — re-copy these files');});+test('bundled telemetry region router is identical to power-pages\' region/', (t) => {+ // model-apps' resolver.js reuses power-pages' Artemis geo + cloud-stamp router (scripts/lib/telemetry/+ // region/) as a verbatim physical copy; model-apps-specific routing lives only in resolver.js. Without+ // this, a router fix landed in one plugin would leave the other silently stale. The workflow's path+ // filter includes the power-pages region/ directory, so a change on either side runs this check.+ const sourceDir = path.join(REPO_ROOT, 'plugins', 'power-pages', 'scripts', 'lib', 'telemetry', 'region');+ const copyDir = path.join(PLUGIN_ROOT, 'scripts', 'lib', 'telemetry', 'region');+ if (!fs.existsSync(sourceDir)) {+ t.skip('plugins/power-pages not present (installed plugin, not a repo checkout)');+ return;+ }+ const sourceFiles = fs.readdirSync(sourceDir).filter((f) => f.endsWith('.js')).sort();+ const copyFiles = fs.readdirSync(copyDir).filter((f) => f.endsWith('.js')).sort();+ assert.deepEqual(copyFiles, sourceFiles, 'region/ copy and power-pages source must contain the same modules');+ const drifted = sourceFiles.filter((f) => text(path.join(sourceDir, f)) !== text(path.join(copyDir, f)));+ assert.deepEqual(drifted, [], 'region/ has drifted from power-pages — apply the change to both copies');+});+test('bundled shared skill workflows match their shared source', (t) => {const pairs = [['telemetry', 'telemetry-workflow.md'],diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 78345573f..e1eb9daf5 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -438,7 +438,7 @@ These requirements apply to scripts, hooks, skills, templates, reports, and docuThis plugin ships 1DS telemetry for skill-run and script-run signals. The canonical shared library lives at the repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a physical copy bundled with this plugin so local checkouts and installed plugins do not depend on symlink handling. Zero npm dependencies — nothing to install.- **`scripts/lib/telemetry/lib` is copied** from the repo-root `shared/telemetry/lib` — edit `shared/telemetry/lib/` first, then refresh this plugin's copy in the same change. The real files next to the copy are `ikey.json` (this plugin's config) and `resolver.js` (the resolver contract implementation). **Posture:** the committed `ikey.json` ships `disabled: false` — transmission is enabled for power-pages (the tenant-side Kusto stream + annotation for `PagesAIPluginEvent` are provisioned). Set `disabled: true` to hard-off (no POST, no local log) if you need to suppress all telemetry at the source.-- **Region routing (Artemis geo + cloud stamp)** lives in `scripts/lib/telemetry/region/` and is wired through `scripts/lib/telemetry/resolver.js`, which implements the resolver contract (`resolve({ event, cfg, cloud, configDir })` / `isProvisioned(cfg)`). The shared dispatcher is routing-agnostic — it auto-discovers `resolver.js` by convention (sibling of `ikey.json`) and calls it; the `region/` implementation is entirely plugin-owned and never referenced by the shared library.+- **Region routing (Artemis geo + cloud stamp)** lives in `scripts/lib/telemetry/region/` and is wired through `scripts/lib/telemetry/resolver.js`, which implements the resolver contract (`resolve({ event, cfg, cloud, configDir })` / `isProvisioned(cfg)`). The shared dispatcher is routing-agnostic — it auto-discovers `resolver.js` by convention (sibling of `ikey.json`) and calls it; the `region/` implementation is entirely plugin-owned and never referenced by the shared library. model-apps bundles a **verbatim copy** of `region/` (its own `resolver.js` differs); `plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js` fails when the two drift, so apply a `region/` change to both copies in the same PR.- **Privacy posture:** usage telemetry is **default-on**. When PAC is signed in, events include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`). Power Pages also includes the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it; otherwise that field is omitted. The local diagnostic mirror retains the same fields. Events do not include file paths, prompts, tool inputs, site names, Dataverse URLs, credentials, usernames, or hostnames. There is no consent prompt in skills. Users opt out via `/power-pages:telemetry off`, which stores a per-plugin choice in `~/.power-platform-skills/config.json` (`telemetry["power-pages"] = "off"`). Opting out stops transmission only; the local diagnostic mirror is still written. Re-enable with `/power-pages:telemetry on`. Automation/CI can disable transmission by setting `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT=1` (or `true`); this opt-out has the **highest precedence** and overrides both a persisted `/power-pages:telemetry` choice and `/power-pages:telemetry on`.- **Strict allowlist:** `shared/telemetry/lib/events.js` enforces exactly the fields listed in the spec. Never add a field to a builder without first adding it to the allowlist and documenting it in the design doc.- **Fail closed:** telemetry code must never change a script's exit code or break a skill run. Emission is fire-and-forget via a detached dispatcher child, so the hook or script returns before the HTTPS POST completes.diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.jsindex 1d0d14e2d..fc6571132 100644--- a/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.js+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -106,6 +106,26 @@ function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName};}+// The wire envelope is the shared shape above unless the plugin's resolver.js+// exports an optional `formatEnvelope({ eventName, time, data, iKey,+// eventStreamName })`. That lets a plugin whose tenant ingests a different+// schema (e.g. the Power Apps client `event` table) reshape the payload without+// forking this dispatcher. `data` is the already-sanitized allowlisted payload,+// so a formatter can only rearrange approved fields, never add new sources.+// A formatter that throws or returns nothing sends NOTHING (fail closed): the+// plugin opted into a specific shape, and the default one would not be+// ingested by its pipeline anyway. The local mirror was already written.+function formatEnvelope(resolver, { eventName, time, data, iKey, eventStreamName }) {+ if (resolver && typeof resolver.formatEnvelope === "function") {+ try {+ return resolver.formatEnvelope({ eventName, time, data, iKey, eventStreamName }) || null;+ } catch {+ return null;+ }+ }+ return buildEnvelope(eventName, time, data, iKey, eventStreamName);+}+function writeProbe(filePath, { headers, body }) {try {fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");@@ -209,7 +229,14 @@ process.stdin.on("end", async () => {// Real iKey → Common Schema envelope (reuses the same time + sanitized data// as the local mirror) → HTTPS POST.- const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ const envelope = formatEnvelope(resolver, {+ eventName: event.name,+ time,+ data: sanitized,+ iKey,+ eventStreamName: cfg.event_stream_name,+ });+ if (!envelope) return exitSilently();const body = JSON.stringify(envelope) + "\n";const headers = {"Content-Type": "application/x-json-stream; charset=utf-8",diff --git a/scripts/validate-telemetry-ikeys.js b/scripts/validate-telemetry-ikeys.jsindex 165349292..20ee3b29a 100644--- a/scripts/validate-telemetry-ikeys.js+++ b/scripts/validate-telemetry-ikeys.js@@ -60,6 +60,15 @@ function isPlaceholder(value) {return false;}+// Stream names that are a SHARED ingestion table by design, so several plugins may+// name them. "event" is the Power Apps client telemetry table: the 1DS tenants that+// mobile-apps and model-apps send to ingest only that stream, and any other stream+// name is accepted by the collector and then dropped. Plugins sharing it must make+// their rows separable in the payload — each sets its own `clientType` and puts its+// `pluginName` in `customDimensions` (see each plugin's telemetry envelope builder).+// Instrumentation keys are still never shareable; only the stream name is exempt.+const SHARED_INGESTION_STREAMS = new Set(['event']);+function toPosix(relativePath) {return relativePath.replace(/\\/g, '/');}@@ -145,7 +154,7 @@ for (const filePath of findIkeyFiles(PLUGINS_DIR)) {record(keyOwners, value, pluginName, `${relPath} (${context})`);}- if (!isPlaceholder(config.event_stream_name)) {+ if (!isPlaceholder(config.event_stream_name) && !SHARED_INGESTION_STREAMS.has(config.event_stream_name.trim())) {record(streamOwners, config.event_stream_name, pluginName, `${relPath} (event_stream_name)`);}}diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex 9bc0b90cb..dc7e6ab68 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -60,7 +60,7 @@ 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. || 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: true` | Hard-off: no event building, network transmission, or local mirror. If enabled later, transmission will be default-on and the standard mirror and opt-out behavior will apply. | No signed-in user object ID. If enabled, the base event can include `orgId` and `tenantId` when PAC is signed in. |+| 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. |### Custom routing (the resolver contract)@@ -74,9 +74,18 @@ module.exports = {async resolve({ event, cfg, cloud, configDir }) { /* ... */ },// optional sync fast-gate so hooks skip the ~3-5s pac shellout when unprovisioned.isProvisioned(cfg) { return true; },+ // optional: reshape the wire envelope for a tenant that ingests a different schema.+ // `data` is the already-sanitized allowlisted payload. Throwing or returning nothing+ // sends nothing (fail closed); the local mirror is unaffected.+ formatEnvelope({ eventName, time, data, iKey, eventStreamName }) { /* ... */ },};```+Model Apps uses `formatEnvelope` to send the Power Apps client `event` shape+(`app_Name`, `clientType: "ModelAppsAIPlugin"`, `event_Name`, `session_Id`, and the+remaining fields as a `customDimensions` JSON string) because its tenants ingest only+the `event` stream.+The dispatcher discovers it by convention (a `resolver.js` sibling of `ikey.json`)and resolves the destination by precedence: env override (test seam) →`resolver.js` → static `instrumentationKey`/`collector_url` in `ikey.json` → none.@@ -149,7 +158,7 @@ The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` be- **Enabled plugins are default-on for transmission.** There is no first-runprompt. A plugin that ships `disabled: true` remains hard-off regardless of auser's saved telemetry choice.-- **Identifiers.** Power Pages, and Model Apps if enabled, can include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`) when PAC is signed in. Power Pages can also include the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it. Mobile Apps excludes all three identity fields. The local diagnostic mirror retains the same fields as the event produced by each plugin.+- **Identifiers.** Power Pages and Model Apps can include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`) when PAC is signed in. Power Pages can also include the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it. Mobile Apps excludes all three identity fields. The local diagnostic mirror retains the same fields as the event produced by each plugin.- **Authenticated scenario.** When an adopter has the authentication or project-environment context required by its routing implementation, the resolved cloud and geo select the corresponding configured regional collector. Depending on the adopter's documented schema, the transmitted event may include End User Pseudonymous Information (EUPI) or Organization Identifiable Information (OII).- **Unauthenticated or unresolved scenario.** When PAC provides no authentication context, the organization, tenant, and Entra user object ID fields are absent. Destination behavior when routing context is unavailable is adopter-specific: configurations with a default region use that configured destination, while configurations that require a resolved project cluster retain the event in the local mirror and do not transmit it until a valid cluster is available. The event can still contain the allowlisted operational and system metadata and separately documented non-identity plugin-specific fields.- **Opt out of transmission** via `/<plugin>:telemetry off` (per-user, per-plugin). This writes `telemetry[<plugin>] = "off"` into `~/.power-platform-skills/config.json` and stops the network POST to the collector — **nothing leaves the machine** — but the local diagnostic mirror (a per-session `events.jsonl`) is still written so the user/developer can see exactly what would have been sent. It is therefore an opt-out of *transmission*, not of local logging. CI/headless can opt out by writing that file directly. Re-enable with `/<plugin>:telemetry on`.diff --git a/shared/telemetry/lib/emit-dispatcher.js b/shared/telemetry/lib/emit-dispatcher.jsindex 1d0d14e2d..fc6571132 100644--- a/shared/telemetry/lib/emit-dispatcher.js+++ b/shared/telemetry/lib/emit-dispatcher.js@@ -106,6 +106,26 @@ function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName};}+// The wire envelope is the shared shape above unless the plugin's resolver.js+// exports an optional `formatEnvelope({ eventName, time, data, iKey,+// eventStreamName })`. That lets a plugin whose tenant ingests a different+// schema (e.g. the Power Apps client `event` table) reshape the payload without+// forking this dispatcher. `data` is the already-sanitized allowlisted payload,+// so a formatter can only rearrange approved fields, never add new sources.+// A formatter that throws or returns nothing sends NOTHING (fail closed): the+// plugin opted into a specific shape, and the default one would not be+// ingested by its pipeline anyway. The local mirror was already written.+function formatEnvelope(resolver, { eventName, time, data, iKey, eventStreamName }) {+ if (resolver && typeof resolver.formatEnvelope === "function") {+ try {+ return resolver.formatEnvelope({ eventName, time, data, iKey, eventStreamName }) || null;+ } catch {+ return null;+ }+ }+ return buildEnvelope(eventName, time, data, iKey, eventStreamName);+}+function writeProbe(filePath, { headers, body }) {try {fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");@@ -209,7 +229,14 @@ process.stdin.on("end", async () => {// Real iKey → Common Schema envelope (reuses the same time + sanitized data// as the local mirror) → HTTPS POST.- const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ const envelope = formatEnvelope(resolver, {+ eventName: event.name,+ time,+ data: sanitized,+ iKey,+ eventStreamName: cfg.event_stream_name,+ });+ if (!envelope) return exitSilently();const body = JSON.stringify(envelope) + "\n";const headers = {"Content-Type": "application/x-json-stream; charset=utf-8",diff --git a/shared/telemetry/tests/emit-dispatcher.test.js b/shared/telemetry/tests/emit-dispatcher.test.jsindex 41d19ad1a..92a513ee9 100644--- a/shared/telemetry/tests/emit-dispatcher.test.js+++ b/shared/telemetry/tests/emit-dispatcher.test.js@@ -501,6 +501,69 @@ test("dispatcher uses an injected resolver.js to pick iKey/collector", () => {assert.equal(probe.headers["x-apikey"], "ikeyusresolved");});+// Static-key ikey.json plus a resolver.js that only supplies formatEnvelope — the+// optional seam a plugin uses to reshape the wire envelope for its tenant's schema.+function mkFormatterPlugin(tmp, formatterSource) {+ const ikeyPath = path.join(tmp, "ikey.json");+ fs.writeFileSync(+ ikeyPath,+ JSON.stringify({+ instrumentationKey: "static-ikey-32-chars-minimum-aaaaaaaaaaaa",+ collector_url: "https://example.invalid/OneCollector/1.0/",+ event_stream_name: "event",+ disabled: false,+ })+ );+ fs.writeFileSync(+ path.join(tmp, "resolver.js"),+ "module.exports = { async resolve() { return null; }, isProvisioned: () => true, formatEnvelope: " ++ formatterSource + " };"+ );+ return ikeyPath;+}++test("dispatcher sends the envelope a resolver's formatEnvelope returns", () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const ikeyPath = mkFormatterPlugin(+ tmp,+ "({ eventName, time, data, iKey, eventStreamName }) => ({ ver: '4.0', name: eventStreamName, time," ++ " iKey: 'o:' + iKey.split('-')[0], data: { event_Name: data.eventName, from: eventName," ++ " customDimensions: JSON.stringify({ skillName: data.skillName }) } })"+ );+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath, ikeyJsonPath: ikeyPath },+ });+ assert.equal(status, 0);+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));+ const body = JSON.parse(probe.body);+ assert.equal(body.name, "event");+ assert.equal(body.iKey, "o:static");+ assert.equal(body.data.event_Name, "skill_started");+ assert.equal(body.data.from, "PowerPagesPluginEvent");+ assert.deepEqual(JSON.parse(body.data.customDimensions), { skillName: "add-seo" });+ assert.equal(body.data.pluginName, undefined, "the default shape must not leak through");+});++for (const [label, formatter] of [+ ["throws", "() => { throw new Error('boom'); }"],+ ["returns nothing", "() => null"],+]) {+ test(`dispatcher fails closed (no POST, mirror kept) when formatEnvelope ${label}`, () => {+ const tmp = mkTmp();+ const probePath = path.join(tmp, "probe.json");+ const ikeyPath = mkFormatterPlugin(tmp, formatter);+ const { status } = runDispatcher({+ event: fakeEvent,+ env: { configDir: tmp, iKey: "", collectorUrl: "", fakeProbe: probePath, ikeyJsonPath: ikeyPath },+ });+ assert.equal(status, 0);+ assert.equal(fs.existsSync(probePath), false, "a broken formatter must not fall back to the default shape");+ assert.ok(fs.existsSync(mirrorPath(tmp)), "the local mirror is still written");+ });+}+test("dispatcher falls back to the static key when a resolver resolves to nothing", () => {// Documented precedence is resolver → static → none. A resolver present but// returning null/undefined must NOT suppress a configured static key.