{"_id":"@authorityrail/axap","name":"@authorityrail/axap","dist-tags":{"latest":"2.0.0"},"versions":{"2.0.0":{"name":"@authorityrail/axap","version":"2.0.0","description":"AuthorityRail SDK — enforce agent authorization with CAR, ASC, and ARES Gateway support","license":"MIT","type":"module","main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"import":"./dist/index.js","types":"./dist/index.d.ts"},"./middleware/express":{"import":"./dist/middleware/express.js","types":"./dist/middleware/express.d.ts"}},"bin":{"axap":"bin/axap"},"scripts":{"build":"tsc","test":"vitest run","test:watch":"vitest","prepublishOnly":"npm run build && npm test","pack-dry":"npm pack --dry-run"},"dependencies":{},"devDependencies":{"@types/express":"^4.17.21","express":"^4.18.0","typescript":"^5.4.0","vitest":"^1.6.0"},"peerDependencies":{"express":">=4.0.0"},"peerDependenciesMeta":{"express":{"optional":true}},"publishConfig":{"access":"public"},"keywords":["authorityrail","authorization","axap","agent-authorization","car","asc","ares-gateway","bypass-prevention","ai-safety","mcp"],"repository":{"type":"git","url":"git+https://github.com/AuthorityRail-ai/authorityrail.git"},"engines":{"node":">=18.0.0"},"gitHead":"17102583d95c449e61ea97282ce2aea05ddf41eb","_id":"@authorityrail/axap@2.0.0","bugs":{"url":"https://github.com/AuthorityRail-ai/authorityrail/issues"},"homepage":"https://github.com/AuthorityRail-ai/authorityrail#readme","_nodeVersion":"24.12.0","_npmVersion":"11.6.2","dist":{"integrity":"sha512-pKRd1I7wEeC3aBFE1q0YNMJoUCRZ95A1uwJCURjIXTRbaa9Ua2gMPJ8ZvHIELWor2WwDiaupnAG4eK9ClCVCcQ==","shasum":"39fee89a574576e805c2d0a61cd77bc6cc311bd2","tarball":"https://registry.npmjs.org/@authorityrail/axap/-/axap-2.0.0.tgz","fileCount":35,"unpackedSize":114785,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIHFz51k8PGYmRTI+I8kQVz0BOvvNqqz6IbIUF2qg4qWEAiBkS2dtAG/mww+FvqIoeIJk/xGmScqYj2AT2DOzPlyeww=="}]},"_npmUser":{"name":"authorityrail-ai","email":"hello@authorityrail.com"},"directories":{},"maintainers":[{"name":"authorityrail-ai","email":"hello@authorityrail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/axap_2.0.0_1775447308754_0.508616035461178"},"_hasShrinkwrap":false}},"time":{"created":"2026-04-06T03:48:28.633Z","2.0.0":"2026-04-06T03:48:28.903Z","modified":"2026-04-06T03:48:29.196Z"},"maintainers":[{"name":"authorityrail-ai","email":"hello@authorityrail.com"}],"description":"AuthorityRail SDK — enforce agent authorization with CAR, ASC, and ARES Gateway support","homepage":"https://github.com/AuthorityRail-ai/authorityrail#readme","keywords":["authorityrail","authorization","axap","agent-authorization","car","asc","ares-gateway","bypass-prevention","ai-safety","mcp"],"repository":{"type":"git","url":"git+https://github.com/AuthorityRail-ai/authorityrail.git"},"bugs":{"url":"https://github.com/AuthorityRail-ai/authorityrail/issues"},"license":"MIT","readme":"# @authorityrail/axap\n\n**AuthorityRail SDK v2** — enforce agent authorization in any TypeScript or JavaScript stack.\n\n> _Probability is not permission. Authority is required._\n\nEvery action an AI agent takes produces a **Certified Action Record (CAR)** — a cryptographically-signed, immutable audit receipt stored in your AuthorityRail ledger. This SDK is the developer interface to that system.\n\n---\n\n## Installation\n\n```bash\nnpm install @authorityrail/axap\n```\n\nRequires **Node.js 18+** and **TypeScript 5+** (optional but recommended).\n\n---\n\n## 10-Minute Quickstart\n\n### 1. Create a client\n\n```ts\nimport { createClient } from '@authorityrail/axap';\n\nconst ar = createClient({\n  gateUrl: 'https://authorityrail-production-5b04.up.railway.app',\n  agentId: 'urn:ar:agent:my-agent',\n  orgId:   'acme-corp',\n  // apiKey: process.env.AR_API_KEY,   // optional\n});\n```\n\n### 2. Authorize an action\n\n```ts\nconst result = await ar.authorize({\n  action:     'transfer_funds',\n  risk_score: 0.8,\n  domain:     'payments',\n  payload:    { amount: 5000, to: 'acct_xyz' },\n});\n\nif (result.decision === 'ALLOW') {\n  console.log('Authorized. CAR ID:', result.car_id);\n  await executeTransfer();\n} else if (result.decision === 'DENY') {\n  throw new Error(`Denied: ${result.reasoning}`);\n}\n```\n\n### 3. One-liner with `withAuthority`\n\n```ts\nconst { output, authorityRail } = await ar.withAuthority(\n  { action: 'delete_record', risk_score: 0.9 },\n  async () => {\n    const output = await db.records.delete(id);\n    return { output };\n  }\n);\n// Throws AXAPDeniedError on DENY, AXAPEscalateError on ESCALATE\n```\n\n---\n\n## Core Concepts\n\n| Concept | Description |\n|---------|-------------|\n| **CAR** | Certified Action Record — immutable audit receipt for every decision |\n| **ASC** | Authority Scope Certificate — scoped permission grant for an agent |\n| **ARES Gateway** | MCP proxy that intercepts tool calls and enforces AuthorityRail decisions |\n| **Decision** | `ALLOW` / `DENY` / `BLOCK` / `ESCALATE` |\n\n---\n\n## API Reference\n\n### `createClient(config)` → `AuthorityRail`\n\nFactory function. Preferred over `new AuthorityRail()`.\n\n```ts\ninterface AuthorityRailConfig {\n  gateUrl:       string;            // AuthorityRail gate URL\n  agentId:       string;            // urn:ar:agent:<name> recommended\n  orgId:         string;            // organization identifier\n  apiKey?:       string;            // API key for authenticated requests\n  timeout?:      number;            // request timeout ms (default: 5000)\n  headers?:      Record<string, string>;\n  signingKey?:   string;            // HMAC key for CAR verification (env AR_SIGNING_KEY)\n  ascCacheTtl?:  number;            // ASC cache TTL ms (default: 300_000)\n  aresGatewayUrl?: string;          // ARES Gateway URL (falls back to gateUrl)\n}\n```\n\n---\n\n### `ar.authorize(opts)` → `AuthorizeResult`\n\nRequest authorization for an action. Always returns a decision — never silently allows.\n\n```ts\nconst result = await ar.authorize({\n  action:           'initiate_payment',   // required\n  risk_score:       0.75,                 // 0–1 (default: 0.5)\n  domain:           'payments',\n  payload:          { amount: 1000 },\n  model_version:    'gpt-5',\n  parent_car_id:    'car_parent_001',     // for delegation chains\n  financial_value:  1000,                 // USD, for risk weighting\n});\n// result: { decision, car_id, car_signature, reasoning, latency_ms, approval_id? }\n```\n\n---\n\n### `ar.withAuthority(opts, fn)` → `T & { authorityRail }`\n\nAuthorize and execute in one step. Throws on DENY/ESCALATE — never executes `fn` unless ALLOW.\n\n```ts\nconst result = await ar.withAuthority(\n  { action: 'send_email', risk_score: 0.3 },\n  async () => sendEmail(payload)\n);\n// result.authorityRail.car_id — audit receipt\n```\n\n---\n\n### `ar.verifyCAR(carId, signingKey?)` → `CARVerificationResult`\n\nFetch a CAR from the gate and confirm it is valid. Optionally verifies the HMAC signature locally.\n\n```ts\nconst check = await ar.verifyCAR('car_abc123');\n// { valid, car_id, agent_id, action, decision, verified_at }\n\n// With local HMAC verification:\nconst check = await ar.verifyCAR('car_abc123', process.env.AR_SIGNING_KEY);\n// check.signature_valid — true/false\n```\n\n**Standalone function:**\n```ts\nimport { verifyCAR } from '@authorityrail/axap';\n\nconst check = await verifyCAR('car_abc123', {\n  gateUrl:    'https://authorityrail-production-5b04.up.railway.app',\n  signingKey: process.env.AR_SIGNING_KEY,\n});\n```\n\n---\n\n### `ar.fetchASC(certId?)` → `ASC`\n\nFetch the active Authority Scope Certificate for this client's agent. Results are cached.\n\n```ts\nconst asc = await ar.fetchASC();\n// asc.authority_scope — ['data:read', 'payments:write']\n// asc.action_patterns — ['read_*', 'transfer_funds']\n// asc.max_risk_ceiling — 0.8\n// asc.expires_at — ISO timestamp\n```\n\n**Standalone function:**\n```ts\nimport { fetchASC, validateASC, ascCoversAction } from '@authorityrail/axap';\n\nconst asc = await fetchASC('urn:ar:agent:my-agent', {\n  gateUrl: 'https://authorityrail-production-5b04.up.railway.app',\n  cacheTtl: 600_000,  // 10 min\n});\n\nconst valid = validateASC(asc);\nconst covered = ascCoversAction(asc, 'transfer_funds');\n```\n\n---\n\n### ARES Gateway (MCP tool call enforcement)\n\n```ts\n// Low-level: authorize a tool call\nconst decision = await ar.aresAuthorize({\n  tool:      'write_database',\n  arguments: { table: 'users', data: { ... } },\n  domain:    'data',\n});\n\n// One-liner: authorize and execute\nconst result = await ar.aresCall(\n  { tool: 'read_config', arguments: { key: 'feature_flags' } },\n  async () => getConfig('feature_flags')\n);\n// result._ar.decision, result._ar.car_id\n\n// Standalone client:\nimport { AresClient } from '@authorityrail/axap';\nconst ares = new AresClient({ gateUrl, agentId, failOpen: false });\n```\n\n---\n\n### Express Middleware\n\n```ts\nimport { axapMiddleware } from '@authorityrail/axap/middleware/express';\n\napp.use(axapMiddleware({\n  gateUrl: process.env.AUTHORITYRAIL_URL,\n  agentId: 'urn:ar:agent:my-service',\n  orgId:   'acme',\n  actionClassMap: {\n    'POST /payments':  'initiate_payment',\n    'DELETE /*':       'delete_resource',\n    'GET /*':          'read_data',\n  },\n  onDeny: (req, res, ctx) => {\n    res.status(403).json({ error: 'Denied', car_id: ctx.car_id });\n  },\n  onAllow: (req, ctx) => {\n    logger.info('authorized', { car_id: ctx.car_id, action: ctx.action });\n  },\n}));\n// req.authorityRail — { decision, car_id, latency_ms, action }\n```\n\n---\n\n### CAR Signature Verification (offline)\n\n```ts\nimport { verifyCARSignatureLocal, computeCARSignature, carCanonicalString } from '@authorityrail/axap';\n\n// Verify a locally-held CAR without a network call\nconst valid = verifyCARSignatureLocal(car, process.env.AR_SIGNING_KEY);\n\n// Compute expected signature\nconst sig = computeCARSignature(car, process.env.AR_SIGNING_KEY);\n\n// Inspect canonical string\nconst canonical = carCanonicalString(car);\n// \"car_abc123|urn:ar:agent:test|transfer_funds|ALLOW\"\n```\n\n---\n\n## Error Handling\n\nAll errors are **explicit and typed**. The SDK never silently allows execution on error.\n\n```ts\nimport {\n  AXAPError,          // base class\n  AXAPDeniedError,    // decision is DENY or BLOCK\n  AXAPEscalateError,  // decision is ESCALATE (approvalId attached)\n  AXAPTimeoutError,   // request timed out\n  AXAPCertError,      // ASC missing, expired, or revoked\n  AXAPSignatureError, // CAR signature verification failed\n} from '@authorityrail/axap';\n\ntry {\n  await ar.withAuthority({ action: 'send_wire_transfer' }, fn);\n} catch (err) {\n  if (err instanceof AXAPDeniedError) {\n    console.error('Denied:', err.reasoning, 'CAR:', err.carId);\n  } else if (err instanceof AXAPEscalateError) {\n    console.log('Awaiting approval:', err.approvalId);\n  } else if (err instanceof AXAPTimeoutError) {\n    console.error('Gate timeout — action blocked');\n  } else {\n    throw err;\n  }\n}\n```\n\n---\n\n## CLI\n\n```bash\n# After installing globally: npm install -g @authorityrail/axap\n\naxap authorize \\\n  --agent urn:ar:agent:demo \\\n  --org acme-corp \\\n  --action transfer_funds \\\n  --risk 80 \\\n  --gateway https://authorityrail-production-5b04.up.railway.app\n\naxap verify --car car_abc123 --gateway https://authorityrail-production-5b04.up.railway.app\n\naxap asc --agent urn:ar:agent:demo --gateway https://authorityrail-production-5b04.up.railway.app\n\naxap status\n```\n\nEnvironment variables:\n- `AUTHORITYRAIL_URL` — gate URL\n- `AXAP_AGENT` — agent ID\n- `AXAP_ORG` — org ID\n- `AR_SIGNING_KEY` — HMAC signing key for CAR verification\n\n---\n\n## TypeScript\n\nFull type definitions are included. Key types:\n\n```ts\nimport type {\n  Decision,             // 'ALLOW' | 'DENY' | 'BLOCK' | 'ESCALATE'\n  CAR,                  // Certified Action Record\n  ASC,                  // Authority Scope Certificate\n  AuthorizeOptions,\n  AuthorizeResult,\n  AresCallOptions,\n  AresDecision,\n  AuthorityRailConfig,\n  CARVerificationResult,\n  ASCValidationResult,\n} from '@authorityrail/axap';\n```\n\n---\n\n## License\n\nMIT — AuthorityRail-ai/authorityrail\n","readmeFilename":"README.md","_rev":"1-5af78d765e99e4d5c6b350be8178a69a"}