Skill: billionsnetwork/identity (version 2.0.4)

--- name: verified-agent-identity description: Know Your Agent (KYA). Billions decentralized identity for agents. Link agents to human identities using Billions ERC-8004 and Attestation Registries. Verify and generate authentication proofs. Based on iden3 self-sovereign identity protocol. metadata: { "category": "identity", "clawdbot": { "requires": { "bins": ["node"] }, "config": { "optionalEnv": ["BILLIONS_NETWORK_MASTER_KMS_KEY"] }, }, } homepage: https://billions.network/ --- ## When to Use This Skill This skill covers two capabilities. Read the **router table** below, then load the relevant reference before proceeding. | Situation | Reference to load | | ----------------------------------------------------------------------- | ----------------------------- | | Create, list, link, verify, or sign with a decentralized identity (DID) | `reference/identity/SKILL.md` | | Handle a **402 Payment Required** HTTP response | `reference/x402/SKILL.md` | > **Always read the appropriate reference SKILL.md before running any script.** > If a task spans both (e.g. you need an identity before you can sign a 402 payment), read both. ## Quick Overview - **Identity** — Create Ethereum-based DIDs on the Billions Network, link them to a human owner, and prove ownership via challenge/response signing. - **x402 Payment** — When a server returns `402 Payment Required`, build a signed `PAYMENT-SIGNATURE` header so you can retry the request and gain access. ## Shared Setup All identity data is stored in `$HOME/.openclaw/billions`. Scripts live in `scripts/`. ```bash cd scripts && npm install && cd .. ``` ## Restrictions / Guardrails (CRITICAL) **These rules apply to ALL references. Always follow them.** 1. **STRICT: Check Identity First** - Before running `linkHumanToAgent.js`, `signChallenge.js`, or `buildX402Payment.js`, **ALWAYS** check if an identity exists: `node scripts/getIdentities.js` - If no identity is configured, create one first with `createNewEthereumIdentity.js` after that run `linkHumanToAgent.js` to link it to a human owner. - Continue processing the task only after confirming that an identity exists and is linked to a human owner. 2. **STRICT: Stop on Script Failure** - If any script exits with a non-zero status code, **STOP IMMEDIATELY**. - Check stderr for error messages. - **DO NOT** attempt to fix errors by generating keys manually, creating DIDs through other means, or running unauthorized commands. - **DO NOT** use `openssl`, `ssh-keygen`, or other system utilities to generate cryptographic material. 3. **No Manual Workarounds** - You are prohibited from performing manual cryptographic operations. - You are prohibited from directly manipulating files in `$HOME/.openclaw/billions`. - Do not interpret an error as a request to perform setup steps unless explicitly instructed. ## Security The directory `$HOME/.openclaw/billions` contains sensitive identity data: - `kms.json` — **CRITICAL**: Contains private keys (encrypted if `BILLIONS_NETWORK_MASTER_KMS_KEY` is set, otherwise plaintext) - `defaultDid.json` — DID identifiers and public keys - `challenges.json` — Authentication challenges history - `credentials.json` — Verifiable credentials - `identities.json` — Identity metadata - `profiles.json` — Profile data After the first run, restrict access to this directory: chmod 700 ~/.openclaw/billions There are several ways of storing private keys, to enable master key encryption as described in the KMS Encryption section below. More about security: `./SECURITY.md`

path: README.md
content: # Verified Agent Identity

A decentralized identity management toolkit for AI agents using iden3 protocol on Billions Network.

## Overview

This skill enables AI agents to create, manage, link, prove and verify ownership of decentralized identities (DIDs) using cryptographic signatures.

## Installation

### Agent CTA:

1. Ask bot to install the skill:

   Install with clawhub:

   ```plaintext
   Install the skill `npx clawhub@latest install verified-agent-identity`
   ```

   Or install with skills.sh:

   ```plaintext
   Intall the skill `npx skills add BillionsNetwork/verified-agent-identity`
   ```

   Or

   ```plaintext
   Install the `verified-agent-identity` skill from the OpenClaw clawhub.ai.
   ```

2. (Optional) If the verification process did not start automatically after installation, ask your bot to initialize the process by sending a message like:

   ```plaintext
   Please link your agent identity to me.
   ```

### Human CTA:

1. Install the skill:

   Use clawhub to install the skill:

   ```bash
   npx clawhub@latest install verified-agent-identity
   ```

   Use skills.sh to install the skill:

   ```bash
   npx skills add BillionsNetwork/verified-agent-identity
   ```

2. Create a new identity:

   ```bash
   # Generate a new key and create a new identity
   node scripts/createNewEthereumIdentity.js
   ```

   Or

   ```bash
   # Use an existing private key to create an identity
   BILLIONS_NETWORK_MASTER_KMS_KEY="<your-strong-secret>" node scripts/createNewEthereumIdentity.js --key <your-ethereum-private-key>
   ```

   > **Warning**: Only pass a **dedicated identity key** to `--key` — never an Ethereum wallet key that holds assets. If the key file is exposed, any key stored here could be used to impersonate the agent or, if reused, to control the associated wallet.

3. Generate a verification link to connect your human identity to the agent:

   ```bash
   node scripts/manualLinkHumanToAgent.js --challenge '{"name": "Agent Name", "description": "Short description of the agent"}'
   ```

   This prints the verification URL to the console. Open it in your browser to complete the identity linking process.

## Features

- **Identity Creation**: Generate new DIDs with random or existing Ethereum private keys
- **Identity Management**: List and manage multiple identities with default identity support
- **Human-Agent Linking**: Link a human identity to an agent's DID through signed challenges
- **Proof Generation**: Generate cryptographic proofs to authenticate as a specific identity
- **Proof Verification**: Verify proofs to confirm identity ownership

## Architecture

### Runtime Requirements

- **Node.js `>= v20`** and **npm** are required to run the scripts.

### Dependency Surface

npm dependencies are intentionally minimal and scoped to well-established, audited packages:

| Package                | Purpose                                                      |
| ---------------------- | ------------------------------------------------------------ |
| `@0xpolygonid/js-sdk`  | iden3/Privado ID cryptographic primitives and key management |
| `@iden3/js-iden3-core` | DID and identity core types                                  |
| `@iden3/js-iden3-auth` | JWS/JWA authorization response construction and verification |
| `ethers`               | Ethereum key utilities                                       |
| `uuid`                 | UUID generation for protocol message IDs                     |

Core libraries governing identity management use pinned, well-tested versions to ensure stability and security.

### Key Storage and Isolation

All cryptographic material is persisted to `$HOME/.openclaw/billions/` — a directory that lives **outside the agent's workspace**:

