@umituz/web-hono 1.10.0 → 1.11.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.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), and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.11.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), 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,7 @@
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",
18
19
  "./package.json": "./package.json"
19
20
  },
20
21
  "scripts": {
@@ -61,12 +62,16 @@
61
62
  },
62
63
  "peerDependencies": {
63
64
  "@neondatabase/serverless": "^1.0.0",
65
+ "better-auth": "^1.7.0",
64
66
  "drizzle-orm": "^0.45.4",
65
67
  "hono": "^4.0.0",
66
68
  "react": "^18.0.0 || ^19.0.0",
67
69
  "zod": "^4.0.0"
68
70
  },
69
71
  "peerDependenciesMeta": {
72
+ "better-auth": {
73
+ "optional": true
74
+ },
70
75
  "react": {
71
76
  "optional": true
72
77
  }
@@ -75,14 +80,17 @@
75
80
  "@electric-sql/pglite": "^0.5.9",
76
81
  "@eslint/js": "^9.32.0",
77
82
  "@neondatabase/serverless": "^1.2.0",
83
+ "@testing-library/dom": "^10.0.0",
78
84
  "@testing-library/react": "^16.3.3",
79
85
  "@types/node": "~22.13.10",
80
86
  "@types/react": "^19.1.0",
87
+ "better-auth": "^1.7.12",
81
88
  "drizzle-orm": "^0.45.4",
82
89
  "eslint": "^9.32.0",
83
90
  "hono": "^4.13.13",
84
91
  "jsdom": "^29.1.1",
85
92
  "react": "^19.1.0",
93
+ "react-dom": "19.3.0",
86
94
  "typescript": "~5.9.2",
87
95
  "typescript-eslint": "^8.58.0",
88
96
  "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/docstore.ts CHANGED
@@ -83,9 +83,13 @@ export function canTransition(map: Record<string, string[]>, from: string, to: s
83
83
  return from === to || (map[from] ?? []).includes(to);
84
84
  }
85
85
 
86
- /** ISO string → epoch ms; anything unparsable falls back to now. */
86
+ /** ISO string → epoch ms; anything unparsable falls back to now. The
87
+ * epoch-0 instant (1970-01-01T00:00:00Z) parses to 0 and must stay 0 —
88
+ * a truthiness check would silently rewrite it to "now". */
87
89
  export function epoch(iso: unknown): number {
88
- return typeof iso === 'string' && Date.parse(iso) ? Date.parse(iso) : Date.now();
90
+ if (typeof iso !== 'string') return Date.now();
91
+ const ms = Date.parse(iso);
92
+ return Number.isNaN(ms) ? Date.now() : ms;
89
93
  }
90
94
 
91
95
  function defaultDb(c: RequestContext): CrudDb {
@@ -145,12 +149,14 @@ export function docStore(spec: DocStoreSpec) {
145
149
  return and(...conds);
146
150
  }
147
151
 
148
- function rowValues(col: DocCollectionSpec, doc: DocInput, nowMs: number): Record<string, unknown> {
152
+ function rowValues(col: DocCollectionSpec, doc: DocInput): Record<string, unknown> {
149
153
  const id = docIdOf(col, doc);
150
154
  const values: Record<string, unknown> = {
151
155
  id,
152
- createdAt: epoch(doc.createdAt) || nowMs,
153
- updatedAt: epoch(doc.updatedAt) || nowMs,
156
+ // epoch() already falls back to now for unparsable input; the extra
157
+ // `|| now` would rewrite a legitimate 0 (epoch-0 instant) to now.
158
+ createdAt: epoch(doc.createdAt),
159
+ updatedAt: epoch(doc.updatedAt),
154
160
  deletedAt: null as number | null,
155
161
  data: doc,
156
162
  ...col.columns?.(doc),
@@ -185,7 +191,7 @@ export function docStore(spec: DocStoreSpec) {
185
191
  }
186
192
  await col.validate?.({ db, doc, existing });
187
193
  }
188
- const values = rowValues(col, doc, Date.now());
194
+ const values = rowValues(col, doc);
189
195
  await db
190
196
  .insert(col.table)
191
197
  .values(values as never)
@@ -203,7 +209,7 @@ export function docStore(spec: DocStoreSpec) {
203
209
  const col = requireSpec(key);
204
210
  let count = 0;
205
211
  for (let i = 0; i < docs.length; i += chunkSize) {
206
- const chunk = docs.slice(i, i + chunkSize).map((doc) => rowValues(col, doc, Date.now()));
212
+ const chunk = docs.slice(i, i + chunkSize).map((doc) => rowValues(col, doc));
207
213
  await db
208
214
  .insert(col.table)
209
215
  .values(chunk as never)