@voyantjs/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.
Files changed (54) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +48 -0
  3. package/dist/app.d.ts +7 -0
  4. package/dist/app.d.ts.map +1 -0
  5. package/dist/app.js +81 -0
  6. package/dist/auth/crypto.d.ts +15 -0
  7. package/dist/auth/crypto.d.ts.map +1 -0
  8. package/dist/auth/crypto.js +58 -0
  9. package/dist/auth/index.d.ts +4 -0
  10. package/dist/auth/index.d.ts.map +1 -0
  11. package/dist/auth/index.js +2 -0
  12. package/dist/auth/session-jwt.d.ts +7 -0
  13. package/dist/auth/session-jwt.d.ts.map +1 -0
  14. package/dist/auth/session-jwt.js +23 -0
  15. package/dist/index.d.ts +10 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +4 -0
  18. package/dist/middleware/auth.d.ts +10 -0
  19. package/dist/middleware/auth.d.ts.map +1 -0
  20. package/dist/middleware/auth.js +154 -0
  21. package/dist/middleware/cors.d.ts +6 -0
  22. package/dist/middleware/cors.d.ts.map +1 -0
  23. package/dist/middleware/cors.js +40 -0
  24. package/dist/middleware/db.d.ts +9 -0
  25. package/dist/middleware/db.d.ts.map +1 -0
  26. package/dist/middleware/db.js +6 -0
  27. package/dist/middleware/error-boundary.d.ts +4 -0
  28. package/dist/middleware/error-boundary.d.ts.map +1 -0
  29. package/dist/middleware/error-boundary.js +47 -0
  30. package/dist/middleware/index.d.ts +9 -0
  31. package/dist/middleware/index.d.ts.map +1 -0
  32. package/dist/middleware/index.js +8 -0
  33. package/dist/middleware/logger.d.ts +5 -0
  34. package/dist/middleware/logger.d.ts.map +1 -0
  35. package/dist/middleware/logger.js +19 -0
  36. package/dist/middleware/rate-limit.d.ts +18 -0
  37. package/dist/middleware/rate-limit.d.ts.map +1 -0
  38. package/dist/middleware/rate-limit.js +45 -0
  39. package/dist/middleware/require-actor.d.ts +27 -0
  40. package/dist/middleware/require-actor.d.ts.map +1 -0
  41. package/dist/middleware/require-actor.js +37 -0
  42. package/dist/middleware/require-permission.d.ts +9 -0
  43. package/dist/middleware/require-permission.d.ts.map +1 -0
  44. package/dist/middleware/require-permission.js +48 -0
  45. package/dist/module.d.ts +27 -0
  46. package/dist/module.d.ts.map +1 -0
  47. package/dist/module.js +1 -0
  48. package/dist/plugin.d.ts +44 -0
  49. package/dist/plugin.d.ts.map +1 -0
  50. package/dist/plugin.js +33 -0
  51. package/dist/types.d.ts +69 -0
  52. package/dist/types.d.ts.map +1 -0
  53. package/dist/types.js +1 -0
  54. package/package.json +105 -0
