← Catalog

pbirs

Typed Power BI Report Server REST API v2.0 client and read-only pi extension

Package

Install

Install with PiG

pig install npm:pbirs

Install with Pi

pi install npm:pbirs
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./extensions/env/index.ts",
    "./extensions/pbirs/index.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.1.1 (README.md). PiG does not review it.

pbirs

A typed Node.js client for the Power BI Report Server (PBIRS) REST API v2.0, with an optional read-only pi extension.

This package targets Power BI Report Server, not the Power BI Service cloud API.

The client covers 18 resources and all 237 documented operations. Every operation has offline wire-contract and type tests. The Node.js transport passed seven live metadata reads over HTTPS against PBIRS build 1.22.9153.7886. Binary download returned HTTP 403 and remains unverified. See live-server verification for the test scope.

Published versions are available on npm. This README describes the transport in this checkout.

Contents

Requirements

  • Node.js 24 or later, as declared by engines.node.
  • ESM imports.
  • HTTPS and a PBIRS account with permission for each requested operation.

The standalone client does not require a native addon, a system curl executable, or the OpenSSL legacy provider.

Install from a local checkout

To install from source, build a local tarball:

npm ci
npm pack

# From the consuming project, use the filename printed by npm pack:
npm install /path/to/pbirs-0.0.1.tgz

npm pack runs the package build through the prepack script. Run npm run ci and npm run test:package to verify the checkout and the packed client without contacting a PBIRS server.

Client quick start

import { BIClient } from "pbirs";

const client = new BIClient({
  baseUrl: "https://reports.example.com/reports",
  credentials: {
    username: "DOMAIN\\username",
    password: process.env.BI_PASSWORD ?? "",
  },
  timeoutMs: 60_000,
});

try {
  const reports = await client.powerBiReports.getPowerBiReports({
    query: { $select: "Id,Name,Path" },
  });
  const report =
    await client.powerBiReports.getPowerBiReport("/Finance/Monthly");
  const bytes =
    await client.powerBiReports.getPowerBiReportContent("/Finance/Monthly");

  // Use reports, report, and bytes without logging sensitive report data.
} finally {
  client.close();
}

A URL containing only an origin defaults to /reports/api/v2.0/. A path such as /custom becomes /custom/api/v2.0/, while a complete /custom/api/v2.0/ base remains unchanged. URL credentials, query strings, and fragments are rejected.

Item identifiers can be:

  • a GUID;
  • a raw absolute path, such as /Finance/Monthly; or
  • an OData literal, such as path='/Finance/Monthly'.

Double any embedded single quote in an OData literal.

Environment configuration

BIClient.fromEnv() reads these variables explicitly:

VariableRequiredPurpose
BI_URLYesReport portal root or complete API base URL.
BI_USERNAMEYesPBIRS username, usually DOMAIN\name.
BI_PASSWORDYesPBIRS password.
BI_FOLLOW_REDIRECTSNotrue or false; redirects are disabled by default.
BI_ALLOW_INSECURE_HTTPNotrue or false; plain HTTP is disabled by default.
BI_REDIRECT_ORIGINSNoComma-separated exact origins allowed as redirect targets.

Explicit constructor options passed to fromEnv() override environment options. Importing the package does not read environment variables, load .env, log, or contact a server.

Request and response behavior

Each operation exports named request and response types. Path arguments, query options, binary content, and asynchronous results are typed.

Microsoft Learn omits most structured response schemas. Those JSON values therefore remain JsonValue or JsonBody rather than claiming unverified field-level types. Narrow JSON results in your application before accessing fields. JSON payloads are forwarded without runtime schema validation.

Other behavior:

  • Collections preserve their JSON/OData envelope, including @odata.nextLink; the client does not follow continuation links automatically.
  • Binary downloads return Uint8Array.
  • Documented no-content operations return undefined, which is compatible with Promise<void>.
  • Query names retain their documented casing, including Properties versus properties.
  • The API documentation—not an operation's name—determines its HTTP method and response behavior.

Writes require explicit permission

Every non-GET method is blocked before any HTTP request unless the client is created with allowMutation: true. This conservative policy also blocks non-mutating POST operations such as connection checks and session creation.

