Cedarling JavaScript/TypeScript API
    Preparing search index...

    Cedarling JavaScript/TypeScript API

    Getting Started with Cedarling in a JavaScript App

    The @janssenproject/cedarling_wasm package brings Cedarling authorization to JavaScript and TypeScript applications. Cedarling evaluates Cedar policies within your application's process, whether it runs in a browser, on a server, or at the edge. It determines whether a principal or token set may perform an action on a resource.

    Use Cedarling to apply consistent access policies, inspect authorization decisions, retain decision logs, and make application context available to policy evaluation.

    npm install @janssenproject/cedarling_wasm
    

    Choose the package entry for your application. The package ships Cedarling's WebAssembly (.wasm) binary; the last column describes how that binary is loaded and initialized. Your application's policy archive is configured separately.

    Environment Package Entry Packaged WASM Loading
    Browser applications with supported bundlers @janssenproject/cedarling_wasm Automatic
    Node.js 22, 24, or 26, ESM or CommonJS @janssenproject/cedarling_wasm Automatic
    Cloudflare Workers and Vercel Edge @janssenproject/cedarling_wasm/edge Bundled as a precompiled module
    Other ESM bundlers @janssenproject/cedarling_wasm/manual and /wasm Application-configured WASM loading

    Browser applications use an ESM-aware bundler. Follow Other Integration Paths for edge deployment and application-controlled WASM loading.

    For local generation, package build, and qualification instructions, see the maintainer guide.

    Create a Cedarling instance with init(). It ensures the package's WASM binary is loaded and initialized, then creates the instance using an object or Map of canonical Cedarling bootstrap properties.

    For browser or Node.js ESM applications:

    import { init } from "@janssenproject/cedarling_wasm";

    const config = {
    CEDARLING_APPLICATION_NAME: "task-api",
    CEDARLING_LOG_TYPE: "memory",
    CEDARLING_LOG_TTL: 120,
    };
    let cedarling;
    try {
    cedarling = await init({
    ...config,
    CEDARLING_POLICY_STORE_URI: "https://example.com/policy-store.cjar",
    });
    } catch (error) {
    console.error("Cedarling initialization failed", error);
    throw error;
    }

    Replace the example URL with your application's policy archive. For Node.js CommonJS, use the following import and run the initialization inside an async function:

    const { init } = require("@janssenproject/cedarling_wasm");
    

    The examples below reuse cedarling. Run each authorization walkthrough separately, with a policy store that matches its entities and attributes. Handle initialization failures in your application's startup error handler. See the bootstrap-property reference for configuration values, defaults, and token-validation settings.

    A Cedar archive (.cjar) packages the schema, policies, and trusted-issuer configuration. Prepare policies with the Agama Lab Policy Designer and follow the Cedar Archive format for packaging.

    Set CEDARLING_POLICY_STORE_URI as shown in Initialization. Cedarling downloads the archive while creating the instance. Use an absolute HTTP(S) URL. For browser downloads, use the application's origin or configure the archive server's CORS headers to allow the application origin.

    Use initFromArchiveBytes() instead of init() when your application controls the download. This browser example reuses config from Initialization and fetches an archive through a same-origin application endpoint:

    import { initFromArchiveBytes } from "@janssenproject/cedarling_wasm";

    let policyArchiveBytes;
    let cedarling;
    try {
    const response = await fetch("/api/policy-store");
    if (!response.ok) throw new Error("Policy-store download failed");
    policyArchiveBytes = new Uint8Array(await response.arrayBuffer());
    cedarling = await initFromArchiveBytes(config, policyArchiveBytes);
    } catch (error) {
    console.error("Policy-store download or initialization failed", error);
    throw error;
    }

    The archive bytes supply the policy store; config supplies the other bootstrap properties. The package still loads and initializes its own WASM binary. In Node.js, use an absolute download URL. Keep upstream policy-store credentials on a trusted server; browser configuration is visible to its users.

    Set CEDARLING_POLICY_STORE_SIGSTORE_MODE to enforce to load an archive only if its Sigstore bundle verifies for the expected signer. For an archive published by Agama Lab:

    const config = {
    // ...other bootstrap properties
    CEDARLING_POLICY_STORE_URI: "https://example.com/policy-store.cjar",
    CEDARLING_POLICY_STORE_SIGSTORE_MODE: "enforce",
    CEDARLING_POLICY_STORE_SIGSTORE_CERT_IDENTITY:
    "asset-signer@prod-gluu-cloud-platform.iam.gserviceaccount.com",
    CEDARLING_POLICY_STORE_SIGSTORE_CERT_OIDC_ISSUER: "https://accounts.google.com",
    };

    Cedarling fetches the bundle from the archive URL with .sigstore.json appended. With initFromArchiveBytes(), also set CEDARLING_POLICY_STORE_SIGSTORE_BUNDLE_URI to the bundle's HTTP(S) URL. In a browser, the bundle server needs the same CORS headers as the archive server. See bootstrap properties.

    Choose token-based authorization when identity comes from JWTs, or unsigned authorization when the application supplies a trusted principal. Both methods accept a JSON-string request and return a promise that resolves to an authorization result containing decision and request_id.

    Use authorizeMultiIssuer() to evaluate tokens from one or more issuers. Your policy store must define the token mappings, trusted issuers, resource schema, action, and context used below. Configure token validation for those issuers; the initialization example retains Cedarling's validation defaults.

    1. Prepare the tokens.

      Obtain acmeAccessToken and dolphinAccessToken from your application's authentication flows. Each mapping must match its policy-store token metadata; each payload is the actual JWT string.

      const tokens = [
      { mapping: "Acme::Access_Token", payload: acmeAccessToken },
      { mapping: "Dolphin::Access_Token", payload: dolphinAccessToken },
      ];
    2. Define the resource.

      This example targets a document. Its type and attributes must match your schema.

      const resource = {
      cedar_entity_mapping: { entity_type: "Task::Document", id: "document-1" },
      owner: "alice",
      };
    3. Define the action.

      const action = 'Task::Action::"Read"';
      
    4. Define the context.

      Supply request-specific data required by your policies and schema.

      const context = { tenant: "example" };
      
    5. Build the request.

      const request = { tokens, action, resource, context };
      
    6. Perform authorization and handle the decision.

      try {
      const result = await cedarling.authorizeMultiIssuer(JSON.stringify(request));
      console.log(result.decision ? "Allowed" : "Denied", result.request_id);
      } catch (error) {
      console.error("Authorization failed", error);
      }

    Use authorizeUnsigned() when your application supplies the principal and its attributes. Obtain those values from trusted application state. The policy store for this example must define Task::User with a role, Task::Document with an owner, and the Read action with the tenant context field.

    1. Prepare the principal.

      const principal = {
      cedar_entity_mapping: { entity_type: "Task::User", id: "alice" },
      role: "member",
      };
    2. Define the resource.

      const resource = {
      cedar_entity_mapping: { entity_type: "Task::Document", id: "document-1" },
      owner: "alice",
      };
    3. Define the action.

      const action = 'Task::Action::"Read"';
      
    4. Define the context.

      const context = { tenant: "example" };
      
    5. Build the request.

      const request = { principal, action, resource, context };
      
    6. Perform authorization and handle the decision.

      try {
      const result = await cedarling.authorizeUnsigned(JSON.stringify(request));
      console.log(result.decision ? "Allowed" : "Denied", result.request_id);
      } catch (error) {
      console.error("Authorization failed", error);
      }

    For both methods, decision: false is a valid denial. Malformed requests reject the call. Multi-issuer authorization can continue with tokens that pass validation, so policies must require the tokens needed for access. Perform the protected operation only after receiving decision: true; enforce server-side access at the server boundary.

    Evaluate several resources with one principal or token set. Each item contains an action, resource, and optional context. Reuse the values from the relevant walkthrough:

    const items = [
    { action, resource, context },
    {
    action,
    resource: {
    ...resource,
    cedar_entity_mapping: { entity_type: "Task::Document", id: "document-2" },
    },
    context,
    },
    ];

    For the unsigned walkthrough:

    let batch;
    try {
    batch = await cedarling.authorizeUnsignedBatch(
    JSON.stringify({ principal, items }),
    );
    } catch (error) {
    console.error("Batch authorization failed", error);
    throw error;
    }

    For the token-based walkthrough, use this call instead:

    let batch;
    try {
    batch = await cedarling.authorizeMultiIssuerBatch(
    JSON.stringify({ tokens, items }),
    );
    } catch (error) {
    console.error("Batch authorization failed", error);
    throw error;
    }

    After a successful batch call, inspect each item in the same order as the submitted items:

    for (const item of batch.results) {
    if (item.is_ok) {
    console.log(item.unwrap().decision ? "Allowed" : "Denied");
    } else {
    console.error(item.error?.category, item.error?.message);
    }
    }

    A valid denial has is_ok === true and a false decision. A per-item build error has is_ok === false. The returned batch_id correlates the batch's decision logs.

    The initialization example enables memory logging and retains entries for up to 120 seconds. Inside either authorization walkthrough's try block, use the returned request ID to inspect its logs:

    const logs = cedarling.getLogsByRequestId(result.request_id);
    console.log(logs);

    Log records are plain JavaScript objects. To retrieve and clear all retained logs when your application is ready to consume them:

    try {
    const retainedLogs = cedarling.popLogs();
    console.log(retainedLogs);
    } catch (error) {
    console.error("Log retrieval failed", error);
    }

    Store application-scoped data for policy evaluation, then retrieve or remove it:

    try {
    cedarling.pushDataCtx("user:alice", { plan: "pro" }, 3600n);
    const value = cedarling.getDataCtx("user:alice");
    console.log(value);
    cedarling.removeDataCtx("user:alice");
    } catch (error) {
    console.error("Context-data operation failed", error);
    }

    The optional TTL is a bigint number of seconds; omitting it uses the configured default. Retrieval returns null when a value is absent or expired.

    Destructive read: returns a metrics snapshot and resets the counters.

    try {
    const snapshot = cedarling.drainMetrics();
    console.log(snapshot.operational_stats.get("authz.requests_total"));
    console.log(snapshot.interval_secs);
    } catch (error) {
    console.error("Metrics snapshot failed", error);
    }

    Requires CEDARLING_METRICS_COLLECTION: "enabled". Fails whenever CEDARLING_LOCK_TELEMETRY_INTERVAL is set, even if the Lock server has no telemetry endpoint. interval_secs is a plain Number (not BigInt), so snapshot.interval_secs + 1 works. It carries fractional seconds, so sub-second intervals are reported exactly. Use snapshot.jsonString() for a JSON-serializable form with plain objects.

    Before token-based authorization, inspect which configured issuers loaded and which failed:

    console.log("Loaded issuers", cedarling.loadedTrustedIssuerIds());
    console.log("Failed issuers", cedarling.failedTrustedIssuerIds());

    To check one issuer, pass its name (the issuer of its token types) to cedarling.isTrustedIssuerLoadedByName(issuerName).

    Annotations attach metadata such as descriptions to policies using @key("value"). They describe policies independently of their authorization rules. For example, a policy in your archive can include:

    @description("Allows Alice to read document-1")
    permit (
        principal == Task::User::"alice",
        action == Task::Action::"Read",
        resource == Task::Document::"document-1"
    );
    

    Inside the unsigned walkthrough's try block, retrieve descriptions for the determining policy IDs returned in the result:

    const descriptions = cedarling.annotationValues(
    result.response.diagnostics.reason,
    "description",
    );
    console.log(descriptions);

    See the Cedar annotation reference for annotation syntax and behavior.

    When the application finishes using a Cedarling instance, shut it down:

    try {
    await cedarling.shutDown();
    } catch (error) {
    console.error("Cedarling shutdown failed", error);
    }

    Use the ESM-only ./edge entry in hosts whose deployment tool bundles the package's WASM binary as a precompiled WebAssembly module. In Cloudflare Workers, initialize inside the request context so policy downloads can run:

    import { init } from "@janssenproject/cedarling_wasm/edge";

    export default {
    async fetch() {
    let cedarling;
    try {
    cedarling = await init({
    CEDARLING_APPLICATION_NAME: "edge-api",
    CEDARLING_POLICY_STORE_URI: "https://example.com/policy-store.cjar",
    });
    return new Response("Cedarling initialized");
    } catch (error) {
    console.error("Cedarling initialization failed", error);
    return new Response("Internal server error", { status: 500 });
    } finally {
    try {
    await cedarling?.shutDown();
    } catch (error) {
    console.error("Cedarling shutdown failed", error);
    }
    }
    },
    };

    For application-controlled WASM loading, configure your ESM bundler to emit the package's ./wasm export as a URL-addressable binary asset. Configure the server to serve it with the application/wasm content type. The example below reuses config and policyArchiveBytes from Load a Cedar Archive from Bytes, replacing that section's initialization call:

    import initWasm, {
    initFromArchiveBytes,
    } from "@janssenproject/cedarling_wasm/manual";
    import wasmUrl from "@janssenproject/cedarling_wasm/wasm";

    let cedarling;
    try {
    await initWasm({ module_or_path: wasmUrl });
    cedarling = await initFromArchiveBytes(config, policyArchiveBytes);
    } catch (error) {
    console.error("WASM loading or Cedarling initialization failed", error);
    throw error;
    }

    Configure the .wasm import to return an asset URL; the exact rule or plugin depends on your bundler.

    Update calls such as authorize_unsigned() to authorizeUnsigned(), shut_down() to shutDown(), and json_string() to jsonString(). Bootstrap keys (CEDARLING_*), request JSON, result/data fields such as request_id, and serialized JSON retain their names.