@umituz/web-hono 1.10.1 → 1.12.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/README.md CHANGED
@@ -182,6 +182,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
182
182
  | `@umituz/web-hono/store` | `createStore`, `StoreConfig`, `REFETCH_ALL` (+ `read`/`view`/`http`/`subscribeAll`/`snapshot`/`immutable` on the store) |
183
183
  | `@umituz/web-hono/store/react` | `makeStoreHooks(store)` → `useQuery`, `useDbValue`, `useCollection`, `useHydration`, `QueryResult` |
184
184
  | `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` |
185
+ | `@umituz/web-hono/auth` | `authTables(prefix)`, `AuthTables`, `AuthEnv`, `createAuthGetter`, `AuthOptions`/`AuthInstance`, `mountAuth`, `createSessionHelpers` (`currentUser`/`scopeOf`), `SessionUserInfo` — better-auth (optional peer) over the shared Neon DB |
185
186
 
186
187
  ## Migration notes (per feature, all optional)
187
188
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.10.1",
4
- "description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.12.0",
4
+ "description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), and db lifecycle scripts (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "types": "./src/index.ts",
@@ -15,6 +15,8 @@
15
15
  "./store": "./src/store.ts",
16
16
  "./store/react": "./src/store-react.ts",
17
17
  "./lifecycle": "./src/lifecycle.ts",
18
+ "./auth": "./src/auth.ts",
19
+ "./etag": "./src/etag.ts",
18
20
  "./package.json": "./package.json"
19
21
  },
20
22
  "scripts": {
@@ -61,12 +63,16 @@
61
63
  },
62
64
  "peerDependencies": {
63
65
  "@neondatabase/serverless": "^1.0.0",
66
+ "better-auth": "^1.7.0",
64
67
  "drizzle-orm": "^0.45.4",
65
68
  "hono": "^4.0.0",
66
69
  "react": "^18.0.0 || ^19.0.0",
67
70
  "zod": "^4.0.0"
68
71
  },