const writer = BIClient.fromEnv(process.env, { allowMutation: true });

try {
  await writer.powerBiReports.uploadPowerBiReport(
    "/Sandbox/Example",
    new Uint8Array([
      /* PBIX bytes */
    ]),
    { contentType: "application/octet-stream" },
  );
} finally {
  writer.close();
}

This example demonstrates the method signature, not valid PBIX content. Use a sandbox, supply a valid report file, and back up existing content before writing. The client provides neither generic rollback nor automatic retries for failed actions.

Authentication, transport, and lifecycle

BIClient uses NtlmTransport by default. The standalone package exports NtlmTransport and NtlmTransportOptions for direct use. CurlTransport and CurlTransportOptions remain aliases of the same class and type for existing imports.

  • The built-in transport uses Node.js HTTP(S) and NTLMv2. Each request and each redirect hop owns a fresh HTTP/1.1 connection. NTLM negotiation stays on that connection; if it closes during the handshake, the transport does not send the authentication response on a new connection.
  • Legacy NTLM challenges without extended security and target information are rejected. There is no NTLMv1 or Basic authentication fallback.
  • TLS certificate and hostname verification remain enabled. Plain HTTP—including HTTPS-to-HTTP redirects—requires allowInsecureHttp: true. HTTP exposes NTLM exchanges and report data to interception; enable it only in a trusted environment after accepting that risk.
  • Redirects are disabled by default. followRedirects: true permits same-origin redirects. Other origins require an exact redirectOrigins allowlist and receive fresh NTLM authentication. The client never automatically trusts a server-provided Location.
  • Redirects share one total timeout. The default limit is 5 hops and maxRedirects accepts 0–20. Loops, unsafe URLs, and non-GET method changes are rejected; 307 and 308 preserve the method and body.
  • The transport does not use global proxy settings or proxy environment variables. Proxy authentication, Kerberos/Negotiate-only servers, and Extended Protection (channel binding, or CBT) are not supported. Use a separately reviewed Transport adapter for requirements outside the built-in transport's scope.
  • Uploads and downloads are buffered. The default response-body limit is 64 MiB and is configurable with maxResponseBytes; response headers are limited to 64 KiB. Large reports may require a deliberate limit increase.
  • timeoutMs bounds the entire request. Pass { signal: abortController.signal } to an endpoint to cancel it. NTLM negotiation may send multiple requests after a 401 challenge, but an authenticated upload sends its body only with the final authentication request. Other failures are not retried automatically.
    • With the default settings, omit credentials for anonymous endpoints. With credentials configured, the transport accepts success before the NTLM handshake finishes. If the request has a body, the transport sends it once on a fresh anonymous connection.
  • close() is idempotent. It cancels pending calls and closes client-owned transport resources. An injected transport remains caller-owned and is not closed by the client.
import { BIClient, BIHTTPError } from "pbirs";

const client = BIClient.fromEnv();
const controller = new AbortController();

try {
  await client.me.getUserDetails({ signal: controller.signal });
} catch (error) {
  if (error instanceof BIHTTPError) {
    // error.status
    // error.retryAfter contains only a numeric Retry-After hint.
  }
  throw error;
} finally {
  client.close();
}

Errors distinguish configuration, mutation policy, HTTP, transport, response decoding, cancellation, and timeout failures. By default, errors omit server bodies, credential-bearing URLs, and arbitrary transport error text. Treat successful endpoint data as sensitive.

Require NTLM authentication

Set requireNtlmAuthentication: true on BIClient, NtlmTransport, or its alias CurlTransport when an anonymous success must not count as a password check. The option defaults to false. To use environment credentials, pass the option as the second argument to fromEnv; there is no new environment variable.

import { BIClient } from "pbirs";

