@tollbase/core 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tollbase contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @tollbase/core
2
+
3
+ Shared protocol types for Tollbase: the agent-facing service manifest, the
4
+ machine-readable HTTP 402 challenge, usage-event shapes, plus configuration and
5
+ logging utilities used by Tollbase services.
6
+
7
+ You normally do not install this directly; it comes with
8
+ [`@tollbase/middleware`](https://www.npmjs.com/package/@tollbase/middleware).
9
+
10
+ ```ts
11
+ import { err402, ManifestSchema, type Plan } from "@tollbase/core/types";
12
+ ```
13
+
14
+ MIT.
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * All runtime configuration comes from the environment and is validated once
4
+ * at boot. Anything invalid fails fast with a readable error instead of
5
+ * surfacing later as a mysterious runtime bug.
6
+ */
7
+ declare const ConfigSchema: z.ZodObject<{
8
+ NODE_ENV: z.ZodDefault<z.ZodEnum<["development", "test", "production"]>>;
9
+ PORT: z.ZodDefault<z.ZodNumber>;
10
+ TOLLBASE_DB: z.ZodDefault<z.ZodString>;
11
+ LOG_LEVEL: z.ZodDefault<z.ZodEnum<["debug", "info", "warn", "error"]>>;
12
+ STRIPE_SECRET_KEY: z.ZodOptional<z.ZodString>;
13
+ TOLLBASE_TAKE_BPS: z.ZodDefault<z.ZodNumber>;
14
+ RESEND_API_KEY: z.ZodOptional<z.ZodString>;
15
+ EMAIL_FROM: z.ZodDefault<z.ZodString>;
16
+ TOLLBASE_SESSION_SECRET: z.ZodOptional<z.ZodString>;
17
+ TOLLBASE_DEMO_MODE: z.ZodDefault<z.ZodBoolean>;
18
+ }, "strip", z.ZodTypeAny, {
19
+ NODE_ENV: "development" | "test" | "production";
20
+ PORT: number;
21
+ TOLLBASE_DB: string;
22
+ LOG_LEVEL: "debug" | "info" | "warn" | "error";
23
+ TOLLBASE_TAKE_BPS: number;
24
+ EMAIL_FROM: string;
25
+ TOLLBASE_DEMO_MODE: boolean;
26
+ STRIPE_SECRET_KEY?: string | undefined;
27
+ RESEND_API_KEY?: string | undefined;
28
+ TOLLBASE_SESSION_SECRET?: string | undefined;
29
+ }, {
30
+ NODE_ENV?: "development" | "test" | "production" | undefined;
31
+ PORT?: number | undefined;
32
+ TOLLBASE_DB?: string | undefined;
33
+ LOG_LEVEL?: "debug" | "info" | "warn" | "error" | undefined;
34
+ STRIPE_SECRET_KEY?: string | undefined;
35
+ TOLLBASE_TAKE_BPS?: number | undefined;
36
+ RESEND_API_KEY?: string | undefined;
37
+ EMAIL_FROM?: string | undefined;
38
+ TOLLBASE_SESSION_SECRET?: string | undefined;
39
+ TOLLBASE_DEMO_MODE?: boolean | undefined;
40
+ }>;
41
+ export type Config = z.infer<typeof ConfigSchema>;
42
+ export declare function loadConfig(env?: NodeJS.ProcessEnv): Config;
43
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,38 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * All runtime configuration comes from the environment and is validated once
4
+ * at boot. Anything invalid fails fast with a readable error instead of
5
+ * surfacing later as a mysterious runtime bug.
6
+ */
7
+ const ConfigSchema = z.object({
8
+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
9
+ PORT: z.coerce.number().int().positive().default(4600),
10
+ TOLLBASE_DB: z.string().default("tollbase.db"),
11
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
12
+ // Payments. When STRIPE_SECRET_KEY is unset the mock adapter is used, which
13
+ // keeps local development and CI runnable with zero external accounts.
14
+ STRIPE_SECRET_KEY: z.string().optional(),
15
+ // Optional Stripe Connect account of the vendor for direct charges. The
16
+ // platform take rate is expressed in basis points of each charge.
17
+ TOLLBASE_TAKE_BPS: z.coerce.number().int().min(0).max(2000).default(150),
18
+ // Notifications. When RESEND_API_KEY is unset, approval links are printed
19
+ // to the server log (development behaviour).
20
+ RESEND_API_KEY: z.string().optional(),
21
+ EMAIL_FROM: z.string().default("Tollbase <approvals@tollbase.local>"),
22
+ // Signs dashboard session cookies. When unset, a random per-boot secret is
23
+ // used (dev behaviour: restarting the control plane logs everyone out).
24
+ TOLLBASE_SESSION_SECRET: z.string().min(16).optional(),
25
+ // Never enable in production: exposes raw approval tokens for the demo.
26
+ TOLLBASE_DEMO_MODE: z.coerce.boolean().default(false),
27
+ });
28
+ export function loadConfig(env = process.env) {
29
+ const parsed = ConfigSchema.safeParse(env);
30
+ if (!parsed.success) {
31
+ const issues = parsed.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
32
+ throw new Error(`Invalid configuration:\n${issues}`);
33
+ }
34
+ if (parsed.data.NODE_ENV === "production" && parsed.data.TOLLBASE_DEMO_MODE) {
35
+ throw new Error("TOLLBASE_DEMO_MODE must not be enabled in production");
36
+ }
37
+ return parsed.data;
38
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Minimal structured logger. JSON lines in production (machine-parseable by
3
+ * any log pipeline), human-readable key=value in development. Deliberately
4
+ * dependency-free: a logging library is not worth a supply-chain edge here.
5
+ */
6
+ type Level = "debug" | "info" | "warn" | "error";
7
+ export interface Logger {
8
+ debug(msg: string, fields?: Record<string, unknown>): void;
9
+ info(msg: string, fields?: Record<string, unknown>): void;
10
+ warn(msg: string, fields?: Record<string, unknown>): void;
11
+ error(msg: string, fields?: Record<string, unknown>): void;
12
+ child(bound: Record<string, unknown>): Logger;
13
+ }
14
+ export declare function createLogger(opts?: {
15
+ level?: Level;
16
+ json?: boolean;
17
+ bound?: Record<string, unknown>;
18
+ }): Logger;
19
+ export {};
package/dist/log.js ADDED
@@ -0,0 +1,25 @@
1
+ const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
2
+ export function createLogger(opts = {}) {
3
+ const threshold = LEVELS[opts.level ?? "info"];
4
+ const emit = (level, msg, fields) => {
5
+ if (LEVELS[level] < threshold)
6
+ return;
7
+ const record = { ts: new Date().toISOString(), level, msg, ...opts.bound, ...fields };
8
+ if (opts.json) {
9
+ console.log(JSON.stringify(record));
10
+ }
11
+ else {
12
+ const kv = Object.entries({ ...opts.bound, ...fields })
13
+ .map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
14
+ .join(" ");
15
+ console.log(`${record.ts} ${level.toUpperCase().padEnd(5)} ${msg}${kv ? " " + kv : ""}`);
16
+ }
17
+ };
18
+ return {
19
+ debug: (m, f) => emit("debug", m, f),
20
+ info: (m, f) => emit("info", m, f),
21
+ warn: (m, f) => emit("warn", m, f),
22
+ error: (m, f) => emit("error", m, f),
23
+ child: (bound) => createLogger({ ...opts, bound: { ...opts.bound, ...bound } }),
24
+ };
25
+ }
@@ -0,0 +1,176 @@
1
+ import { z } from "zod";
2
+ /** Pricing: MVP supports per-call pricing. Tiered/per-unit models follow the same shape. */
3
+ export declare const PlanSchema: z.ZodObject<{
4
+ name: z.ZodString;
5
+ model: z.ZodLiteral<"per_call">;
6
+ unit_cents: z.ZodNumber;
7
+ currency: z.ZodDefault<z.ZodString>;
8
+ scopes: z.ZodArray<z.ZodString, "many">;
9
+ }, "strip", z.ZodTypeAny, {
10
+ name: string;
11
+ model: "per_call";
12
+ unit_cents: number;
13
+ currency: string;
14
+ scopes: string[];
15
+ }, {
16
+ name: string;
17
+ model: "per_call";
18
+ unit_cents: number;
19
+ scopes: string[];
20
+ currency?: string | undefined;
21
+ }>;
22
+ export type Plan = z.infer<typeof PlanSchema>;
23
+ /** /.well-known/agent.json — the discovery manifest agents parse. Keep stable: it is a public protocol. */
24
+ export declare const ManifestSchema: z.ZodObject<{
25
+ tollbase_version: z.ZodLiteral<"1">;
26
+ service: z.ZodObject<{
27
+ name: z.ZodString;
28
+ slug: z.ZodString;
29
+ }, "strip", z.ZodTypeAny, {
30
+ name: string;
31
+ slug: string;
32
+ }, {
33
+ name: string;
34
+ slug: string;
35
+ }>;
36
+ auth: z.ZodObject<{
37
+ register_url: z.ZodString;
38
+ methods: z.ZodArray<z.ZodEnum<["web_bot_auth", "email_claim"]>, "many">;
39
+ key_url: z.ZodString;
40
+ claim_required: z.ZodBoolean;
41
+ }, "strip", z.ZodTypeAny, {
42
+ register_url: string;
43
+ methods: ("web_bot_auth" | "email_claim")[];
44
+ key_url: string;
45
+ claim_required: boolean;
46
+ }, {
47
+ register_url: string;
48
+ methods: ("web_bot_auth" | "email_claim")[];
49
+ key_url: string;
50
+ claim_required: boolean;
51
+ }>;
52
+ plans: z.ZodArray<z.ZodObject<{
53
+ name: z.ZodString;
54
+ model: z.ZodLiteral<"per_call">;
55
+ unit_cents: z.ZodNumber;
56
+ currency: z.ZodDefault<z.ZodString>;
57
+ scopes: z.ZodArray<z.ZodString, "many">;
58
+ }, "strip", z.ZodTypeAny, {
59
+ name: string;
60
+ model: "per_call";
61
+ unit_cents: number;
62
+ currency: string;
63
+ scopes: string[];
64
+ }, {
65
+ name: string;
66
+ model: "per_call";
67
+ unit_cents: number;
68
+ scopes: string[];
69
+ currency?: string | undefined;
70
+ }>, "many">;
71
+ docs: z.ZodOptional<z.ZodString>;
72
+ }, "strip", z.ZodTypeAny, {
73
+ tollbase_version: "1";
74
+ service: {
75
+ name: string;
76
+ slug: string;
77
+ };
78
+ auth: {
79
+ register_url: string;
80
+ methods: ("web_bot_auth" | "email_claim")[];
81
+ key_url: string;
82
+ claim_required: boolean;
83
+ };
84
+ plans: {
85
+ name: string;
86
+ model: "per_call";
87
+ unit_cents: number;
88
+ currency: string;
89
+ scopes: string[];
90
+ }[];
91
+ docs?: string | undefined;
92
+ }, {
93
+ tollbase_version: "1";
94
+ service: {
95
+ name: string;
96
+ slug: string;
97
+ };
98
+ auth: {
99
+ register_url: string;
100
+ methods: ("web_bot_auth" | "email_claim")[];
101
+ key_url: string;
102
+ claim_required: boolean;
103
+ };
104
+ plans: {
105
+ name: string;
106
+ model: "per_call";
107
+ unit_cents: number;
108
+ scopes: string[];
109
+ currency?: string | undefined;
110
+ }[];
111
+ docs?: string | undefined;
112
+ }>;
113
+ export type Manifest = z.infer<typeof ManifestSchema>;
114
+ /** Structured HTTP 402 challenge — the machine-readable paywall loop. `reason` enum is the contract. */
115
+ export declare const Err402Reason: z.ZodEnum<["cap_exceeded", "no_plan", "payment_failed", "not_claimed"]>;
116
+ export type Err402ReasonT = z.infer<typeof Err402Reason>;
117
+ export interface Err402Body {
118
+ error: "payment_required";
119
+ reason: Err402ReasonT;
120
+ account_id: string | null;
121
+ topup_url: string | null;
122
+ claim_url: string | null;
123
+ plan_options: Plan[];
124
+ message: string;
125
+ }
126
+ export declare function err402(reason: Err402ReasonT, opts: {
127
+ accountId?: string;
128
+ topupUrl?: string;
129
+ claimUrl?: string;
130
+ plans?: Plan[];
131
+ }): Err402Body;
132
+ export declare const RegisterRequestSchema: z.ZodObject<{
133
+ requested_scopes: z.ZodArray<z.ZodString, "many">;
134
+ operator_email: z.ZodString;
135
+ agent_label: z.ZodOptional<z.ZodString>;
136
+ }, "strip", z.ZodTypeAny, {
137
+ requested_scopes: string[];
138
+ operator_email: string;
139
+ agent_label?: string | undefined;
140
+ }, {
141
+ requested_scopes: string[];
142
+ operator_email: string;
143
+ agent_label?: string | undefined;
144
+ }>;
145
+ export type RegisterRequest = z.infer<typeof RegisterRequestSchema>;
146
+ export declare const UsageEventSchema: z.ZodObject<{
147
+ idempotency_key: z.ZodString;
148
+ account_id: z.ZodString;
149
+ tool: z.ZodString;
150
+ units: z.ZodNumber;
151
+ cost_cents: z.ZodNumber;
152
+ occurred_at: z.ZodString;
153
+ }, "strip", z.ZodTypeAny, {
154
+ idempotency_key: string;
155
+ account_id: string;
156
+ tool: string;
157
+ units: number;
158
+ cost_cents: number;
159
+ occurred_at: string;
160
+ }, {
161
+ idempotency_key: string;
162
+ account_id: string;
163
+ tool: string;
164
+ units: number;
165
+ cost_cents: number;
166
+ occurred_at: string;
167
+ }>;
168
+ export type UsageEvent = z.infer<typeof UsageEventSchema>;
169
+ /** JWT claims carried by agent access tokens. Cap is embedded so the vendor enforces locally (P1). */
170
+ export interface AgentTokenClaims {
171
+ sub: string;
172
+ svc: string;
173
+ scope: string;
174
+ cap: number;
175
+ [k: string]: unknown;
176
+ }
package/dist/types.js ADDED
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ /** Pricing: MVP supports per-call pricing. Tiered/per-unit models follow the same shape. */
3
+ export const PlanSchema = z.object({
4
+ name: z.string(),
5
+ model: z.literal("per_call"),
6
+ unit_cents: z.number().int().positive(),
7
+ currency: z.string().default("usd"),
8
+ scopes: z.array(z.string()).min(1),
9
+ });
10
+ /** /.well-known/agent.json — the discovery manifest agents parse. Keep stable: it is a public protocol. */
11
+ export const ManifestSchema = z.object({
12
+ tollbase_version: z.literal("1"),
13
+ service: z.object({ name: z.string(), slug: z.string() }),
14
+ auth: z.object({
15
+ register_url: z.string().url(),
16
+ methods: z.array(z.enum(["web_bot_auth", "email_claim"])),
17
+ key_url: z.string().url(),
18
+ claim_required: z.boolean(),
19
+ }),
20
+ plans: z.array(PlanSchema),
21
+ docs: z.string().url().optional(),
22
+ });
23
+ /** Structured HTTP 402 challenge — the machine-readable paywall loop. `reason` enum is the contract. */
24
+ export const Err402Reason = z.enum(["cap_exceeded", "no_plan", "payment_failed", "not_claimed"]);
25
+ export function err402(reason, opts) {
26
+ const messages = {
27
+ cap_exceeded: "Spend cap reached. Request a top-up to continue.",
28
+ no_plan: "No plan selected for this account. Register first.",
29
+ payment_failed: "Payment method failed. Ask your operator to update it.",
30
+ not_claimed: "Account pending operator approval. Poll status or ask your operator to claim.",
31
+ };
32
+ return {
33
+ error: "payment_required",
34
+ reason,
35
+ account_id: opts.accountId ?? null,
36
+ topup_url: opts.topupUrl ?? null,
37
+ claim_url: opts.claimUrl ?? null,
38
+ plan_options: opts.plans ?? [],
39
+ message: messages[reason],
40
+ };
41
+ }
42
+ export const RegisterRequestSchema = z.object({
43
+ requested_scopes: z.array(z.string()).min(1),
44
+ operator_email: z.string().email(),
45
+ agent_label: z.string().max(120).optional(),
46
+ });
47
+ export const UsageEventSchema = z.object({
48
+ idempotency_key: z.string().min(8),
49
+ account_id: z.string(),
50
+ tool: z.string(),
51
+ units: z.number().positive(),
52
+ cost_cents: z.number().int().nonnegative(),
53
+ occurred_at: z.string(),
54
+ });
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@tollbase/core",
3
+ "version": "0.3.0",
4
+ "description": "Tollbase shared protocol types (manifest, 402 challenge) plus config and logging utilities.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ "./types": {
9
+ "source": "./src/types.ts",
10
+ "types": "./dist/types.d.ts",
11
+ "default": "./dist/types.js"
12
+ },
13
+ "./config": {
14
+ "source": "./src/config.ts",
15
+ "types": "./dist/config.d.ts",
16
+ "default": "./dist/config.js"
17
+ },
18
+ "./log": {
19
+ "source": "./src/log.ts",
20
+ "types": "./dist/log.d.ts",
21
+ "default": "./dist/log.js"
22
+ }
23
+ },
24
+ "dependencies": {
25
+ "zod": "^3.23.8"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/tollbase/tollbase.git"
30
+ },
31
+ "homepage": "https://tollbase.dev",
32
+ "keywords": [
33
+ "ai-agents",
34
+ "agents",
35
+ "billing",
36
+ "metering",
37
+ "mcp",
38
+ "payments",
39
+ "402",
40
+ "usage-based"
41
+ ],
42
+ "engines": {
43
+ "node": ">=20"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "files": [
49
+ "dist",
50
+ "README.md",
51
+ "LICENSE"
52
+ ],
53
+ "scripts": {
54
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
55
+ "prepublishOnly": "npm run build"
56
+ }
57
+ }