kite-x402-hono 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example ADDED
@@ -0,0 +1,11 @@
1
+ PAY_TO=0x0000000000000000000000000000000000000001
2
+ KITE_NETWORK=testnet
3
+ UPSTREAM_URL=http://127.0.0.1:8081
4
+ PRICE_USD=0.001
5
+ PORT=8080
6
+ # Replace PAY_TO with your own receiving wallet before real paid calls.
7
+ # FACILITATOR_URL=https://facilitator.pieverse.io/v2
8
+ # UPSTREAM_AUTH_HEADER=Authorization
9
+ # UPSTREAM_AUTH_VALUE=Bearer your-upstream-key
10
+ # UPSTREAM_TIMEOUT_MS=10000
11
+ # MAX_BODY_BYTES=1048576
@@ -0,0 +1,22 @@
1
+ # Contributing
2
+
3
+ Use Bun 1.4.2 and Node.js 22. Install with `npm ci` (package-lock.json is the
4
+ canonical dependency lock), then run `npm run check` and `npm run test:coverage`.
5
+ Keep the official Kite environment names and `/v1/*` route prefix compatible.
6
+ Never include real credentials, wallet keys, `.env`, or fabricated payment receipts.
7
+
8
+ Any change affecting payments must test missing/invalid payment, successful
9
+ verify -> upstream -> settle ordering, upstream failure, and settlement failure.
10
+ Keep simulated-facilitator tests distinct from any real paid-call evidence.
11
+
12
+ ## Release v0.1.0
13
+
14
+ 1. Run checks and `npm audit --omit=dev --audit-level=high`.
15
+ 2. Run `npm pack --dry-run`, review contents, then `npm pack`.
16
+ 3. Install the tarball into an empty directory and exercise CLI help and health.
17
+ 4. Confirm the GitHub CI result for the commit being released.
18
+ 5. Authenticate to npm interactively; never put tokens or OTPs in committed files.
19
+ 6. Publish the reviewed tarball: `npm publish kite-x402-hono-0.1.0.tgz --access public`.
20
+ 7. Verify registry version/integrity, then tag the exact source revision.
21
+
22
+ Do not claim a version has been published until the npm registry confirms it.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ Kite x402 Hono
2
+ Copyright 2026 BrK
3
+
4
+ Kite network constants and the environment/route compatibility contract are
5
+ adapted from gokite-ai/kite-x402-services, Apache-2.0:
6
+ https://github.com/gokite-ai/kite-x402-services
7
+ Reference revision: 893a27509648b660bbba626b0da59619a94f04ab
8
+
9
+ Payment processing uses the separately licensed x402 SDK:
10
+ https://github.com/x402-foundation/x402
11
+
12
+ This is an independent community project, not an official Kite release.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # Kite x402 Hono
2
+
3
+ [![CI](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml/badge.svg)](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml)
4
+
5
+ A Bun/Hono reverse-proxy template for paid HTTP APIs on Kite. It complements
6
+ the [official Express and Go templates](https://github.com/gokite-ai/kite-x402-services)
7
+ with the same environment variables and `/v1/*` contract, using the official
8
+ `@x402/hono` middleware rather than implementing payment verification itself.
9
+
10
+ Independent community project. Apache-2.0; upstream attribution is in NOTICE.
11
+
12
+ ## Quick start from source
13
+
14
+ Requires Bun 1.3 or later and Node.js 22 or later for npm/build tooling.
15
+ CI is pinned to Bun 1.4.2.
16
+
17
+ ```sh
18
+ git clone https://github.com/BrKDDD/kite-x402-hono.git
19
+ cd kite-x402-hono
20
+ npm ci
21
+ cp .env.example .env
22
+ # Replace PAY_TO in .env with your own receiving wallet.
23
+ bun run example
24
+ ```
25
+
26
+ In another terminal in the same directory:
27
+
28
+ ```sh
29
+ bun run start
30
+ curl -i http://localhost:8080/healthz
31
+ curl -i 'http://localhost:8080/v1/echo?message=hello'
32
+ ```
33
+
34
+ `/healthz` returns 200 without contacting a facilitator. `/v1/echo` returns
35
+ 402 with an x402 v2 `PAYMENT-REQUIRED` header when the configured facilitator
36
+ is reachable and supports the selected network. A facilitator outage returns
37
+ 503 instead; the upstream is never called without verified payment.
38
+
39
+ The example is a local echo API, not a deployed service or paid-call receipt.
40
+ Bun reads `.env` automatically; the library's `loadConfig()` only reads the
41
+ environment supplied to it.
42
+
43
+ ## Package use
44
+
45
+ After version 0.1.0 has been published to npm:
46
+
47
+ ```sh
48
+ npm install kite-x402-hono
49
+ bunx kite-x402-hono --help
50
+ # Set PAY_TO and UPSTREAM_URL, or provide a local .env, before starting.
51
+ bunx kite-x402-hono
52
+ ```
53
+
54
+ Library API:
55
+
56
+ ```ts
57
+ import { createApp, loadConfig } from "kite-x402-hono";
58
+
59
+ const config = loadConfig();
60
+ const app = createApp(config);
61
+ Bun.serve({ port: config.port, fetch: app.fetch });
62
+ ```
63
+
64
+ `createApp(config, { facilitator, fetchUpstream })` also allows dependency
65
+ injection for tests. Never use a simulated facilitator in a production service.
66
+
67
+ ## Configuration
68
+
69
+ | Variable | Default | Meaning |
70
+ | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------- |
71
+ | `PAY_TO` | Required | Nonzero EVM receiving address |
72
+ | `UPSTREAM_URL` | Required | Fixed HTTP(S) origin, with no path, credentials or query |
73
+ | `KITE_NETWORK` | `mainnet` | `mainnet` or `testnet` |
74
+ | `PRICE_USD` | `0.001` | Positive decimal, at most 6 fractional digits; optional `$` prefix |
75
+ | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | Keep the `/v2` suffix |
76
+ | `UPSTREAM_AUTH_HEADER` | `Authorization` | Upstream credential header name |
77
+ | `UPSTREAM_AUTH_VALUE` | Empty | Server-side credential; replaces buyer-supplied values |
78
+ | `SERVICE_DESCRIPTION` | Kite paid API description | Included in the payment challenge |
79
+ | `PORT` | `8080` | Wrapper port |
80
+ | `UPSTREAM_TIMEOUT_MS` | `10000` | Timeout for reading the request body, then separately for upstream headers/body |
81
+ | `MAX_BODY_BYTES` | `1048576` | Request and response byte limit; maximum 16 MiB |
82
+
83
+ HTTPS is required for upstream/facilitator URLs except localhost development.
84
+ The example `.env` explicitly selects testnet; the compatibility default remains
85
+ mainnet. This wrapper requires no wallet private key.
86
+
87
+ | Network | CAIP-2 | Token | Decimals | EIP-712 domain |
88
+ | ------- | ------------- | ------ | -------- | ------------------------------------- |
89
+ | Mainnet | `eip155:2366` | USDC.e | 6 | `Bridged USDC (Kite AI)`, version `2` |
90
+ | Testnet | `eip155:2368` | pieUSD | 18 | `pieUSD`, version `1` |
91
+
92
+ Token addresses are pinned in `src/networks.ts` from official Kite template
93
+ revision `893a27509648b660bbba626b0da59619a94f04ab`. Price conversion uses
94
+ integer arithmetic, including for testnet's 18 decimals.
95
+
96
+ ## Payment and proxy contract
97
+
98
+ 1. No payment or invalid payment: return 402; do not call the upstream.
99
+ 2. Verified payment: strip `/v1`, preserve the query/method/body, inject the
100
+ configured upstream credential, and call the fixed upstream origin.
101
+ 3. Upstream 2xx: buffer the bounded response, then ask the facilitator to settle.
102
+ 4. Successful settlement: return the upstream response and `PAYMENT-RESPONSE`.
103
+ 5. Upstream 4xx/5xx, timeout, oversized body or connection failure: do not settle.
104
+ 6. Settlement refusal: return the SDK failure response, withholding protected data.
105
+
106
+ Compatibility notes:
107
+
108
+ - `/v1/echo` maps to upstream `/echo`. `/v1/v1/forecast` maps to `/v1/forecast`.
109
+ - All HTTP methods under `/v1/*` are paid; the selected upstream must support them.
110
+ - Unlike the reference template's general below-400 rule, this template **refuses
111
+ upstream redirects** with 502, without settlement, so credentials cannot follow
112
+ redirects to a different host. Use the final upstream origin directly.
113
+ - Payment headers, client authorization/cookies, proxy headers and hop-by-hop
114
+ headers are removed. Upstream authentication response headers and cookies are
115
+ also stripped. The upstream is trusted: do not select one that echoes secrets
116
+ into response bodies or unrelated headers.
117
+ - Response buffering is deliberate. Streaming/SSE, WebSocket and unbounded
118
+ downloads are outside v0.1.0.
119
+ - Upstream actions happen before settlement. For non-idempotent POST operations,
120
+ settlement failure does not undo the upstream action. Use an upstream with
121
+ idempotency support; the wrapper does not provide exactly-once execution.
122
+ - A facilitator timeout may leave the on-chain settlement outcome unknown. An
123
+ error response is not proof of no charge. Reconcile before retrying a payment.
124
+ - `/healthz` is process liveness, not proof of upstream/facilitator readiness.
125
+ - The CLI disables Bun's short idle timeout so it does not disconnect a client
126
+ during settlement. SDK facilitator calls have their own 90-second timeout;
127
+ deploy behind a reverse proxy with suitable request deadlines and rate limits.
128
+
129
+ ## Verification
130
+
131
+ ```sh
132
+ npm run typecheck
133
+ bun test --coverage
134
+ npm run build
135
+ npm audit --omit=dev --audit-level=high
136
+ npm pack
137
+ ```
138
+
139
+ Tests exercise the real x402 Hono middleware. A deterministic fake facilitator
140
+ supplies verification/settlement results; a separate HTTP test runs the SDK
141
+ client against local `/v2/supported`, `/v2/verify`, `/v2/settle` endpoints and
142
+ proxies real HTTP requests. Fixtures are clearly labeled and are **not valid
143
+ signatures or evidence of on-chain payment**. CI publishes coverage, JUnit and
144
+ the installable package artifact, and tests installing that artifact separately.
145
+
146
+ For real paid acceptance, deploy a public HTTPS origin, replace PAY_TO, use a
147
+ Kite Passport sandbox session with testnet pieUSD, and retain the real response
148
+ and transaction hash. Follow the current Passport CLI documentation because its
149
+ commands evolve. No mainnet transaction is required for local development.
150
+
151
+ ## Release and contribution
152
+
153
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
154
+ [docs/week-1.md](docs/week-1.md) for the bounty scope and evidence checklist.
155
+ AI tools assisted development; BrK reviews and owns the contribution. Original
156
+ wrapper/configuration/test work is distinguished from upstream SDK functionality.
package/SECURITY.md ADDED
@@ -0,0 +1,18 @@
1
+ # Security
2
+
3
+ Use this template with a trusted upstream and a trusted facilitator. Payment
4
+ cryptography and on-chain verification are delegated to the official x402 SDK
5
+ and the configured facilitator; the proxy does not independently validate chain
6
+ state. Pin dependencies and review updates before upgrading.
7
+
8
+ Run behind HTTPS with request-rate limits. Keep the receiving wallet separate
9
+ from application secrets. No signing key belongs in this wrapper. Never log
10
+ payment signatures, authorization headers, full request bodies or `.env`.
11
+
12
+ This is a bounded-response template, not a hardened multi-tenant API gateway.
13
+ An upstream can perform an action before settlement fails. Idempotency and
14
+ reconciliation for such actions must be provided by the upstream/application.
15
+ Do not automatically retry an indeterminate settlement.
16
+
17
+ Report security issues using GitHub's private vulnerability reporting when
18
+ enabled; do not publish credentials or exploitable details in public issues.
package/dist/app.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { Hono } from "hono";
2
+ import { type FacilitatorClient } from "@x402/core/server";
3
+ import { type Config } from "./config.js";
4
+ import { type FetchUpstream } from "./proxy.js";
5
+ export interface AppOptions {
6
+ facilitator?: FacilitatorClient;
7
+ fetchUpstream?: FetchUpstream;
8
+ }
9
+ export declare function createApp(config?: Config, options?: AppOptions): Hono;
package/dist/app.js ADDED
@@ -0,0 +1,52 @@
1
+ import { Hono } from "hono";
2
+ import { paymentMiddlewareFromHTTPServer, x402HTTPResourceServer, x402ResourceServer, } from "@x402/hono";
3
+ import { HTTPFacilitatorClient, } from "@x402/core/server";
4
+ import { ExactEvmScheme } from "@x402/evm/exact/server";
5
+ import { loadConfig } from "./config.js";
6
+ import { parsePrice } from "./networks.js";
7
+ import { proxy } from "./proxy.js";
8
+ export function createApp(config = loadConfig(), options = {}) {
9
+ const app = new Hono();
10
+ const facilitator = options.facilitator ??
11
+ new HTTPFacilitatorClient({ url: config.facilitatorUrl });
12
+ const server = new x402ResourceServer(facilitator).register(config.chain.network, new ExactEvmScheme());
13
+ const httpServer = new x402HTTPResourceServer(server, {
14
+ "/v1/*": {
15
+ accepts: {
16
+ scheme: "exact",
17
+ price: parsePrice(config.price, config.chain),
18
+ network: config.chain.network,
19
+ payTo: config.payTo,
20
+ maxTimeoutSeconds: 60,
21
+ },
22
+ description: config.description,
23
+ mimeType: "application/json",
24
+ },
25
+ });
26
+ const payments = paymentMiddlewareFromHTTPServer(httpServer, undefined, undefined, false);
27
+ // Initialize lazily so /healthz never needs network access and startup errors stay request-scoped.
28
+ let initialization;
29
+ app.get("/healthz", (c) => c.json({
30
+ ok: true,
31
+ network: config.chain.network,
32
+ asset: config.chain.symbol,
33
+ price: `$${config.price}`,
34
+ }));
35
+ app.use("/v1/*", async (c, next) => {
36
+ c.header("cache-control", "no-store");
37
+ try {
38
+ initialization ??= httpServer.initialize().catch((error) => {
39
+ initialization = undefined;
40
+ throw error;
41
+ });
42
+ await initialization;
43
+ }
44
+ catch {
45
+ return c.json({ error: "facilitator_unavailable" }, 503);
46
+ }
47
+ return payments(c, next);
48
+ });
49
+ app.all("/v1/*", (c) => proxy(c.req.raw, config, options.fetchUpstream ?? ((request) => fetch(request))));
50
+ app.onError(() => Response.json({ error: "internal_error" }, { status: 500, headers: { "cache-control": "no-store" } }));
51
+ return app;
52
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bun
2
+ import { createApp } from "./app.js";
3
+ import { loadConfig } from "./config.js";
4
+ if (process.argv.includes("--help")) {
5
+ console.log("Usage: kite-x402-hono\nRequired: PAY_TO, UPSTREAM_URL\nOptional: KITE_NETWORK, PRICE_USD, PORT, FACILITATOR_URL, UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_VALUE, UPSTREAM_TIMEOUT_MS, MAX_BODY_BYTES\nSee README.md for configuration and examples.");
6
+ }
7
+ else {
8
+ try {
9
+ const config = loadConfig();
10
+ const app = createApp(config);
11
+ const server = Bun.serve({
12
+ port: config.port,
13
+ fetch: app.fetch,
14
+ maxRequestBodySize: config.maxBodyBytes,
15
+ idleTimeout: 0,
16
+ });
17
+ console.log(`Kite x402 Hono listening at ${server.url} (${config.chain.network})`);
18
+ const shutdown = () => {
19
+ void server.stop(true);
20
+ };
21
+ process.once("SIGINT", shutdown);
22
+ process.once("SIGTERM", shutdown);
23
+ }
24
+ catch (error) {
25
+ console.error(error instanceof Error ? error.message : "Unable to start wrapper");
26
+ process.exitCode = 1;
27
+ }
28
+ }
@@ -0,0 +1,15 @@
1
+ import { type KiteNetwork } from "./networks.js";
2
+ export interface Config {
3
+ payTo: string;
4
+ chain: KiteNetwork;
5
+ upstream: string;
6
+ price: string;
7
+ facilitatorUrl: string;
8
+ authHeader: string;
9
+ authValue: string;
10
+ description: string;
11
+ port: number;
12
+ timeoutMs: number;
13
+ maxBodyBytes: number;
14
+ }
15
+ export declare function loadConfig(env?: Record<string, string | undefined>): Config;
package/dist/config.js ADDED
@@ -0,0 +1,82 @@
1
+ import { KITE_NETWORKS, parsePrice } from "./networks.js";
2
+ function integer(value, key, max) {
3
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > max) {
4
+ throw new Error(`${key} must be an integer between 1 and ${max}`);
5
+ }
6
+ return Number(value);
7
+ }
8
+ function httpUrl(value, key, originOnly = false) {
9
+ let url;
10
+ try {
11
+ url = new URL(value);
12
+ }
13
+ catch {
14
+ throw new Error(`${key} must be an absolute HTTP(S) URL`);
15
+ }
16
+ if (!["http:", "https:"].includes(url.protocol) ||
17
+ url.username ||
18
+ url.password ||
19
+ url.search ||
20
+ url.hash ||
21
+ (originOnly && url.pathname !== "/")) {
22
+ throw new Error(`${key} must be an HTTP(S) ${originOnly ? "origin" : "URL"} without credentials, query or fragment`);
23
+ }
24
+ if (url.protocol === "http:" &&
25
+ !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
26
+ throw new Error(`${key} requires HTTPS except on localhost`);
27
+ }
28
+ return originOnly ? url.origin : url.href.replace(/\/$/, "");
29
+ }
30
+ export function loadConfig(env = process.env) {
31
+ const get = (key, fallback = "") => env[key]?.trim() || fallback;
32
+ const payTo = get("PAY_TO");
33
+ if (!/^0x[\da-fA-F]{40}$/.test(payTo) || /^0x0{40}$/i.test(payTo))
34
+ throw new Error("PAY_TO must be a nonzero EVM address");
35
+ const network = get("KITE_NETWORK", "mainnet");
36
+ if (network !== "mainnet" && network !== "testnet")
37
+ throw new Error("KITE_NETWORK must be mainnet or testnet");
38
+ const chain = KITE_NETWORKS[network];
39
+ const price = get("PRICE_USD", "0.001").replace(/^\$/, "");
40
+ parsePrice(price, chain);
41
+ const authHeader = get("UPSTREAM_AUTH_HEADER", "Authorization").toLowerCase();
42
+ if (!/^[!#$%&'*+.^_`|~\da-z-]+$/.test(authHeader) ||
43
+ [
44
+ "host",
45
+ "connection",
46
+ "content-length",
47
+ "transfer-encoding",
48
+ "payment-signature",
49
+ "payment-response",
50
+ "payment-required",
51
+ "x-payment",
52
+ "x-payment-response",
53
+ "cookie",
54
+ "set-cookie",
55
+ "proxy-authorization",
56
+ "proxy-authenticate",
57
+ "content-encoding",
58
+ "accept-encoding",
59
+ "upgrade",
60
+ "te",
61
+ "trailer",
62
+ "keep-alive",
63
+ ].includes(authHeader)) {
64
+ throw new Error("UPSTREAM_AUTH_HEADER must be a valid application authentication header");
65
+ }
66
+ const authValue = get("UPSTREAM_AUTH_VALUE");
67
+ if (/[\r\n\0]/.test(authValue))
68
+ throw new Error("UPSTREAM_AUTH_VALUE contains invalid characters");
69
+ return {
70
+ payTo,
71
+ chain,
72
+ price,
73
+ authHeader,
74
+ authValue,
75
+ upstream: httpUrl(get("UPSTREAM_URL"), "UPSTREAM_URL", true),
76
+ facilitatorUrl: httpUrl(get("FACILITATOR_URL", "https://facilitator.pieverse.io/v2"), "FACILITATOR_URL"),
77
+ description: get("SERVICE_DESCRIPTION", "Paid API wrapped for the Kite network"),
78
+ port: integer(get("PORT", "8080"), "PORT", 65535),
79
+ timeoutMs: integer(get("UPSTREAM_TIMEOUT_MS", "10000"), "UPSTREAM_TIMEOUT_MS", 120000),
80
+ maxBodyBytes: integer(get("MAX_BODY_BYTES", "1048576"), "MAX_BODY_BYTES", 16777216),
81
+ };
82
+ }
@@ -0,0 +1,3 @@
1
+ export { createApp, type AppOptions } from "./app.js";
2
+ export { loadConfig, type Config } from "./config.js";
3
+ export { KITE_NETWORKS, parsePrice, type KiteNetwork } from "./networks.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createApp } from "./app.js";
2
+ export { loadConfig } from "./config.js";
3
+ export { KITE_NETWORKS, parsePrice } from "./networks.js";
@@ -0,0 +1,28 @@
1
+ import type { AssetAmount, Network } from "@x402/core/types";
2
+ export interface KiteNetwork {
3
+ readonly network: Network;
4
+ readonly asset: string;
5
+ readonly symbol: string;
6
+ readonly decimals: number;
7
+ readonly name: string;
8
+ readonly version: string;
9
+ }
10
+ export declare const KITE_NETWORKS: {
11
+ readonly mainnet: {
12
+ readonly network: "eip155:2366";
13
+ readonly asset: "0x7aB6f3ed87C42eF0aDb67Ed95090f8bF5240149e";
14
+ readonly symbol: "USDC.e";
15
+ readonly decimals: 6;
16
+ readonly name: "Bridged USDC (Kite AI)";
17
+ readonly version: "2";
18
+ };
19
+ readonly testnet: {
20
+ readonly network: "eip155:2368";
21
+ readonly asset: "0x38129cf4CE5E183eFF248F42A7D345Bb1B47621A";
22
+ readonly symbol: "pieUSD";
23
+ readonly decimals: 18;
24
+ readonly name: "pieUSD";
25
+ readonly version: "1";
26
+ };
27
+ };
28
+ export declare function parsePrice(price: string, chain: KiteNetwork): AssetAmount;
@@ -0,0 +1,34 @@
1
+ // Network constants follow gokite-ai/kite-x402-services (see NOTICE).
2
+ export const KITE_NETWORKS = {
3
+ mainnet: {
4
+ network: "eip155:2366",
5
+ asset: "0x7aB6f3ed87C42eF0aDb67Ed95090f8bF5240149e",
6
+ symbol: "USDC.e",
7
+ decimals: 6,
8
+ name: "Bridged USDC (Kite AI)",
9
+ version: "2",
10
+ },
11
+ testnet: {
12
+ network: "eip155:2368",
13
+ asset: "0x38129cf4CE5E183eFF248F42A7D345Bb1B47621A",
14
+ symbol: "pieUSD",
15
+ decimals: 18,
16
+ name: "pieUSD",
17
+ version: "1",
18
+ },
19
+ };
20
+ export function parsePrice(price, chain) {
21
+ const value = price.trim().replace(/^\$/, "");
22
+ if (!/^\d+(?:\.\d{1,6})?$/.test(value) || value.length > 40) {
23
+ throw new Error("PRICE_USD must be a positive decimal with at most 6 fractional digits");
24
+ }
25
+ const [whole = "0", fractional = ""] = value.split(".");
26
+ const units = BigInt(whole + fractional.padEnd(chain.decimals, "0"));
27
+ if (units <= 0n)
28
+ throw new Error("PRICE_USD must be greater than zero");
29
+ return {
30
+ asset: chain.asset,
31
+ amount: units.toString(),
32
+ extra: { name: chain.name, version: chain.version },
33
+ };
34
+ }
@@ -0,0 +1,5 @@
1
+ import type { Config } from "./config.js";
2
+ export type FetchUpstream = (request: Request) => Promise<Response>;
3
+ export declare function cleanHeaders(source: Headers, authHeader: string): Headers;
4
+ export declare function readLimited(stream: ReadableStream<Uint8Array> | null, limit: number, signal?: AbortSignal): Promise<Uint8Array<ArrayBuffer>>;
5
+ export declare function proxy(request: Request, config: Config, fetchUpstream: FetchUpstream): Promise<Response>;
package/dist/proxy.js ADDED
@@ -0,0 +1,149 @@
1
+ const blocked = new Set([
2
+ "connection",
3
+ "keep-alive",
4
+ "transfer-encoding",
5
+ "te",
6
+ "trailer",
7
+ "upgrade",
8
+ "host",
9
+ "content-length",
10
+ "proxy-authorization",
11
+ "proxy-authenticate",
12
+ "payment-signature",
13
+ "payment-required",
14
+ "payment-response",
15
+ "x-payment",
16
+ "x-payment-response",
17
+ "x-payment-required",
18
+ "cookie",
19
+ "set-cookie",
20
+ "authorization",
21
+ "forwarded",
22
+ "x-forwarded-for",
23
+ "x-forwarded-host",
24
+ "x-forwarded-proto",
25
+ "x-real-ip",
26
+ ]);
27
+ export function cleanHeaders(source, authHeader) {
28
+ const headers = new Headers(source);
29
+ const connectionTokens = (headers.get("connection") ?? "")
30
+ .split(",")
31
+ .map((token) => token.trim().toLowerCase());
32
+ for (const key of [...headers.keys()]) {
33
+ if (blocked.has(key) ||
34
+ key === authHeader ||
35
+ connectionTokens.includes(key) ||
36
+ key.startsWith("x402-"))
37
+ headers.delete(key);
38
+ }
39
+ return headers;
40
+ }
41
+ class BodyTooLarge extends Error {
42
+ }
43
+ export async function readLimited(stream, limit, signal) {
44
+ if (!stream)
45
+ return new Uint8Array();
46
+ const reader = stream.getReader();
47
+ const cancel = () => {
48
+ void reader.cancel().catch(() => { });
49
+ };
50
+ signal?.addEventListener("abort", cancel, { once: true });
51
+ const chunks = [];
52
+ let size = 0;
53
+ try {
54
+ while (true) {
55
+ signal?.throwIfAborted();
56
+ const { done, value } = await reader.read();
57
+ signal?.throwIfAborted();
58
+ if (done)
59
+ break;
60
+ size += value.byteLength;
61
+ if (size > limit) {
62
+ await reader.cancel();
63
+ throw new BodyTooLarge();
64
+ }
65
+ chunks.push(value);
66
+ }
67
+ }
68
+ finally {
69
+ signal?.removeEventListener("abort", cancel);
70
+ reader.releaseLock();
71
+ }
72
+ const output = new Uint8Array(size);
73
+ let offset = 0;
74
+ for (const chunk of chunks) {
75
+ output.set(chunk, offset);
76
+ offset += chunk.byteLength;
77
+ }
78
+ return output;
79
+ }
80
+ export async function proxy(request, config, fetchUpstream) {
81
+ const incoming = new URL(request.url);
82
+ // Assign pathname rather than resolving user input: //host must never replace the configured origin.
83
+ const target = new URL(config.upstream);
84
+ target.pathname = incoming.pathname.slice(3) || "/";
85
+ target.search = incoming.search;
86
+ const headers = cleanHeaders(request.headers, config.authHeader);
87
+ headers.set("accept-encoding", "identity");
88
+ if (config.authValue)
89
+ headers.set(config.authHeader, config.authValue);
90
+ let body;
91
+ const bodySignal = AbortSignal.any([
92
+ request.signal,
93
+ AbortSignal.timeout(config.timeoutMs),
94
+ ]);
95
+ try {
96
+ if (!["GET", "HEAD"].includes(request.method))
97
+ body = await readLimited(request.body, config.maxBodyBytes, bodySignal);
98
+ }
99
+ catch (error) {
100
+ if (bodySignal.aborted)
101
+ return Response.json({ error: "request_timeout_or_abort" }, { status: 408 });
102
+ return Response.json({
103
+ error: error instanceof BodyTooLarge
104
+ ? "request_too_large"
105
+ : "invalid_request_body",
106
+ }, { status: error instanceof BodyTooLarge ? 413 : 400 });
107
+ }
108
+ const controller = new AbortController();
109
+ const onAbort = () => controller.abort();
110
+ request.signal.addEventListener("abort", onAbort, { once: true });
111
+ if (request.signal.aborted)
112
+ controller.abort();
113
+ const timer = setTimeout(() => controller.abort(), config.timeoutMs);
114
+ try {
115
+ const upstream = await fetchUpstream(new Request(target, {
116
+ method: request.method,
117
+ headers,
118
+ ...(body ? { body } : {}),
119
+ signal: controller.signal,
120
+ redirect: "manual",
121
+ }));
122
+ // No redirect following: an upstream cannot forward the injected credential to another host.
123
+ if (upstream.status >= 300 && upstream.status < 400) {
124
+ await upstream.body?.cancel();
125
+ return Response.json({ error: "upstream_redirect_refused" }, { status: 502 });
126
+ }
127
+ const bytes = await readLimited(upstream.body, config.maxBodyBytes, controller.signal);
128
+ const responseHeaders = cleanHeaders(upstream.headers, config.authHeader);
129
+ responseHeaders.delete("content-encoding");
130
+ responseHeaders.set("cache-control", "no-store");
131
+ return new Response(request.method === "HEAD" || [204, 205, 304].includes(upstream.status)
132
+ ? null
133
+ : bytes, { status: upstream.status, headers: responseHeaders });
134
+ }
135
+ catch (error) {
136
+ const timeout = controller.signal.aborted;
137
+ return Response.json({
138
+ error: timeout
139
+ ? "upstream_timeout_or_abort"
140
+ : error instanceof BodyTooLarge
141
+ ? "upstream_response_too_large"
142
+ : "upstream_unavailable",
143
+ }, { status: timeout ? 504 : 502 });
144
+ }
145
+ finally {
146
+ clearTimeout(timer);
147
+ request.signal.removeEventListener("abort", onAbort);
148
+ }
149
+ }
package/docs/week-1.md ADDED
@@ -0,0 +1,41 @@
1
+ # Week 1: Bun/Hono x402 Wrapper
2
+
3
+ - Direction: `x402-wrapper`
4
+ - Owner: BrKDDD
5
+ - Repository: https://github.com/BrKDDD/kite-x402-hono
6
+ - Target release: `kite-x402-hono@0.1.0`
7
+ - Reference: gokite-ai/kite-x402-services at `893a27509648b660bbba626b0da59619a94f04ab`
8
+
9
+ ## Contribution
10
+
11
+ Added a Bun/Hono wrapper using the official x402 SDK with Kite mainnet/testnet
12
+ asset configuration, precise integer pricing, compatible environment names and
13
+ routes, bounded proxying, credential/header filtering, and explicit failure
14
+ handling. Tests verify the payment lifecycle and real local HTTP transport.
15
+ GitHub Actions builds, audits, tests, and installs the packed package.
16
+
17
+ The Hono/Bun application, config validation, proxy restrictions, test suite and
18
+ packaging are this project's work. Kite network constants and compatibility
19
+ requirements come from the attributed official templates. x402 cryptography,
20
+ protocol negotiation and settlement middleware come from the upstream SDK.
21
+
22
+ ## Submission checklist
23
+
24
+ - Public repository under the bound GitHub account.
25
+ - Current-week commit authored by BrK and linked to BrKDDD.
26
+ - Passing CI for the submitted commit, with downloadable evidence artifacts.
27
+ - npm package URL and installable version verified after publication.
28
+ - Commands, example requests and known compatibility differences in README.
29
+ - No claim that mocked settlement receipts are real paid calls.
30
+
31
+ Suggested summary:
32
+
33
+ > Implemented a Kite x402 Bun/Hono wrapper with mainnet/testnet pricing,
34
+ > /v1/\* proxy compatibility, verify-before-upstream and settle-after-success
35
+ > behavior, failure-path coverage, a runnable echo example, and package/CI
36
+ > verification. Payment handling reuses the official x402 SDK. Automated
37
+ > payment evidence uses a simulated facilitator; no on-chain payment is claimed.
38
+
39
+ Append the actual commit link, successful Actions run, and published npm URL
40
+ when submitting. The activity dashboard's owner/week/EC rules remain external
41
+ acceptance criteria; repository checks alone do not imply bounty approval.
@@ -0,0 +1,21 @@
1
+ import { Hono } from "hono";
2
+
3
+ const app = new Hono();
4
+ app.get("/echo", (c) =>
5
+ c.json({
6
+ message: c.req.query("message") ?? "Hello from Kite",
7
+ method: c.req.method,
8
+ }),
9
+ );
10
+ app.post("/echo", async (c) =>
11
+ c.json({ body: await c.req.text(), method: c.req.method }),
12
+ );
13
+ app.get("/fail", (c) =>
14
+ c.json({ error: "demonstration_upstream_failure" }, 503),
15
+ );
16
+ const server = Bun.serve({
17
+ hostname: "127.0.0.1",
18
+ port: 8081,
19
+ fetch: app.fetch,
20
+ });
21
+ console.log(`Example upstream: ${server.url}`);
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "kite-x402-hono",
3
+ "version": "0.1.0",
4
+ "description": "Bun and Hono reverse proxy for x402 payments on Kite",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "author": "BrK",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/BrKDDD/kite-x402-hono.git"
11
+ },
12
+ "homepage": "https://github.com/BrKDDD/kite-x402-hono#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/BrKDDD/kite-x402-hono/issues"
15
+ },
16
+ "keywords": [
17
+ "kite",
18
+ "x402",
19
+ "hono",
20
+ "bun",
21
+ "payments"
22
+ ],
23
+ "engines": {
24
+ "bun": ">=1.3.0"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE",
30
+ "NOTICE",
31
+ "CONTRIBUTING.md",
32
+ "SECURITY.md",
33
+ "docs",
34
+ ".env.example",
35
+ "examples"
36
+ ],
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "import": "./dist/index.js"
41
+ }
42
+ },
43
+ "bin": {
44
+ "kite-x402-hono": "dist/cli.js"
45
+ },
46
+ "scripts": {
47
+ "format": "prettier --write .",
48
+ "format:check": "prettier --check .",
49
+ "dev": "bun --watch src/cli.ts",
50
+ "start": "bun src/cli.ts",
51
+ "example": "bun examples/upstream.ts",
52
+ "typecheck": "tsc --noEmit",
53
+ "build": "tsc -p tsconfig.build.json",
54
+ "test": "bun test",
55
+ "test:coverage": "bun test --coverage",
56
+ "check": "npm run typecheck && npm test && npm run build",
57
+ "prepack": "npm run build"
58
+ },
59
+ "dependencies": {
60
+ "@x402/core": "2.26.0",
61
+ "@x402/evm": "2.26.0",
62
+ "@x402/hono": "2.26.0",
63
+ "hono": "4.13.8"
64
+ },
65
+ "devDependencies": {
66
+ "@types/bun": "^1.3.0",
67
+ "prettier": "3.6.2",
68
+ "typescript": "^5.9.3"
69
+ }
70
+ }