package/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 PixelMakers Studio SRL
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly
28
+ display and redistribute the Software for any Permitted Purpose identified
29
+ below.
30
+
31
+ ### Permitted Purpose
32
+
33
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing
34
+ Use means making the Software available to others in a commercial product or
35
+ service that:
36
+
37
+ 1. substitutes for the Software;
38
+
39
+ 2. substitutes for any other product or service we offer using the Software
40
+ that exists as of the date we make the Software available; or
41
+
42
+ 3. offers the same or substantially similar functionality as the Software.
43
+
44
+ Permitted Purposes specifically include using the Software:
45
+
46
+ 1. for your internal use and access;
47
+
48
+ 2. for non-commercial education;
49
+
50
+ 3. for non-commercial research; and
51
+
52
+ 4. in connection with professional services that you provide to a licensee
53
+ using the Software in accordance with these Terms and Conditions.
54
+
55
+ ### Patents
56
+
57
+ To the extent your use for a Permitted Purpose would necessarily infringe
58
+ our patents, the license grant above includes a license under our patents.
59
+ If you make a claim against any party that the Software infringes or
60
+ contributes to the infringement of any patent, then your patent license to
61
+ the Software ends immediately.
62
+
63
+ ### Redistribution
64
+
65
+ The Terms and Conditions apply to all copies, modifications and derivatives
66
+ of the Software.
67
+
68
+ If you redistribute any copies, modifications or derivatives of the
69
+ Software, you must include a copy of or a link to these Terms and Conditions
70
+ and not remove any copyright notices provided in or with the Software.
71
+
72
+ ### Disclaimer
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS
75
+ OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A
76
+ PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
77
+
78
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO
79
+ THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
80
+ DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
81
+
82
+ ### Trademarks
83
+
84
+ Except for displaying the License Details and identifying us as the origin
85
+ of the Software, you have no right under these Terms and Conditions to use
86
+ our trademarks, trade names, service marks or product names.
87
+
88
+ ---
89
+
90
+ ## Grant of Future License
91
+
92
+ We hereby irrevocably grant you an additional license to use the Software
93
+ under the Apache License, Version 2.0 that is effective on the second
94
+ anniversary of the date we make the Software available. On or after that
95
+ date, you may use the Software under the Apache License, Version 2.0, in
96
+ which case the following will apply:
97
+
98
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
99
+ use this file except in compliance with the License.
100
+
101
+ You may obtain a copy of the License at
102
+
103
+ http://www.apache.org/licenses/LICENSE-2.0
104
+
105
+ Unless required by applicable law or agreed to in writing, software
106
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
107
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
108
+ License for the specific language governing permissions and limitations
109
+ under the License.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @voyantjs/hono
2
+
3
+ Hono transport adapter for Voyant. Provides `createApp()`, middleware, auth helpers, and plugin expansion for mounting Voyant modules behind a Hono app.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @voyantjs/hono hono
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { createApp } from "@voyantjs/hono"
15
+
16
+ const app = createApp({
17
+ db: (env) => getDb(env),
18
+ auth: { handler, resolve },
19
+ modules: [crmModule, productsModule, bookingsModule],
20
+ plugins: [payloadCmsPlugin({ /* ... */ })],
21
+ })
22
+ ```
23
+
24
+ The middleware chain is: container → requestId → logger → errorBoundary → CORS → health → auth handler → requireAuth → db → actor guards → module routes.
25
+
26
+ ## Exports
27
+
28
+ | Entry | Description |
29
+ | --- | --- |
30
+ | `.` | Barrel re-exports |
31
+ | `./app` | `createApp` factory |
32
+ | `./module` | `HonoModule`, `HonoExtension` contracts |
33
+ | `./plugin` | `HonoPlugin`, `defineHonoPlugin`, `expandHonoPlugins` |
34
+ | `./middleware` | All middleware re-exports |
35
+ | `./middleware/auth` | `requireAuth` session/API-key/JWT auth |
36
+ | `./middleware/cors` | CORS configuration |
37
+ | `./middleware/error-boundary` | Error handling + JSON error envelope |
38
+ | `./middleware/db` | Attach db client to `c.var.db` |
39
+ | `./middleware/rate-limit` | KV-backed rate limiter |
40
+ | `./middleware/require-actor` | Enforce `staff`/`customer`/`partner`/`supplier` actor |
41
+ | `./middleware/require-permission` | Permission-based guards |
42
+ | `./middleware/logger` | Request logger |
43
+ | `./auth/session-jwt` | `verifySession` JWT verification |
44
+ | `./auth/crypto` | `sha256Base64Url`, cookie helpers |
45
+
46
+ ## License
47
+
48
+ FSL-1.1-Apache-2.0
package/dist/app.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { Hono } from "hono";
2
+ import type { VoyantAppConfig, VoyantBindings, VoyantVariables } from "./types.js";
3
+ export declare function createApp<TBindings extends VoyantBindings>(config: VoyantAppConfig<TBindings>): Hono<{
4
+ Bindings: TBindings;
5
+ Variables: VoyantVariables;
6
+ }>;
7
+ //# sourceMappingURL=app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAS3B,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAElF,wBAAgB,SAAS,CAAC,SAAS,SAAS,cAAc,EACxD,MAAM,EAAE,eAAe,CAAC,SAAS,CAAC,GACjC,IAAI,CAAC;IAAE,QAAQ,EAAE,SAAS,CAAC;IAAC,SAAS,EAAE,eAAe,CAAA;CAAE,CAAC,CAsF3D"}
package/dist/app.js ADDED
@@ -0,0 +1,81 @@
1
+ import { createContainer } from "@voyantjs/core";
2
+ import { Hono } from "hono";
3
+ import { requireAuth } from "./middleware/auth.js";
4
+ import { cors } from "./middleware/cors.js";
5
+ import { db } from "./middleware/db.js";
6
+ import { errorBoundary, requestId } from "./middleware/error-boundary.js";
7
+ import { logger } from "./middleware/logger.js";
8
+ import { requireActor } from "./middleware/require-actor.js";
9
+ import { expandHonoPlugins } from "./plugin.js";
10
+ export function createApp(config) {
11
+ const app = new Hono();
12
+ // Expand plugins into their constituent modules/extensions before mounting
13
+ const expanded = config.plugins ? expandHonoPlugins(config.plugins) : null;
14
+ const allModules = [...(config.modules ?? []), ...(expanded?.modules ?? [])];
15
+ const allExtensions = [...(config.extensions ?? []), ...(expanded?.extensions ?? [])];
16
+ // Module container — registered services are resolvable from routes
17
+ const container = createContainer();
18
+ for (const mod of allModules) {
19
+ if (mod.module.service !== undefined) {
20
+ container.register(mod.module.name, mod.module.service);
21
+ }
22
+ }
23
+ app.use("*", async (c, next) => {
24
+ c.set("container", container);
25
+ return next();
26
+ });
27
+ // Request ID header
28
+ app.use("*", requestId);
29
+ // Structured logger
30
+ app.use("*", logger(config.logger));
31
+ // Global error boundary
32
+ app.use("*", errorBoundary);
33
+ // CORS (allowlist via env CORS_ALLOWLIST)
34
+ app.use("*", cors());
35
+ // Health check (public, no auth)
36
+ app.get("/health", (c) => c.json({ status: "ok" }));
37
+ // App-owned auth handler (must be before auth middleware — these routes are public)
38
+ const authHandler = config.auth?.handler;
39
+ if (authHandler) {
40
+ app.all("/auth/*", async (c) => {
41
+ const authApp = authHandler(c.env);
42
+ return authApp.fetch(c.req.raw, c.env, c.executionCtx);
43
+ });
44
+ }
45
+ // Auth middleware for all other routes
46
+ app.use("*", requireAuth(config.db, { publicPaths: config.publicPaths, auth: config.auth }));
47
+ // DB middleware — sets c.var.db for all downstream handlers
48
+ app.use("*", db(config.db));
49
+ // Actor guards for the two API surfaces
50
+ app.use("/v1/admin/*", requireActor("staff"));
51
+ app.use("/v1/public/*", requireActor("customer", "partner", "supplier"));
52
+ // Mount module routes
53
+ for (const mod of allModules) {
54
+ if (mod.adminRoutes) {
55
+ app.route(`/v1/admin/${mod.module.name}`, mod.adminRoutes);
56
+ }
57
+ if (mod.publicRoutes) {
58
+ app.route(`/v1/public/${mod.module.name}`, mod.publicRoutes);
59
+ }
60
+ if (mod.routes) {
61
+ app.route(`/v1/${mod.module.name}`, mod.routes);
62
+ }
63
+ }
64
+ // Mount extension routes
65
+ for (const ext of allExtensions) {
66
+ if (ext.adminRoutes) {
67
+ app.route(`/v1/admin/${ext.extension.module}`, ext.adminRoutes);
68
+ }
69
+ if (ext.publicRoutes) {
70
+ app.route(`/v1/public/${ext.extension.module}`, ext.publicRoutes);
71
+ }
72
+ if (ext.routes) {
73
+ app.route(`/v1/${ext.extension.module}`, ext.routes);
74
+ }
75
+ }
76
+ // Additional routes
77
+ if (config.additionalRoutes) {
78
+ config.additionalRoutes(app);
79
+ }
80
+ return app;
81
+ }
@@ -0,0 +1,15 @@
1
+ export declare function randomBytesHex(lengthBytes: number): string;
2
+ export declare function sha256Hex(input: string | Uint8Array): Promise<string>;
3
+ export declare function generateNumericCode(length: number): string;
4
+ /**
5
+ * SHA-256 hash a string using Web Crypto API.
6
+ * Returns the hash as a base64url string without padding,
7
+ * matching Better Auth's `defaultKeyHasher` format.
8
+ */
9
+ export declare function sha256Base64Url(input: string): Promise<string>;
10
+ /**
11
+ * Unsign a Better Auth session cookie.
12
+ * Better Auth signs cookies as: encodeURIComponent(value + "." + base64(HMAC-SHA256(value, secret)))
13
+ */
14
+ export declare function unsignCookie(rawCookieValue: string, secret: string): Promise<string | null>;
15
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/auth/crypto.ts"],"names":[],"mappings":"AAAA,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAM1D;AAED,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAK3E;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAM1D;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAUpE;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAwBjG"}
@@ -0,0 +1,58 @@
1
+ export function randomBytesHex(lengthBytes) {
2
+ const bytes = new Uint8Array(lengthBytes);
3
+ crypto.getRandomValues(bytes);
4
+ return Array.from(bytes)
5
+ .map((b) => b.toString(16).padStart(2, "0"))
6
+ .join("");
7
+ }
8
+ export async function sha256Hex(input) {
9
+ const data = typeof input === "string" ? new TextEncoder().encode(input) : input;
10
+ const hash = await crypto.subtle.digest("SHA-256", data.buffer);
11
+ const arr = Array.from(new Uint8Array(hash));
12
+ return arr.map((b) => b.toString(16).padStart(2, "0")).join("");
13
+ }
14
+ export function generateNumericCode(length) {
15
+ const max = 10 ** length;
16
+ const buf = new Uint32Array(1);
17
+ crypto.getRandomValues(buf);
18
+ const code = Number((buf[0] ?? 0) % max);
19
+ return String(code).padStart(length, "0");
20
+ }
21
+ /**
22
+ * SHA-256 hash a string using Web Crypto API.
23
+ * Returns the hash as a base64url string without padding,
24
+ * matching Better Auth's `defaultKeyHasher` format.
25
+ */
26
+ export async function sha256Base64Url(input) {
27
+ const data = new TextEncoder().encode(input);
28
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
29
+ const bytes = new Uint8Array(hashBuffer);
30
+ let binary = "";
31
+ for (const byte of bytes) {
32
+ binary += String.fromCharCode(byte);
33
+ }
34
+ const base64 = btoa(binary);
35
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
36
+ }
37
+ /**
38
+ * Unsign a Better Auth session cookie.
39
+ * Better Auth signs cookies as: encodeURIComponent(value + "." + base64(HMAC-SHA256(value, secret)))
40
+ */
41
+ export async function unsignCookie(rawCookieValue, secret) {
42
+ const decoded = decodeURIComponent(rawCookieValue);
43
+ const lastDot = decoded.lastIndexOf(".");
44
+ if (lastDot < 1)
45
+ return null;
46
+ const value = decoded.substring(0, lastDot);
47
+ const signature = decoded.substring(lastDot + 1);
48
+ if (signature.length !== 44 || !signature.endsWith("="))
49
+ return null;
50
+ const encoder = new TextEncoder();
51
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
52
+ const sigBinStr = atob(signature);
53
+ const sigBytes = new Uint8Array(sigBinStr.length);
54
+ for (let i = 0; i < sigBinStr.length; i++)
55
+ sigBytes[i] = sigBinStr.charCodeAt(i);
56
+ const valid = await crypto.subtle.verify("HMAC", key, sigBytes, encoder.encode(value));
57
+ return valid ? value : null;
58
+ }
@@ -0,0 +1,4 @@
1
+ export { generateNumericCode, randomBytesHex, sha256Base64Url, sha256Hex, unsignCookie, } from "./crypto.js";
2
+ export type { SessionAuthContext } from "./session-jwt.js";
3
+ export { extractBearerToken, verifySession } from "./session-jwt.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,GACb,MAAM,aAAa,CAAA;AACpB,YAAY,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAC1D,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA"}
@@ -0,0 +1,2 @@
1
+ export { generateNumericCode, randomBytesHex, sha256Base64Url, sha256Hex, unsignCookie, } from "./crypto.js";
2
+ export { extractBearerToken, verifySession } from "./session-jwt.js";
@@ -0,0 +1,7 @@
1
+ export interface SessionAuthContext {
2
+ userId: string;
3
+ sessionId?: string;
4
+ }
5
+ export declare function verifySession(token: string, secretKey: string): Promise<SessionAuthContext>;
6
+ export declare function extractBearerToken(authHeader: string | undefined): string | null;
7
+ //# sourceMappingURL=session-jwt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-jwt.d.ts","sourceRoot":"","sources":["../../src/auth/session-jwt.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED,wBAAsB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAWjG;AAED,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAWhF"}
@@ -0,0 +1,23 @@
1
+ import { verifySessionClaims } from "@voyantjs/utils/session-claims";
2
+ export async function verifySession(token, secretKey) {
3
+ const payload = await verifySessionClaims(token, secretKey);
4
+ if (!payload) {
5
+ throw new Error("Invalid or expired token");
6
+ }
7
+ return {
8
+ userId: payload.userId,
9
+ sessionId: payload.sessionId,
10
+ };
11
+ }
12
+ export function extractBearerToken(authHeader) {
13
+ if (!authHeader)
14
+ return null;
15
+ const parts = authHeader.trim().split(/\s+/);
16
+ if (parts.length !== 2)
17
+ return null;
18
+ const scheme = parts[0];
19
+ const token = parts[1];
20
+ if (!scheme || !token || !/^bearer$/i.test(scheme))
21
+ return null;
22
+ return token;
23
+ }
@@ -0,0 +1,10 @@
1
+ export type { VoyantPermission } from "@voyantjs/core";
2
+ export { createApp } from "./app.js";
3
+ export type { SessionAuthContext } from "./auth/index.js";
4
+ export { extractBearerToken, generateNumericCode, randomBytesHex, sha256Base64Url, sha256Hex, unsignCookie, verifySession, } from "./auth/index.js";
5
+ export { consoleLoggerProvider, cors, db, errorBoundary, LIVE_LIMITS, logger, rateLimit, requestId, requireActor, requireAuth, requirePermission, } from "./middleware/index.js";
6
+ export type { HonoExtension, HonoModule } from "./module.js";
7
+ export type { ExpandedHonoPlugins, HonoPlugin } from "./plugin.js";
8
+ export { defineHonoPlugin, expandHonoPlugins } from "./plugin.js";
9
+ export type { DbFactory, LogEntry, LoggerProvider, VoyantAppConfig, VoyantAuthIntegration, VoyantAuthPermissionArgs, VoyantAuthResolveArgs, VoyantBindings, VoyantDb, VoyantExecutionContext, VoyantRequestAuthContext, VoyantVariables, } from "./types.js";
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AACzD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,EACZ,aAAa,GACd,MAAM,iBAAiB,CAAA;AACxB,OAAO,EACL,qBAAqB,EACrB,IAAI,EACJ,EAAE,EACF,aAAa,EACb,WAAW,EACX,MAAM,EACN,SAAS,EACT,SAAS,EACT,YAAY,EACZ,WAAW,EACX,iBAAiB,GAClB,MAAM,uBAAuB,CAAA;AAC9B,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC5D,YAAY,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AACjE,YAAY,EACV,SAAS,EACT,QAAQ,EACR,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,QAAQ,EACR,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createApp } from "./app.js";
2
+ export { extractBearerToken, generateNumericCode, randomBytesHex, sha256Base64Url, sha256Hex, unsignCookie, verifySession, } from "./auth/index.js";
3
+ export { consoleLoggerProvider, cors, db, errorBoundary, LIVE_LIMITS, logger, rateLimit, requestId, requireActor, requireAuth, requirePermission, } from "./middleware/index.js";
4
+ export { defineHonoPlugin, expandHonoPlugins } from "./plugin.js";
@@ -0,0 +1,10 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import type { DbFactory, VoyantAuthIntegration, VoyantBindings, VoyantVariables } from "../types.js";
3
+ export declare function requireAuth<TBindings extends VoyantBindings>(dbFactory: DbFactory<TBindings>, opts?: {
4
+ publicPaths?: string[];
5
+ auth?: VoyantAuthIntegration<TBindings>;
6
+ }): MiddlewareHandler<{
7
+ Bindings: TBindings;
8
+ Variables: VoyantVariables;
9
+ }>;
10
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAI7C,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAsCpG,wBAAgB,WAAW,CAAC,SAAS,SAAS,cAAc,EAC1D,SAAS,EAAE,SAAS,CAAC,SAAS,CAAC,EAC/B,IAAI,CAAC,EAAE;IACL,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;IACtB,IAAI,CAAC,EAAE,qBAAqB,CAAC,SAAS,CAAC,CAAA;CACxC,GACA,iBAAiB,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAA;IACnB,SAAS,EAAE,eAAe,CAAA;CAC3B,CAAC,CAmID"}
@@ -0,0 +1,154 @@
1
+ import { apikeyTable } from "@voyantjs/db/schema/iam";
2
+ import { and, eq } from "drizzle-orm";
3
+ import { sha256Base64Url } from "../auth/crypto.js";
4
+ import { extractBearerToken, verifySession } from "../auth/session-jwt.js";
5
+ function permissionsToScopes(permissions) {
6
+ if (!permissions)
7
+ return [];
8
+ try {
9
+ const parsed = JSON.parse(permissions);
10
+ const scopes = [];
11
+ for (const [resource, actions] of Object.entries(parsed)) {
12
+ if (Array.isArray(actions)) {
13
+ for (const action of actions) {
14
+ scopes.push(`${resource}:${action}`);
15
+ }
16
+ }
17
+ }
18
+ return scopes;
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ }
24
+ const API_KEY_PREFIX = "voy_";
25
+ function applyAuthContext(c, auth) {
26
+ if (auth.userId)
27
+ c.set("userId", auth.userId);
28
+ if (auth.sessionId)
29
+ c.set("sessionId", auth.sessionId);
30
+ if (auth.organizationId !== undefined)
31
+ c.set("organizationId", auth.organizationId ?? undefined);
32
+ if (auth.callerType)
33
+ c.set("callerType", auth.callerType);
34
+ if (auth.actor)
35
+ c.set("actor", auth.actor);
36
+ if (auth.scopes !== undefined)
37
+ c.set("scopes", auth.scopes);
38
+ if (auth.isInternalRequest !== undefined)
39
+ c.set("isInternalRequest", auth.isInternalRequest);
40
+ if (auth.apiKeyId)
41
+ c.set("apiKeyId", auth.apiKeyId);
42
+ }
43
+ export function requireAuth(dbFactory, opts) {
44
+ const publicPaths = opts?.publicPaths ?? [];
45
+ return async (c, next) => {
46
+ if (c.req.method === "OPTIONS")
47
+ return next();
48
+ const url = new URL(c.req.url);
49
+ const p = url.pathname.replace(/\/$/, "");
50
+ const isPublicAuth = p === "/auth/callback" || p.startsWith("/auth/");
51
+ const isHealthCheck = p === "/health";
52
+ if (isPublicAuth || isHealthCheck)
53
+ return next();
54
+ for (const pp of publicPaths) {
55
+ if (p === pp || p.startsWith(`${pp}/`))
56
+ return next();
57
+ }
58
+ const authHeader = c.req.header("authorization") || c.req.header("Authorization");
59
+ const token = extractBearerToken(authHeader);
60
+ // Strategy 1: Internal API Key
61
+ const internalKey = c.env.INTERNAL_API_KEY;
62
+ if (token && internalKey && token === internalKey) {
63
+ applyAuthContext(c, {
64
+ callerType: "internal",
65
+ isInternalRequest: true,
66
+ });
67
+ return next();
68
+ }
69
+ // Strategy 2: Core-owned API key support (voy_ prefixed)
70
+ if (token?.startsWith(API_KEY_PREFIX)) {
71
+ try {
72
+ const db = dbFactory(c.env);
73
+ const keyHash = await sha256Base64Url(token);
74
+ const [row] = await db
75
+ .select()
76
+ .from(apikeyTable)
77
+ .where(and(eq(apikeyTable.key, keyHash), eq(apikeyTable.enabled, true)))
78
+ .limit(1);
79
+ if (!row) {
80
+ return c.json({ error: "Invalid API key" }, 401);
81
+ }
82
+ if (row.expiresAt && row.expiresAt < new Date()) {
83
+ return c.json({ error: "API key expired" }, 401);
84
+ }
85
+ if (row.remaining !== null && row.remaining <= 0) {
86
+ return c.json({ error: "API key usage limit exceeded" }, 429);
87
+ }
88
+ if (row.remaining !== null) {
89
+ c.executionCtx.waitUntil?.(db
90
+ .update(apikeyTable)
91
+ .set({
92
+ remaining: row.remaining - 1,
93
+ requestCount: row.requestCount + 1,
94
+ lastRequest: new Date(),
95
+ })
96
+ .where(eq(apikeyTable.id, row.id))
97
+ .then(() => { })
98
+ .catch(() => { }));
99
+ }
100
+ else {
101
+ c.executionCtx.waitUntil?.(db
102
+ .update(apikeyTable)
103
+ .set({
104
+ requestCount: row.requestCount + 1,
105
+ lastRequest: new Date(),
106
+ })
107
+ .where(eq(apikeyTable.id, row.id))
108
+ .then(() => { })
109
+ .catch(() => { }));
110
+ }
111
+ const scopes = permissionsToScopes(row.permissions);
112
+ applyAuthContext(c, {
113
+ organizationId: row.referenceId,
114
+ scopes,
115
+ callerType: "api_key",
116
+ apiKeyId: row.id,
117
+ });
118
+ return next();
119
+ }
120
+ catch {
121
+ // fall through to next strategy
122
+ }
123
+ }
124
+ // Strategy 3: App-provided auth resolution (cookies, provider tokens, etc.)
125
+ if (opts?.auth?.resolve) {
126
+ const resolved = await opts.auth.resolve({
127
+ request: c.req.raw,
128
+ env: c.env,
129
+ db: dbFactory(c.env),
130
+ ctx: c.executionCtx,
131
+ });
132
+ if (resolved?.userId) {
133
+ applyAuthContext(c, resolved);
134
+ return next();
135
+ }
136
+ }
137
+ // Strategy 4: Generic session-claims bearer token support
138
+ const sessionSecret = c.env.SESSION_CLAIMS_SECRET;
139
+ if (token && sessionSecret && token.includes(".")) {
140
+ try {
141
+ const sessionAuth = await verifySession(token, sessionSecret);
142
+ applyAuthContext(c, {
143
+ ...sessionAuth,
144
+ callerType: "session",
145
+ });
146
+ return next();
147
+ }
148
+ catch {
149
+ // fall through
150
+ }
151
+ }
152
+ return c.json({ error: "Unauthorized" }, 401);
153
+ };
154
+ }
@@ -0,0 +1,6 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import type { VoyantBindings } from "../types.js";
3
+ export declare function cors(): MiddlewareHandler<{
4
+ Bindings: VoyantBindings;
5
+ }>;
6
+ //# sourceMappingURL=cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.d.ts","sourceRoot":"","sources":["../../src/middleware/cors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAWjD,wBAAgB,IAAI,IAAI,iBAAiB,CAAC;IAAE,QAAQ,EAAE,cAAc,CAAA;CAAE,CAAC,CAwCtE"}
@@ -0,0 +1,40 @@
1
+ function parseAllowlist(env) {
2
+ const raw = env.CORS_ALLOWLIST;
3
+ if (!raw)
4
+ return [];
5
+ return raw
6
+ .split(",")
7
+ .map((s) => s.trim())
8
+ .filter(Boolean);
9
+ }
10
+ export function cors() {
11
+ return async (c, next) => {
12
+ const origin = c.req.header("origin") || "";
13
+ const allowlist = parseAllowlist(c.env);
14
+ const allowed = allowlist.length === 0 ? false : allowlist.includes(origin);
15
+ if (origin && !allowed) {
16
+ console.warn("[CORS] Origin not in allowlist - CORS headers will NOT be set", {
17
+ origin,
18
+ allowlist,
19
+ path: c.req.path,
20
+ method: c.req.method,
21
+ });
22
+ }
23
+ if (c.req.method === "OPTIONS") {
24
+ if (allowed) {
25
+ c.header("Access-Control-Allow-Origin", origin);
26
+ c.header("Vary", "Origin");
27
+ c.header("Access-Control-Allow-Credentials", "true");
28
+ c.header("Access-Control-Allow-Headers", c.req.header("access-control-request-headers") || "content-type, authorization");
29
+ c.header("Access-Control-Allow-Methods", c.req.header("access-control-request-method") || "GET,POST,PUT,PATCH,DELETE,OPTIONS");
30
+ }
31
+ return new Response(null, { status: 204 });
32
+ }
33
+ await next();
34
+ if (allowed) {
35
+ c.header("Access-Control-Allow-Origin", origin);
36
+ c.header("Vary", "Origin");
37
+ c.header("Access-Control-Allow-Credentials", "true");
38
+ }
39
+ };
40
+ }
@@ -0,0 +1,9 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import type { DbFactory, VoyantBindings, VoyantDb } from "../types.js";
3
+ export declare function db<TBindings extends VoyantBindings>(factory: DbFactory<TBindings>): MiddlewareHandler<{
4
+ Bindings: TBindings;
5
+ Variables: {
6
+ db: VoyantDb;
7
+ };
8
+ }>;
9
+ //# sourceMappingURL=db.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/middleware/db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAE7C,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtE,wBAAgB,EAAE,CAAC,SAAS,SAAS,cAAc,EACjD,OAAO,EAAE,SAAS,CAAC,SAAS,CAAC,GAC5B,iBAAiB,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAA;IACnB,SAAS,EAAE;QAAE,EAAE,EAAE,QAAQ,CAAA;KAAE,CAAA;CAC5B,CAAC,CAKD"}
@@ -0,0 +1,6 @@
1
+ export function db(factory) {
2
+ return async (c, next) => {
3
+ c.set("db", factory(c.env));
4
+ await next();
5
+ };
6
+ }
@@ -0,0 +1,4 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ export declare const requestId: MiddlewareHandler;
3
+ export declare const errorBoundary: MiddlewareHandler;
4
+ //# sourceMappingURL=error-boundary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-boundary.d.ts","sourceRoot":"","sources":["../../src/middleware/error-boundary.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAU7C,eAAO,MAAM,SAAS,EAAE,iBAKvB,CAAA;AAID,eAAO,MAAM,aAAa,EAAE,iBAmC3B,CAAA"}