@donghanh/hono 0.2.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donghanh/hono",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Hono routes for GPT Store and LLM chat — renderers for ChatGPT and OpenAI-compatible APIs",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,7 +13,7 @@
13
13
  "directory": "packages/hono"
14
14
  },
15
15
  "peerDependencies": {
16
- "@donghanh/core": "^0.2.0",
16
+ "@donghanh/core": "^0.3.0",
17
17
  "hono": "^4.7.0"
18
18
  }
19
19
  }
@@ -0,0 +1,276 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type {
3
+ Executor,
4
+ OperationComponent,
5
+ OperationConfig,
6
+ } from "@donghanh/core";
7
+ import { App, Brief, buildRegistry, Message } from "@donghanh/core";
8
+ import { gptRoutes } from "./gpt";
9
+ import type { Authenticate } from "./middleware";
10
+
11
+ function makeOp(
12
+ id: string,
13
+ overrides: Partial<OperationConfig> = {},
14
+ ): OperationComponent {
15
+ const op = ((_props: { data: unknown }) =>
16
+ Brief({
17
+ children: [Message({ children: "ok" })],
18
+ })) as unknown as OperationComponent;
19
+ op.operationConfig = {
20
+ id,
21
+ type: "query",
22
+ description: `${id} desc`,
23
+ instruction: `call ${id}`,
24
+ input: { type: "object", properties: {} },
25
+ responseKey: id,
26
+ ...overrides,
27
+ };
28
+ return op;
29
+ }
30
+
31
+ function makeApp(ops: Record<string, OperationComponent>) {
32
+ return buildRegistry(App({ operations: ops }));
33
+ }
34
+
35
+ function makeExecutor(capture: { userId?: string; opId?: string }): Executor {
36
+ return async (opId, _vars, ctx) => {
37
+ capture.opId = opId;
38
+ capture.userId = (ctx.userId ?? "") as string;
39
+ return { ok: true };
40
+ };
41
+ }
42
+
43
+ function makeAuth(
44
+ mode: "valid" | "invalid",
45
+ flag: { called: boolean },
46
+ ): Authenticate {
47
+ return async (request) => {
48
+ flag.called = true;
49
+ const token = request.headers
50
+ .get("Authorization")
51
+ ?.replace(/^Bearer\s+/i, "");
52
+ if (mode === "valid" && token) return { userId: `user:${token}` };
53
+ return { error: new Response("unauth", { status: 401 }) };
54
+ };
55
+ }
56
+
57
+ async function req(
58
+ app: ReturnType<typeof gptRoutes>,
59
+ path: string,
60
+ init: RequestInit = {},
61
+ ) {
62
+ const res = await app.request(path, init);
63
+ let body: unknown = null;
64
+ try {
65
+ body = await res.clone().json();
66
+ } catch {
67
+ body = await res.text();
68
+ }
69
+ return { status: res.status, body };
70
+ }
71
+
72
+ describe("gptRoutes /operations listing", () => {
73
+ test("includes auth for each op when set", async () => {
74
+ const registry = makeApp({
75
+ a: makeOp("a", { auth: "required" }),
76
+ b: makeOp("b", { auth: "optional" }),
77
+ c: makeOp("c", { auth: "none" }),
78
+ d: makeOp("d"), // no auth → omitted in compact form
79
+ });
80
+ const app = gptRoutes({
81
+ registry,
82
+ executor: (async () => ({})) as Executor,
83
+ authenticate: async () => ({ userId: "x" }),
84
+ });
85
+ const { status, body } = await req(app, "/operations");
86
+ expect(status).toBe(200);
87
+ const b = body as { operations: Array<{ id: string; auth?: string }> };
88
+ const authById = Object.fromEntries(
89
+ b.operations.map((o) => [o.id, o.auth]),
90
+ );
91
+ expect(authById).toEqual({
92
+ a: "required",
93
+ b: "optional",
94
+ c: "none",
95
+ d: undefined,
96
+ });
97
+ });
98
+ });
99
+
100
+ describe("gptRoutes default /query /mutate", () => {
101
+ test("auth=required + no token → 401", async () => {
102
+ const flag = { called: false };
103
+ const app = gptRoutes({
104
+ registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
105
+ executor: (async () => ({})) as Executor,
106
+ authenticate: makeAuth("invalid", flag),
107
+ });
108
+ const r = await req(app, "/query/op");
109
+ expect(r.status).toBe(401);
110
+ expect(flag.called).toBe(true);
111
+ });
112
+
113
+ test("auth=required + valid token → 200 w/ userId", async () => {
114
+ const capture: { userId?: string; opId?: string } = {};
115
+ const flag = { called: false };
116
+ const app = gptRoutes({
117
+ registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
118
+ executor: makeExecutor(capture),
119
+ authenticate: makeAuth("valid", flag),
120
+ });
121
+ const r = await req(app, "/query/op", {
122
+ headers: { Authorization: "Bearer tok1" },
123
+ });
124
+ expect(r.status).toBe(200);
125
+ expect(capture.userId).toBe("user:tok1");
126
+ expect(flag.called).toBe(true);
127
+ });
128
+
129
+ test("auth=optional + no token → 200 anonymous", async () => {
130
+ const capture: { userId?: string } = {};
131
+ const flag = { called: false };
132
+ const app = gptRoutes({
133
+ registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
134
+ executor: makeExecutor(capture),
135
+ authenticate: makeAuth("invalid", flag),
136
+ });
137
+ const r = await req(app, "/query/op");
138
+ expect(r.status).toBe(200);
139
+ expect(capture.userId).toBe("anonymous");
140
+ expect(flag.called).toBe(true);
141
+ });
142
+
143
+ test("auth=optional + valid token → 200 w/ real userId", async () => {
144
+ const capture: { userId?: string } = {};
145
+ const flag = { called: false };
146
+ const app = gptRoutes({
147
+ registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
148
+ executor: makeExecutor(capture),
149
+ authenticate: makeAuth("valid", flag),
150
+ });
151
+ const r = await req(app, "/query/op", {
152
+ headers: { Authorization: "Bearer tok2" },
153
+ });
154
+ expect(r.status).toBe(200);
155
+ expect(capture.userId).toBe("user:tok2");
156
+ });
157
+
158
+ test("auth=none + no token → 200 anonymous", async () => {
159
+ const capture: { userId?: string } = {};
160
+ const flag = { called: false };
161
+ const app = gptRoutes({
162
+ registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
163
+ executor: makeExecutor(capture),
164
+ authenticate: makeAuth("invalid", flag),
165
+ });
166
+ const r = await req(app, "/query/op");
167
+ expect(r.status).toBe(200);
168
+ expect(capture.userId).toBe("anonymous");
169
+ expect(flag.called).toBe(false);
170
+ });
171
+
172
+ test("auth=none + valid token → 200 ANONYMOUS (authenticate not called)", async () => {
173
+ const capture: { userId?: string } = {};
174
+ const flag = { called: false };
175
+ const app = gptRoutes({
176
+ registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
177
+ executor: makeExecutor(capture),
178
+ authenticate: makeAuth("valid", flag),
179
+ });
180
+ const r = await req(app, "/query/op", {
181
+ headers: { Authorization: "Bearer tok3" },
182
+ });
183
+ expect(r.status).toBe(200);
184
+ expect(capture.userId).toBe("anonymous");
185
+ expect(flag.called).toBe(false);
186
+ });
187
+ });
188
+
189
+ describe("gptRoutes /public sub-paths", () => {
190
+ test("unknown op → 404", async () => {
191
+ const app = gptRoutes({
192
+ registry: makeApp({}),
193
+ executor: (async () => ({})) as Executor,
194
+ authenticate: async () => ({ userId: "x" }),
195
+ });
196
+ const r = await req(app, "/public/query/nope");
197
+ expect(r.status).toBe(404);
198
+ const b = r.body as { error: string };
199
+ expect(b.error).toContain("requires auth");
200
+ });
201
+
202
+ test("auth=required op → 404 (does not leak existence)", async () => {
203
+ const app = gptRoutes({
204
+ registry: makeApp({ priv: makeOp("priv", { auth: "required" }) }),
205
+ executor: (async () => ({})) as Executor,
206
+ authenticate: async () => ({ userId: "x" }),
207
+ });
208
+ const r = await req(app, "/public/query/priv");
209
+ expect(r.status).toBe(404);
210
+ });
211
+
212
+ test("auth=none op → 200 anonymous", async () => {
213
+ const capture: { userId?: string } = {};
214
+ const flag = { called: false };
215
+ const app = gptRoutes({
216
+ registry: makeApp({ pub: makeOp("pub", { auth: "none" }) }),
217
+ executor: makeExecutor(capture),
218
+ authenticate: makeAuth("valid", flag),
219
+ });
220
+ const r = await req(app, "/public/query/pub");
221
+ expect(r.status).toBe(200);
222
+ expect(capture.userId).toBe("anonymous");
223
+ expect(flag.called).toBe(false);
224
+ });
225
+
226
+ test("auth=optional + valid token → 200 w/ real userId", async () => {
227
+ const capture: { userId?: string } = {};
228
+ const flag = { called: false };
229
+ const app = gptRoutes({
230
+ registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
231
+ executor: makeExecutor(capture),
232
+ authenticate: makeAuth("valid", flag),
233
+ });
234
+ const r = await req(app, "/public/query/start", {
235
+ headers: { Authorization: "Bearer tok4" },
236
+ });
237
+ expect(r.status).toBe(200);
238
+ expect(capture.userId).toBe("user:tok4");
239
+ expect(flag.called).toBe(true);
240
+ });
241
+
242
+ test("auth=optional + bad token → 200 anonymous (public swallows)", async () => {
243
+ const capture: { userId?: string } = {};
244
+ const flag = { called: false };
245
+ const app = gptRoutes({
246
+ registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
247
+ executor: makeExecutor(capture),
248
+ authenticate: makeAuth("invalid", flag),
249
+ });
250
+ const r = await req(app, "/public/query/start", {
251
+ headers: { Authorization: "Bearer badtok" },
252
+ });
253
+ expect(r.status).toBe(200);
254
+ expect(capture.userId).toBe("anonymous");
255
+ expect(flag.called).toBe(true);
256
+ });
257
+
258
+ test("public mutate routes", async () => {
259
+ const capture: { userId?: string; opId?: string } = {};
260
+ const app = gptRoutes({
261
+ registry: makeApp({
262
+ pubmut: makeOp("pubmut", { auth: "none", type: "mutation" }),
263
+ }),
264
+ executor: makeExecutor(capture),
265
+ authenticate: async () => ({ userId: "x" }),
266
+ });
267
+ const r = await req(app, "/public/mutate/pubmut", {
268
+ method: "POST",
269
+ headers: { "content-type": "application/json" },
270
+ body: JSON.stringify({ $variables: "{}" }),
271
+ });
272
+ expect(r.status).toBe(200);
273
+ expect(capture.opId).toBe("pubmut");
274
+ expect(capture.userId).toBe("anonymous");
275
+ });
276
+ });
package/src/gpt.ts CHANGED
@@ -24,6 +24,11 @@ export interface GptRoutesConfig {
24
24
  ) => Promise<void>;
