Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions apps/chrome-extension/src/components/NostrApproval.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ export default function NostrApproval({ requestId, autoApprove }: NostrApprovalP
);
}, [requestId]);

const sendError = useCallback((error: string) => {
setProcessing(false);
chrome.runtime.sendMessage({
action: "NOSTR_RESPONSE",
id: requestId,
error,
}, () => window.close());
}, [requestId]);

const handleApprove = useCallback(async () => {
if (!keymaster) {
sendError("Wallet not initialized");
Expand Down Expand Up @@ -72,7 +81,7 @@ export default function NostrApproval({ requestId, autoApprove }: NostrApprovalP
} catch (error: any) {
sendError(error?.message || String(error));
}
}, [keymaster, method, params, currentDID, requestId, alwaysApprove, origin]);
}, [keymaster, method, params, currentDID, requestId, alwaysApprove, origin, sendError]);

// Auto-approve when ready (getPublicKey or remembered origin)
useEffect(() => {
Expand All @@ -82,15 +91,6 @@ export default function NostrApproval({ requestId, autoApprove }: NostrApprovalP
}
}, [autoApprove, loading, method, keymaster, handleApprove]);

function sendError(error: string) {
setProcessing(false);
chrome.runtime.sendMessage({
action: "NOSTR_RESPONSE",
id: requestId,
error,
}, () => window.close());
}

function handleDeny() {
sendError("User denied the request");
}
Expand Down
79 changes: 79 additions & 0 deletions docs/lightning-wallet-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Lightning Wallet Integration — Design Document

## Problem

Archon agents need Lightning Network payment capabilities (zaps, L402 paywalls, peer-to-peer payments). Each agent identity (DID) needs its own Lightning wallet so funds are isolated.

## Architecture

LNbits is the Lightning backend, hosted internally. Agents never interact with LNbits directly — all Lightning operations go through Drawbridge, the public-facing API gateway.

```
Agent (Keymaster) ──POST──▶ Drawbridge ──POST──▶ LNbits
│ │ (internal)
encrypted env var
wallet (server URL)
(per-DID
credentials)
```

**Keymaster** manages agent identities and wallets. It knows about Drawbridge (its gateway) but has no knowledge of LNbits.

**Drawbridge** is the public gateway. It knows the LNbits server URL (env var) and proxies all Lightning operations. It is stateless per-wallet — it doesn't store any per-DID state.

**LNbits** is never exposed publicly. Each DID gets its own LNbits account (via `POST /api/v1/account`), providing full isolation at the account level.

## Credential Flow

**Wallet creation:**
1. Agent calls `addLightning()` on Keymaster
2. Keymaster POSTs to Drawbridge `/lightning/wallet`
3. Drawbridge calls LNbits `POST /api/v1/account` to create a new account with an initial wallet
4. LNbits returns `walletId`, `adminKey` (spend), `invoiceKey` (read-only)
5. Drawbridge passes these back to Keymaster
6. Keymaster stores them in the agent's encrypted wallet under `idInfo.lightning`

**Subsequent operations:**
1. Agent calls a Lightning method (e.g. `createLightningInvoice`)
2. Keymaster reads stored credentials from wallet
3. Keymaster POSTs to Drawbridge with the relevant key (`adminKey` for spending, `invoiceKey` for read-only)
4. Drawbridge forwards to LNbits with that key in the `X-Api-Key` header
5. Result flows back to the agent

This means Drawbridge needs no per-agent state — credentials travel with each request.

## Security Model

- **LNbits URL**: Only in Drawbridge env var. Keymaster and agents never learn the LNbits server address.
- **Per-DID keys** (`adminKey`, `invoiceKey`): Stored only in the agent's encrypted wallet. Never in the public DID document. Sent to Drawbridge per-request over HTTPS.
- **`adminKey`** authorizes spending. Only sent for `pay` operations.
- **`invoiceKey`** is read-only. Used for balance checks, invoice creation, and payment status queries.
- **No shared account key**: Each DID gets its own LNbits account via `POST /api/v1/account` (no auth required). Drawbridge holds no account-level secrets — only the LNbits server URL.

## Operations

All Drawbridge Lightning endpoints use POST to keep keys out of URLs and query strings.

