From 7de3c1cf2808c2d03940e1bddc734a4c22ced471 Mon Sep 17 00:00:00 2001 From: Chris Troutner Date: Tue, 24 Mar 2026 19:06:59 -0700 Subject: [PATCH 1/4] fix(Docker): Fixing logging --- package-lock.json | 6 +++--- production/docker/docker-compose.yml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index c935549..7786b19 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15510,9 +15510,9 @@ "license": "MIT" }, "node_modules/typescript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", - "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "license": "Apache-2.0", "peer": true, "bin": { diff --git a/production/docker/docker-compose.yml b/production/docker/docker-compose.yml index 5fe930c..6524137 100644 --- a/production/docker/docker-compose.yml +++ b/production/docker/docker-compose.yml @@ -17,7 +17,7 @@ services: volumes: #- ./start-rest2nostr.sh:/home/safeuser/REST2NOSTR/start-rest2nostr.sh - ./.env:/home/safeuser/.env - - ../data:/home/safeuser/psf-bch-api/production/data - - ../data/logs:/home/safeuser/psf-bch-api/logs + - ../data:/home/safeuser/psf-bch-api-base/production/data + - ../data/logs:/home/safeuser/psf-bch-api-base/logs restart: always From aade1c58f5cc88e54a909695e8bd91dd1e890ce1 Mon Sep 17 00:00:00 2001 From: Chris Troutner Date: Sat, 28 Mar 2026 19:23:10 -0700 Subject: [PATCH 2/4] feat(PSF Liquidity): Off by default, new endpoint reports PSF token price in BCH --- .env-example | 4 + production/docker/.env-example | 4 + src/config/env/common.js | 15 +++ src/controllers/rest-api/price/controller.js | 25 +++++ src/controllers/rest-api/price/router.js | 1 + src/use-cases/price-use-cases.js | 57 +++++++++++ .../unit/controllers/price-controller-unit.js | 39 +++++++- test/unit/use-cases/price-use-cases-unit.js | 96 +++++++++++++++++++ 8 files changed, 240 insertions(+), 1 deletion(-) diff --git a/.env-example b/.env-example index 59b22be..f8e010a 100644 --- a/.env-example +++ b/.env-example @@ -33,3 +33,7 @@ BASIC_AUTH_TOKEN=some-random-token # END ACCESS CONTROL +# PSF token liquidity price proxy (GET /v6/price/psf). Off by default. +#PSF_LIQUIDITY_PROXY_ENABLED=true +#PSF_LIQUIDITY_URL=http://192.168.0.126:5000 + diff --git a/production/docker/.env-example b/production/docker/.env-example index 53488be..12a1d3d 100644 --- a/production/docker/.env-example +++ b/production/docker/.env-example @@ -35,3 +35,7 @@ USE_BASIC_AUTH=false # END ACCESS CONTROL +# PSF token liquidity price proxy (GET /v6/price/psf). Off by default. +#PSF_LIQUIDITY_PROXY_ENABLED=true +#PSF_LIQUIDITY_URL=http://192.168.0.126:5000 + diff --git a/src/config/env/common.js b/src/config/env/common.js index 8e59f86..8bb1d0b 100644 --- a/src/config/env/common.js +++ b/src/config/env/common.js @@ -43,6 +43,19 @@ const basicAuthDefaults = { token: process.env.BASIC_AUTH_TOKEN || '' } +const psfLiquidityUrlEnv = process.env.PSF_LIQUIDITY_URL +const psfLiquidityProxyBaseUrl = + psfLiquidityUrlEnv !== undefined && + psfLiquidityUrlEnv !== null && + String(psfLiquidityUrlEnv).trim() !== '' + ? String(psfLiquidityUrlEnv).trim().replace(/\/$/, '') + : 'http://192.168.0.126:5000' + +const psfLiquidityProxyDefaults = { + enabled: normalizeBoolean(process.env.PSF_LIQUIDITY_PROXY_ENABLED, false), + baseUrl: psfLiquidityProxyBaseUrl +} + export default { // Server port port: parseInt(process.env.PORT, 10) || 5942, @@ -92,6 +105,8 @@ export default { basicAuth: basicAuthDefaults, + psfLiquidityProxy: psfLiquidityProxyDefaults, + // Version version } diff --git a/src/controllers/rest-api/price/controller.js b/src/controllers/rest-api/price/controller.js index 76dd401..192c233 100644 --- a/src/controllers/rest-api/price/controller.js +++ b/src/controllers/rest-api/price/controller.js @@ -26,6 +26,7 @@ class PriceRESTController { this.root = this.root.bind(this) this.getBCHUSD = this.getBCHUSD.bind(this) this.getPsffppWritePrice = this.getPsffppWritePrice.bind(this) + this.getPsfLiquidityPrice = this.getPsfLiquidityPrice.bind(this) this.handleError = this.handleError.bind(this) } @@ -83,6 +84,30 @@ class PriceRESTController { } } + /** + * @api {get} /v6/price/psf PSF token liquidity spot price (proxied) + * @apiName GetPsfLiquidityPrice + * @apiGroup Price + * @apiDescription Proxies GET /price from the PSF token liquidity app when + * `PSF_LIQUIDITY_PROXY_ENABLED` is true. Returns 503 when the proxy is disabled. + * + * @apiExample Example usage: + * curl -X GET "https://api.fullstack.cash/v6/price/psf" -H "accept: application/json" + * + * @apiSuccess {Number} usdPerBCH USD price per 1 BCH + * @apiSuccess {Number} bchBalance BCH balance (liquidity app) + * @apiSuccess {Number} tokenBalance Effective PSF token balance + * @apiSuccess {Number} usdPerToken USD price per 1 PSF token + */ + async getPsfLiquidityPrice (req, res) { + try { + const payload = await this.priceUseCases.getPsfLiquidityPrice() + return res.status(200).json(payload) + } catch (err) { + return this.handleError(err, res) + } + } + handleError (err, res) { wlogger.error('Error in PriceRESTController:', err) diff --git a/src/controllers/rest-api/price/router.js b/src/controllers/rest-api/price/router.js index 65e332d..0372efe 100644 --- a/src/controllers/rest-api/price/router.js +++ b/src/controllers/rest-api/price/router.js @@ -44,6 +44,7 @@ class PriceRouter { this.router.get('/', this.priceController.root) this.router.get('/bchusd', this.priceController.getBCHUSD) this.router.get('/psffpp', this.priceController.getPsffppWritePrice) + this.router.get('/psf', this.priceController.getPsfLiquidityPrice) app.use(this.baseUrl, this.router) } diff --git a/src/use-cases/price-use-cases.js b/src/use-cases/price-use-cases.js index 2bbf4a2..0790988 100644 --- a/src/use-cases/price-use-cases.js +++ b/src/use-cases/price-use-cases.js @@ -28,6 +28,13 @@ class PriceUseCases { // Allow axios to be injected for testing this.axios = localConfig.axios || axios + + this.psfLiquidityPriceKeys = [ + 'usdPerBCH', + 'bchBalance', + 'tokenBalance', + 'usdPerToken' + ] } /** @@ -78,6 +85,56 @@ class PriceUseCases { throw err } } + + /** + * Proxies PSF token liquidity spot price from the token-liquidity app (GET /price). + * @returns {Promise} usdPerBCH, bchBalance, tokenBalance, usdPerToken + */ + async getPsfLiquidityPrice () { + try { + const proxy = this.config.psfLiquidityProxy + if (!proxy || !proxy.enabled) { + const err = new Error('PSF liquidity price proxy is disabled') + err.status = 503 + throw err + } + + const baseUrl = String(proxy.baseUrl).replace(/\/$/, '') + const fullUrl = `${baseUrl}/price` + + const opt = { + method: 'get', + url: fullUrl, + timeout: 15000 + } + + const response = await this.axios.request(opt) + const data = response.data + + if ( + !data || + typeof data !== 'object' || + Array.isArray(data) || + !this.psfLiquidityPriceKeys.every( + (k) => typeof data[k] === 'number' && !Number.isNaN(data[k]) + ) + ) { + const err = new Error('Invalid response from PSF liquidity price service') + err.status = 502 + throw err + } + + return { + usdPerBCH: data.usdPerBCH, + bchBalance: data.bchBalance, + tokenBalance: data.tokenBalance, + usdPerToken: data.usdPerToken + } + } catch (err) { + wlogger.error('Error in PriceUseCases.getPsfLiquidityPrice()', err) + throw err + } + } } export default PriceUseCases diff --git a/test/unit/controllers/price-controller-unit.js b/test/unit/controllers/price-controller-unit.js index 68e046f..a6bc02c 100644 --- a/test/unit/controllers/price-controller-unit.js +++ b/test/unit/controllers/price-controller-unit.js @@ -20,7 +20,13 @@ describe('#price-controller.js', () => { mockUseCases = { price: { getBCHUSD: sandbox.stub().resolves(250.5), - getPsffppWritePrice: sandbox.stub().resolves(0.08335233) + getPsffppWritePrice: sandbox.stub().resolves(0.08335233), + getPsfLiquidityPrice: sandbox.stub().resolves({ + usdPerBCH: 483.1, + bchBalance: 25.65337297, + tokenBalance: 39590.96686314, + usdPerToken: 0.50532753 + }) } } @@ -113,4 +119,35 @@ describe('#price-controller.js', () => { assert.deepEqual(res.jsonData, { error: 'PSFFPP failure' }) }) }) + + describe('#getPsfLiquidityPrice()', () => { + it('should return PSF liquidity price payload on success', async () => { + const req = createMockRequest() + const res = createMockResponse() + + await uut.getPsfLiquidityPrice(req, res) + + assert.equal(res.statusValue, 200) + assert.deepEqual(res.jsonData, { + usdPerBCH: 483.1, + bchBalance: 25.65337297, + tokenBalance: 39590.96686314, + usdPerToken: 0.50532753 + }) + assert.isTrue(mockUseCases.price.getPsfLiquidityPrice.calledOnce) + }) + + it('should handle errors via handleError', async () => { + const error = new Error('proxy off') + error.status = 503 + mockUseCases.price.getPsfLiquidityPrice.rejects(error) + const req = createMockRequest() + const res = createMockResponse() + + await uut.getPsfLiquidityPrice(req, res) + + assert.equal(res.statusValue, 503) + assert.deepEqual(res.jsonData, { error: 'proxy off' }) + }) + }) }) diff --git a/test/unit/use-cases/price-use-cases-unit.js b/test/unit/use-cases/price-use-cases-unit.js index cf0f30a..f0c36b2 100644 --- a/test/unit/use-cases/price-use-cases-unit.js +++ b/test/unit/use-cases/price-use-cases-unit.js @@ -83,6 +83,102 @@ describe('#price-use-cases.js', () => { }) }) + describe('#getPsfLiquidityPrice()', () => { + const validBody = { + usdPerBCH: 483.1, + bchBalance: 25.65337297, + tokenBalance: 39590.96686314, + usdPerToken: 0.50532753 + } + + it('should reject with 503 when proxy config is missing', async () => { + try { + await uut.getPsfLiquidityPrice() + assert.fail('Should have thrown an error') + } catch (err) { + assert.equal(err.status, 503) + assert.include(err.message, 'disabled') + } + }) + + it('should reject with 503 when proxy is disabled', async () => { + mockConfig.psfLiquidityProxy = { + enabled: false, + baseUrl: 'http://192.168.0.126:5000' + } + + try { + await uut.getPsfLiquidityPrice() + assert.fail('Should have thrown an error') + } catch (err) { + assert.equal(err.status, 503) + assert.include(err.message, 'disabled') + } + }) + + it('should return payload when enabled and upstream returns valid JSON', async () => { + mockConfig.psfLiquidityProxy = { + enabled: true, + baseUrl: 'http://192.168.0.126:5000' + } + mockAxios.request.resolves({ data: { ...validBody } }) + + const result = await uut.getPsfLiquidityPrice() + + assert.deepEqual(result, validBody) + assert.isTrue(mockAxios.request.calledOnce) + const callArgs = mockAxios.request.getCall(0).args[0] + assert.equal(callArgs.method, 'get') + assert.equal(callArgs.url, 'http://192.168.0.126:5000/price') + assert.equal(callArgs.timeout, 15000) + }) + + it('should normalize base URL trailing slash before /price', async () => { + mockConfig.psfLiquidityProxy = { + enabled: true, + baseUrl: 'http://example.com:5000/' + } + mockAxios.request.resolves({ data: { ...validBody } }) + + await uut.getPsfLiquidityPrice() + + const callArgs = mockAxios.request.getCall(0).args[0] + assert.equal(callArgs.url, 'http://example.com:5000/price') + }) + + it('should reject with 502 when upstream body is invalid', async () => { + mockConfig.psfLiquidityProxy = { + enabled: true, + baseUrl: 'http://192.168.0.126:5000' + } + mockAxios.request.resolves({ data: { usdPerBCH: 'not-a-number' } }) + + try { + await uut.getPsfLiquidityPrice() + assert.fail('Should have thrown an error') + } catch (err) { + assert.equal(err.status, 502) + assert.include(err.message, 'Invalid response') + } + }) + + it('should propagate axios errors', async () => { + mockConfig.psfLiquidityProxy = { + enabled: true, + baseUrl: 'http://192.168.0.126:5000' + } + const error = new Error('network down') + mockAxios.request.rejects(error) + + try { + await uut.getPsfLiquidityPrice() + assert.fail('Should have thrown an error') + } catch (err) { + assert.equal(err.message, 'network down') + } + }) + }) + describe('#getPsffppWritePrice()', () => { it('should handle errors properly', async () => { // Note: Full unit testing of getPsffppWritePrice is difficult due to dynamic imports From 5d77880a0e5120c481b87be7f78ae77b3428098c Mon Sep 17 00:00:00 2001 From: Chris Troutner Date: Wed, 1 Apr 2026 08:36:47 -0700 Subject: [PATCH 3/4] fix(x402 docs): Adding common LLM discovery documentation --- .env-example | 2 + README.md | 16 ++ bin/server.js | 3 + dev-docs/update-logs/2026-04-01.md | 72 ++++++ package.json | 2 + scripts/build-discovery-artifacts.js | 21 ++ src/controllers/discovery/controller.js | 152 ++++++++++++ src/controllers/discovery/router.js | 30 +++ src/discovery/build-documents.js | 223 ++++++++++++++++++ .../controllers/discovery-controller-unit.js | 106 +++++++++ .../controllers/discovery-documents-unit.js | 25 ++ .../unit/controllers/discovery-router-unit.js | 43 ++++ 12 files changed, 695 insertions(+) create mode 100644 dev-docs/update-logs/2026-04-01.md create mode 100644 scripts/build-discovery-artifacts.js create mode 100644 src/controllers/discovery/controller.js create mode 100644 src/controllers/discovery/router.js create mode 100644 src/discovery/build-documents.js create mode 100644 test/unit/controllers/discovery-controller-unit.js create mode 100644 test/unit/controllers/discovery-documents-unit.js create mode 100644 test/unit/controllers/discovery-router-unit.js diff --git a/.env-example b/.env-example index f8e010a..921a806 100644 --- a/.env-example +++ b/.env-example @@ -23,6 +23,8 @@ PORT=5942 # x402 payments required to access this API? X402_ENABLED=true +# Also gates discovery endpoints: +# /.well-known/x402, /openapi.json, /swagger.json, /llms.txt, /.well-known/agent.json SERVER_BCH_ADDRESS=bitcoincash:qqlrzp23w08434twmvr4fxw672whkjy0py26r63g3d FACILITATOR_URL=http://localhost:4345/facilitator X402_PRICE_SAT=200 diff --git a/README.md b/README.md index 790c23f..a51a7fc 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,16 @@ Every API call under the `/v6` prefix requires a BCH micro-payment. When a reque This is the right choice for **public, monetized APIs** where you want to charge per call. +When `X402_ENABLED=true`, the server also exposes machine-discovery endpoints: + +- `/.well-known/x402` - x402-bch v2 payment discovery manifest +- `/openapi.json` - OpenAPI 3 projection generated from apiDoc annotations +- `/swagger.json` - Swagger 2.0 compatibility projection +- `/llms.txt` - LLM-oriented markdown index of service metadata +- `/.well-known/agent.json` - draft agent manifest describing API actions + +When `X402_ENABLED=false`, these discovery endpoints return `404`. + #### Combined: x402 + Bearer Token You can enable both at the same time: @@ -147,6 +157,12 @@ The API reference documentation is generated by [apiDoc](https://apidocjs.com/) The output is written to the `docs/` directory and served by the running server at its root URL. +To regenerate API docs plus discovery artifacts (`openapi.json`, `swagger.json`, `llms.txt`, and `agent.json` payload source): + +`npm run docs:all` + +This runs apiDoc first, then generates `docs/discovery-artifacts.json` from the same annotation source. + A live version can be found at [bch.fullstack.cash](https://bch.fullstack.cash/). ## Production (Docker) diff --git a/bin/server.js b/bin/server.js index 63a1643..3efa974 100644 --- a/bin/server.js +++ b/bin/server.js @@ -17,6 +17,7 @@ import Controllers from '../src/controllers/index.js' import wlogger from '../src/adapters/wlogger.js' import { buildX402Routes, getX402Settings, getBasicAuthSettings } from '../src/config/x402.js' import { basicAuthMiddleware } from '../src/middleware/basic-auth.js' +import DiscoveryRouter from '../src/controllers/discovery/router.js' // Load environment variables dotenv.config() @@ -216,6 +217,8 @@ class Server { // Attach REST API controllers to the app. this.controllers.attachRESTControllers(app) + const discoveryRouter = new DiscoveryRouter() + discoveryRouter.attach(app) // Initialize any other controller libraries. this.controllers.initControllers() diff --git a/dev-docs/update-logs/2026-04-01.md b/dev-docs/update-logs/2026-04-01.md new file mode 100644 index 0000000..b9f2285 --- /dev/null +++ b/dev-docs/update-logs/2026-04-01.md @@ -0,0 +1,72 @@ +# 2026-04-01 Update Log + +## Summary + +Added x402-gated discovery endpoints for agent/tool self-discovery, built a docs-derived artifact pipeline from apiDoc annotations, and documented the new flow and behavior. + +## Changes Made + +- Added new discovery controller/router: + - `src/controllers/discovery/controller.js` + - `src/controllers/discovery/router.js` +- Added five root-path discovery endpoints: + - `GET /.well-known/x402` + - `GET /openapi.json` + - `GET /swagger.json` + - `GET /llms.txt` + - `GET /.well-known/agent.json` +- Added x402-enabled gating: + - All five endpoints now return `404` when `X402_ENABLED=false`. + - When enabled, payloads are returned with x402-bch v2-oriented metadata. +- Added apiDoc-derived document builder: + - `src/discovery/build-documents.js` + - Parses `@api` annotations and builds OpenAPI, Swagger, llms, and agent documents. + - Uses `docs/discovery-artifacts.json` if present, otherwise builds in-process. +- Added artifact generation script: + - `scripts/build-discovery-artifacts.js` + - Writes `docs/discovery-artifacts.json` +- Updated npm scripts in `package.json`: + - `docs:discovery` + - `docs:all` (runs `docs` then `docs:discovery`) +- Wired discovery routes into server bootstrap: + - `bin/server.js` +- Added tests: + - `test/unit/controllers/discovery-controller-unit.js` + - `test/unit/controllers/discovery-router-unit.js` + - `test/unit/controllers/discovery-documents-unit.js` +- Updated docs/config examples: + - `README.md` (discovery endpoints + docs workflow) + - `.env-example` (x402 gating note for discovery endpoints) + +## Why This Was Changed + +- Endpoint probes for discovery paths are common from API tooling and AI agents. +- Serving structured discovery metadata improves machine interoperability for: + - API clients and SDK tooling (`openapi.json`, `swagger.json`) + - LLM retrieval workflows (`llms.txt`) + - Agent capability discovery (`agent.json`) + - x402 payment discovery (`/.well-known/x402`) +- Gating by `X402_ENABLED` keeps discovery aligned with monetization mode and avoids advertising payment surfaces when x402 is disabled. + +## Validation Notes + +- Lint passed. +- New discovery-focused unit tests passed. +- Full `npm test` run showed one pre-existing timeout failure in `test/unit/use-cases/price-use-cases-unit.js` unrelated to discovery endpoint changes. + +## References + +- Local protocol spec: + - `../x402-bch/specs/x402-bch-specification-v2.2.md` +- OpenAPI Specification: + - https://spec.openapis.org/oas/latest.html +- Swagger / OpenAPI 2.0: + - https://swagger.io/specification/v2/ +- llms.txt proposal: + - https://www.llmstxt.org/index.html +- Agent manifest draft reference: + - https://agentwebprotocol.org/spec +- x402 HTTP 402 background: + - https://docs.x402.org/core-concepts/http-402 +- x402 DNS discovery draft: + - https://www.ietf.org/archive/id/draft-jeftovic-x402-dns-discovery-00.html diff --git a/package.json b/package.json index 684ac12..1898bdf 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,8 @@ "scripts": { "start": "node bin/server.js", "docs": "./node_modules/.bin/apidoc -i src/ -o docs", + "docs:discovery": "node scripts/build-discovery-artifacts.js", + "docs:all": "npm run docs && npm run docs:discovery", "lint": "standard --env mocha --fix", "test": "npm run lint && TEST=unit c8 mocha 'test/unit/**/*.js' --exit", "test:integration": "mocha --timeout 25000 'test/integration/**/*.js' --exit", diff --git a/scripts/build-discovery-artifacts.js b/scripts/build-discovery-artifacts.js new file mode 100644 index 0000000..1005186 --- /dev/null +++ b/scripts/build-discovery-artifacts.js @@ -0,0 +1,21 @@ +/* + Build discovery endpoint artifacts from apiDoc source annotations. +*/ + +import { mkdirSync, writeFileSync } from 'fs' +import { dirname, resolve } from 'path' + +import { buildDiscoveryDocuments } from '../src/discovery/build-documents.js' + +function main () { + const outputPath = resolve(process.cwd(), 'docs/discovery-artifacts.json') + const docs = buildDiscoveryDocuments() + + mkdirSync(dirname(outputPath), { recursive: true }) + writeFileSync(outputPath, `${JSON.stringify(docs, null, 2)}\n`) + + // eslint-disable-next-line no-console + console.log(`Wrote discovery artifacts to ${outputPath}`) +} + +main() diff --git a/src/controllers/discovery/controller.js b/src/controllers/discovery/controller.js new file mode 100644 index 0000000..f5605cf --- /dev/null +++ b/src/controllers/discovery/controller.js @@ -0,0 +1,152 @@ +/* + Controller for discovery and machine-readable metadata endpoints. +*/ + +import config from '../../config/index.js' +import { getX402Settings } from '../../config/x402.js' +import { getDiscoveryDocuments } from '../../discovery/build-documents.js' + +const BCH_MAINNET_CAIP2 = 'bip122:000000000000000000651ef99cb9fcbe' +const BCH_NATIVE_ASSET = '0x0000000000000000000000000000000000000001' +const X402_TIMEOUT_SECONDS = 60 + +class DiscoveryController { + constructor (localConfig = {}) { + this.getX402Settings = localConfig.getX402Settings || getX402Settings + this.getDiscoveryDocuments = localConfig.getDiscoveryDocuments || getDiscoveryDocuments + this.apiPrefix = localConfig.apiPrefix || config.apiPrefix + + this.x402Manifest = this.x402Manifest.bind(this) + this.openapi = this.openapi.bind(this) + this.swagger = this.swagger.bind(this) + this.llmsTxt = this.llmsTxt.bind(this) + this.agentManifest = this.agentManifest.bind(this) + this.respondNotFoundWhenDisabled = this.respondNotFoundWhenDisabled.bind(this) + this.sendText = this.sendText.bind(this) + } + + respondNotFoundWhenDisabled (res) { + const { enabled } = this.getX402Settings() + if (enabled) return false + + res.status(404).json({ + error: 'Not found' + }) + return true + } + + /** + * @api {get} /.well-known/x402 x402-bch resource discovery + * @apiName X402Discovery + * @apiGroup Discovery + * @apiDescription Returns x402-bch v2 resource and payment requirement metadata. + */ + x402Manifest (req, res) { + if (this.respondNotFoundWhenDisabled(res)) return + + const x402 = this.getX402Settings() + const apiPrefix = this.apiPrefix || '/v6' + const prefixWithSlash = apiPrefix.startsWith('/') ? apiPrefix : `/${apiPrefix}` + + const payload = { + x402Version: 2, + network: BCH_MAINNET_CAIP2, + facilitator: { + url: x402.facilitatorUrl + }, + resources: [ + { + resource: `${prefixWithSlash}/*`, + type: 'http', + x402Version: 2, + accepts: [ + { + scheme: 'utxo', + network: BCH_MAINNET_CAIP2, + amount: String(x402.priceSat), + description: `Access to protected psf-bch-api resources (${x402.priceSat} satoshis)`, + mimeType: 'application/json', + payTo: x402.serverAddress, + maxTimeoutSeconds: X402_TIMEOUT_SECONDS, + asset: BCH_NATIVE_ASSET, + extra: {} + } + ] + } + ] + } + + return res.status(200).json(payload) + } + + /** + * @api {get} /openapi.json OpenAPI discovery document + * @apiName OpenApiDiscovery + * @apiGroup Discovery + * @apiDescription Returns an OpenAPI document generated from apiDoc annotations. + */ + openapi (req, res) { + if (this.respondNotFoundWhenDisabled(res)) return + + const docs = this.getDiscoveryDocuments() + return res.status(200).json(docs.openapi) + } + + /** + * @api {get} /swagger.json Swagger discovery document + * @apiName SwaggerDiscovery + * @apiGroup Discovery + * @apiDescription Returns a Swagger 2.0 compatibility document generated from apiDoc annotations. + */ + swagger (req, res) { + if (this.respondNotFoundWhenDisabled(res)) return + + const docs = this.getDiscoveryDocuments() + return res.status(200).json(docs.swagger) + } + + /** + * @api {get} /llms.txt LLM discovery file + * @apiName LlmsDiscovery + * @apiGroup Discovery + * @apiDescription Returns an llms.txt markdown index for AI tooling discovery. + */ + llmsTxt (req, res) { + if (this.respondNotFoundWhenDisabled(res)) return + + const docs = this.getDiscoveryDocuments() + return this.sendText(res, docs.llms) + } + + /** + * @api {get} /.well-known/agent.json Agent manifest + * @apiName AgentManifestDiscovery + * @apiGroup Discovery + * @apiDescription Returns a draft agent manifest describing API capabilities. + */ + agentManifest (req, res) { + if (this.respondNotFoundWhenDisabled(res)) return + + const docs = this.getDiscoveryDocuments() + return res.status(200).json(docs.agent) + } + + sendText (res, text) { + res.status(200) + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + + if (typeof res.send === 'function') { + return res.send(text) + } + + if (typeof res.write === 'function') { + res.write(text) + } + if (typeof res.end === 'function') { + res.end() + } + return res + } +} + +export default DiscoveryController diff --git a/src/controllers/discovery/router.js b/src/controllers/discovery/router.js new file mode 100644 index 0000000..ea7918a --- /dev/null +++ b/src/controllers/discovery/router.js @@ -0,0 +1,30 @@ +/* + Router for discovery and machine-readable metadata endpoints. +*/ + +import express from 'express' +import DiscoveryController from './controller.js' + +class DiscoveryRouter { + constructor (localConfig = {}) { + this.controller = localConfig.controller || new DiscoveryController() + this.router = express.Router() + this.attach = this.attach.bind(this) + } + + attach (app) { + if (!app) { + throw new Error('Must pass app object when attaching DiscoveryRouter.') + } + + this.router.get('/.well-known/x402', this.controller.x402Manifest) + this.router.get('/openapi.json', this.controller.openapi) + this.router.get('/swagger.json', this.controller.swagger) + this.router.get('/llms.txt', this.controller.llmsTxt) + this.router.get('/.well-known/agent.json', this.controller.agentManifest) + + app.use(this.router) + } +} + +export default DiscoveryRouter diff --git a/src/discovery/build-documents.js b/src/discovery/build-documents.js new file mode 100644 index 0000000..7bf5ed0 --- /dev/null +++ b/src/discovery/build-documents.js @@ -0,0 +1,223 @@ +/* + Build and cache discovery documents from apiDoc-style annotations. +*/ + +import { readFileSync, existsSync, readdirSync } from 'fs' +import { resolve } from 'path' + +import config from '../config/index.js' +import { getX402Settings } from '../config/x402.js' + +const BCH_MAINNET_CAIP2 = 'bip122:000000000000000000651ef99cb9fcbe' +const X402_SPEC_VERSION = 2 + +let cachedDocs = null + +function parseApiAnnotations () { + const srcRoot = resolve(process.cwd(), 'src/controllers/rest-api') + const entries = [] + const files = walkJsFiles(srcRoot) + + for (const file of files) { + const text = readFileSync(file, 'utf8') + const blocks = text.match(/\/\*\*[\s\S]*?\*\//g) || [] + + for (const block of blocks) { + const endpoint = parseBlock(block) + if (endpoint) entries.push(endpoint) + } + } + + return entries +} + +function parseBlock (block) { + const methodMatch = block.match(/@api\s+\{([^}]+)\}\s+(\S+)\s+([^\n\r*]+)/) + if (!methodMatch) return null + + const method = methodMatch[1].trim().toUpperCase() + const path = methodMatch[2].trim() + const summary = methodMatch[3].trim() + + const groupMatch = block.match(/@apiGroup\s+([^\n\r*]+)/) + const descriptionMatch = block.match(/@apiDescription\s+([^\n\r*][\s\S]*?)(?=\n\s*\*\s*@api|\n\s*\*\/)/) + const apiNameMatch = block.match(/@apiName\s+([^\n\r*]+)/) + + return { + method, + path, + summary, + group: groupMatch ? groupMatch[1].trim() : 'General', + operationId: apiNameMatch ? apiNameMatch[1].trim() : `${method.toLowerCase()}_${path.replace(/[^\w]/g, '_')}`, + description: descriptionMatch + ? descriptionMatch[1].replace(/\n\s*\*\s?/g, ' ').trim() + : summary + } +} + +function walkJsFiles (dir) { + const output = [] + + for (const item of readdirSync(dir, { withFileTypes: true })) { + const fullPath = resolve(dir, item.name) + if (item.isDirectory()) { + output.push(...walkJsFiles(fullPath)) + continue + } + + if (item.isFile() && fullPath.endsWith('.js')) output.push(fullPath) + } + + return output +} + +function normalizePaths (endpoints) { + const paths = {} + + for (const endpoint of endpoints) { + if (!paths[endpoint.path]) paths[endpoint.path] = {} + + const op = { + tags: [endpoint.group], + summary: endpoint.summary, + description: endpoint.description, + operationId: endpoint.operationId, + responses: { + 200: { + description: 'Successful response' + }, + 402: { + description: 'Payment required when x402 is enabled' + } + }, + 'x-payment-model': 'x402-bch-v2' + } + + paths[endpoint.path][endpoint.method.toLowerCase()] = op + } + + return paths +} + +function buildOpenApi (paths) { + return { + openapi: '3.0.3', + info: { + title: 'psf-bch-api', + version: config.version, + description: 'OpenAPI projection generated from apiDoc annotations' + }, + servers: [ + { + url: '/' + } + ], + paths + } +} + +function buildSwagger (paths) { + return { + swagger: '2.0', + info: { + title: 'psf-bch-api', + version: config.version, + description: 'Swagger projection generated from apiDoc annotations' + }, + basePath: '/', + schemes: ['https', 'http'], + paths + } +} + +function buildLlms (endpoints) { + const lines = [ + '# psf-bch-api', + '', + '> REST API proxy to Bitcoin Cash infrastructure with optional x402-bch monetized access.', + '', + '## Discovery', + '- [OpenAPI document](/openapi.json): OpenAPI 3 projection generated from apiDoc annotations.', + '- [Swagger document](/swagger.json): Swagger 2.0 compatibility projection.', + '- [x402 manifest](/.well-known/x402): x402-bch v2 payment requirement discovery.', + '- [Agent manifest](/.well-known/agent.json): draft agent capability surface.', + '', + '## API Groups' + ] + + const seen = new Set() + for (const endpoint of endpoints) { + if (seen.has(endpoint.group)) continue + seen.add(endpoint.group) + lines.push(`- ${endpoint.group}`) + } + + lines.push('', '## Optional', '- [Human docs](/): apiDoc HTML documentation root.') + return lines.join('\n') +} + +function buildAgent (endpoints) { + const x402 = getX402Settings() + const actions = endpoints.map(endpoint => ({ + id: endpoint.operationId, + description: endpoint.summary, + auth_required: true, + endpoint: endpoint.path, + method: endpoint.method + })) + + return { + awp_version: '0.1', + domain: 'localhost', + intent: 'Programmatic BCH blockchain API access', + capabilities: { + batch_actions: false, + streaming: false + }, + auth: { + type: 'x402-bch-v2', + required_for: actions.map(a => a.id), + pricing: { + amountSat: String(x402.priceSat), + payTo: x402.serverAddress, + network: BCH_MAINNET_CAIP2, + x402Version: X402_SPEC_VERSION + } + }, + actions + } +} + +export function buildDiscoveryDocuments () { + const endpoints = parseApiAnnotations() + const paths = normalizePaths(endpoints) + + return { + openapi: buildOpenApi(paths), + swagger: buildSwagger(paths), + llms: buildLlms(endpoints), + agent: buildAgent(endpoints) + } +} + +export function getDiscoveryDocuments () { + if (cachedDocs) return cachedDocs + + const artifactPath = resolve(process.cwd(), 'docs/discovery-artifacts.json') + if (existsSync(artifactPath)) { + try { + cachedDocs = JSON.parse(readFileSync(artifactPath, 'utf8')) + return cachedDocs + } catch { + cachedDocs = buildDiscoveryDocuments() + return cachedDocs + } + } + + cachedDocs = buildDiscoveryDocuments() + return cachedDocs +} + +export function resetDiscoveryDocumentCache () { + cachedDocs = null +} diff --git a/test/unit/controllers/discovery-controller-unit.js b/test/unit/controllers/discovery-controller-unit.js new file mode 100644 index 0000000..834cec1 --- /dev/null +++ b/test/unit/controllers/discovery-controller-unit.js @@ -0,0 +1,106 @@ +/* + Unit tests for DiscoveryController. +*/ + +import { assert } from 'chai' + +import DiscoveryController from '../../../src/controllers/discovery/controller.js' +import { createMockRequest, createMockResponse } from '../mocks/controller-mocks.js' + +describe('#discovery-controller.js', () => { + const makeController = ({ enabled = true } = {}) => { + return new DiscoveryController({ + apiPrefix: '/v6', + getX402Settings: () => ({ + enabled, + facilitatorUrl: 'http://localhost:4345/facilitator', + serverAddress: 'bitcoincash:qtestaddress', + priceSat: 200 + }), + getDiscoveryDocuments: () => ({ + openapi: { openapi: '3.0.3', paths: { '/v6/price/bchusd': {} } }, + swagger: { swagger: '2.0', paths: { '/v6/price/bchusd': {} } }, + llms: '# psf-bch-api', + agent: { awp_version: '0.1', actions: [] } + }) + }) + } + + describe('x402 disabled gating', () => { + it('should return 404 for all discovery endpoints when x402 disabled', async () => { + const uut = makeController({ enabled: false }) + const req = createMockRequest() + + const handlers = [ + uut.x402Manifest, + uut.openapi, + uut.swagger, + uut.llmsTxt, + uut.agentManifest + ] + + for (const handler of handlers) { + const res = createMockResponse() + await handler(req, res) + assert.equal(res.statusValue, 404) + assert.deepEqual(res.jsonData, { error: 'Not found' }) + } + }) + }) + + describe('x402 enabled responses', () => { + it('should return x402 manifest schema fields', async () => { + const uut = makeController({ enabled: true }) + const req = createMockRequest() + const res = createMockResponse() + + await uut.x402Manifest(req, res) + + assert.equal(res.statusValue, 200) + assert.equal(res.jsonData.x402Version, 2) + assert.isArray(res.jsonData.resources) + assert.equal(res.jsonData.resources[0].accepts[0].scheme, 'utxo') + assert.equal(res.jsonData.resources[0].accepts[0].amount, '200') + }) + + it('should return openapi and swagger docs', async () => { + const uut = makeController({ enabled: true }) + const req = createMockRequest() + + const openapiRes = createMockResponse() + await uut.openapi(req, openapiRes) + assert.equal(openapiRes.statusValue, 200) + assert.equal(openapiRes.jsonData.openapi, '3.0.3') + + const swaggerRes = createMockResponse() + await uut.swagger(req, swaggerRes) + assert.equal(swaggerRes.statusValue, 200) + assert.equal(swaggerRes.jsonData.swagger, '2.0') + }) + + it('should return llms.txt as text/plain', async () => { + const uut = makeController({ enabled: true }) + const req = createMockRequest() + const res = createMockResponse() + + await uut.llmsTxt(req, res) + + assert.equal(res.statusValue, 200) + assert.equal(res.headers['Content-Type'], 'text/plain; charset=utf-8') + assert.equal(res.writeData[0], '# psf-bch-api') + assert.isTrue(res.endCalled) + }) + + it('should return agent manifest json', async () => { + const uut = makeController({ enabled: true }) + const req = createMockRequest() + const res = createMockResponse() + + await uut.agentManifest(req, res) + + assert.equal(res.statusValue, 200) + assert.equal(res.jsonData.awp_version, '0.1') + assert.isArray(res.jsonData.actions) + }) + }) +}) diff --git a/test/unit/controllers/discovery-documents-unit.js b/test/unit/controllers/discovery-documents-unit.js new file mode 100644 index 0000000..4d80a92 --- /dev/null +++ b/test/unit/controllers/discovery-documents-unit.js @@ -0,0 +1,25 @@ +/* + Unit tests for discovery document builder. +*/ + +import { assert } from 'chai' + +import { buildDiscoveryDocuments } from '../../../src/discovery/build-documents.js' + +describe('#discovery-build-documents.js', () => { + it('should build openapi and swagger documents with v6 paths', () => { + const docs = buildDiscoveryDocuments() + + assert.property(docs, 'openapi') + assert.property(docs, 'swagger') + assert.property(docs, 'llms') + assert.property(docs, 'agent') + + assert.isString(docs.openapi.openapi) + assert.equal(docs.swagger.swagger, '2.0') + assert.isAbove(Object.keys(docs.openapi.paths).length, 0) + + const hasV6Path = Object.keys(docs.openapi.paths).some(path => path.startsWith('/v6/')) + assert.isTrue(hasV6Path) + }) +}) diff --git a/test/unit/controllers/discovery-router-unit.js b/test/unit/controllers/discovery-router-unit.js new file mode 100644 index 0000000..b682f7c --- /dev/null +++ b/test/unit/controllers/discovery-router-unit.js @@ -0,0 +1,43 @@ +/* + Unit tests for DiscoveryRouter. +*/ + +import { assert } from 'chai' + +import DiscoveryRouter from '../../../src/controllers/discovery/router.js' + +describe('#discovery-router.js', () => { + it('should require app object in attach()', () => { + const uut = new DiscoveryRouter() + assert.throws(() => uut.attach(), /Must pass app object/) + }) + + it('should register all discovery routes', () => { + const calls = [] + const app = { + use: () => {} + } + + const mockRouter = { + get: (path, handler) => calls.push({ path, handler }) + } + + const mockController = { + x402Manifest: () => {}, + openapi: () => {}, + swagger: () => {}, + llmsTxt: () => {}, + agentManifest: () => {} + } + + const uut = new DiscoveryRouter({ controller: mockController }) + uut.router = mockRouter + uut.attach(app) + + assert.equal(calls.length, 5) + assert.deepEqual( + calls.map(x => x.path), + ['/.well-known/x402', '/openapi.json', '/swagger.json', '/llms.txt', '/.well-known/agent.json'] + ) + }) +}) From 67b141fc037bc3c011c6667505f0b44b50a3aa2d Mon Sep 17 00:00:00 2001 From: Chris Troutner Date: Wed, 1 Apr 2026 08:57:10 -0700 Subject: [PATCH 4/4] fix(Docker): Can change URL in api docs --- .env-example | 3 ++ README.md | 2 ++ dev-docs/update-logs/2026-04-02.md | 19 +++++++++++++ production/docker/.env-example | 4 +++ production/docker/Dockerfile | 12 ++++---- production/docker/docker-compose.yml | 6 ++-- production/docker/entrypoint.sh | 10 +++++++ scripts/patch-apidoc-from-env.js | 41 ++++++++++++++++++++++++++++ 8 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 dev-docs/update-logs/2026-04-02.md create mode 100644 production/docker/entrypoint.sh create mode 100644 scripts/patch-apidoc-from-env.js diff --git a/.env-example b/.env-example index 921a806..33dc0ed 100644 --- a/.env-example +++ b/.env-example @@ -16,6 +16,9 @@ LOCAL_RESTURL=http://localhost:5942/v6 # END INFRASTRUCTURE SETUP +# Public base URL for apiDoc HTML (optional; used by Docker entrypoint before `npm run docs`). +#APIDOC_URL=https://api.example.com + # START ACCESS CONTROL diff --git a/README.md b/README.md index a51a7fc..dc3e8e2 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,8 @@ FULCRUM_API=http://172.17.0.1:3001/v1 SLP_INDEXER_API=http://172.17.0.1:5010 ``` +Set `APIDOC_URL` to the public base URL for your deployment (for example `https://api.example.com` or your subdomain). The container entrypoint applies this value to `apidoc.json` and the `apidoc` section of `package.json`, then runs `npm run docs` before starting the server so generated HTML matches each instance. The compose file mounts `./.env` to `/home/safeuser/psf-bch-api/.env` so it matches `dotenv.config()` in the app. + 4. Build the Docker image: `docker-compose build --no-cache` diff --git a/dev-docs/update-logs/2026-04-02.md b/dev-docs/update-logs/2026-04-02.md new file mode 100644 index 0000000..cd40bd5 --- /dev/null +++ b/dev-docs/update-logs/2026-04-02.md @@ -0,0 +1,19 @@ +# 2026-04-02 Update Log + +## Summary + +Docker deployments now run `npm run docs` at container start via an entrypoint script, and optionally apply `APIDOC_URL` from the environment so apiDoc HTML matches each deployment subdomain or public URL. + +## Changes Made + +- Added `scripts/patch-apidoc-from-env.js` to set `apidoc.json` and `package.json` `apidoc.url` from `APIDOC_URL` (dotenv loads the project `.env`, same path as `bin/server.js`). +- Added `production/docker/entrypoint.sh` to run the patch script, `npm run docs`, then `exec npm start`. +- Updated `production/docker/Dockerfile` to remove build-time `npm run docs`, copy the entrypoint and patch script from the build context, and use `ENTRYPOINT` for the shell script. +- Updated `production/docker/docker-compose.yml` to use build `context: ../..` and `dockerfile: production/docker/Dockerfile` so COPY paths resolve from the repository root. +- Compose mounts `./.env` at `/home/safeuser/psf-bch-api/.env` so the app and entrypoint share one file (not `/home/safeuser/.env`). +- Documented `APIDOC_URL` in `.env-example`, `production/docker/.env-example`, and `README.md` (Production Docker section). + +## Outcome + +- Operators can set `APIDOC_URL` in the mounted `.env` (for example `https://api.example.com`) per instance without rebuilding the image for each subdomain. +- The HTML apiDoc bundle is regenerated on every container start so it stays aligned with the configured URL. diff --git a/production/docker/.env-example b/production/docker/.env-example index 12a1d3d..e8dd3f7 100644 --- a/production/docker/.env-example +++ b/production/docker/.env-example @@ -16,6 +16,10 @@ LOCAL_RESTURL=http://172.17.0.1:5942/v6 # END INFRASTRUCTURE SETUP +# Public base URL for apiDoc HTML (set per deployment / subdomain). +# Applied at container start before `npm run docs`. Example: https://api.example.com +#APIDOC_URL=https://api.example.com + # START ACCESS CONTROL diff --git a/production/docker/Dockerfile b/production/docker/Dockerfile index b445ac5..c151d16 100644 --- a/production/docker/Dockerfile +++ b/production/docker/Dockerfile @@ -57,13 +57,15 @@ RUN git checkout ct-unstable RUN npm install RUN npm install minimal-slp-wallet -# Generate the API docs -RUN npm run docs +# Runtime entrypoint + apidoc URL patch (see production/docker/entrypoint.sh). +# API docs are generated at container start so APIDOC_URL can be set per deployment. +COPY production/docker/entrypoint.sh /home/safeuser/psf-bch-api/entrypoint.sh +COPY scripts/patch-apidoc-from-env.js /home/safeuser/psf-bch-api/scripts/patch-apidoc-from-env.js +RUN chmod +x /home/safeuser/psf-bch-api/entrypoint.sh -COPY .env .env +# Runtime `.env` is provided by docker-compose (mount at psf-bch-api/.env), not baked into the image. - -CMD ["npm", "start"] +ENTRYPOINT ["/home/safeuser/psf-bch-api/entrypoint.sh"] # Used to debug the container. #COPY temp.js temp.js diff --git a/production/docker/docker-compose.yml b/production/docker/docker-compose.yml index 0bca108..f1d8317 100644 --- a/production/docker/docker-compose.yml +++ b/production/docker/docker-compose.yml @@ -2,7 +2,9 @@ services: psf-bch-api: - build: . + build: + context: ../.. + dockerfile: production/docker/Dockerfile container_name: psf-bch-api logging: driver: 'json-file' @@ -16,7 +18,7 @@ services: - '5942:5942' # : volumes: #- ./start-rest2nostr.sh:/home/safeuser/REST2NOSTR/start-rest2nostr.sh - - ./.env:/home/safeuser/.env + - ./.env:/home/safeuser/psf-bch-api/.env - ../data:/home/safeuser/psf-bch-api/production/data - ../data/logs:/home/safeuser/psf-bch-api/logs restart: always \ No newline at end of file diff --git a/production/docker/entrypoint.sh b/production/docker/entrypoint.sh new file mode 100644 index 0000000..7040f8c --- /dev/null +++ b/production/docker/entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -euo pipefail + +cd /home/safeuser/psf-bch-api + +node scripts/patch-apidoc-from-env.js + +npm run docs + +exec npm start diff --git a/scripts/patch-apidoc-from-env.js b/scripts/patch-apidoc-from-env.js new file mode 100644 index 0000000..f14c4b2 --- /dev/null +++ b/scripts/patch-apidoc-from-env.js @@ -0,0 +1,41 @@ +/* + Applies APIDOC_URL from the environment to apidoc.json and package.json (apidoc.url). + Loads dotenv from the project root `.env` (same file as `dotenv.config()` in bin/server.js). + Exits without changes when APIDOC_URL is unset or empty. +*/ + +import dotenv from 'dotenv' +import { readFileSync, writeFileSync } from 'fs' +import { dirname, resolve } from 'path' +import { fileURLToPath } from 'url' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const root = resolve(__dirname, '..') + +dotenv.config({ path: resolve(root, '.env') }) + +const url = process.env.APIDOC_URL +if (url === undefined || url === null || String(url).trim() === '') { + process.exit(0) +} + +const normalized = String(url).trim() + +function patchApidocJson () { + const path = resolve(root, 'apidoc.json') + const data = JSON.parse(readFileSync(path, 'utf8')) + data.url = normalized + data.sampleUrl = normalized + writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`) +} + +function patchPackageJson () { + const path = resolve(root, 'package.json') + const data = JSON.parse(readFileSync(path, 'utf8')) + if (!data.apidoc) data.apidoc = {} + data.apidoc.url = normalized + writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`) +} + +patchApidocJson() +patchPackageJson()