25
25
  }
26
26
 
27
+ /** Sentinel used when a request runs without an authenticated user. */
28
+ const ANONYMOUS: string = "anonymous";
29
+
30
+ type AuthMode = "none" | "optional" | "required";
31
+
27
32
  function jsonError(message: string, status = 400): Response {
28
33
  return new Response(JSON.stringify({ errors: [{ message }] }), {
29
34
  status,
@@ -43,7 +48,7 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
43
48
 
44
49
  const app = new Hono();
45
50
 
46
- // List operations
51
+ // List operations (auth advertised per-op)
47
52
  app.get("/operations", (c) => {
48
53
  const url = new URL(c.req.url);
49
54
  const search = url.searchParams.get("search")?.toLowerCase();
@@ -84,11 +89,36 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
84
89
  return c.json(detail);
85
90
  });
86
91
 
87
- // Execute query
88
- app.get("/query/:operation", async (c) => {
89
- const authResult = await authenticate(c.req.raw);
90
- if (isAuthError(authResult)) return authResult.error;
92
+ /**
93
+ * Resolve the userId to execute with, given the op's auth posture and the
94
+ * inbound request. Returns either a string userId or a Response to short-circuit.
95
+ */
96
+ async function resolveUser(
97
+ request: Request,
98
+ authMode: AuthMode,
99
+ public_: boolean,
100
+ ): Promise<string | Response> {
101
+ // auth: "none" — always anonymous, never call authenticate
102
+ if (authMode === "none") return ANONYMOUS;
103
+
104
+ // Public sub-router: be lenient — swallow errors, fall back to anonymous
105
+ if (public_) {
106
+ const result = await authenticate(request);
107
+ if (isAuthError(result)) return ANONYMOUS;
108
+ return result.userId;
109
+ }
110
+
111
+ // Default path: propagate auth error when required; swallow when optional
112
+ const result = await authenticate(request);
113
+ if (isAuthError(result)) {
114
+ if (authMode === "optional") return ANONYMOUS;
115
+ return result.error;
116
+ }
117
+ return result.userId;
118
+ }
91
119
 
120
+ // Execute query (default)
121
+ app.get("/query/:operation", async (c) => {
92
122
  const operationId = c.req.param("operation");
93
123
  const op = registry.get(operationId);
94
124
 
@@ -103,17 +133,18 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
103
133
  );
104
134
  }
105
135
 
106
- return handleExecution(c.req.raw, authResult.userId, operationId, () => {
136
+ const authMode: AuthMode = op.operationConfig.auth ?? "required";
137
+ const user = await resolveUser(c.req.raw, authMode, false);
138
+ if (user instanceof Response) return user;
139
+
140
+ return handleExecution(c.req.raw, user, operationId, () => {
107
141
  const url = new URL(c.req.url);
108
142
  return url.searchParams.get("$variables") ?? undefined;
109
143
  });
110
144
  });
111
145
 
112
- // Execute mutation
146
+ // Execute mutation (default)
113
147
  app.post("/mutate/:operation", async (c) => {
114
- const authResult = await authenticate(c.req.raw);
115
- if (isAuthError(authResult)) return authResult.error;
116
-
117
148
  const operationId = c.req.param("operation");
118
149
  const op = registry.get(operationId);
119
150
 
@@ -128,15 +159,73 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
128
159
  );
129
160
  }
130
161
 
131
- return handleExecution(
132
- c.req.raw,
133
- authResult.userId,
134
- operationId,
135
- async () => {
136
- const body = await c.req.json();
137
- return body.$variables;
138
- },
139
- );
162
+ const authMode: AuthMode = op.operationConfig.auth ?? "required";
163
+ const user = await resolveUser(c.req.raw, authMode, false);
164
+ if (user instanceof Response) return user;
165
+
166
+ return handleExecution(c.req.raw, user, operationId, async () => {
167
+ const body = await c.req.json();
168
+ return body.$variables;
169
+ });
170
+ });
171
+
172
+ // ---------- /public sub-paths ----------
173
+ // OAS-friendly no-auth surface. Rejects ops whose auth posture is "required".
174
+
175
+ const notFound404 = (body: { error: string }): Response =>
176
+ new Response(JSON.stringify(body), {
177
+ status: 404,
178
+ headers: { "content-type": "application/json" },
179
+ });
180
+
181
+ app.get("/public/query/:operation", async (c) => {
182
+ const operationId = c.req.param("operation");
183
+ const op = registry.get(operationId);
184
+ if (!op) {
185
+ return notFound404({ error: "Operation not found or requires auth." });
186
+ }
187
+ const authMode: AuthMode = op.operationConfig.auth ?? "required";
188
+ if (authMode === "required") {
189
+ return notFound404({ error: "Operation not found or requires auth." });
190
+ }
191
+ if (op.operationConfig.type !== "query") {
192
+ return jsonError(
193
+ `"${operationId}" is a mutation. Use POST /public/mutate/${operationId} instead.`,
194
+ );
195
+ }
196
+
197
+ const user = await resolveUser(c.req.raw, authMode, true);
198
+ if (user instanceof Response) return user;
199
+
200
+ return handleExecution(c.req.raw, user, operationId, () => {
201
+ const url = new URL(c.req.url);
202
+ return url.searchParams.get("$variables") ?? undefined;
203
+ });
204
+ });
205
+
206
+ app.post("/public/mutate/:operation", async (c) => {
207
+ const operationId = c.req.param("operation");
208
+ const op = registry.get(operationId);
209
+ if (!op) {
210
+ return notFound404({ error: "Operation not found or requires auth." });
211
+ }
212
+ const authMode: AuthMode = op.operationConfig.auth ?? "required";
213
+ if (authMode === "required") {
214
+ return notFound404({ error: "Operation not found or requires auth." });
215
+ }
216
+ if (op.operationConfig.type !== "mutation") {
217
+ return jsonError(
218
+ `"${operationId}" is a query. Use GET /public/query/${operationId} instead.`,
219
+ );
220
+ }
221
+
222
+ const user = await resolveUser(c.req.raw, authMode, true);
223
+ if (user instanceof Response) return user;
224
+
225
+ return handleExecution(c.req.raw, user, operationId, async () => {
226
+ const body = await c.req.json();
227
+ return body.$variables;
228
+ });
140
229
  });
141
230
 
142
231
  async function handleExecution(
@@ -153,20 +242,11 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
153
242
  }
154
243
 
155
244
  let variables: Record<string, unknown> = {};
156
- if (typeof rawVariables === "string" && encodeVariables) {
157
- // Decode using the inverse - we expect TOON format
158
- // The app provides its own decode in the executor or via a decode option
159
- // For now, pass raw through and let the executor handle it
160
- }
161
245
 
162
- // We need a decode function. Let's accept raw variables as TOON or JSON.
163
246
  if (typeof rawVariables === "string") {
164
247
  try {
165
- // Try JSON first
166
248
  variables = JSON.parse(rawVariables);
167
249
  } catch {
168
- // Pass as-is, let the app's decode handle it
169
- // Store raw so executor can decode
170
250
  variables = { $raw: rawVariables };
171
251
  }
172
252
  }
@@ -180,7 +260,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
180
260
  context: { userId, request },
181
261
  });
182
262
 
183
- // Render JSX tree through ChatGPT renderer
184
263
  const rendered = renderForChatGpt(brief, {
185
264
  encodeVariables,
186
265
  getOperationInput: (id) => {
@@ -189,7 +268,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
189
268
  },
190
269
  });
191
270
 
192
- // Build response
193
271
  const result: Record<string, unknown> = {
194
272
  data: {
195
273
  [registry.get(operationId)!.operationConfig.responseKey]: data,
@@ -203,7 +281,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
203
281
  result.nextSteps = rendered.nextSteps;
204
282
  }
205
283
 
206
- // Enrich response (inject display, etc)
207
284
  if (enrichResponse) {
208
285
  await enrichResponse(result, {
209
286
  operationId,
@@ -214,12 +291,10 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
214
291
  });
215
292
  }
216
293
 
217
- // Include response schema for start
218
294
  if (operationId === "start" && responseSchemas?.start) {
219
295
  result.responseSchema = responseSchemas.start;
220
296
  }
221
297
 
222
- // Always include operations list
223
298
  result.operations = registry.list();
224
299
 
225
300
  return new Response(JSON.stringify(result), {
@@ -232,7 +307,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
232
307
  errors: [{ message }],
233
308
  };
234
309
 
235
- // Include operation detail for self-correction
236
310
  const detail = registry.detail(operationId);
237
311
  if (detail) {
238
312
  errorResult.operationDetail = {
package/src/mcp.ts CHANGED
@@ -225,7 +225,7 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
225
225
  }
226
226
 
227
227
  case "resources/read": {
228
- const uri = (body.params ?? {}).uri as string | undefined;
228
+ const uri = body.params?.uri as string | undefined;
229
229
  if (!uri) return c.json(failure(id, -32602, "Missing uri"), 400);
230
230
  const widget = Object.values(widgets).find((w) => w.uri === uri);
231
231
  if (!widget) {