| Operation | Key Used | Description |
|---|---|---|
| Create wallet | *(none — unauthenticated LNbits call)* | Creates a new LNbits account+wallet for a DID |
| Get balance | `invoiceKey` | Returns balance in satoshis |
| Create invoice | `invoiceKey` | Creates a BOLT11 payment request |
| Pay invoice | `adminKey` | Pays an external BOLT11 invoice |
| Check payment | `invoiceKey` | Checks whether an invoice has been paid |

Wallet creation is idempotent — calling it again for a DID that already has credentials returns the existing config without hitting LNbits.

## Graceful Degradation

Two error modes, clearly distinguished:

1. **Lightning unavailable**: Keymaster is connected to a plain Gatekeeper (no Drawbridge), or Drawbridge has no LNbits configured. The agent gets a clean error and can continue using all non-Lightning features.

2. **Lightning not configured**: The agent hasn't created a wallet yet (no `addLightning()` call). Error tells them to set up Lightning first.

This ensures agents that don't need Lightning are completely unaffected, and agents connected to infrastructure without Lightning get actionable errors rather than cryptic failures.

## Multi-Identity Support

All operations accept an optional identity parameter. An agent managing multiple DIDs can create separate wallets for each and operate on any of them. Funds are fully isolated between DIDs. Removing Lightning credentials from a DID only deletes the local keys — the LNbits wallet continues to exist (this is intentional; credentials could be backed up or recovered).
2 changes: 2 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const config = {
'^@didcid/gatekeeper$': '<rootDir>/packages/gatekeeper/src/gatekeeper.ts',
'^@didcid/gatekeeper/types$': '<rootDir>/packages/gatekeeper/src/types.ts',
'^@didcid/gatekeeper/client$': '<rootDir>/packages/gatekeeper/src/gatekeeper-client.ts',
'^@didcid/gatekeeper/drawbridge$': '<rootDir>/packages/gatekeeper/src/drawbridge-client.ts',
'^@didcid/gatekeeper/db/(.*)$': '<rootDir>/packages/gatekeeper/src/db/$1',
'^@didcid/ipfs/helia$': '<rootDir>/packages/ipfs/src/helia-client.ts',
'^@didcid/ipfs/utils$': '<rootDir>/packages/ipfs/src/utils.ts',
Expand All @@ -30,6 +31,7 @@ const config = {
'^@didcid/cipher/passphrase': '<rootDir>/packages/cipher/src/passphrase.ts',
'^\\.\\/typeGuards\\.js$': '<rootDir>/packages/keymaster/src/db/typeGuards.ts',
'^\\.\\/db\\/typeGuards\\.js$': '<rootDir>/packages/keymaster/src/db/typeGuards.ts',
'^\\.\\/gatekeeper-client\\.js$': '<rootDir>/packages/gatekeeper/src/gatekeeper-client.ts',
'^\\.\\/abstract-json\\.js$': '<rootDir>/packages/gatekeeper/src/db/abstract-json.ts',
'^\\.\\/cipher-base\\.js$': '<rootDir>/packages/cipher/src/cipher-base.ts',
'^\\.\\/jwe\\.js$': '<rootDir>/packages/cipher/src/jwe.ts',
Expand Down
16 changes: 16 additions & 0 deletions packages/common/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@ export class UnknownIDError extends ArchonError {
}
}

export class LightningNotConfiguredError extends ArchonError {
static type = 'Lightning not configured';

constructor(detail?: string) {
super(LightningNotConfiguredError.type, detail);
}
}

export class LightningUnavailableError extends ArchonError {
static type = 'Lightning service unavailable';

constructor(detail?: string) {
super(LightningUnavailableError.type, detail);
}
}

// For unit tests
export class ExpectedExceptionError extends ArchonError {
static type = 'Expected to throw an exception';
Expand Down
8 changes: 8 additions & 0 deletions packages/gatekeeper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
"require": "./dist/cjs/gatekeeper-client.cjs",
"types": "./dist/types/gatekeeper-client.d.ts"
},
"./drawbridge": {
"import": "./dist/esm/drawbridge-client.js",
"require": "./dist/cjs/drawbridge-client.cjs",
"types": "./dist/types/drawbridge-client.d.ts"
},
"./db/json": {
"import": "./dist/esm/db/json.js",
"require": "./dist/cjs/db/json.cjs",
Expand Down Expand Up @@ -73,6 +78,9 @@
"client": [
"./dist/types/gatekeeper-client.d.ts"
],
"drawbridge": [
"./dist/types/drawbridge-client.d.ts"
],
"db/json": [
"./dist/types/db/json.d.ts"
],
Expand Down
1 change: 1 addition & 0 deletions packages/gatekeeper/rollup.cjs.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const config = {
'node': 'dist/esm/node.js',
'gatekeeper': 'dist/esm/gatekeeper.js',
'gatekeeper-client': 'dist/esm/gatekeeper-client.js',
'drawbridge-client': 'dist/esm/drawbridge-client.js',
'db/json': 'dist/esm/db/json.js',
'db/json-cache': 'dist/esm/db/json-cache.js',
'db/json-memory': 'dist/esm/db/json-memory.js',
Expand Down
71 changes: 71 additions & 0 deletions packages/gatekeeper/src/drawbridge-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import {
DrawbridgeInterface,
GatekeeperClientOptions,
LightningBalance,
LightningConfig,
LightningInvoice,
LightningPayment,
LightningPaymentStatus,
} from './types.js';
import GatekeeperClient from './gatekeeper-client.js';

function throwError(error: any): never {
if (error.response) {
throw error.response.data;
}
throw error.message;
}

export default class DrawbridgeClient extends GatekeeperClient implements DrawbridgeInterface {

static override async create(options: GatekeeperClientOptions): Promise<DrawbridgeClient> {
const client = new DrawbridgeClient();
await client.connect(options);
return client;
}

async createLightningWallet(name: string): Promise<LightningConfig> {
try {
const response = await this.axios.post(`${this.API}/lightning/wallet`, { name });
return response.data;
} catch (error) {
throwError(error);
}
}

async getLightningBalance(invoiceKey: string): Promise<LightningBalance> {
try {
const response = await this.axios.post(`${this.API}/lightning/balance`, { invoiceKey });
return response.data;
} catch (error) {
throwError(error);
}
}

async createLightningInvoice(invoiceKey: string, amount: number, memo: string): Promise<LightningInvoice> {
try {
const response = await this.axios.post(`${this.API}/lightning/invoice`, { invoiceKey, amount, memo });
return response.data;
} catch (error) {
throwError(error);
}
}

async payLightningInvoice(adminKey: string, bolt11: string): Promise<LightningPayment> {
try {
const response = await this.axios.post(`${this.API}/lightning/pay`, { adminKey, bolt11 });
return response.data;
} catch (error) {
throwError(error);
}
}

async checkLightningPayment(invoiceKey: string, paymentHash: string): Promise<LightningPaymentStatus> {
try {
const response = await this.axios.post(`${this.API}/lightning/payment`, { invoiceKey, paymentHash });
return response.data;
} catch (error) {
throwError(error);
}
}
}
4 changes: 2 additions & 2 deletions packages/gatekeeper/src/gatekeeper-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ function throwError(error: AxiosError | any): never {
}

export default class GatekeeperClient implements GatekeeperInterface {
private API: string;
private axios: AxiosInstance;
protected API: string;
protected axios: AxiosInstance;

// Factory method
static async create(options: GatekeeperClientOptions): Promise<GatekeeperClient> {
Expand Down
35 changes: 35 additions & 0 deletions packages/gatekeeper/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,41 @@ export interface GatekeeperInterface {
search(query: { where: Record<string, unknown> }): Promise<string[]>;
}

// Lightning types used by DrawbridgeInterface

export interface LightningConfig {
walletId: string;
adminKey: string;
invoiceKey: string;
}

export interface LightningBalance {
balance: number;
}

export interface LightningInvoice {
paymentRequest: string;
paymentHash: string;
}

export interface LightningPayment {
paymentHash: string;
}

export interface LightningPaymentStatus {
paid: boolean;
preimage?: string;
paymentHash: string;
}

export interface DrawbridgeInterface extends GatekeeperInterface {
createLightningWallet(name: string): Promise<LightningConfig>;
getLightningBalance(invoiceKey: string): Promise<LightningBalance>;
createLightningInvoice(invoiceKey: string, amount: number, memo: string): Promise<LightningInvoice>;
payLightningInvoice(adminKey: string, bolt11: string): Promise<LightningPayment>;
checkLightningPayment(invoiceKey: string, paymentHash: string): Promise<LightningPaymentStatus>;
}

export interface DidRegistration {
height?: number;
index?: number;
Expand Down
Loading
Loading