const client = BIClient.fromEnv(process.env, {
  requireNtlmAuthentication: true,
  allowInsecureHttp: false,
  followRedirects: false,
});
try {
  const identity = await client.me.getUserDetails();
  // Verify that identity matches the expected account before saving credentials.
} finally {
  client.close();
}
  • Strict mode requires credentials. Missing credentials fail before any request with BIConfigurationError. BIClient also rejects combining strict mode with an injected transport.
  • A successful HTTP status (2xx) counts only after the client receives a valid NTLM challenge (Type 2) and sends an authentication response (Type 3) on the same connection. An earlier 2xx or a 401 without a valid challenge produces a BITransportError. The transport does not send the request body before Type 3 or retry anonymously. After Type 3, 401 and 403 are still failures; BIClient reports BIHTTPError.
  • If enabled, redirects are followed only after sending Type 3. Each hop starts a fresh NTLM handshake and still follows the existing origin and TLS rules.

This option verifies that the client sent the authentication response and received a success status. It does not prove how the server validated the credentials or which account it used. For credential validation, use trusted HTTPS, disable redirects, and check that /Me returns the expected identity on your authorized server.

Trust an internal CA

For a server certificate issued by your organization, obtain its approved certificate authority (CA) certificate in PEM format. Set NODE_EXTRA_CA_CERTS before starting your Node.js application, pi, or the integration command. For example:

NODE_EXTRA_CA_CERTS=/absolute/path/to/organization-ca.pem node app.js

Node.js reads this variable at process start. Setting it in application code or a .env file loaded after startup does not update trust. If the CA is already in the operating system trust store, you can start Node.js with --use-system-ca to include that store. Keep TLS certificate and hostname verification enabled.

pi extension

The package includes four read-only pi tools backed by src/client.ts. They are tested against @earendil-works/pi-coding-agent 0.85.1. The standalone client does not depend on pi at runtime; pi packages are optional peers supplied by the host.

Load the extension

The package manifest registers two entry points:

  • extensions/pbirs/index.ts provides the PBIRS tools.
  • extensions/env/index.ts loads environment variables for a trusted project.

Pi loads these TypeScript files through Jiti, so no build is required:

npm ci
pi -e ./extensions/env/index.ts -e ./extensions/pbirs/index.ts

# Or persist this local package in pi settings:
pi install /absolute/path/to/pi-pbirs

Use /reload inside pi after changing extension source. npm run build is required only for the standalone client's dist/ exports. This repository uses pi's package layout; it does not modify the standalone auto-discovery directories .pi/extensions/ or ~/.pi/agent/extensions/.

Configure credentials

Set BI_URL, BI_USERNAME, and BI_PASSWORD in the pi process environment or in the trusted project's .env. The env extension:

  • calls Node.js process.loadEnvFile() on session_start, including /reload;
  • reads only ctx.cwd/.env after ctx.isProjectTrusted() succeeds;
  • does not search parent directories;
  • ignores a missing file and reports other read failures without exposing file contents or raw error messages; and
  • never prints loaded names or values or adds them to model context.

Existing environment values—including empty strings—take precedence. Loaded values affect the entire pi process and its child processes until process exit. /reload can add missing values but cannot replace or remove values already loaded. Restart pi after editing an existing value or switching project configuration. Load .env files only from projects you trust.

To disable automatic .env loading, load only extensions/pbirs/index.ts or disable the env entry point in pi package settings. To use another trusted file, ask Node.js to load it explicitly:

NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--env-file=/absolute/path/to/pbirs.env" pi -e ./extensions/pbirs/index.ts

The PBIRS extension reads only process.env when a tool executes and never asks the model for credentials. Missing configuration fails that call without preventing the extension from loading. Do not place passwords in prompts or tool arguments.

Optional redirect and HTTP settings match BIClient.fromEnv(). TLS verification remains enabled. Each tool call owns and closes its client, forwards cancellation, and uses the client's 60-second timeout and 64 MiB response limit. Session shutdown cancels active clients. Tools add no automatic retries.

Tools

ToolScope
pbirs_listReturns one page of catalogItems, folders, powerBiReports (PBIX), or reports (paginated RDL). folderId applies only to catalogItems.
pbirs_getReturns metadata for one item from those four resources, addressed by GUID or absolute server path.
pbirs_infoReturns the current user (me) or server information (system) with one GET request.
pbirs_downloadSaves existing PBIX or RDL content to a new private temporary file and returns only its path and byte count. Requires download permission.