69
72
  "peerDependenciesMeta": {
73
+ "better-auth": {
74
+ "optional": true
75
+ },
70
76
  "react": {
71
77
  "optional": true
72
78
  }
@@ -75,14 +81,17 @@
75
81
  "@electric-sql/pglite": "^0.5.9",
76
82
  "@eslint/js": "^9.32.0",
77
83
  "@neondatabase/serverless": "^1.2.0",
84
+ "@testing-library/dom": "^10.0.0",
78
85
  "@testing-library/react": "^16.3.3",
79
86
  "@types/node": "~22.13.10",
80
87
  "@types/react": "^19.1.0",
88
+ "better-auth": "^1.7.12",
81
89
  "drizzle-orm": "^0.45.4",
82
90
  "eslint": "^9.32.0",
83
91
  "hono": "^4.13.13",
84
92
  "jsdom": "^29.1.1",
85
93
  "react": "^19.1.0",
94
+ "react-dom": "19.3.0",
86
95
  "typescript": "~5.9.2",
87
96
  "typescript-eslint": "^8.58.0",
88
97
  "vitest": "3.2.4",
package/src/auth.ts ADDED
@@ -0,0 +1,166 @@
1
+ import { betterAuth } from 'better-auth';
2
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
3
+ import { eq } from 'drizzle-orm';
4
+ import { Hono } from 'hono';
5
+ import { boolean, index, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
6
+
7
+ export interface AuthEnv {
8
+ BETTER_AUTH_SECRET: string;
9
+ BETTER_AUTH_URL?: string;
10
+ }
11
+
12
+ const SESSION_SECONDS = 60 * 60 * 24 * 30;
13
+ const UPDATE_AGE_SECONDS = 60 * 60 * 24;
14
+
15
+ function authTableSet(prefix: string) {
16
+ const idx = (table: string, name: string) => `${prefix}_ba_${table}_${name}_idx`;
17
+ const baTime = {
18
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
19
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
20
+ };
21
+ const user = pgTable(`${prefix}_ba_user`, {
22
+ id: text().primaryKey(),
23
+ name: text().notNull(),
24
+ email: text().notNull().unique(),
25
+ emailVerified: boolean('email_verified').notNull().default(false),
26
+ image: text(),
27
+ ...baTime,
28
+ });
29
+ const session = pgTable(
30
+ `${prefix}_ba_session`,
31
+ {
32
+ id: text().primaryKey(),
33
+ expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
34
+ token: text().notNull().unique(),
35
+ ipAddress: text('ip_address'),
36
+ userAgent: text('user_agent'),
37
+ userId: text('user_id')
38
+ .notNull()
39
+ .references(() => user.id, { onDelete: 'cascade' }),
40
+ ...baTime,
41
+ },
42
+ (t) => [index(idx('session', 'user')).on(t.userId)],
43
+ );
44
+ const account = pgTable(
45
+ `${prefix}_ba_account`,
46
+ {
47
+ id: text().primaryKey(),
48
+ accountId: text('account_id').notNull(),
49
+ providerId: text('provider_id').notNull(),
50
+ userId: text('user_id')
51
+ .notNull()
52
+ .references(() => user.id, { onDelete: 'cascade' }),
53
+ accessToken: text('access_token'),
54
+ refreshToken: text('refresh_token'),
55
+ idToken: text('id_token'),
56
+ accessTokenExpiresAt: timestamp('access_token_expires_at', { withTimezone: true }),
57
+ refreshTokenExpiresAt: timestamp('refresh_token_expires_at', { withTimezone: true }),
58
+ scope: text(),
59
+ password: text(),
60
+ ...baTime,
61
+ },
62
+ (t) => [index(idx('account', 'user')).on(t.userId), uniqueIndex(idx('account', 'provider_account')).on(t.providerId, t.accountId)],
63
+ );
64
+ const verification = pgTable(
65
+ `${prefix}_ba_verification`,
66
+ {
67
+ id: text().primaryKey(),
68
+ identifier: text().notNull(),
69
+ value: text().notNull(),
70
+ expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
71
+ ...baTime,
72
+ },
73
+ (t) => [index(idx('verification', 'identifier')).on(t.identifier)],
74
+ );
75
+ return { user, session, account, verification };
76
+ }
77
+
78
+ export const authTables = authTableSet;
79
+ export type AuthTables = ReturnType<typeof authTableSet>;
80
+
81
+ type DbLike = Parameters<typeof drizzleAdapter>[0];
82
+
83
+ export interface ResetPasswordArgs {
84
+ user: { id: string; email: string; name: string };
85
+ url: string;
86
+ token: string;
87
+ }
88
+
89
+ export interface AuthOptions<E extends AuthEnv = AuthEnv> {
90
+ db: (env: E) => DbLike;
91
+ tables: AuthTables;
92
+ trustedOrigins?: string[];
93
+ sendResetPassword?: (args: ResetPasswordArgs) => Promise<void> | void;
94
+ }
95
+
96
+ function initAuth(env: AuthEnv, opts: AuthOptions<AuthEnv>) {
97
+ return betterAuth({
98
+ secret: env.BETTER_AUTH_SECRET,
99
+ baseURL: env.BETTER_AUTH_URL,
100
+ database: drizzleAdapter(opts.db(env), {
101
+ provider: 'pg',
102
+ schema: {
103
+ user: opts.tables.user,
104
+ session: opts.tables.session,
105
+ account: opts.tables.account,
106
+ verification: opts.tables.verification,
107
+ },
108
+ }),
109
+ emailAndPassword: {
110
+ enabled: true,
111
+ sendResetPassword: async (data) => {
112
+ const send =
113
+ opts.sendResetPassword ?? (({ user, url }) => console.log(`[password-reset] ${user.email} ${url}`));
114
+ await send({ user: data.user, url: data.url, token: data.token });
115
+ },
116
+ onPasswordReset: async ({ user }) => {
117
+ await opts.db(env).delete(opts.tables.session).where(eq(opts.tables.session.userId, user.id));
118
+ },
119
+ },
120
+ session: { expiresIn: SESSION_SECONDS, updateAge: UPDATE_AGE_SECONDS },
121
+ trustedOrigins: opts.trustedOrigins ?? [],
122
+ });
123
+ }
124
+
125
+ export type AuthInstance = ReturnType<typeof initAuth>;
126
+
127
+ export function createAuthGetter<E extends AuthEnv>(opts: AuthOptions<E>): (env: E) => AuthInstance {
128
+ const cache = new WeakMap<object, AuthInstance>();
129
+ return (env) => {
130
+ let auth = cache.get(env);
131
+ if (!auth) {
132
+ auth = initAuth(env, opts as AuthOptions<AuthEnv>);
133
+ cache.set(env, auth);
134
+ }
135
+ return auth;
136
+ };
137
+ }
138
+
139
+ export function mountAuth<E extends AuthEnv>(getAuth: (env: E) => AuthInstance): Hono<{ Bindings: E }> {
140
+ const router = new Hono<{ Bindings: E }>();
141
+ router.all('*', (c) => getAuth(c.env).handler(c.req.raw));
142
+ return router;
143
+ }
144
+
145
+ export interface AuthContext<E extends AuthEnv = AuthEnv> {
146
+ env: E;
147
+ req: { raw: Request };
148
+ }
149
+
150
+ export interface SessionUserInfo {
151
+ id: string;
152
+ email: string;
153
+ name: string;
154
+ }
155
+
156
+ export function createSessionHelpers<E extends AuthEnv>(getAuth: (env: E) => AuthInstance) {
157
+ async function currentUser(c: AuthContext<E>): Promise<SessionUserInfo | null> {
158
+ const session = await getAuth(c.env).api.getSession({ headers: c.req.raw.headers });
159
+ if (!session) return null;
160
+ return { id: session.user.id, email: session.user.email, name: session.user.name };
161
+ }
162
+ async function scopeOf(c: AuthContext<E>): Promise<string | null> {
163
+ return (await currentUser(c))?.id ?? null;
164
+ }
165
+ return { currentUser, scopeOf };
166
+ }
package/src/etag.ts ADDED
@@ -0,0 +1,5 @@
1
+ export function matchesEtag(header: string | undefined, etag: string): boolean {
2
+ if (!header) return false;
3
+ if (header.trim() === '*') return true;
4
+ return header.split(',').some((tag) => tag.trim().replace(/^W\//, '') === etag);
5
+ }