| File               | Contents                                                                           |
| ------------------ | ---------------------------------------------------------------------------------- |
| `kms.json`         | Private keys — per-entry versioned format; keys are plain or AES-256-GCM encrypted |
| `identities.json`  | Identity metadata                                                                  |
| `defaultDid.json`  | Active DID and associated public key                                               |
| `challenges.json`  | Per-DID challenge history                                                          |
| `credentials.json` | Verifiable credentials                                                             |

After the first run, restrict access to this directory: `chmod 700 ~/.openclaw/billions`

There are several ways of storing private keys, to enable master key encryption as described in the **KMS Encryption** section below.

### KMS Encryption

> See [SECURITY.md](SECURITY.md) for the full threat model, the rationale for shipping a plaintext storage mode, and the operator hardening checklist.

Set the environment variable `BILLIONS_NETWORK_MASTER_KMS_KEY` to enable AES-256-GCM at-rest encryption for the private keys inside `kms.json`. When set, every key value is individually encrypted on write; when absent, keys are stored as plain hex strings.

**`kms.json` entry format**

Each entry in the array is versioned. The `alias` is always stored in plaintext — only the `key` value is encrypted:

```json
[
  {
    "version": 1,
    "provider": "plain",
    "data": {
      "alias": "secp256k1:abc123",
      "key": "deadbeef...",
      "createdAt": "2026-03-12T13:46:04.094Z"
    }
  },
  {
    "version": 1,
    "provider": "encrypted",
    "data": {
      "alias": "secp256k1:xyz456",
      "key": "<iv_hex>:<authTag_hex>:<ciphertext_hex>",
      "createdAt": "2026-02-11T13:00:02.032Z"
    }
  }
]
```

**Behavior summary**

| `BILLIONS_NETWORK_MASTER_KMS_KEY` | `provider` on disk | `key` value on disk     |
| --------------------------------- | ------------------ | ----------------------- |
| Not set                           | `"plain"`          | Raw hex string          |
| Set                               | `"encrypted"`      | `iv:authTag:ciphertext` |

> **Backward compatibility** — the legacy format `[ { "alias": "...", "privateKeyHex": "..." } ]` is still read correctly. On the first write the file is automatically migrated to the new per-entry format. No manual step is required.

**How to set the variable**

_Option 1 — openclaw skill config (recommended for agent deployments):_

Add an `env` block for the skill inside your openclaw config:

```json
"skills": {
  "entries": {
    "verified-agent-identity": {
      "env": {
        "BILLIONS_NETWORK_MASTER_KMS_KEY": "<your-strong-secret>"
      }
    }
  }
}
```

_Option 2 — shell or process environment:_

```bash
export BILLIONS_NETWORK_MASTER_KMS_KEY="<your-strong-secret>"
node scripts/createNewEthereumIdentity.js
node scripts/manualLinkHumanToAgent.js --challenge '{"name": "Agent Name", "description": "Short description of the agent"}'
```