Example prompts:

  • Show the current Power BI Report Server user and server version.
  • List catalog items in /Finance, then show metadata for /Finance/Monthly.
  • List Power BI reports whose names contain Sales.
  • Download the PBIX at /Finance/Monthly to a temporary file.

pbirs_list supports top (default 50, maximum 200), skip, filter, select, and orderBy, mapped to OData query options. Server support varies. Results preserve the OData envelope and @odata.nextLink, but the extension never follows server-provided URLs. Use supported offsets or filters to request later pages. A single page does not prove that a catalog is complete, and continuation links requiring unsupported options cannot currently be resumed by these tools.

JSON previews are limited to 48 KiB or 1900 lines plus a truncation notice. Full oversized JSON and downloads are stored in a new pi-pbirs-* directory under the OS temporary directory. On POSIX, directories use mode 0700 and files use 0600. Files remain available for later reads; delete them when no longer needed.

Successful output can contain sensitive report or user data and is sent to the model and stored in the pi session. Treat server text as data, not instructions. Binary bytes are never included in tool results.

The extension provides no mutation tools, arbitrary HTTP requests, report-data queries, refreshes, subscriptions, uploads, or rendered PDF/CSV exports. It creates the client with allowMutation: false; that setting restricts these tools, not pi's other tools or the account's server permissions. HTTP 401, 403, and other client errors are surfaced as failed tool calls. Extension tests use offline transports and package loading; they do not claim live-server or real-download acceptance.

Development and verification

Use Node.js 26 for local development and the full CI suite.

Use npm ci for a clean install. Dependency and tarball consumer installation can require registry access, but offline endpoint checks use only mock transports or loopback servers. Offline TLS tests use openssl to generate disposable self-signed certificates; no test private keys are committed.

npm ci
npm run ci                          # Lint, offline tests, build, types, and audits
npm run audit:docs -- --online      # Compare the live TOC and 237 operation pages
npm run audit:api -- --implemented-only
npm test -- tests/resources/reports.test.ts -t E180
npm run test:package                # Test a tarball in an isolated consumer project

After npm ci, run prek install if you want these checks to run before each commit. Run prek run to migrate the Biome configuration, apply Biome fixes to matching staged files, and audit .github with zizmor via uvx. When TypeScript files, TypeScript configuration, or npm manifests change, tsc-rs checks the whole project with tsconfig.check.json. Use prek run --all-files to check all matching tracked files.

The immutable API baseline is tests/data/toc.json. tests/data/endpoint-contracts.json records each official page's method, path, parameter table, responses, and known schema or encoding gaps. Expected requests are not generated from the implementation under test.

API coverage executes all public resource methods through contract suites and rejects missing, extra, duplicate, or skipped endpoints; it is not statement-coverage percentage. An individual -t E### command filters unrelated tests, and its selected suite must pass without skipped cases. The complete audit runs all 237 suites. Resource modules are static and require no runtime registry or code generator.

Release PRs

For a user-facing change, add a note with uvx changenote add. Specify --package pbirs, a --bump (patch, minor, or major), and a --message that describes the change. Check the plan with uvx changenote status and commit the note with the change. Biome skips formatting these notes and the generated CHANGELOG.md so changenote can verify the release files unchanged.

The Release workflow opens or updates a Release PR on pushes to main and on manual runs from main. Review the proposed version and changelog, run CI, then merge the PR. The resulting push tests and publishes the verified release commit to npm, then creates its tag and GitHub Release. Manual runs do not publish. Do not use the legacy Bump Version workflow for a changenote-managed release.

Before merging a Release PR:

  1. Enable Allow GitHub Actions to create and approve pull requests and allow the workflow to push to changenote-release/main and create version tags. With the default GITHUB_TOKEN, the generated PR does not automatically start PR workflows. Run checks separately, or configure an authorized GitHub App token if the PR must trigger CI.
  2. Configure npm Trusted Publishing for pbirs with repository narumiruna/pbirs-ts and workflow release.yml. Replace the old publish.yml entry if present. For new and existing Trusted Publishers, enable direct npm publish; npm stage publish alone is not enough.
    • Create the configuration shortly before merging. npm expires a new configuration if its first publish does not succeed within two days. If it expires, delete it and create a new one.

