### Quick Start Falcon Client Initialization and API Call Source: https://github.com/crowdstrike/falconjs/blob/main/README.md Initialize the FalconClient with your credentials and cloud environment. This example demonstrates fetching sensor installers by CCID and includes error handling. ```typescript import { FalconClient, FalconErrorExplain } from "crowdstrike-falcon"; const client = new FalconClient({ cloud: "us-1", clientId: "your-client-id", clientSecret: "your-client-secret", }); await client.sensorDownload .getSensorInstallersCCIDByQuery() .catch(async function (err) { console.error("Could not fetch CCID: " + (await FalconErrorExplain(err))); }) .then((value) => { console.log("my CCID: ", value); }); ``` -------------------------------- ### Build Browser Sensor Download Example Source: https://github.com/crowdstrike/falconjs/blob/main/examples/browser/README.md Builds the sensor download example using esbuild. Ensure you have npm installed and run this command in your terminal. ```bash npm run build:devel NAME=sensor_download ./node_modules/esbuild/bin/esbuild --bundle ./examples/browser/${NAME}.ts --outfile=./examples/browser/${NAME}.js --global-name=${NAME} ``` -------------------------------- ### Execute Example in Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/docs/devel.md Compiles the TypeScript example file to JavaScript and then executes it using Node.js. This is how to run your SDK experiments locally. ```bash tsc && node ./build/example.js ``` -------------------------------- ### Install FalconJS SDK Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Use npm to install the package in your project. ```bash npm install crowdstrike-falcon ``` -------------------------------- ### Download Sensor Installer Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Downloads a binary installer using its SHA256 hash, with examples for Node.js and browser environments. ```typescript const blob = await client.sensorDownload.downloadSensorInstallerById( "9f86d081884c7d6d9ffd60bb675ad2b89e0365319b3df634f33625ea6eaeafa1", ); // In Node.js import fs from "fs"; fs.writeFileSync("falcon-installer.exe", Buffer.from(await blob.arrayBuffer())); // In Browser const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "falcon-installer.exe"; a.click(); ``` -------------------------------- ### Get Installer Entities Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Fetches detailed information for specific installers by providing an array of SHA256 hashes. ```typescript const installers = await client.sensorDownload.getSensorInstallersEntities({ ids: ["hash1", "hash2"], }); installers.resources.forEach((installer) => { console.log(installer.name, installer.version); }); ``` -------------------------------- ### Install Fetch API for Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/docs/devel.md Installs the `cross-fetch` package, which provides a `fetch` API implementation compatible with Node.js environments. This is necessary for using the SDK in Node.js. ```bash npm install cross-fetch ``` -------------------------------- ### Download Latest Linux Installer Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves the most recent Linux x86_64 installer and saves it to the local filesystem. ```typescript const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); // Find latest Linux x86_64 installer const installers = await client.sensorDownload.getCombinedSensorInstallersByQuery({ filter: "os:linux AND architecture:x86_64", limit: 1, sort: "release_date.desc", }); if (installers.resources.length === 0) { throw new Error("No Linux installers found"); } const installer = installers.resources[0]; console.log(`Downloading: ${installer.name} (${installer.sha256})`); // Download the installer const blob = await client.sensorDownload.downloadSensorInstallerById( installer.sha256, ); // Save to file import fs from "fs"; fs.writeFileSync(installer.name, Buffer.from(await blob.arrayBuffer())); ``` -------------------------------- ### Download Sensor Installer Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Download a specific sensor installer by its hash and save it to disk in Node.js. ```typescript const blob = await client.sensorDownload.downloadSensorInstallerById( "sha256-hash-of-installer", ); // In Node.js import fs from "fs"; fs.writeFileSync("installer.exe", Buffer.from(await blob.arrayBuffer())); ``` -------------------------------- ### Install CrowdStrike FalconJS SDK Source: https://github.com/crowdstrike/falconjs/blob/main/README.md Use npm to install the CrowdStrike FalconJS SDK. This is the first step to integrating with the CrowdStrike Falcon API. ```bash npm install crowdstrike-falcon ``` -------------------------------- ### Initialize FalconClient with OAuth2 Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Example of initializing the client, which automatically applies the OAuth2 middleware. ```typescript const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); // OAuth2 middleware is automatically applied // All requests include "Authorization: Bearer " header const hosts = await client.hosts.combinedDevicesByFilter(); ``` -------------------------------- ### List Available Platforms and Architectures Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Queries all available installers to extract and display unique operating systems and architectures. ```typescript const installers = await client.sensorDownload.getCombinedSensorInstallersByQuery({ limit: 1000, }); const platforms = new Set(); const architectures = new Set(); installers.resources.forEach((installer) => { platforms.add(installer.os); architectures.add(installer.architecture); }); console.log("Supported platforms:", Array.from(platforms)); console.log("Supported architectures:", Array.from(architectures)); ``` -------------------------------- ### Query Sensor Installers Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md List available sensor installers matching specific criteria. ```typescript const installers = await client.sensorDownload.getCombinedSensorInstallersByQuery({ filter: "os:linux AND architecture:x86_64", limit: 50, }); installers.resources?.forEach((installer) => { console.log(installer.name, installer.version); }); ``` -------------------------------- ### Define .env Configuration Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Example content for a .env file to store Falcon configuration variables. ```text FALCON_CLOUD=us-1 FALCON_CLIENT_ID=your-client-id FALCON_CLIENT_SECRET=your-client-secret FALCON_MEMBER_CID= ``` -------------------------------- ### Attaching Pre-Request Middleware Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Example of using withPreMiddleware to log request methods and URLs. ```typescript const loggingApi = client.hosts.withPreMiddleware( async (context) => { console.log("Request:", context.method, context.url); return { url: context.url, init: context.init }; }, ); ``` -------------------------------- ### Attaching Custom Middleware Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Example of using withMiddleware to log request URLs. ```typescript const customApi = client.hosts.withMiddleware({ pre: async (context) => { console.log("Request to:", context.url); return { url: context.url, init: context.init }; }, }); const hosts = await customApi.combinedDevicesByFilter(); ``` -------------------------------- ### Select cloud from environment variables Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Example of dynamically selecting the cloud region and initializing the FalconClient using environment variables. ```typescript function getCloud(): FalconCloud { const cloud = process.env.FALCON_CLOUD || "us-1"; if (!["us-1", "us-2", "eu-1", "us-gov-1"].includes(cloud)) { throw new Error(`Invalid cloud: ${cloud}`); } return cloud as FalconCloud; } const client = new FalconClient({ fetchApi: fetch, cloud: getCloud(), clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### getCombinedSensorInstallersByQuery() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves a list of sensor installers based on provided query criteria and filters. ```APIDOC ## getCombinedSensorInstallersByQuery() ### Description Get combined sensor installer information matching query criteria. ### Parameters - **offset** (number) - Optional - Pagination offset (Default: 0) - **limit** (number) - Optional - Maximum results to return (max 500) (Default: 20) - **sort** (string) - Optional - Sort field and direction (e.g., "name.asc") - **filter** (string) - Optional - FQL filter query - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Return Type DomainSensorInstallersV1 ### OAuth2 Scope sensor-installers:read ``` -------------------------------- ### Attaching Post-Response Middleware Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Example of using withPostMiddleware to log response status codes. ```typescript const cachingApi = client.hosts.withPostMiddleware( async (context) => { console.log("Response status:", context.response.status); return context.response; }, ); ``` -------------------------------- ### downloadSensorInstallerById() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Downloads a specific sensor installer binary using its SHA256 ID. ```APIDOC ## downloadSensorInstallerById() ### Description Download sensor installer binary by SHA256 ID. ### Parameters - **id** (string) - Required - SHA256 hash of the installer - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Return Type Blob ### OAuth2 Scope sensor-installers:read ``` -------------------------------- ### Configure Fetch API in Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Provides examples for integrating cross-fetch or node-fetch in Node.js environments. ```typescript import fetch from "cross-fetch"; const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` ```typescript import fetch from "node-fetch"; const client = new FalconClient({ fetchApi: fetch as any, // Type assertion may be needed cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### Get Host Details Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Fetch detailed information for specific device IDs. ```typescript const details = await client.hosts.getDeviceDetailsV2({ ids: ["device-id-1", "device-id-2"], }); details.resources?.forEach((device) => { console.log(device.hostname, device.agent_version); }); ``` -------------------------------- ### Query Sensor Installers Definition Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Method signature for retrieving sensor installer IDs based on query criteria. ```typescript async getSensorInstallersByQuery( offset?: number, limit?: number, sort?: string, filter?: string, initOverrides?: RequestInit | runtime.InitOverrideFunction, ): Promise ``` -------------------------------- ### getSensorInstallersEntities() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves detailed information for multiple sensor installers by their SHA256 IDs. ```APIDOC ## getSensorInstallersEntities() ### Description Get full sensor installer entity details by SHA256 IDs. ### Parameters - **ids** (Array) - Required - SHA256 hashes (max 100 per request) - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Return Type DomainSensorInstallersV1 ### OAuth2 Scope sensor-installers:read ``` -------------------------------- ### Retrieving Device Details with getDeviceDetailsV2 Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Example usage of getDeviceDetailsV2 to fetch details for specific host IDs. ```typescript const response = await client.hosts.getDeviceDetailsV2({ ids: ["abc123def456", "xyz789uvi012"], }); response.resources.forEach((device) => { console.log( device.hostname, device.platform, device.agent_version, device.system_product_name, ); }); ``` -------------------------------- ### getSensorInstallersByQuery() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves a list of sensor installer IDs that match the specified query criteria. ```APIDOC ## getSensorInstallersByQuery() ### Description Get sensor installer IDs matching query criteria (query-only, no full details). ### Method SDK Method ### Signature `async getSensorInstallersByQuery(offset?: number, limit?: number, sort?: string, filter?: string, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise` ### Parameters - **offset** (number) - Optional - Pagination offset - **limit** (number) - Optional - Max results - **sort** (string) - Optional - Sort field and direction - **filter** (string) - Optional - FQL filter query - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### OAuth2 Scope `sensor-installers:read` ### Example ```typescript const response = await client.sensorDownload.getSensorInstallersByQuery({ filter: "os:windows AND name:*Sensor*", limit: 1000, }); const installerIds = response.resources; console.log(`Found ${installerIds.length} installers`); ``` ``` -------------------------------- ### Implement Pagination for Sensor Installers Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Use a while loop to iterate through paginated results by incrementing the offset until fewer than 500 resources are returned. ```typescript let allInstallers = []; let offset = 0; while (true) { const response = await client.sensorDownload.getCombinedSensorInstallersByQuery({ offset: offset, limit: 500, }); allInstallers = allInstallers.concat(response.resources); if (response.resources.length < 500) { break; // Last page } offset += 500; } console.log(`Total installers: ${allInstallers.length}`); ``` -------------------------------- ### getDeviceDetailsV2() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Get details on one or more hosts by providing host IDs. Supports up to 100 IDs per request. ```APIDOC ## getDeviceDetailsV2() ### Description Get details on one or more hosts by providing host IDs. Supports up to 100 IDs per request. ### Method SDK Method ### Parameters - **ids** (Array) - Required - Host IDs to retrieve (max 100 per request) - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Return Type DeviceapiDeviceDetailsResponseSwagger ### OAuth2 Scope devices:read ``` -------------------------------- ### FQL Filter Syntax Examples Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/03-detects-api.md Common filter strings used to query detections based on severity, status, platform, or name patterns. ```typescript // Critical detections created this week filter: "severity:critical AND created_timestamp:>=2024-01-25T00:00:00Z" // Unresolved detections on Linux hosts filter: "status:new AND device.platform:linux" // Specific detection type filter: "detection.name:*Ransomware*" ``` -------------------------------- ### Searching Hosts with combinedDevicesByFilter Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Example usage of the combinedDevicesByFilter method to retrieve hosts based on platform and OS version criteria. ```typescript const response = await client.hosts.combinedDevicesByFilter({ filter: "platform:linux AND os_version:*22.04*", limit: 50, sort: "hostname.asc", }); console.log(`Found ${response.meta.pagination.total} hosts`); response.resources.forEach((device) => { console.log(device.hostname, device.platform); }); ``` -------------------------------- ### DomainSensorInstallersV1 Interface Definition Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Defines the structure of the response object containing installer metadata, pagination details, and potential error messages. ```typescript interface DomainSensorInstallersV1 { resources?: Array<{ sha256: string; name: string; version: string; os: string; architecture: string; build: string; release_date: string; file_size: number; file_type: string; }>; meta?: { pagination?: { total: number; offset: number; limit: number; }; }; errors?: Array<{ code: number; message: string; }>; } ``` -------------------------------- ### Importing and Initializing HostsApi Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Shows how to import the necessary classes and initialize the HostsApi either through a FalconClient or directly with a configuration object. ```typescript import { HostsApi, FalconClient } from "crowdstrike-falcon"; // Via FalconClient const client = new FalconClient({ /* ... */ }); const api = client.hosts; // Or directly const api = new HostsApi(configuration); ``` -------------------------------- ### Get CCID Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Retrieve the Customer ID (CCID) for sensor installation. ```typescript const ccid = await client.sensorDownload.getSensorInstallersCCIDByQuery(); console.log("CCID:", ccid.resources?.[0]); ``` -------------------------------- ### Initialize DetectsApi Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/03-detects-api.md Shows how to import and instantiate the DetectsApi either through the FalconClient or directly. ```typescript import { DetectsApi, FalconClient } from "crowdstrike-falcon"; // Via FalconClient const client = new FalconClient({ /* ... */ }); const api = client.detects; // Or directly const api = new DetectsApi(configuration); ``` -------------------------------- ### FalconClient Initialization Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md How to initialize the FalconClient in a Node.js environment using credentials and a fetch implementation. ```APIDOC ## FalconClient Initialization ### Description Initializes the FalconJS client for use in Node.js environments. ### Constructor `new FalconClient(options)` ### Parameters - **fetchApi** (function) - Required - The fetch implementation (e.g., cross-fetch). - **cloud** (string) - Required - The Falcon cloud region (e.g., "us-1"). - **clientId** (string) - Required - Falcon API Client ID. - **clientSecret** (string) - Required - Falcon API Client Secret. ### Example ```typescript import { FalconClient } from "crowdstrike-falcon"; import fetch from "cross-fetch"; const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` ``` -------------------------------- ### Initialize SensorDownloadApi Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Shows how to instantiate the API class either directly or via the FalconClient. ```typescript import { SensorDownloadApi, FalconClient } from "crowdstrike-falcon"; // Via FalconClient const client = new FalconClient({ /* ... */ }); const api = client.sensorDownload; // Or directly const api = new SensorDownloadApi(configuration); ``` -------------------------------- ### Get CCID Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves the Customer Checksum ID for the current environment. ```typescript const ccidResponse = await client.sensorDownload.getSensorInstallersCCIDByQuery(); console.log("CCID:", ccidResponse.resources[0]); ``` -------------------------------- ### Initialize Falcon Client with Fetch API in Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/docs/devel.md Demonstrates how to initialize the FalconClient in a Node.js environment by passing a `fetch` API implementation, such as `cross-fetch`, to the client's constructor. This ensures the SDK can make HTTP requests. ```typescript import fetch from "cross-fetch"; import { FalconClient } from "./src"; const client = new FalconClient({ fetchApi: fetch, ... }) ``` -------------------------------- ### Setting Environment Variables Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Configure authentication and cloud settings via environment variables for better security. ```bash export FALCON_CLOUD=us-1 export FALCON_CLIENT_ID=your-id export FALCON_CLIENT_SECRET=your-secret ``` ```typescript cloud: (process.env.FALCON_CLOUD || "us-1") as FalconCloud, clientId: process.env.FALCON_CLIENT_ID!, clientSecret: process.env.FALCON_CLIENT_SECRET!, ``` -------------------------------- ### Access Sensor Download API Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/01-client-initialization.md Demonstrates initializing the client and interacting with the sensorDownload service. ```typescript const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); // Get CCID without parameters const ccidResponse = await client.sensorDownload.getSensorInstallersCCIDByQuery(); console.log("CCID:", ccidResponse); // Get sensor installers with filters const installers = await client.sensorDownload.getCombinedSensorInstallersByQuery({ filter: "os:linux", limit: 10, }); ``` -------------------------------- ### Handle API errors with MsaAPIError Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/06-types.md Example of catching and iterating through API error responses. ```typescript interface ErrorResponse { errors?: Array; } try { await client.hosts.combinedDevicesByFilter({ filter: "invalid_field:value", }); } catch (error) { const response = error as Response; const data = await response.json(); data.errors.forEach((err: MsaAPIError) => { console.error(`[${err.code}] ${err.message}`); }); } ``` -------------------------------- ### Query and Update Devices with TypeScript Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/INDEX.md Demonstrates a three-step workflow to query device IDs, fetch full details, and apply tags to the filtered devices. ```typescript // 1. Query for IDs const queryResponse = await client.hosts.queryDevicesByFilter({ filter: "platform:linux", }); // 2. Fetch full details const details = await client.hosts.getDeviceDetailsV2({ ids: queryResponse.resources.slice(0, 100), }); // 3. Perform action await client.hosts.updateDeviceTags({ action: "add", device_ids: queryResponse.resources, tags: ["critical"], }); ``` -------------------------------- ### Import and apply SDK types Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/06-types.md Demonstrates importing SDK types and applying them to variables and function return types. ```typescript // Import individual types import { MsaQueryResponse, MsaMetaInfo, DeviceapiDeviceCombinedResponseSwagger, MsaIdsRequest, } from "crowdstrike-falcon"; // Type a variable const response: MsaQueryResponse = await client.hosts.queryDevicesByFilter(); // Type an async function async function fetchAllHosts(): Promise> { const response: DeviceapiDeviceCombinedResponseSwagger = await client.hosts.combinedDevicesByFilter({ limit: 500 }); return response.resources || []; } ``` -------------------------------- ### Initialize FalconClient with Environment Variables Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Use environment variables to provide credentials and configuration to the FalconClient constructor. ```typescript // Required const clientId = process.env.FALCON_CLIENT_ID; const clientSecret = process.env.FALCON_CLIENT_SECRET; // Optional const cloud = (process.env.FALCON_CLOUD || "us-1") as FalconCloud; const memberCid = process.env.FALCON_MEMBER_CID; if (!clientId || !clientSecret) { throw new Error( "Missing FALCON_CLIENT_ID or FALCON_CLIENT_SECRET environment variables", ); } const client = new FalconClient({ fetchApi: fetch, cloud: cloud, clientId: clientId, clientSecret: clientSecret, memberCid: memberCid, }); ``` -------------------------------- ### getDetectSummaries() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/03-detects-api.md Get full detection summaries by detection IDs. Note: This method is deprecated. ```APIDOC ## getDetectSummaries() ### Description Get full detection summaries by detection IDs. ⚠️ Deprecated. ### Parameters - **body** (MsaIdsRequest) - Required - Request object with detection IDs - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Request Body - **ids** (Array) - Required - List of detection IDs - **limit** (number) - Optional - Limit results - **offset** (string) - Optional - Pagination offset ### OAuth2 Scope `detects:read` ``` -------------------------------- ### FalconClient Service Access Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/08-api-services.md Demonstrates how to initialize the FalconClient and access specific API service modules. ```APIDOC ## SDK Usage: Accessing API Services ### Description Services are accessed as properties on the `FalconClient` instance. Each service corresponds to a specific functional area of the CrowdStrike Falcon platform. ### Initialization ```typescript import { FalconClient } from "crowdstrike-falcon"; const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` ### Usage Example ```typescript // Accessing services as properties const hosts = await client.hosts.combinedDevicesByFilter(); const alerts = await client.alerts.queryAlertsV2(); const policies = await client.preventionPolicies.queriesPoliciesV1(); ``` ``` -------------------------------- ### View Project File Structure Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/INDEX.md Displays the directory layout of the FalconJS documentation repository. ```text /output/ ├── INDEX.md # This file ├── 01-client-initialization.md # FalconClient setup ├── 02-error-handling.md # Error handling ├── 03-middleware.md # Middleware system ├── 04-runtime.md # Request handling ├── 05-event-stream.md # Event streaming ├── 06-types.md # Type definitions ├── 07-configuration.md # Configuration options ├── 08-api-services.md # Service listing ├── 09-quick-reference.md # Quick reference guide └── api-reference/ ├── 01-hosts-api.md # Hosts API documentation ├── 02-sensor-download-api.md # Sensor Download API └── 03-detects-api.md # Detects API (deprecated) ``` -------------------------------- ### Initialize FalconClient Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/README.md Configure the FalconClient with credentials and a fetch implementation. Required for all API interactions. ```typescript import { FalconClient } from "crowdstrike-falcon"; import fetch from "cross-fetch"; // Node.js only const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### Handle JSON API Responses Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md Response handler for JSON payloads with an example of usage for domain-specific models. ```typescript export class JSONApiResponse extends ApiResponse { constructor( response: Response, transformer: (json: any) => T, ); } ``` ```typescript return new runtime.JSONApiResponse(response, (jsonValue) => DomainAccessTokenResponseV1FromJSON(jsonValue), ); ``` -------------------------------- ### Use MsaIdsRequest in a client call Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/06-types.md Example of passing an array of IDs to a host detail retrieval method. ```typescript const details = await client.hosts.getDeviceDetailsV2({ ids: ["device-id-1", "device-id-2"], }); ``` -------------------------------- ### Initialize FalconClient in Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Requires cross-fetch for environment compatibility and environment variables for authentication. ```typescript import { FalconClient } from "crowdstrike-falcon"; import fetch from "cross-fetch"; const client = new FalconClient({ fetchApi: fetch, // Required in Node.js cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); const hosts = await client.hosts.combinedDevicesByFilter(); ``` -------------------------------- ### Searching Hidden Devices with combinedHiddenDevicesByFilter Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Example usage of the combinedHiddenDevicesByFilter method to retrieve a list of hidden devices. ```typescript const response = await client.hosts.combinedHiddenDevicesByFilter({ limit: 100, }); console.log(`Found ${response.meta.pagination.total} hidden devices`); ``` -------------------------------- ### Load Configuration with dotenv Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Use the dotenv package to load environment variables from a file before initializing the client. ```typescript import dotenv from "dotenv"; dotenv.config(); const client = new FalconClient({ fetchApi: fetch, cloud: (process.env.FALCON_CLOUD || "us-1") as FalconCloud, clientId: process.env.FALCON_CLIENT_ID!, clientSecret: process.env.FALCON_CLIENT_SECRET!, }); ``` -------------------------------- ### Initialize FalconClient in Browser Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/01-client-initialization.md Uses the global fetch API available in browser environments. ```typescript import { FalconClient } from "crowdstrike-falcon"; const client = new FalconClient({ // fetch is available globally in browsers cloud: "us-1", clientId: process.env.REACT_APP_FALCON_CLIENT_ID, clientSecret: process.env.REACT_APP_FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### Get CCID and Verify Environment Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/02-sensor-download-api.md Retrieves the Customer ID (CCID) to verify that the environment is correctly configured for sensor downloads. ```typescript try { const ccidResponse = await client.sensorDownload.getSensorInstallersCCIDByQuery(); if (ccidResponse.resources && ccidResponse.resources.length > 0) { console.log("CCID:", ccidResponse.resources[0]); console.log("Environment is properly configured"); } else { console.log("No CCID available"); } } catch (error) { console.error("Failed to retrieve CCID:", error); } ``` -------------------------------- ### FalconClient Constructor Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/01-client-initialization.md Initializes the FalconClient instance using the FalconClientOptions configuration object. ```APIDOC ## FalconClient Constructor ### Description Initializes the main entry point for the CrowdStrike Falcon SDK. This constructor manages OAuth2 authentication and prepares the client for API service module access. ### Parameters #### Configuration Object (FalconClientOptions) - **cloud** (FalconCloud) - Required - Cloud instance to connect to: "us-1", "us-2", "eu-1", or "us-gov-1" - **clientId** (string) - Required - OAuth2 Client ID from CrowdStrike Falcon console - **clientSecret** (string) - Required - OAuth2 Client Secret from CrowdStrike Falcon console - **fetchApi** (FetchAPI) - Optional - Custom fetch implementation. Required for Node.js environments (use cross-fetch or node-fetch) - **memberCid** (string) - Optional - Customer ID for MSSP scenarios when credentials have access to multiple environments ``` -------------------------------- ### Configure Fetch API in Browser Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Demonstrates default usage in browser environments where native fetch is available. ```typescript const client = new FalconClient({ // fetchApi is optional; defaults to global fetch cloud: "us-1", clientId: process.env.REACT_APP_FALCON_CLIENT_ID, clientSecret: process.env.REACT_APP_FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### withMiddleware(middleware: Middleware) Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Registers a custom middleware to the client. Middlewares are executed in the order they are provided, with pre-hooks running before the request and post-hooks running after the response. ```APIDOC ## withMiddleware(middleware) ### Description Adds a custom middleware to the FalconClient instance. Multiple middlewares can be chained, and they will execute in the order they are added. ### Usage ```typescript const api = client.hosts .withMiddleware(middleware1) .withMiddleware(middleware2); ``` ### Execution Order 1. **Pre-request**: middleware1.pre() -> middleware2.pre() 2. **Request**: fetch() 3. **Post-request**: middleware2.post() -> middleware1.post() ``` -------------------------------- ### Get host online status Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Retrieves the online status for specified host IDs. The ids parameter is limited to 100 per request. ```typescript async getOnlineStateV1( ids: Array, initOverrides?: RequestInit | runtime.InitOverrideFunction, ): Promise ``` ```typescript const states = await client.hosts.getOnlineStateV1({ ids: ["device-id-1", "device-id-2"], }); states.resources.forEach((state) => { console.log(`${state.id}: ${state.state}`); }); ``` -------------------------------- ### Receive Events via FalconClient Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/05-event-stream.md Demonstrates initializing the client, retrieving a stream resource, and processing incoming events. ```typescript import { FalconClient } from "crowdstrike-falcon"; import fetch from "cross-fetch"; const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); // Get stream resource (implementation depends on specific event stream API) const streamResource = await client.eventStreams.refreshActiveSession({ appName: "my-app", actionName: "refresh_active_session", }); // Create event stream processor const stream = new EventStream( client["config"], // Access internal configuration "my-app", streamResource, ); // Process events const eventCount = { count: 0 }; stream.process((event) => { console.log("Event received:", event); eventCount.count++; }, 0); // Start from latest ``` -------------------------------- ### Import fetch for Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Required when encountering 'fetch is not defined' errors in Node.js environments. ```javascript import fetch from "cross-fetch" ``` -------------------------------- ### Initialize Default Configuration Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md Creates a singleton instance of the Configuration class pre-configured for the CrowdStrike US-1 cloud. ```typescript export const DefaultConfig = new Configuration(); ``` -------------------------------- ### Configuration Class Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md The Configuration class is used to initialize the SDK with specific authentication and request settings. ```APIDOC ## Configuration ### Description Initializes the SDK configuration for making requests to the Falcon API. ### Constructor `new Configuration(configuration: ConfigurationParameters)` ### Parameters - **basePath** (string) - Optional - Base URL for API endpoints. Default: "https://api.crowdstrike.com" - **fetchApi** (FetchAPI) - Optional - Custom fetch implementation. - **middleware** (Middleware[]) - Optional - Array of middleware objects to execute pre/post request. - **accessToken** (string | Promise | Function) - Optional - OAuth2 access token or function returning token. - **apiKey** (string | Promise | Function) - Optional - API key for alternative authentication. - **headers** (HTTPHeaders) - Optional - Default HTTP headers to include on all requests. - **credentials** (RequestCredentials) - Optional - Fetch credentials option: "omit" | "same-origin" | "include". - **username** (string) - Optional - Basic auth username. - **password** (string) - Optional - Basic auth password. - **queryParamsStringify** (Function) - Optional - Custom query string serialization function. ``` -------------------------------- ### Define Platform, OSVersion, and Architecture Types Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/06-types.md Use these type aliases to enforce consistent string values for platform, OS version, and architecture properties. ```typescript type Platform = "linux" | "windows" | "mac"; type OSVersion = string; // e.g., "22.04" for Ubuntu, "10.0" for Windows type Architecture = "x86_64" | "x86" | "arm64"; ``` -------------------------------- ### Initialize API with Configuration Object Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Pass a custom Configuration object to API classes to override default behavior and headers. ```typescript import { Configuration, HostsApi } from "crowdstrike-falcon"; const config = new Configuration({ basePath: "https://api.crowdstrike.com", fetchApi: fetch, accessToken: "Bearer abc123...", // Static token (not recommended) headers: { "X-Custom-Header": "value", }, middleware: [ /* custom middleware */ ], }); const hostsApi = new HostsApi(config); const hosts = await hostsApi.combinedDevicesByFilter(); ``` -------------------------------- ### withPostMiddleware() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Adds only post-response middleware to an API instance. ```APIDOC ## withPostMiddleware() ### Description Adds only post-response middleware to an API instance. ### Signature `withPostMiddleware(this: T, ...postMiddlewares: Array): T` ### Example ```typescript const cachingApi = client.hosts.withPostMiddleware( async (context) => { console.log("Response status:", context.response.status); return context.response; }, ); ``` -------------------------------- ### Provide fetch implementation for Node.js Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Inject a fetch-compatible library when the environment lacks a native fetch implementation. ```typescript import fetch from "cross-fetch"; const client = new FalconClient({ fetchApi: fetch, // ... other options }); ``` -------------------------------- ### Define Configuration Parameters and Class Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md Defines the structure for API configuration parameters and the main Configuration class used for initialization. ```typescript export interface ConfigurationParameters { basePath?: string; fetchApi?: FetchAPI; middleware?: Middleware[]; queryParamsStringify?: (params: HTTPQuery) => string; username?: string; password?: string; apiKey?: string | Promise | ((name: string) => string | Promise); accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); headers?: HTTPHeaders; credentials?: RequestCredentials; } export class Configuration { constructor(private configuration: ConfigurationParameters = {}); } ``` -------------------------------- ### Implement Custom Fetch API Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Shows how to create a custom fetch function for logging, proxying, or modifying request headers. ```typescript const customFetch: FetchAPI = async (url: string, init?: RequestInit) => { console.log(`[${new Date().toISOString()}] ${init?.method || 'GET'} ${url}`); // Add custom header const modifiedInit = { ...init, headers: { ...init?.headers, "X-Custom-Header": "custom-value", }, }; // Proxy through custom handler return globalThis.fetch(url, modifiedInit); }; const client = new FalconClient({ fetchApi: customFetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); ``` -------------------------------- ### Initialize and Access Falcon API Services Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/08-api-services.md Instantiate the FalconClient with authentication credentials and access specific API services as properties on the client object. ```typescript import { FalconClient } from "crowdstrike-falcon"; const client = new FalconClient({ fetchApi: fetch, cloud: "us-1", clientId: process.env.FALCON_CLIENT_ID, clientSecret: process.env.FALCON_CLIENT_SECRET, }); // Access services as properties const hosts = await client.hosts.combinedDevicesByFilter(); const alerts = await client.alerts.queryAlertsV2(); const policies = await client.preventionPolicies.queriesPoliciesV1(); ``` -------------------------------- ### Query and Fetch Details Pattern Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/08-api-services.md Use this two-step pattern to first retrieve resource IDs via a filter and then fetch full details in batches of up to 100. ```typescript // 1. Query for IDs const queryResponse = await client.hosts.queryDevicesByFilter({ filter: "platform:linux", limit: 500, }); const deviceIds = queryResponse.resources || []; // 2. Fetch full details const detailResponse = await client.hosts.getDeviceDetailsV2({ ids: deviceIds.slice(0, 100), // Max 100 per request }); detailResponse.resources?.forEach((device) => { console.log(device.hostname); }); ``` -------------------------------- ### Configuration Parameters and Class Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md The ConfigurationParameters interface defines the structure for client settings, including middleware, while the Configuration class manages these settings. ```typescript export interface ConfigurationParameters { basePath?: string; fetchApi?: FetchAPI; middleware?: Middleware[]; queryParamsStringify?: (params: HTTPQuery) => string; username?: string; password?: string; apiKey?: string | Promise | ((name: string) => string | Promise); accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); headers?: HTTPHeaders; credentials?: RequestCredentials; } export class Configuration { constructor(private configuration: ConfigurationParameters = {}); get middleware(): Middleware[]; // ... other getters } ``` -------------------------------- ### withPreMiddleware() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Adds only pre-request middleware to an API instance. ```APIDOC ## withPreMiddleware() ### Description Adds only pre-request middleware to an API instance. ### Signature `withPreMiddleware(this: T, ...preMiddlewares: Array): T` ### Example ```typescript const loggingApi = client.hosts.withPreMiddleware( async (context) => { console.log("Request:", context.method, context.url); return { url: context.url, init: context.init }; }, ); ``` -------------------------------- ### combinedDevicesByFilter() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Search for hosts by platform, hostname, IP, and other criteria using FQL filters. ```APIDOC ## combinedDevicesByFilter() ### Description Search for hosts by platform, hostname, IP, and other criteria. Returns full device records. ### Method SDK Method ### Parameters - **offset** (string) - Optional - Pagination cursor (opaque string from previous response) - **limit** (number) - Optional - Maximum number of results to return (max 500) - **sort** (CombinedDevicesByFilterSortEnum) - Optional - Sort field and direction - **filter** (string) - Optional - FQL filter query - **fields** (string) - Optional - Comma-separated list of fields to include in response - **initOverrides** (RequestInit | InitOverrideFunction) - Optional - Request init overrides ### Return Type DeviceapiDeviceCombinedResponseSwagger ### OAuth2 Scope devices:read ``` -------------------------------- ### OAuth2 Configuration Options Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Required configuration parameters for initializing the OAuth2 middleware. ```typescript type OAuth2Options = { fetchApi?: FetchAPI; cloud: FalconCloud; clientId: string; clientSecret: string; memberCid?: string; }; ``` -------------------------------- ### Build with npm Source: https://github.com/crowdstrike/falconjs/blob/main/docs/devel.md Builds the TypeScript code to JavaScript using the npm command. This is an alternative to using the `tsc` command directly. ```bash npm run build ``` -------------------------------- ### client.hosts.combinedDevicesByFilter Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/01-hosts-api.md Retrieves a list of devices using cursor-based pagination. ```APIDOC ## client.hosts.combinedDevicesByFilter ### Description Retrieves a list of devices based on provided filters, supporting cursor-based pagination to handle large result sets. ### Parameters #### Request Body - **offset** (string) - Optional - The cursor for the next page of results. - **limit** (number) - Optional - The maximum number of records to return (default 500). ### Request Example { "offset": "string", "limit": 500 } ### Response #### Success Response (200) - **resources** (array) - List of device objects. - **meta.pagination.offset** (string) - The cursor for the next page of results. ``` -------------------------------- ### Accessing Falcon Services Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Services are exposed as properties on the initialized client instance. ```typescript client.hosts // Hosts/devices client.alerts // Security alerts client.detects // Detections (deprecated) client.incidents // Incidents client.realTimeResponse // RTR commands client.preventionPolicies // Policies client.intel // Threat intelligence client.spotlight // Vulnerabilities client.containerAlerts // Container security client.kubernetesProtection // K8s security client.sensorDownload // Sensor installers client.workflows // Falcon Fusion workflows client.eventStreams // Real-time events // ... 100+ more services ``` -------------------------------- ### withMiddleware() Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Adds one or more middleware objects to an API instance. ```APIDOC ## withMiddleware() ### Description Adds one or more middleware to an API instance. ### Signature `withMiddleware(this: T, ...middlewares: Middleware[]): T` ### Parameters - **middlewares** (Middleware[]) - Required - Variable-length array of Middleware objects ### Returns New API instance with middleware attached ### Example ```typescript const customApi = client.hosts.withMiddleware({ pre: async (context) => { console.log("Request to:", context.url); return { url: context.url, init: context.init }; }, }); ``` ``` -------------------------------- ### Query Hosts with Filters Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/README.md Retrieve a list of devices using filtering and limit parameters. ```typescript const hosts = await client.hosts.combinedDevicesByFilter({ filter: "platform:linux", limit: 100, }); hosts.resources?.forEach((device) => { console.log(device.hostname, device.agent_version); }); ``` -------------------------------- ### withPostMiddleware Method Signature Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/03-middleware.md Method signature for adding only post-response middleware. ```typescript withPostMiddleware(this: T, ...postMiddlewares: Array): T ``` -------------------------------- ### Query Hosts Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/09-quick-reference.md Retrieve a list of devices filtered by platform. ```typescript const hosts = await client.hosts.combinedDevicesByFilter({ filter: "platform:linux", limit: 100, }); hosts.resources?.forEach((device) => { console.log(device.hostname, device.platform); }); ``` -------------------------------- ### Extend BaseAPI for custom endpoints Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md Demonstrates how to create a custom API class by extending BaseAPI and configuring it with a base path and access token. ```typescript import { BaseAPI, Configuration } from "crowdstrike-falcon"; class CustomApi extends BaseAPI { async listItems(): Promise { const response = await this.request({ path: "/custom/items/v1", method: "GET", headers: {}, }); return new JSONApiResponse(response, (json) => json); } } const config = new Configuration({ basePath: "https://api.crowdstrike.com", accessToken: "Bearer token...", }); const api = new CustomApi(config); const items = await api.listItems(); ``` -------------------------------- ### BaseAPI Constructor Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/04-runtime.md Initializes the BaseAPI with a configuration object, defaulting to DefaultConfig. ```typescript export class BaseAPI { constructor(protected configuration = DefaultConfig); } ``` -------------------------------- ### Display File Organization Structure Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/MANIFEST.md Visual representation of the documentation directory structure. ```text /output/ ├── README.md # Overview ├── INDEX.md # Master index ├── MANIFEST.md # This file ├── 01-client-initialization.md # Setup ├── 02-error-handling.md # Error handling ├── 03-middleware.md # Middleware ├── 04-runtime.md # Request handling ├── 05-event-stream.md # Events ├── 06-types.md # Types ├── 07-configuration.md # Configuration ├── 08-api-services.md # Services listing ├── 09-quick-reference.md # Quick reference ├── 10-advanced-patterns.md # Advanced usage └── api-reference/ ├── 01-hosts-api.md # Hosts API ├── 02-sensor-download-api.md # Sensor API └── 03-detects-api.md # Detects API ``` -------------------------------- ### Set environment variables for authentication Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/07-configuration.md Configure credentials via shell environment variables or directly within the Node.js process. ```bash export FALCON_CLIENT_ID=your-id export FALCON_CLIENT_SECRET=your-secret node app.js ``` ```typescript process.env.FALCON_CLIENT_ID = "your-id"; process.env.FALCON_CLIENT_SECRET = "your-secret"; ``` -------------------------------- ### DetectsApi to AlertsApi Migration Source: https://github.com/crowdstrike/falconjs/blob/main/_autodocs/api-reference/03-detects-api.md Comparison of query syntax between the legacy DetectsApi and the current AlertsApi. ```typescript const detections = await client.detects.queryDetects({ filter: "severity:critical", limit: 500, }); ``` ```typescript const alerts = await client.alerts.queryAlertsV2({ filter: "severity:critical", limit: 500, }); ```