For all other ways to pass environment variables to a skill see the [OpenClaw environment documentation](https://docs.openclaw.ai/help/environment).

**CRITICAL**: Save master keys securely and do not share them. If the master key is lost, all encrypted keys will be lost.

### Network and External Binary Policy

- All external https calls will be made to trusted resources. Signed JWS attestation (proof of agent ownership) is encoded securely by utilizing robust security practices. It requires an explicit user consent to pass it to any other source.
- All network calls are directed to legitimate DID resolvers (resolver.privado.id) or the project's own infrastructure (billions.network). These network calls cannot exfiltrate signed attestations or identity data to other third-party services by skill design. Wallet interaction is possible only through explicit action from the user side with consent. Also attestation contains only publicly verifiable information.
- Whitelisted domains:
  - `resolver.privado.id` (DID resolution)
  - `billions.network` (Billions Network interactions)
  - `polygonid.me` (Polygon ID interactions)

## Documentation

See [SKILL.md](SKILL.md) for detailed usage instructions and examples.


path: SECURITY.md
content: # Security Policy

This document describes the security model of the `verified-agent-identity` skill, the threats it does and does not defend against, and the rationale behind design decisions that may surface in automated security scans.

## Scope

`verified-agent-identity` is a **local CLI skill**. It runs on a single operator's host, creates a decentralized identity (DID) for an AI agent, signs challenges with the agent's private key, and persists state under `~/.openclaw/billions/`. It is not a network service, has no listening port, and does not provide multi-tenant trust boundaries.

The only secret it manages is the agent's identity private key, stored in `~/.openclaw/billions/kms.json`.

## Threat Model

**In scope:**

- Preventing the identity key from being accidentally committed into the workspace or read by tools that operate inside the project directory.
- Protecting the key against casual disclosure on a single-user host (e.g. shoulder-surfing, accidental file sharing, careless backups).
- Preventing operator mistakes that would let an identity key double as an asset-holding wallet key.
- Providing opt-in at-rest encryption for shared/multi-user hosts and for environments where compliance requires it.

**Out of scope:**

- An attacker with read access to the operator's home directory or process memory. This is equivalent to full host compromise; no local secret-storage scheme defends against it without an external HSM or OS keystore, and integrating those would expand the dependency surface beyond what this skill commits to.
- Full-disk forensic recovery on a host the attacker physically controls.
- Hostile code already running with the operator's privileges.

## Storage Modes

Private keys are written to `~/.openclaw/billions/kms.json` in one of two formats, selected by the presence of the `BILLIONS_NETWORK_MASTER_KMS_KEY` environment variable.

| `BILLIONS_NETWORK_MASTER_KMS_KEY` | `provider` on disk | `key` value on disk     | Posture                      |
| --------------------------------- | ------------------ | ----------------------- | ---------------------------- |
| Not set                           | `"plain"`          | Raw hex string          | Acceptable on a single-user host with `chmod 700 ~/.openclaw/billions`. |
| Set                               | `"encrypted"`      | `iv:authTag:ciphertext` | **Recommended for all deployments.** AES-256-GCM at rest. |

Mode is selected per-write, so an operator can switch from `plain` to `encrypted` at any time by exporting the variable before the next key creation or import — no migration step is required.

## Compensating Controls

The following mitigations are present in the codebase and the documented installation flow:

- **Out-of-workspace storage.** Keys live under `~/.openclaw/billions/`, never inside the project directory. Tools (and the agent itself) that operate inside the workspace cannot read or exfiltrate them.
- **Filesystem hardening.** The README instructs the operator to run `chmod 700 ~/.openclaw/billions` after the first run (`README.md` → "Key Storage and Isolation").
- **Dedicated-key warning.** The README warns the operator never to import an Ethereum wallet key that holds assets, only a dedicated identity key (`README.md` step 2 warning under the Human CTA).
- **At-rest encryption available behind one env var.** AES-256-GCM is provided via `BILLIONS_NETWORK_MASTER_KMS_KEY`. No code change, no migration, no extra dependency.
- **Versioned on-disk format.** Each `kms.json` entry carries a `version` and `provider` field, so future format upgrades (e.g. an OS-keystore provider) can ship without breaking existing installs. Legacy entries auto-migrate on next write (see `scripts/shared/storage/keys.js`, `_decodeEntry` legacy branch).

## Scanner Findings — Acknowledged Risks

### Identity and Privilege Abuse — `scripts/shared/storage/keys.js` (plaintext storage branch)

**Finding (verbatim):**

> When no master key is configured, the key-storage code writes the raw private key value into `kms.json` as a plaintext entry.
>
> **User impact** — Anyone or any process that can read `~/.openclaw/billions/kms.json` may be able to impersonate the agent identity; if a real asset-holding Ethereum key is imported, the impact could extend beyond the agent identity.
>
> **Recommendation** — Set `BILLIONS_NETWORK_MASTER_KMS_KEY` before creating or importing keys, use only a dedicated no-assets identity key, restrict `~/.openclaw/billions` permissions, and avoid importing any wallet key that controls funds.

**Status: acknowledged, accepted — every item in the scanner's recommendation is already a documented and shipped control.**

The flagged code path is the documented `provider: "plain"` mode (see [Storage Modes](#storage-modes)). It is the default **only because the env var is unset**; setting `BILLIONS_NETWORK_MASTER_KMS_KEY` switches the same code path to AES-256-GCM with no further operator action. The threat the plaintext mode enables — local read of `~/.openclaw/billions/kms.json` on the operator's own host — is out of scope per the [Threat Model](#threat-model) above: an attacker with that level of access already controls the operator's shell history, SSH agent, browser secrets, and process memory.

#### Recommendation-to-Control mapping

| Scanner recommendation | Control in this repository | Reference |
| --- | --- | --- |
| Set `BILLIONS_NETWORK_MASTER_KMS_KEY` before creating or importing keys | A `> Note` block immediately precedes every key-creation command in the README, instructing the operator to set the variable. The `KMS Encryption` section documents the on-disk format change and the AES-256-GCM scheme. | `README.md` → "KMS Encryption" |
| Use only a dedicated, no-assets identity key | An explicit `> Warning` block under the key-creation step tells the operator never to pass an asset-holding wallet key to `--key`. | `README.md` step 2 of "Human CTA" |
| Restrict `~/.openclaw/billions` permissions | The "Key Storage and Isolation" section instructs `chmod 700 ~/.openclaw/billions` after the first run. The directory itself sits **outside the agent workspace**, so workspace-scoped tools cannot read it. | `README.md` → "Key Storage and Isolation" |
| Avoid importing any wallet key that controls funds | Same `> Warning` block as above; reinforced in the [Operator Checklist](#operator-checklist) below. | `README.md` step 2 warning + this document |

#### Why the plaintext mode is retained

1. **Zero-config local development and CI smoke tests** — no master secret to fetch or commit.
2. **Backward compatibility** — existing `kms.json` files written by earlier versions of the skill remain readable; legacy entries auto-migrate on the next write (`scripts/shared/storage/keys.js` → `_decodeEntry` legacy branch).
3. **Single code path** — the same write path becomes encrypted at rest the moment `BILLIONS_NETWORK_MASTER_KMS_KEY` is set. There is no separate "secure mode" the operator has to migrate to, so the plaintext default cannot drift away from the encrypted path over time.

The [Operator Checklist](#operator-checklist) is the recommended deployment posture and exactly matches the scanner's recommendation.

## Operator Checklist

1. **Set the master key first.**
   ```bash
   export BILLIONS_NETWORK_MASTER_KMS_KEY="<a strong secret>"
   ```
   Do this **before** the first `node scripts/createNewEthereumIdentity.js`. Keys created without it are written as `provider: "plain"`.
2. **Use a dedicated identity key.** Never reuse an Ethereum private key that holds assets. If the `kms.json` file is exposed, every key inside it should be revocable / disposable.
3. **Restrict the storage directory.**
   ```bash
   chmod 700 ~/.openclaw/billions
   ```
4. **Back up the master key out of band.** If `BILLIONS_NETWORK_MASTER_KMS_KEY` is lost, every entry written under `provider: "encrypted"` is unrecoverable.

## Reporting a Vulnerability

Please report suspected vulnerabilities privately to the Billions Network security contact rather than filing a public issue. Open an issue marked `security` requesting a private disclosure channel if you do not already have one.


path: scripts/buildX402Payment.js
content: const fs = require("fs");
const os = require("os");
const path = require("path");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const {
  hashstr,
  outputSuccess,
  outputError,
  outputInputRequired,
  getUserWallet,
  createAuthRequestMessage,
  getRequiredDidEntry,
} = require("./shared/utils");
const { getInitializedRuntime } = require("./shared/bootstrap");
const { x402Client } = require("@x402/core/client");
const { ExactEvmScheme } = require("@x402/evm/exact/client");
const {
  createHumanProofExtension,
  MissingAttestationsError,
  checkAttestation,
  isMaxUseExceededError,
} = require("@billionsnetwork/x402-human-proof-client");
const { toClientEvmSigner } = require("@x402/evm");
const {
  schemaId,
  transactionSender,
  requiredAttestationsMessage,
} = require("./shared/constants");
const { createPOUScope, createAuthScope } = require("./shared/scopes");
const { signChallenge } = require("./signChallenge");
const { v4: uuidv4 } = require("uuid");

function getPaymentHash(payment) {
  return hashstr(JSON.stringify(payment));
}

function getPaymentRequiredHash(paymentRequired) {
  return hashstr(JSON.stringify(paymentRequired));
}

function parsePaymentRequiredHeader(headerValue) {
  const trimmed = headerValue.trim();
  return trimmed.startsWith("{")
    ? JSON.parse(trimmed)
    : JSON.parse(atob(trimmed));
}

async function fetchPaymentRequired(url) {
  let response;
  try {
    response = await fetch(url);
  } catch (e) {
    outputError(`Failed to reach resource: ${e.message || e}`, true);
    return;
  }
  if (response.status !== 402) {
    outputError(`Expected 402 from ${url}, got ${response.status}`, true);
    return;
  }
  const headerValue = response.headers.get("payment-required");
  if (!headerValue) {
    outputError(
      "Resource returned 402 but no PAYMENT-REQUIRED header",
      true,
    );
    return;
  }
  try {
    return parsePaymentRequiredHeader(headerValue);
  } catch (e) {
    outputError(
      `PAYMENT-REQUIRED header is not valid JSON or Base64 JSON: ${e.message || e}`,
      true,
    );
  }
}

function persistPaymentRequired(paymentRequired) {
  const hash = getPaymentRequiredHash(paymentRequired);
  const filePath = path.join(os.tmpdir(), `${hash}.json`);
  const tempPath = `${filePath}.tmp`;
  fs.writeFileSync(tempPath, JSON.stringify(paymentRequired, null, 2), "utf-8");
  fs.renameSync(tempPath, filePath);
  return { hash, filePath };
}

function loadPaymentRequiredFile(filePath) {
  let raw;
  try {
    raw = fs.readFileSync(filePath, "utf-8");
  } catch (e) {
    outputError(
      `Failed to read --paymentRequiredFilePath ${filePath}: ${e.message || e}`,
      true,
    );
    return;
  }
  try {
    return JSON.parse(raw);
  } catch (e) {
    outputError(
      `--paymentRequiredFilePath ${filePath} is not valid JSON: ${e.message || e}`,
      true,
    );
  }
}

function getRequiredAttestations(payment) {
  return (payment.extra && payment.extra.requiredAttestations) || [];
}

async function getMissingAttestations(did, payment) {
  const requiredAttestations = getRequiredAttestations(payment);
  const results = await Promise.all(
    requiredAttestations.map(async (id) => ({
      id,
      exists: await checkAttestation(did, id),
    })),
  );
  return results.filter((r) => !r.exists).map((r) => r.id);
}

async function createAttestationLinks(
  attestationSchemaIds,
  transactionSenderAddr,
  did,
  entry,
  kms,
) {
  return await Promise.all(
    attestationSchemaIds.map(async (attestationSchemaId) => {
      if (attestationSchemaId !== schemaId) {
        throw new Error(
          `Unknown attestation requirement with schema ${attestationSchemaId}`,
        );
      }
      const scope = [
        createPOUScope(transactionSenderAddr),
        createAuthScope(did),
      ];
      const signedChallenge = await signChallenge(
        { name: uuidv4(), description: uuidv4() },
        entry,
        kms,
      );
      return await createAuthRequestMessage(signedChallenge, scope);
    }),
  );
}

async function handleMissingAttestations(error, entry, kms) {
  const attestationLinks = await createAttestationLinks(
    error.attestationRequirements,
    transactionSender,
    entry.did,
    entry,
    kms,
  );
  outputInputRequired(
    {
      attestationsRequired: true,
      message: requiredAttestationsMessage,
      attestationLinks,
    },
    true,
  );
}

async function buildPaymentInfo(payment, entry, kms) {
  const requiredAttestations = getRequiredAttestations(payment);
  const missingAttestations = await getMissingAttestations(entry.did, payment);

  let attestationLinks = [];
  if (missingAttestations.length > 0) {
    attestationLinks = await createAttestationLinks(
      missingAttestations,
      transactionSender,
      entry.did,
      entry,
      kms,
    );
  }

  return {
    hash: getPaymentHash(payment),
    amount: payment.amount,
    asset: (payment.extra && payment.extra.name) || payment.asset,
    network: payment.network,
    requiredAttestations,
    hasAllAttestations: missingAttestations.length === 0,
    attestationLinks,
  };
}

function parseCliArgs() {
  return yargs(hideBin(process.argv))
    .scriptName("buildX402Payment")
    .usage(
      "$0 [options]\n\n" +
        "Execute the x402 payment flow in two phases.\n\n" +
        "Phase 1 — Discover (--resource only):\n" +
        "  Fetches the 402 challenge from the resource, caches the\n" +
        "  PAYMENT-REQUIRED payload to a temp file named by its hash, and\n" +
        "  returns { paymentRequiredFilePath, paymentOptions }. Never signs a\n" +
        "  payment. Pass --paymentHash here is an error.\n\n" +
        "Phase 2 — Execute (--paymentRequiredFilePath + --paymentHash):\n" +
        "  Reads the cached payment-required file, looks up the chosen option\n" +
        "  by --paymentHash, and signs/sends the payment. Cannot be combined\n" +
        "  with --resource.",
    )
    .option("resource", {
      type: "string",
      describe:
        "Phase 1 only. URL of the resource that returns 402 with a " +
        "PAYMENT-REQUIRED header. Mutually exclusive with " +
        "--paymentRequiredFilePath and --paymentHash.",
    })
    .option("paymentRequiredFilePath", {
      type: "string",
      describe:
        "Phase 2 only. Path to the cached payment-required JSON file " +
        "returned by phase 1. Must be combined with --paymentHash. " +
        "Mutually exclusive with --resource.",
    })
    .option("paymentHash", {
      type: "string",
      describe:
        "Phase 2 only. Hash of the payment option to execute (from phase 1's " +
        "paymentOptions[].hash). Must be combined with --paymentRequiredFilePath.",
    })
    .option("did", {
      type: "string",
      describe:
        "Optional. DID to use for signing. Defaults to the default DID in local storage.",
    })
    .example(
      "$0 --resource https://api.example.com/paid",
      "Phase 1: discover payment options and cache the challenge",
    )
    .example(
      "$0 --paymentRequiredFilePath /tmp/<hash>.json --paymentHash <hash>",
      "Phase 2: execute the selected payment from the cached challenge",
    )
    .example(
      "$0 --resource https://api.example.com/paid --did did:iden3:...",
      "Phase 1 with an explicit DID instead of the default",
    )
    .check((argv) => {
      const hasResource = Boolean(argv.resource);
      const hasFilePath = Boolean(argv.paymentRequiredFilePath);
      const hasHash = Boolean(argv.paymentHash);

      if (!hasResource && !hasFilePath) {
        throw new Error(
          "Provide --resource (phase 1) or --paymentRequiredFilePath + --paymentHash (phase 2).",
        );
      }
      if (hasResource && hasFilePath) {
        throw new Error(
          "--resource and --paymentRequiredFilePath are mutually exclusive. " +
            "Use --resource alone for phase 1, or " +
            "--paymentRequiredFilePath + --paymentHash for phase 2.",
        );
      }
      if (hasResource && hasHash) {
        throw new Error(
          "--paymentHash is not allowed with --resource. Run phase 1 with " +
            "--resource alone, then pass the returned paymentRequiredFilePath " +
            "together with --paymentHash in phase 2.",
        );
      }
      if (hasFilePath && !hasHash) {
        throw new Error(
          "--paymentHash is required with --paymentRequiredFilePath (phase 2).",
        );
      }
      return true;
    })
    .strict()
    .help("help")
    .alias("help", "h")
    .wrap(Math.min(120, yargs().terminalWidth()))
    .fail((msg, err, y) => {
      console.error(y.help());
      console.error(`\nError: ${msg || (err && err.message) || "invalid arguments"}`);
      process.exit(1);
    })
    .parse();
}

function requirePaymentResourceUrl(paymentRequired) {
  const paymentResource = paymentRequired.resource;
  if (!paymentResource || !paymentResource.url) {
    outputError("paymentRequired.resource.url is required", true);
    return null;
  }
  return paymentResource;
}

async function runDiscovery(args, entry, kms) {
  const paymentRequired = await fetchPaymentRequired(args.resource);
  const paymentResource = requirePaymentResourceUrl(paymentRequired);
  if (!paymentResource) return;

  const { filePath } = persistPaymentRequired(paymentRequired);
  const paymentOptions = await Promise.all(
    paymentRequired.accepts.map((p) => buildPaymentInfo(p, entry, kms)),
  );

  outputInputRequired(
    {
      resource: {
        url: paymentResource.url,
        description: paymentResource.description,
      },
      paymentOptions,
      paymentRequiredFilePath: filePath,
    },
    true,
  );
}

async function main() {
  try {
    const args = parseCliArgs();

    const { kms, memoryKeyStore, didsStorage } = await getInitializedRuntime();
    const entry = await getRequiredDidEntry(didsStorage, args.did);

    // Phase 1: --resource only. Fetch, cache, return options.
    if (args.resource) {
      await runDiscovery(args, entry, kms);
      return;
    }

    // Phase 2: --paymentRequiredFilePath + --paymentHash. Load file, find hash, execute.
    const paymentRequired = loadPaymentRequiredFile(args.paymentRequiredFilePath);
    const paymentResource = requirePaymentResourceUrl(paymentRequired);
    if (!paymentResource) return;

    const matched = paymentRequired.accepts.find(
      (p) => getPaymentHash(p) === args.paymentHash,
    );
    if (!matched) {
      outputError("No payment matching the provided --paymentHash", true);
      return;
    }
    paymentRequired.accepts = [matched];

    // Phase 2: Single payment - check attestations before proceeding
    const selectedPayment = paymentRequired.accepts[0];
    const missingAttestations = await getMissingAttestations(
      entry.did,
      selectedPayment,
    );

    if (missingAttestations.length > 0) {
      const attestationLinks = await createAttestationLinks(
        missingAttestations,
        transactionSender,
        entry.did,
        entry,
        kms,
      );
      outputInputRequired(
        {
          attestationsRequired: true,
          message: requiredAttestationsMessage,
          attestationLinks,
        },
        true,
      );
      return;
    }

    // Phase 4: Execute payment and fetch the resource
    const { wallet } = await getUserWallet(entry, memoryKeyStore);
    const signer = toClientEvmSigner(wallet);

    const x402 = new x402Client();
    x402.register("eip155:*", new ExactEvmScheme(signer));
    x402.registerExtension(
      createHumanProofExtension({
        address: wallet.address,
        pubKey: wallet.publicKey,
        signMessage: (msg) => wallet.signMessage({ message: msg }),
      }),
    );
    x402.onPaymentCreationFailure(async ({ error }) => {
      if (error instanceof MissingAttestationsError) {
        await handleMissingAttestations(error, entry, kms);
      }
    });

    let paymentPayload;
    try {
      paymentPayload = await x402.createPaymentPayload(paymentRequired);
    } catch (error) {
      if (error instanceof MissingAttestationsError) {
        return;
      } else {
        throw error;
      }
    }

    // Phase 5: Fetch the resource with the payment signature
    const paymentSignature = btoa(JSON.stringify(paymentPayload));
    const url = paymentResource.url;
    let response;
    response = await fetch(url, {
      headers: { "PAYMENT-SIGNATURE": paymentSignature },
    });

    if (response.status === 402) {
      console.log(response);
      if (isMaxUseExceededError({ response })) {
        outputInputRequired(
          {
            maxUseExceeded: true,
            message:
              "Payment has exceeded its maximum allowed uses. Choose a different payment or contact the resource provider.",
          },
          true,
        );
      }
      // if not max use exceeded, check for new payment required
      const newPaymentRequired = response.headers.get("payment-required");
      if (newPaymentRequired) {
        outputInputRequired({ newPaymentRequired: newPaymentRequired }, true);
        return;
      }
      outputError("Received 402 but no PAYMENT-REQUIRED header found", true);
      return;
    }

    const responseText = await response.text();
    let responseBody;
    try {
      responseBody = JSON.parse(responseText);
    } catch {
      responseBody = responseText;
    }

    if (response.ok) {
      outputSuccess(responseBody, true);
    } else {
      outputError(
        `HTTP ${response.status}: ${typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody)}`,
        true,
      );
    }
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/createNewEthereumIdentity.js
content: const { hexToBytes } = require("@0xpolygonid/js-sdk");
const { DidMethod, Blockchain, NetworkId } = require("@iden3/js-iden3-core");
const { SigningKey, Wallet, JsonRpcProvider } = require("ethers");
const { getInitializedRuntime } = require("./shared/bootstrap");
const {
  parseArgs,
  outputError,
  outputSuccess,
  addHexPrefix,
} = require("./shared/utils");

async function main() {
  try {
    const args = parseArgs();
    const {
      identityWallet,
      didsStorage,
      billionsMainnetConfig,
      revocationOpts,
    } = await getInitializedRuntime();

    // Use provided key or generate a new one
    let privateKeyHex = args.key;
    if (!privateKeyHex) {
      privateKeyHex = new SigningKey(Wallet.createRandom().privateKey)
        .privateKey;
    }

    // Create signer from private key
    const signer = new SigningKey(addHexPrefix(privateKeyHex));

    // Create wallet with Billions Network provider
    const wallet = new Wallet(
      signer,
      new JsonRpcProvider(billionsMainnetConfig.url),
    );

    // Create Ethereum-based identity
    let did;
    try {
      const result = await identityWallet.createEthereumBasedIdentity({
        method: DidMethod.Iden3,
        blockchain: Blockchain.Billions,
        networkId: NetworkId.Main,
        seed: hexToBytes(privateKeyHex),
        revocationOpts: revocationOpts,
        ethSigner: wallet,
        createBjjCredential: false,
      });
      did = result.did;
    } catch (err) {
      throw new Error(
        `Failed to create Ethereum-based identity: ${err.message}`,
      );
    }

    // Save DID to storage
    await didsStorage.save({
      did: did.string(),
      publicKeyHex: signer.publicKey,
      isDefault: true,
    });

    outputSuccess(did.string());
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/generateChallenge.js
content: const { randomInt } = require("crypto");
const { getInitializedRuntime } = require("./shared/bootstrap");
const { parseArgs, outputError, outputSuccess } = require("./shared/utils");

async function main() {
  try {
    const args = parseArgs();

    if (!args.did) {
      throw new Error(
        "--did parameter is required. Usage: node scripts/generateChallenge.js --did <did>",
      );
    }

    const { challengeStorage } = await getInitializedRuntime();

    // Generate random challenge
    const challenge = randomInt(0, 10000000000).toString();

    // Save challenge to storage
    await challengeStorage.save(args.did, challenge);

    outputSuccess(challenge);
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/getDidDocument.js
content: const { getInitializedRuntime } = require("./shared/bootstrap");
const {
  parseArgs,
  outputError,
  outputSuccess,
  createDidDocument,
  getRequiredDidEntry,
} = require("./shared/utils");

async function main() {
  try {
    const args = parseArgs();
    const { didsStorage } = await getInitializedRuntime();
    const entry = await getRequiredDidEntry(didsStorage, args.did);

    const didDocument = createDidDocument(entry.did, entry.publicKeyHex);

    outputSuccess({
      didDocument,
      did: entry.did,
    });
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/getIdentities.js
content: const { getInitializedRuntime } = require("./shared/bootstrap");
const { outputError, outputSuccess } = require("./shared/utils");

async function main() {
  try {
    const { didsStorage } = await getInitializedRuntime();

    const identities = await didsStorage.list();

    if (identities.length === 0) {
      throw new Error(
        "No identities found. Create one with createNewEthereumIdentity.js",
      );
    }

    outputSuccess(identities);
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/linkHumanToAgent.js
content: const {
  parseArgs,
  urlFormatting,
  outputSuccess,
  outputError,
  createAuthRequestMessage,
  getRequiredDidEntry,
} = require("./shared/utils");
const { getInitializedRuntime } = require("./shared/bootstrap");
const { signChallenge } = require("./signChallenge");
const { createPOUScope, createAuthScope } = require("./shared/scopes");
const {
  transactionSender,
  verificationMessage,
} = require("./shared/constants");

/**
 * Creates a pairing URL for linking a human identity to the agent.
 * @param {object} challenge - Challenge object with name and description fields.
 * @param {string} [didOverride] - Optional DID to use instead of the default.
 * @returns {Promise<string>} The wallet URL the human must open to complete verification.
 */
async function createPairing(challenge, didOverride) {
  const { kms, didsStorage } = await getInitializedRuntime();
  const entry = await getRequiredDidEntry(didsStorage, didOverride);

  const recipientDid = entry.did;
  const signedChallenge = await signChallenge(challenge, entry, kms);

  const scope = [
    createPOUScope(transactionSender),
    createAuthScope(recipientDid),
  ];
  return await createAuthRequestMessage(signedChallenge, scope);
}

async function main() {
  try {
    const args = parseArgs();

    if (!args.challenge) {
      throw new Error(
        "Invalid arguments. Usage: node linkHumanToAgent.js --challenge <json> [--did <did>]",
      );
    }

    const challenge = JSON.parse(args.challenge);
    const url = await createPairing(challenge, args.did);

    outputSuccess(urlFormatting(verificationMessage, url));
  } catch (error) {
    outputError(error, true);
  }
}

module.exports = { createPairing };

if (require.main === module) {
  main();
}


path: scripts/manualLinkHumanToAgent.js
content: const { createPairing } = require("./linkHumanToAgent");
const { parseArgs, outputError } = require("./shared/utils");

async function main() {
  try {
    const args = parseArgs();

    if (!args.challenge) {
      throw new Error(
        'Invalid arguments. Usage: node manualLinkHumanToAgent.js --challenge <json> [--did <did>]\nExample: node manualLinkHumanToAgent.js --challenge \'{"name": "Agent Name", "description": "Short description of the agent"}\'',
      );
    }

    const challenge = JSON.parse(args.challenge);
    const url = await createPairing(challenge, args.did);

    console.log(url);
  } catch (error) {
    outputError(error, true);
  }
}

main();


path: scripts/package.json
content: {
  "name": "verified-agent-identity",
  "version": "1.0.0",
  "description": "Billions OpenClaw verification skill",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "identity",
    "openclaw",
    "zk"
  ],
  "author": "BillionsNetwork",
  "license": "UNLICENSED",
  "dependencies": {
    "@0xpolygonid/js-sdk": "1.42.1",
    "@billionsnetwork/x402-human-proof-client": "^0.1.6",
    "@iden3/js-iden3-auth": "1.14.0",
    "@iden3/js-iden3-core": "1.8.0",
    "@noble/curves": "1.9.2",
    "@x402/core": "2.9.0",
    "@x402/evm": "2.9.0",
    "ethers": "6.13.4",
    "uuid": "11.0.3",
    "viem": "2.47.6",
    "yargs": "^18.0.0"
  }
}


path: scripts/shared/attestation.js
content: const { ethers } = require("ethers");
const { DID } = require("@iden3/js-iden3-core");
const { schemaId: ATTESTATION_SCHEMA_ID } = require("./constants");

const ATTESTER_DID = ""; // string
const ATTESTER_IDEN3_ID = 0n; // uint256
const ATTESTER_ETH_ADDRESS = "0x0000000000000000000000000000000000000000"; // address

const EXPIRATION_TIME = 0n; // uint256 — 0 means no expiration
const REVOCABLE = false; // bool
const REF_ID =
  "0x0000000000000000000000000000000000000000000000000000000000000000"; // bytes32
const DATA = "0x"; // bytes

function extractIdFromDid(did) {
  return DID.idFromDID(DID.parse(did)).bigInt();
}

function buildJsonAttestation(req) {
  return {
    schemaId: ATTESTATION_SCHEMA_ID,
    attester: {
      did: ATTESTER_DID,
      iden3Id: ATTESTER_IDEN3_ID.toString(),
      ethereumAddress: ATTESTER_ETH_ADDRESS,
    },
    recipient: {
      did: req.recipientDid,
      iden3Id: extractIdFromDid(req.recipientDid).toString(),
      ethereumAddress: req.recipientEthAddress,
    },
    expirationTime: EXPIRATION_TIME.toString(),
    revocable: REVOCABLE,
    refId: REF_ID,
    data: DATA,
  };
}

function buildEncodedAttestation(req) {
  const encoded = ethers.AbiCoder.defaultAbiCoder().encode(
    [
      "bytes32", // schemaId
      "string", // attester.did
      "uint256", // attester.iden3Id
      "address", // attester.ethereumAddress
      "string", // recipient.did
      "uint256", // recipient.iden3Id
      "address", // recipient.ethereumAddress
      "uint256", // expirationTime
      "bool", // revocable
      "bytes32", // refId
      "bytes", // data
    ],
    [
      ATTESTATION_SCHEMA_ID,
      ATTESTER_DID,
      ATTESTER_IDEN3_ID,
      ATTESTER_ETH_ADDRESS,
      req.recipientDid,
      extractIdFromDid(req.recipientDid),
      req.recipientEthAddress,
      EXPIRATION_TIME,
      REVOCABLE,
      REF_ID,
      DATA,
    ],
  );
  return encoded;
}

function computeAttestationHash(req) {
  const hashHex = ethers.keccak256(buildEncodedAttestation(req));
  return (
    BigInt(hashHex) &
    BigInt([REDACTED_SECRET])
  ).toString();
}

module.exports = {
  computeAttestationHash,
  buildJsonAttestation,
};


path: scripts/shared/bootstrap.js
content: const {
  KMS,
  Sec256k1Provider,
  KmsKeyType,
  IdentityWallet,
  CredentialStatusType,
  EthStateStorage,
  CredentialStorage,
  IdentityStorage,
  InMemoryMerkleTreeStorage,
  CredentialStatusResolverRegistry,
  RHSResolver,
  CredentialWallet,
  defaultEthConnectionConfig,
  BjjProvider,
} = require("@0xpolygonid/js-sdk");

const { KeysFileStorage } = require("./storage/keys");
const { IdentitiesFileStorage } = require("./storage/identities");
const { DidsFileStorage } = require("./storage/did");
const { ChallengeFileStorage } = require("./storage/challenge");
const {
  rpcUrl,
  stateContractAddress,
  chainId,
  rhsUrl,
} = require("./constants");

let cachedRuntime = null;

/**
 * Creates and configures the KMS (Key Management System)
 */
async function newInMemoryKMS() {
  const memoryKeyStore = new KeysFileStorage("kms.json");
  const secpProvider = new Sec256k1Provider(
    KmsKeyType.Secp256k1,
    memoryKeyStore,
  );
  const bjjProvider = new BjjProvider(KmsKeyType.BabyJubJub, memoryKeyStore);
  const kms = new KMS();
  kms.registerKeyProvider(KmsKeyType.Secp256k1, secpProvider);
  kms.registerKeyProvider(KmsKeyType.BabyJubJub, bjjProvider);
  return { kms, memoryKeyStore };
}

/**
 * Creates Ethereum state storage for Billions Network
 */
function newEthStateStorage(billionsMainnetConfig) {
  return new EthStateStorage(billionsMainnetConfig);
}

/**
 * Creates data storage with credential, identity, merkle tree, and state storages
 */
function newDataStorage(ethStateStorage) {
  return {
    credential: new CredentialStorage(
      new IdentitiesFileStorage("credentials.json"),
    ),
    identity: new IdentityStorage(
      new IdentitiesFileStorage("identities.json"),
      new IdentitiesFileStorage("profiles.json"),
    ),
    mt: new InMemoryMerkleTreeStorage(40),
    states: ethStateStorage,
  };
}

/**
 * Creates credential wallet with credential status resolvers
 */
function newCredentialWallet(dataStorage) {
  const resolvers = new CredentialStatusResolverRegistry();
  resolvers.register(
    CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
    new RHSResolver(dataStorage.states),
  );
  return new CredentialWallet(dataStorage, resolvers);
}

/**
 * Creates identity wallet
 */
function newIdentityWallet(kms, dataStorage, credentialWallet) {
  return new IdentityWallet(kms, dataStorage, credentialWallet);
}

/**
 * Gets Billions Network mainnet configuration
 */
function getBillionsMainnetConfig() {
  return {
    ...defaultEthConnectionConfig,
    url: rpcUrl,
    contractAddress: stateContractAddress,
    chainId: chainId,
  };
}

/**
 * Gets default revocation options
 */
function getRevocationOpts() {
  return {
    type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
    id: rhsUrl,
  };
}

/**
 * Initializes and returns all runtime dependencies.
 * Uses caching to avoid re-initialization.
 *
 * @returns {Promise<Object>} Runtime object containing:
 *   - kms: Key Management System
 *   - identityWallet: Identity wallet instance
 *   - didsStorage: DID storage
 *   - challengeStorage: Challenge storage
 *   - billionsMainnetConfig: Billions Network configuration
 *   - revocationOpts: Revocation options
 */
async function getInitializedRuntime() {
  if (cachedRuntime) {
    return cachedRuntime;
  }

  const billionsMainnetConfig = getBillionsMainnetConfig();
  const revocationOpts = getRevocationOpts();

  const { kms, memoryKeyStore } = await newInMemoryKMS();
  const stateStorage = newEthStateStorage(billionsMainnetConfig);
  const dataStorage = newDataStorage(stateStorage);
  const credentialWallet = newCredentialWallet(dataStorage);
  const identityWallet = newIdentityWallet(kms, dataStorage, credentialWallet);

  const didsStorage = new DidsFileStorage("defaultDid.json");
  const challengeStorage = new ChallengeFileStorage("challenges.json");

  cachedRuntime = {
    kms,
    identityWallet,
    didsStorage,
    challengeStorage,
    billionsMainnetConfig,
    revocationOpts,
    memoryKeyStore,
  };

  return cachedRuntime;
}

module.exports = {
  getInitializedRuntime,
};


path: scripts/shared/constants.js
content: const transactionSender = [REDACTED_SECRET]; // relay sender address
const verifierDid =
  "did:iden3:privado:main:2SZu1G6YDUtk9AAY6TZic24CcCYcZvtdyp1cQv9cig"; // should be the same as dashboard DID
const callbackBase =
  "https://attestation-relay.billions.network/api/v1/callback?attestation=";
const walletAddress = "https://wallet.billions.network";
const verificationMessage =
  "Complete the verification to link your identity to the agent";
const requiredAttestationsMessage =
  "The following attestations are required to complete the payment:";
const pairingReasonMessage = "agent_pairing:v1";
const accept = [
  "iden3comm/v1;env=application/iden3-zkp-json;circuitId=authV2,authV3,authV3-8-32;alg=groth16",
];
const nullifierSessionId = "240416041207230509012302";
const pouScopeId = 1; // keccak256(nullifierSessionId)
const pouAllowedIssuer = [
  "did:iden3:billions:main:2VwqkgA2dNEwsnmojaay7C5jJEb8ZygecqCSU3xVfm",
];
const authScopeId = 2;
const urlShortener = "https://identity-dashboard.billions.network";
const schemaId =
  "0xca354bee6dc5eded165461d15ccb13aceb6f77ebbb1fd3fe45aca686097f2911";
const resolverUrl = "https://resolver.privado.id/1.0/identifiers";
const rpcUrl = "https://rpc-mainnet.billions.network";
const stateContractAddress = "0x3c9acb2205aa72a05f6d77d708b5cf85fca3a896";
const chainId = 45056;
const rhsUrl = "https://rhs-staging.polygonid.me";
const pouCredentialContext =
  "ipfs://QmcUEDa42Er4nfNFmGQVjiNYFaik6kvNQjfTeBrdSx83At";

module.exports = {
  transactionSender,
  verifierDid,
  callbackBase,
  walletAddress,
  verificationMessage,
  requiredAttestationsMessage,
  pairingReasonMessage,
  accept,
  nullifierSessionId,
  pouScopeId,
  pouAllowedIssuer,
  authScopeId,
  urlShortener,
  schemaId,
  resolverUrl,
  rpcUrl,
  stateContractAddress,
  chainId,
  rhsUrl,
  pouCredentialContext,
};


path: scripts/shared/scopes.js
content: const { CircuitId } = require("@0xpolygonid/js-sdk");
const { computeAttestationHash } = require("./attestation");
const { buildEthereumAddressFromDid } = require("./utils");
const {
  nullifierSessionId,
  pouScopeId,
  pouAllowedIssuer,
  authScopeId,
  pouCredentialContext,
} = require("./constants");

function createPOUScope(transactionSender) {
  return {
    id: pouScopeId,
    circuitId: CircuitId.AtomicQueryV3OnChainStable,
    params: {
      sender: transactionSender,
      nullifierSessionId: nullifierSessionId,
    },
    query: {
      allowedIssuers: pouAllowedIssuer,
      type: "UniquenessCredential",
      context: pouCredentialContext,
    },
  };
}

function createAuthScope(recipientDid) {
  return {
    id: authScopeId,
    circuitId: CircuitId.AuthV3_8_32,
    params: {
      challenge: computeAttestationHash({
        recipientDid: recipientDid,
        recipientEthAddress: buildEthereumAddressFromDid(recipientDid),
      }),
    },
  };
}

module.exports = {
  createPOUScope,
  createAuthScope,
};


path: scripts/shared/storage/base.js
content: const fs = require("fs/promises");
const path = require("path");

class FileStorage {
  constructor(filename, baseDir = `${process.env.HOME}/.openclaw/billions`) {
    this.filePath = path.join(baseDir, filename);
  }

  async ensureDirectory() {
    const dir = path.dirname(this.filePath);
    await fs.mkdir(dir, { recursive: true });
  }

  async readFile() {
    try {
      const data = await fs.readFile(this.filePath, "utf-8");
      return JSON.parse(data);
    } catch (error) {
      if (error.code === "ENOENT") {
        return [];
      }
      throw error;
    }
  }

  async writeFile(data) {
    await this.ensureDirectory();
    const json = JSON.stringify(data, null, 2);
    const tempPath = `${this.filePath}.tmp`;
    await fs.writeFile(tempPath, json, "utf-8");
    await fs.rename(tempPath, this.filePath);
  }
}

module.exports = { FileStorage };


path: scripts/shared/storage/challenge.js
content: const { FileStorage } = require("./base");

class ChallengeFileStorage extends FileStorage {
  constructor(filename = "challenges.json") {
    super(filename);
  }

  async save(did, challenge) {
    const entries = await this.readFile();
    const created_at = new Date();

    const index = entries.findIndex((entry) => entry.did === did);

    if (index >= 0) {
      // Update existing entry
      entries[index] = { did, challenge, created_at };
    } else {
      // Add new entry
      entries.push({ did, challenge, created_at });
    }

    await this.writeFile(entries);
  }

  async find(did) {
    const entries = await this.readFile();
    return entries.find((entry) => entry.did === did);
  }

  async getChallenge(did) {
    const entry = await this.find(did);
    return entry?.challenge;
  }

  async list() {
    return this.readFile();
  }

  async delete(did) {
    const entries = await this.readFile();
    const initialLength = entries.length;
    const filtered = entries.filter((entry) => entry.did !== did);

    if (filtered.length < initialLength) {
      await this.writeFile(filtered);
      return true;
    }

    return false;
  }
}

module.exports = { ChallengeFileStorage };


path: scripts/shared/storage/crypto.js
content: "use strict";

const crypto = require("crypto");

const ALGORITHM = "aes-256-gcm";
const IV_BYTES = 12;
const TAG_BYTES = 16;

function getMasterKey() {
  const rawKey = process.env.BILLIONS_NETWORK_MASTER_KMS_KEY;

  if (typeof rawKey !== "string") {
    return null;
  }

  const trimmedKey = rawKey.trim();

  // Reject whitespace-only or too-short keys to avoid weak/blank-looking master keys.
  // Returning null keeps behavior consistent with the "no key configured" case.
  const MIN_MASTER_KEY_LENGTH = 16;
  if (trimmedKey.length < MIN_MASTER_KEY_LENGTH) {
    return null;
  }

  return trimmedKey;
}

function deriveAesKey(masterKeyString) {
  return crypto.createHash("sha256").update(masterKeyString, "utf8").digest();
}

function encryptKey(keyHex, masterKeyString) {
  const aesKey = deriveAesKey(masterKeyString);
  const iv = crypto.randomBytes(IV_BYTES);
  const cipher = crypto.createCipheriv(ALGORITHM, aesKey, iv, {
    authTagLength: TAG_BYTES,
  });

  const encrypted = Buffer.concat([
    cipher.update(keyHex, "utf8"),
    cipher.final(),
  ]);
  const authTag = cipher.getAuthTag();

  return [
    iv.toString("hex"),
    authTag.toString("hex"),
    encrypted.toString("hex"),
  ].join(":");
}

function decryptKey(encryptedPayload, masterKeyString) {
  const parts = encryptedPayload.split(":");
  if (parts.length !== 3) {
    throw new Error("Invalid encrypted key format in kms.json");
  }
  const [ivHex, authTagHex, ciphertextHex] = parts;

  const aesKey = deriveAesKey(masterKeyString);
  const iv = Buffer.from(ivHex, "hex");
  const authTag = Buffer.from(authTagHex, "hex");
  const ciphertext = Buffer.from(ciphertextHex, "hex");

  const decipher = crypto.createDecipheriv(ALGORITHM, aesKey, iv, {
    authTagLength: TAG_BYTES,
  });
  decipher.setAuthTag(authTag);

  try {
    return Buffer.concat([
      decipher.update(ciphertext),
      decipher.final(),
    ]).toString("utf8");
  } catch {
    throw new Error(
      "kms.json decryption failed: wrong BILLIONS_NETWORK_MASTER_KMS_KEY or file has been tampered with",
    );
  }
}

module.exports = { getMasterKey, encryptKey, decryptKey };


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)