If npm publish fails with ENEEDAUTH, check that the Trusted Publisher uses the GitHub Actions provider and that the owner (narumiruna), repository (pbirs-ts), and workflow filename (release.yml) match exactly. Leave the environment field blank because the Release job does not specify one. Check that the configuration has not expired and permits direct npm publish. A successful dry run does not verify publishing access.

After correcting the npm settings, use Re-run failed jobs on the original Release PR merge run. Do not use Run workflow or merge another Release PR to retry publication. The publish script skips an existing npm version only if its tarball integrity matches.

Live-server verification

Offline loopback checks cover transport behavior and NTLMv2 negotiation. For live verification, run the read-only integration check against an authorized PBIRS target. The metadata milestone requires all seven reads to pass, including the GUID/path match. Full acceptance also requires downloading nonempty report bytes.

Run the check only with authorization for the target server and test report content. If the server uses an internal CA, configure Node.js trust before startup. The command loads the repository's ignored .env; existing process environment values take precedence.

BI_URL=https://reports.example.com
BI_USERNAME='DOMAIN\name'
BI_PASSWORD='your-password'

Use one literal backslash in the single-quoted username: BI_USERNAME='DOMAIN\name', not BI_USERNAME='DOMAIN\\name'. Unlike the TypeScript string "DOMAIN\\name", a single-quoted .env value does not unescape doubled backslashes. Node.js also interprets \n inside double-quoted .env values as a newline. Repeated username backslashes are rejected before authentication; passwords are never normalized.

The suite discovers a report from the first collection page. PBIRS_TEST_REPORT_ID and PBIRS_TEST_REPORT_PATH can override that report but are not required.

For an approved redirect, set BI_FOLLOW_REDIRECTS=true and BI_REDIRECT_ORIGINS=https://trusted-target.example.com. An HTTP target also requires BI_ALLOW_INSECURE_HTTP=true. The command never discovers or expands the redirect allowlist automatically.

npm run test:integration -- --read-only

Use --env-file /path/to/file to select another file. Missing --read-only, credentials, or an explicitly requested file exits with code 2 before any server request; it is not treated as a skipped success.

The suite sequentially reads Me, System, Folders, Catalog Items, Power BI Reports, a report by GUID and path, and its binary content. It verifies matching identifiers and nonempty bytes without printing report data. It performs no writes, refreshes, or subscription actions. Normal CI neither contacts a real server nor reads the repository's .env.

The command reports the seven-read metadata milestone before attempting the download. A download failure exits with code 1 and is not an eight-call success. If the server returns HTTP 403, leave the download unverified and retry only with an approved account or report that permits downloads. Record the server version, stage outcomes, and necessary HTTP status codes, not report data or credentials.

Strict NTLM rollout check

Strict mode has loopback coverage but has not been verified against a live PBIRS server. Before enabling credential storage, pin a published version that includes strict mode. On an authorized staging server, use read-only /Me calls over trusted HTTPS with redirects disabled: verify that valid credentials return the expected account and that wrong or missing credentials fail. Do not log credentials, NTLM tokens, or the identity response.

Latest live result

On 2026-11-25, the Node.js transport authenticated with NTLMv2 over HTTPS with certificate and hostname verification enabled and redirects and plain HTTP disabled. PBIRS ProductVersion 1.22.9153.7886 returned seven successful metadata reads, including matching report metadata by GUID and path. getPowerBiReportContent() returned HTTP 403, so the integration command exited with code 1 and live binary download remains unverified. No writes were performed.

The previous libcurl transport produced the same seven-read milestone and download HTTP 403 on 2026-09-06. To complete live download verification, rerun with an authorized account and report that permit downloading the content.

Scope and references

Covered resources: Cache Refresh Plans, Catalog Items, Data Sets, Data Sources, Excel Workbooks, Extensions, Favorite Items, Folders, KPIs, Linked Reports, Me, Mobile Reports, Power BI Reports, Reports, Resources, Session, Subscriptions, and System.

This repository is licensed under the MIT License.