@guren/core 1.1.0 → 1.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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { ApiTokenStore, ApiToken } from '@guren/server';
1
+ import { ApiTokenStore, ApiToken, SessionStore, SessionData, OAuthStateStore, OAuthStatePayload } from '@guren/server';
2
2
  export * from '@guren/server';
3
- export { AccessorDefinitions, AccessorFn, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, CastType, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
3
+ export { AccessorDefinitions, AccessorFn, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
4
 
5
5
  /**
6
6
  * Options for DatabaseApiTokenStore.
@@ -59,4 +59,153 @@ declare class DatabaseApiTokenStore implements ApiTokenStore {
59
59
  private deserialize;
60
60
  }
61
61
 
62
- export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions };
62
+ /**
63
+ * Options for DatabaseSessionStore.
64
+ */
65
+ interface DatabaseSessionStoreOptions {
66
+ /**
67
+ * How the `data` column stores the serialized session.
68
+ *
69
+ * - `'json'` (default) passes the object straight through — use with a
70
+ * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
71
+ * - `'text'` serializes to a JSON string for plain text columns.
72
+ *
73
+ * Reads always accept both representations.
74
+ * @default 'json'
75
+ */
76
+ dataMode?: 'json' | 'text';
77
+ }
78
+ /**
79
+ * Database-backed session store built on the Guren ORM — works on any
80
+ * configured connection (SQLite, Postgres, MySQL, or Cloudflare D1), which
81
+ * makes it the serverless default: no Redis required on Lambda, Vercel, or
82
+ * Workers, and reads are strongly consistent (login → redirect → read works).
83
+ *
84
+ * Pass the Drizzle table for your `sessions` schema. Column property names
85
+ * must match `id` (text primary key), `data`, and `expiresAt`:
86
+ *
87
+ * ```ts
88
+ * export const sessions = sqliteTable('sessions', {
89
+ * id: text('id').primaryKey(),
90
+ * data: text('data', { mode: 'json' }).$type<Record<string, unknown>>().notNull(),
91
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
92
+ * })
93
+ * ```
94
+ *
95
+ * Session values must be JSON-serializable: Dates come back as ISO strings,
96
+ * `undefined` properties are dropped, and `bigint` values fail to serialize —
97
+ * unlike `MemorySessionStore`, which keeps live references. Store primitives
98
+ * and plain objects/arrays in sessions.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { DatabaseSessionStore } from '@guren/core'
103
+ * import { sessions } from '@/db/schema'
104
+ *
105
+ * app.use(createSessionMiddleware({ store: new DatabaseSessionStore(sessions) }))
106
+ * ```
107
+ */
108
+ declare class DatabaseSessionStore implements SessionStore {
109
+ private readonly model;
110
+ private readonly dataMode;
111
+ constructor(table: unknown, options?: DatabaseSessionStoreOptions);
112
+ read(id: string): Promise<SessionData | undefined>;
113
+ write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
114
+ destroy(id: string): Promise<void>;
115
+ /**
116
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
117
+ * data rewrite, no existence check. Missing rows and rows that have
118
+ * already expired (but not yet been swept) are left untouched, never
119
+ * resurrected — matching the `SessionStore.touch` contract and the memory
120
+ * store's behavior.
121
+ */
122
+ touch(id: string, ttlSeconds: number): Promise<void>;
123
+ /**
124
+ * Delete sessions whose expiration time has passed. Expired rows are
125
+ * already treated as missing (and removed) by `read`; call this from a
126
+ * scheduled job to keep the table small.
127
+ */
128
+ deleteExpired(now?: Date): Promise<void>;
129
+ private deserialize;
130
+ private expiryDate;
131
+ }
132
+
133
+ /**
134
+ * Database-backed OAuth state store built on the Guren ORM.
135
+ *
136
+ * The default `MemoryOAuthStateStore` keeps state in per-isolate memory,
137
+ * which breaks on serverless: the OAuth authorize redirect and the callback
138
+ * that follows it can land on different instances, so an in-memory map
139
+ * never sees the state that was just written. Backing the store with the
140
+ * database makes state visible to whichever instance handles the callback.
141
+ *
142
+ * Pass the Drizzle table for your `oauth_states` schema. Column property
143
+ * names must match `stateHash` (text primary key), `provider`,
144
+ * `redirectTo`, and `expiresAt`:
145
+ *
146
+ * ```ts
147
+ * export const oauthStates = sqliteTable('oauth_states', {
148
+ * stateHash: text('state_hash').primaryKey(),
149
+ * provider: text('provider').notNull(),
150
+ * redirectTo: text('redirect_to'),
151
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
152
+ * })
153
+ * ```
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * import { createOAuthManager, DatabaseOAuthStateStore } from '@guren/core'
158
+ * import { oauthStates } from '@/db/schema'
159
+ *
160
+ * export const oauth = createOAuthManager({
161
+ * stateStore: new DatabaseOAuthStateStore(oauthStates),
162
+ * })
163
+ * ```
164
+ */
165
+ declare class DatabaseOAuthStateStore implements OAuthStateStore {
166
+ private readonly model;
167
+ constructor(table: unknown);
168
+ store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
169
+ find(stateHash: string): Promise<OAuthStatePayload | null>;
170
+ /**
171
+ * Fetch the row for `stateHash`, clearing it out and returning null if
172
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
173
+ * in what they do with a live row.
174
+ */
175
+ private fetchLive;
176
+ delete(stateHash: string): Promise<void>;
177
+ /**
178
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
179
+ * caller for the same hash receives the payload.
180
+ *
181
+ * This guarantee depends on the configured ORM adapter's `delete()`
182
+ * reporting whether a row actually matched — either the deleted row
183
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
184
+ * default and only shipped adapter, always does this: RETURNING drivers
185
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
186
+ * when zero rows matched; MySQL resolves to a result carrying
187
+ * `affectedRows` (verified by inspection, not a dedicated test).
188
+ *
189
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
190
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
191
+ * unconditionally — on both a successful delete and a no-op — gives
192
+ * `consume()` no way to tell which caller won: the value is identical for
193
+ * both, so no post-hoc check can attribute the deletion. Rather than
194
+ * silently rejecting every real login for such adapters,
195
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
196
+ * this reopens the pre-consume find-then-delete race window (multiple
197
+ * concurrent callers can pass) for adapters that can't report a match,
198
+ * but does not break login. It is fail-closed (returns null / rejects)
199
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
200
+ * matched" signal.
201
+ */
202
+ consume(stateHash: string): Promise<OAuthStatePayload | null>;
203
+ /**
204
+ * Delete OAuth states whose expiration time has passed. Expired states
205
+ * are already rejected by `find`; call this from a scheduled job to keep
206
+ * the table small.
207
+ */
208
+ deleteExpired(now?: Date): Promise<void>;
209
+ }
210
+
211
+ export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/index.ts
2
2
  export * from "@guren/server";
3
3
  import {
4
- Model as Model2,
4
+ Model as Model4,
5
5
  defineModel,
6
6
  ModelNotFoundException,
7
7
  MassAssignmentException,
@@ -11,12 +11,43 @@ import {
11
11
  createPostgresDatabase,
12
12
  createMySqlDatabase,
13
13
  createSqliteDatabase,
14
+ createD1Database,
14
15
  runSeeders,
15
16
  defineSeeder
16
17
  } from "@guren/orm";
17
18
 
18
19
  // src/api-token-store.ts
19
20
  import { Model } from "@guren/orm";
21
+
22
+ // src/store-utils.ts
23
+ function toDate(value) {
24
+ if (value == null) return null;
25
+ if (value instanceof Date) return value;
26
+ if (typeof value === "number") return new Date(value);
27
+ if (typeof value === "string") {
28
+ const date = new Date(/^\d+$/.test(value) ? Number(value) : value);
29
+ return Number.isNaN(date.getTime()) ? null : date;
30
+ }
31
+ return null;
32
+ }
33
+ function isExpired(value, now = Date.now()) {
34
+ const date = toDate(value);
35
+ if (date === null) return true;
36
+ const time = date.getTime();
37
+ return Number.isNaN(time) || time <= now;
38
+ }
39
+ function decodeJsonColumn(value, fallback) {
40
+ if (typeof value === "string") {
41
+ try {
42
+ return JSON.parse(value);
43
+ } catch {
44
+ return fallback;
45
+ }
46
+ }
47
+ return value ?? fallback;
48
+ }
49
+
50
+ // src/api-token-store.ts
20
51
  var DatabaseApiTokenStore = class {
21
52
  model;
22
53
  abilitiesMode;
@@ -67,27 +98,203 @@ var DatabaseApiTokenStore = class {
67
98
  name: String(record.name),
68
99
  hashedToken: String(record.hashedToken),
69
100
  userId: typeof record.userId === "bigint" ? record.userId.toString() : record.userId,
70
- abilities: typeof abilities === "string" ? JSON.parse(abilities) : abilities,
101
+ // Corrupt text degrades to no abilities (deny-by-default) instead of
102
+ // throwing on every verification of the affected token.
103
+ abilities: decodeJsonColumn(abilities, []),
71
104
  lastUsedAt: toDate(record.lastUsedAt),
72
105
  expiresAt: toDate(record.expiresAt),
73
106
  createdAt: toDate(record.createdAt) ?? /* @__PURE__ */ new Date(0)
74
107
  };
75
108
  }
76
109
  };
77
- function toDate(value) {
78
- if (value == null) return null;
79
- if (value instanceof Date) return value;
80
- if (typeof value === "string" || typeof value === "number") return new Date(value);
81
- return null;
110
+
111
+ // src/session-store.ts
112
+ import { Model as Model2 } from "@guren/orm";
113
+ var DatabaseSessionStore = class {
114
+ model;
115
+ dataMode;
116
+ constructor(table, options = {}) {
117
+ this.dataMode = options.dataMode ?? "json";
118
+ this.model = class SessionModel extends Model2 {
119
+ static table = table;
120
+ };
121
+ }
122
+ async read(id) {
123
+ const record = await this.model.where({ id }).first();
124
+ if (!record) {
125
+ return void 0;
126
+ }
127
+ if (isExpired(record.expiresAt)) {
128
+ await this.model.where({ id, expiresAt: record.expiresAt }).delete();
129
+ return void 0;
130
+ }
131
+ return this.deserialize(record);
132
+ }
133
+ async write(id, data, ttlSeconds) {
134
+ const payload = {
135
+ data: this.dataMode === "text" ? JSON.stringify(data) : data,
136
+ expiresAt: this.expiryDate(ttlSeconds)
137
+ };
138
+ const existing = await this.model.where({ id }).first();
139
+ if (existing) {
140
+ await this.model.forceUpdate({ id }, payload);
141
+ return;
142
+ }
143
+ try {
144
+ await this.model.forceCreate({ id, ...payload });
145
+ } catch (error) {
146
+ const nowExists = await this.model.where({ id }).first();
147
+ if (!nowExists) {
148
+ throw error;
149
+ }
150
+ await this.model.forceUpdate({ id }, payload);
151
+ }
152
+ }
153
+ async destroy(id) {
154
+ await this.model.where({ id }).delete();
155
+ }
156
+ /**
157
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
158
+ * data rewrite, no existence check. Missing rows and rows that have
159
+ * already expired (but not yet been swept) are left untouched, never
160
+ * resurrected — matching the `SessionStore.touch` contract and the memory
161
+ * store's behavior.
162
+ */
163
+ async touch(id, ttlSeconds) {
164
+ await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
165
+ }
166
+ /**
167
+ * Delete sessions whose expiration time has passed. Expired rows are
168
+ * already treated as missing (and removed) by `read`; call this from a
169
+ * scheduled job to keep the table small.
170
+ */
171
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
172
+ await this.model.where("expiresAt", "<=", now).delete();
173
+ }
174
+ deserialize(record) {
175
+ return decodeJsonColumn(record.data, {});
176
+ }
177
+ expiryDate(ttlSeconds) {
178
+ return new Date(Date.now() + ttlSeconds * 1e3);
179
+ }
180
+ };
181
+
182
+ // src/oauth-state-store.ts
183
+ import { Model as Model3 } from "@guren/orm";
184
+ var DatabaseOAuthStateStore = class {
185
+ model;
186
+ constructor(table) {
187
+ this.model = class OAuthStateModel extends Model3 {
188
+ static table = table;
189
+ };
190
+ }
191
+ async store(stateHash, payload) {
192
+ await this.model.forceCreate({
193
+ stateHash,
194
+ provider: payload.provider,
195
+ redirectTo: payload.redirectTo ?? null,
196
+ expiresAt: payload.expiresAt
197
+ });
198
+ }
199
+ async find(stateHash) {
200
+ const record = await this.fetchLive(stateHash);
201
+ return record ? mapRecordToPayload(record) : null;
202
+ }
203
+ /**
204
+ * Fetch the row for `stateHash`, clearing it out and returning null if
205
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
206
+ * in what they do with a live row.
207
+ */
208
+ async fetchLive(stateHash) {
209
+ const record = await this.model.where({ stateHash }).first();
210
+ if (!record) {
211
+ return null;
212
+ }
213
+ if (isExpired(record.expiresAt)) {
214
+ await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
215
+ return null;
216
+ }
217
+ return record;
218
+ }
219
+ async delete(stateHash) {
220
+ await this.model.where({ stateHash }).delete();
221
+ }
222
+ /**
223
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
224
+ * caller for the same hash receives the payload.
225
+ *
226
+ * This guarantee depends on the configured ORM adapter's `delete()`
227
+ * reporting whether a row actually matched — either the deleted row
228
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
229
+ * default and only shipped adapter, always does this: RETURNING drivers
230
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
231
+ * when zero rows matched; MySQL resolves to a result carrying
232
+ * `affectedRows` (verified by inspection, not a dedicated test).
233
+ *
234
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
235
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
236
+ * unconditionally — on both a successful delete and a no-op — gives
237
+ * `consume()` no way to tell which caller won: the value is identical for
238
+ * both, so no post-hoc check can attribute the deletion. Rather than
239
+ * silently rejecting every real login for such adapters,
240
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
241
+ * this reopens the pre-consume find-then-delete race window (multiple
242
+ * concurrent callers can pass) for adapters that can't report a match,
243
+ * but does not break login. It is fail-closed (returns null / rejects)
244
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
245
+ * matched" signal.
246
+ */
247
+ async consume(stateHash) {
248
+ const record = await this.fetchLive(stateHash);
249
+ if (!record) {
250
+ return null;
251
+ }
252
+ const result = await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
253
+ return deleteRemovedRow(result) ? mapRecordToPayload(record) : null;
254
+ }
255
+ /**
256
+ * Delete OAuth states whose expiration time has passed. Expired states
257
+ * are already rejected by `find`; call this from a scheduled job to keep
258
+ * the table small.
259
+ */
260
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
261
+ await this.model.where("expiresAt", "<=", now).delete();
262
+ }
263
+ };
264
+ function mapRecordToPayload(record) {
265
+ return {
266
+ provider: String(record.provider),
267
+ redirectTo: record.redirectTo == null ? void 0 : String(record.redirectTo),
268
+ // fetchLive's isExpired check guarantees this parses.
269
+ expiresAt: toDate(record.expiresAt)
270
+ };
271
+ }
272
+ function deleteRemovedRow(result) {
273
+ if (result == null) return false;
274
+ if (typeof result === "number") return result > 0;
275
+ if (Array.isArray(result)) {
276
+ return result.length > 0 && deleteRemovedRow(result[0]);
277
+ }
278
+ if (typeof result === "object") {
279
+ const record = result;
280
+ for (const key of ["affectedRows", "rowsAffected", "rowCount", "changes"]) {
281
+ if (typeof record[key] === "number") return record[key] > 0;
282
+ }
283
+ return true;
284
+ }
285
+ return Boolean(result);
82
286
  }
83
287
  export {
84
288
  DatabaseApiTokenStore,
289
+ DatabaseOAuthStateStore,
290
+ DatabaseSessionStore,
85
291
  DrizzleAdapter,
86
292
  MassAssignmentException,
87
- Model2 as Model,
293
+ Model4 as Model,
88
294
  ModelNotFoundException,
89
295
  QueryBuilder,
90
296
  SoftDeletes,
297
+ createD1Database,
91
298
  createMySqlDatabase,
92
299
  createPostgresDatabase,
93
300
  createSqliteDatabase,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,9 +52,9 @@
52
52
  "typecheck": "tsc --noEmit"
53
53
  },
54
54
  "dependencies": {
55
- "@guren/cli": "^1.2.0",
56
- "@guren/orm": "^1.0.0",
57
- "@guren/server": "^1.3.0"
55
+ "@guren/cli": "^1.5.0",
56
+ "@guren/orm": "^1.2.0",
57
+ "@guren/server": "^1.4.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^20.14.10",