@cossackframework/database 0.7.7 → 0.8.0-licenseprobe.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.
@@ -1,98 +0,0 @@
1
- // src/session-middleware.ts
2
- //
3
- // Per-request session middleware. Resolves the session ID (from an optional
4
- // auth-cookie reader, else the anonymous `cossack_sid` cookie), creates one if
5
- // missing, and scopes a `SessionStore` into AsyncLocalStorage so `session()`
6
- // works context-free. Ensures the ID cookie is set on the response when a new
7
- // anonymous session is issued.
8
- //
9
- // Register via `cossack add database` (same pattern as `dbMiddleware`):
10
- //
11
- // // src/middlewares/session.ts
12
- // import { createSessionMiddleware } from '@cossackframework/database';
13
- // export const sessionMiddleware = createSessionMiddleware();
14
- //
15
- // // src/config/middlewares.ts
16
- // import { sessionMiddleware } from '../middlewares/session';
17
- // export const middlewares = [sessionMiddleware];
18
-
19
- import type { MiddlewareHandler } from 'hono';
20
- import { getCookie, setCookie } from 'hono/cookie';
21
- import { db } from './store';
22
- import { SessionStore } from './session-store';
23
- import { ensureSessionAlsWired, runWithSession } from './session-als';
24
-
25
- export interface SessionMiddlewareOptions {
26
- /** Anonymous-session cookie name. Defaults to `cossack_sid`. */
27
- cookieName?: string;
28
- /** Session TTL in milliseconds. Defaults to 30 days. */
29
- ttl?: number;
30
- /**
31
- * Optional: read the session ID from auth's cookie instead of the anonymous
32
- * one. Return the auth session ID when the user is logged in; return
33
- * undefined to fall back to the anonymous cookie. This is the "ID bridge"
34
- * that lets an authenticated session reuse its existing ID.
35
- */
36
- authCookieReader?: (c: any) => string | undefined | Promise<string | undefined>;
37
- /**
38
- * Whether to set the anonymous cookie as `httpOnly`. Defaults to true.
39
- * (Auth-managed cookies set their own attributes via the auth module.)
40
- */
41
- httpOnly?: boolean;
42
- }
43
-
44
- const DEFAULT_COOKIE_NAME = 'cossack_sid';
45
- const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
46
-
47
- export function createSessionMiddleware(
48
- options: SessionMiddlewareOptions = {},
49
- ): MiddlewareHandler {
50
- const cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
51
- const ttl = options.ttl ?? DEFAULT_TTL_MS;
52
- const httpOnly = options.httpOnly ?? true;
53
-
54
- return async (c, next) => {
55
- ensureSessionAlsWired();
56
- const store = new SessionStore(db());
57
-
58
- // 1. Resolve an existing session ID: auth cookie first, then anonymous.
59
- // `authProvidedId` tracks whether auth handed us an ID so we know
60
- // not to set the anonymous cookie in that case (auth manages its own).
61
- let sessionId: string | undefined;
62
- let authProvidedId = false;
63
- if (options.authCookieReader) {
64
- sessionId = await options.authCookieReader(c);
65
- if (sessionId) authProvidedId = true;
66
- }
67
- if (!sessionId) {
68
- sessionId = getCookie(c, cookieName);
69
- }
70
-
71
- // 2. If neither auth nor the anonymous cookie gave us an ID, create a
72
- // fresh anonymous session. We set its cookie after `next()` so it
73
- // survives redirects.
74
- let issuedNewAnonymousId = false;
75
- if (!sessionId) {
76
- sessionId = await store.create(ttl);
77
- issuedNewAnonymousId = true;
78
- }
79
-
80
- // 3. Scope the session for downstream handlers.
81
- await runWithSession({ sessionId, store }, () => next());
82
-
83
- // 4. Persist a newly-issued ANONYMOUS ID as a cookie. We must NOT skip
84
- // this when `authCookieReader` is configured but returned undefined
85
- // (an unauthenticated request) — otherwise the new anonymous session
86
- // is orphaned and lost on the next request. Only an auth-provided ID
87
- // is excluded, because the auth module sets its own cookie.
88
- if (issuedNewAnonymousId && !authProvidedId) {
89
- setCookie(c, cookieName, sessionId, {
90
- httpOnly,
91
- secure: c.req.url.startsWith('https://'),
92
- sameSite: 'Lax',
93
- path: '/',
94
- maxAge: Math.floor(ttl / 1000),
95
- });
96
- }
97
- };
98
- }
@@ -1,201 +0,0 @@
1
- // src/session-store.ts
2
- //
3
- // DB-backed key/value session storage. Promotes the inline session CRUD that
4
- // `cossack add auth` generates (see `authModuleTemplate` in the cossack CLI)
5
- // into a reusable, tested class. Reuses the per-request `db()` client from the
6
- // database ALS scope — no separate client, no new binding.
7
- //
8
- // Sessions are addressed by an opaque high-entropy ID (32 random bytes,
9
- // base64url). The ID is carried in a cookie (see `createSessionMiddleware`);
10
- // the store is the source of truth. IDs need no signing — forging is futile
11
- // against 256 bits of entropy.
12
- //
13
- // Anonymous sessions (`user_id` null) work for carts/wizards/A-B without auth;
14
- // authenticated sessions carry the `user_id`. The `data` column holds a JSON
15
- // key/value bag so `set('cart', ...)` / `get('cart')` work like a hash.
16
- //
17
- // Expected schema (shipped via the `cossack add database` migration template):
18
- // create table sessions (
19
- // id text primary key not null,
20
- // user_id text, -- nullable for anonymous sessions
21
- // data text, -- JSON key/value bag
22
- // expires_at text not null
23
- // );
24
-
25
- import type { DbClient } from './types';
26
- import { db } from './store';
27
-
28
- /** Sessions-table row shape (snake_case to match the migration). */
29
- export interface SessionRow {
30
- id: string;
31
- user_id: string | null;
32
- data: string | null;
33
- /** JSON bag for auth-session metadata (user-agent, ip, type discriminator, ...). */
34
- meta: string | null;
35
- /** Geo (Cloudflare request.cf country/city) captured at login; null off-CF. */
36
- location: string | null;
37
- /** User-Agent header captured at login. */
38
- user_agent: string | null;
39
- /** Client IP (cf-connecting-ip) captured at login. */
40
- ip_address: string | null;
41
- /** When the session row was created (the "Logged in" time). Optional on insert
42
- * (the generic SessionStore doesn't set it; app auth flows do via migration). */
43
- created_at?: string;
44
- expires_at: string;
45
- }
46
-
47
- // Augment the Database interface so `selectFrom('sessions')` is typed.
48
- declare module './types' {
49
- interface Database {
50
- sessions: SessionRow;
51
- }
52
- }
53
-
54
- /** Default session TTL: 30 days, in milliseconds. */
55
- const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
56
-
57
- function nowISO(): string {
58
- return new Date().toISOString();
59
- }
60
-
61
- function expiryISO(ttlMs: number): string {
62
- return new Date(Date.now() + ttlMs).toISOString();
63
- }
64
-
65
- function isExpired(expiresAt: string): boolean {
66
- return new Date(expiresAt).getTime() <= Date.now();
67
- }
68
-
69
- /**
70
- * DB-backed session key/value store. Construct per request (the session
71
- * middleware does this) with the scoped `db()` client, or pass an explicit
72
- * client for scripts/tests.
73
- *
74
- * const store = new SessionStore(); // uses db()
75
- * await store.set(sessionId, 'cart', { items: [] });
76
- * const cart = await store.get(sessionId, 'cart');
77
- */
78
- export class SessionStore {
79
- constructor(private client: DbClient = db()) {}
80
-
81
- /**
82
- * Read + parse the JSON `data` bag for a session. Returns `{}` if the
83
- * session is missing, expired, or has no data. Does NOT auto-delete expired
84
- * rows here (see `purgeExpired`); callers just see an empty bag.
85
- */
86
- async load(sessionId: string): Promise<Record<string, unknown>> {
87
- const row = await this.client
88
- .selectFrom('sessions')
89
- .select(['data', 'expires_at'])
90
- .where('id', '=', sessionId)
91
- .executeTakeFirst();
92
- if (!row) return {};
93
- if (isExpired(row.expires_at as string)) return {};
94
- if (!row.data) return {};
95
- try {
96
- return JSON.parse(row.data as string) as Record<string, unknown>;
97
- } catch {
98
- return {};
99
- }
100
- }
101
-
102
- /**
103
- * Set a single key in the session's data bag (merging with existing data).
104
- * Also refreshes `expires_at` to extend the session on activity (sliding
105
- * expiration). Creates the row if it doesn't exist.
106
- */
107
- async set(
108
- sessionId: string,
109
- key: string,
110
- value: unknown,
111
- ttlMs: number = DEFAULT_TTL_MS,
112
- ): Promise<void> {
113
- const data = await this.load(sessionId);
114
- data[key] = value;
115
- await this.client
116
- .insertInto('sessions')
117
- .values({
118
- id: sessionId,
119
- user_id: null,
120
- data: JSON.stringify(data),
121
- expires_at: expiryISO(ttlMs),
122
- })
123
- .onConflict((oc) =>
124
- oc.column('id').doUpdateSet({
125
- data: JSON.stringify(data),
126
- expires_at: expiryISO(ttlMs),
127
- }),
128
- )
129
- .execute();
130
- }
131
-
132
- /** Read a single key from the session's data bag. */
133
- async get<T = unknown>(sessionId: string, key: string): Promise<T | undefined> {
134
- const data = await this.load(sessionId);
135
- return data[key] as T | undefined;
136
- }
137
-
138
- /** Read the entire data bag. */
139
- async getAll(sessionId: string): Promise<Record<string, unknown>> {
140
- return this.load(sessionId);
141
- }
142
-
143
- /** Remove a single key from the data bag. */
144
- async unset(sessionId: string, key: string): Promise<void> {
145
- const data = await this.load(sessionId);
146
- if (!(key in data)) return;
147
- delete data[key];
148
- await this.client
149
- .updateTable('sessions')
150
- .set({ data: JSON.stringify(data) })
151
- .where('id', '=', sessionId)
152
- .execute();
153
- }
154
-
155
- /** Delete the session row entirely. */
156
- async destroy(sessionId: string): Promise<void> {
157
- await this.client.deleteFrom('sessions').where('id', '=', sessionId).execute();
158
- }
159
-
160
- /** Delete all expired rows. Call opportunistically (e.g. on a sample of requests). */
161
- async purgeExpired(): Promise<number> {
162
- const now = nowISO();
163
- const result = await this.client
164
- .deleteFrom('sessions')
165
- .where('expires_at', '<', now)
166
- .executeTakeFirst();
167
- // Kysely's DeleteResult exposes numDeletedRows (bigint).
168
- return Number(result?.numDeletedRows ?? 0);
169
- }
170
-
171
- /**
172
- * Create a new session row with a fresh high-entropy ID. Returns the ID.
173
- * Use when no session ID is present (anonymous first visit).
174
- */
175
- async create(ttlMs: number = DEFAULT_TTL_MS): Promise<string> {
176
- // 32 random bytes → ~43 base64url chars. See crypto.generateToken in
177
- // @cossackframework/core; we inline here to keep this package
178
- // dependency-free on core (the database package is standalone, only
179
- // depending on kysely + hono peer deps).
180
- const bytes = new Uint8Array(32);
181
- crypto.getRandomValues(bytes);
182
- let binary = '';
183
- for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
184
- const id = btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
185
-
186
- await this.client
187
- .insertInto('sessions')
188
- .values({ id, user_id: null, data: null, expires_at: expiryISO(ttlMs) })
189
- .execute();
190
- return id;
191
- }
192
-
193
- /** Attach a user ID to a session (called on login). */
194
- async bindUser(sessionId: string, userId: string): Promise<void> {
195
- await this.client
196
- .updateTable('sessions')
197
- .set({ user_id: userId })
198
- .where('id', '=', sessionId)
199
- .execute();
200
- }
201
- }
package/src/session.ts DELETED
@@ -1,59 +0,0 @@
1
- // src/session.ts
2
- //
3
- // Context-free session access: `session()` returns a handle bound to the active
4
- // request's session for key/value get/set. Mirrors `db()` — throws a clear
5
- // `[Cossack]` error if called outside a request scope (register the session
6
- // middleware via `cossack add database`).
7
- //
8
- // await session().set('cart', { items: [...] });
9
- // const cart = await session().get('cart');
10
- // const sid = session().id();
11
- //
12
- // Sessions are DB-backed (the `sessions` table) and addressed by an opaque ID
13
- // carried in a cookie. With auth installed, the ID is the auth session cookie;
14
- // otherwise an anonymous `cossack_sid` cookie is used (see
15
- // `createSessionMiddleware`).
16
-
17
- import { getSessionScope } from './session-als';
18
-
19
- /**
20
- * Returns a handle to the active request's session. The handle caches the
21
- * session ID and exposes async get/set over the scoped `SessionStore`.
22
- *
23
- * Throws if no session scope is active.
24
- */
25
- export function session() {
26
- const scope = getSessionScope();
27
- if (!scope) {
28
- throw new Error(
29
- '[Cossack] No session in scope. `session()` must be called within a request ' +
30
- 'handler with the session middleware registered (run `cossack add database`).',
31
- );
32
- }
33
- return {
34
- /** The active session ID for this request. */
35
- id(): string {
36
- return scope.sessionId;
37
- },
38
- /** Read a single key from the session data bag. */
39
- async get<T = unknown>(key: string): Promise<T | undefined> {
40
- return scope.store.get<T>(scope.sessionId, key);
41
- },
42
- /** Read the entire data bag. */
43
- async getAll(): Promise<Record<string, unknown>> {
44
- return scope.store.getAll(scope.sessionId);
45
- },
46
- /** Set a single key (merges into the bag; refreshes expiry). */
47
- async set(key: string, value: unknown): Promise<void> {
48
- return scope.store.set(scope.sessionId, key, value);
49
- },
50
- /** Remove a single key from the bag. */
51
- async unset(key: string): Promise<void> {
52
- return scope.store.unset(scope.sessionId, key);
53
- },
54
- /** Delete the session row entirely (e.g. on logout). */
55
- async destroy(): Promise<void> {
56
- return scope.store.destroy(scope.sessionId);
57
- },
58
- };
59
- }
package/src/store.ts DELETED
@@ -1,38 +0,0 @@
1
- // src/store.ts
2
- import type { DbClient } from './types';
3
-
4
- /**
5
- * Injected by {@link ensureDbAlsWired} so the global {@link db} helper reads
6
- * the per-request client from the framework's AsyncLocalStorage scope.
7
- */
8
- let dbStoreGetter: (() => DbClient | undefined) | null = null;
9
-
10
- /** @internal Framework wires the per-request store getter here (once). */
11
- export function setDbStoreGetter(getter: (() => DbClient | undefined) | null): void {
12
- dbStoreGetter = getter;
13
- }
14
-
15
- /**
16
- * Returns the per-request {@link DbClient}. Must be called inside a request
17
- * scope (the database middleware wraps every request in `runWithDb`) or inside
18
- * an explicit `runWithDb(...)` block.
19
- *
20
- * Throws if no client is in scope — there is no sensible default database
21
- * client, so misuse fails loudly instead of silently.
22
- *
23
- * ```ts
24
- * import { db } from '@cossackframework/database'
25
- *
26
- * const users = await db().selectFrom('users').selectAll().execute()
27
- * ```
28
- */
29
- export function db(): DbClient {
30
- const client = dbStoreGetter?.();
31
- if (!client) {
32
- throw new Error(
33
- '[Cossack] No database client in scope. `db()` must be called within a ' +
34
- 'request handler (register the database middleware) or inside `runWithDb(...)`.',
35
- );
36
- }
37
- return client;
38
- }
package/src/types.ts DELETED
@@ -1,108 +0,0 @@
1
- // src/types.ts
2
-
3
- /**
4
- * The database schema. Each property maps a table name to its row type.
5
- *
6
- * Empty by default. Augment it from your model files (`src/models/*.ts`) so
7
- * `db.selectFrom('users')` is fully typed:
8
- *
9
- * ```ts
10
- * declare module '@cossackframework/database' {
11
- * interface Database {
12
- * users: UserRow
13
- * sessions: SessionRow
14
- * }
15
- * }
16
- * ```
17
- */
18
- export interface Database {}
19
-
20
- /** A Kysely client typed against the (augmented) {@link Database}. */
21
- export type DbClient = import('kysely').Kysely<Database>;
22
-
23
- // ---------------------------------------------------------------------------
24
- // D1 binding (structural — compatible with Cloudflare's `D1Database`)
25
- // ---------------------------------------------------------------------------
26
-
27
- export interface D1DatabaseLike {
28
- prepare(query: string): D1PreparedStatementLike;
29
- }
30
-
31
- export interface D1PreparedStatementLike {
32
- bind(...values: unknown[]): D1PreparedStatementLike;
33
- all<T = unknown>(): Promise<D1ResultLike<T>>;
34
- run<T = unknown>(): Promise<D1ResultLike<T>>;
35
- first<T = unknown>(col?: string): Promise<T | null>;
36
- }
37
-
38
- export interface D1ResultLike<T = unknown> {
39
- results?: T[];
40
- success: boolean;
41
- meta?: {
42
- changes?: number;
43
- last_row_id?: number | string | null;
44
- [key: string]: unknown;
45
- };
46
- }
47
-
48
- // ---------------------------------------------------------------------------
49
- // libSQL / Turso client (structural — compatible with `@libsql/client` and
50
- // `@tursodatabase/serverless/compat`)
51
- // ---------------------------------------------------------------------------
52
-
53
- export interface LibsqlClientLike {
54
- execute(stmt: LibsqlInStatement): Promise<LibsqlResultSetLike>;
55
- close?(): void;
56
- }
57
-
58
- /**
59
- * Loose statement shape — `args` is forwarded to the underlying client
60
- * verbatim, so we type it broadly. The `| string` member mirrors libSQL's
61
- * `InStatement` so a real `@libsql/client` / `@tursodatabase/serverless` client
62
- * is structurally assignable to {@link LibsqlClientLike}.
63
- */
64
- export type LibsqlInStatement =
65
- | { sql: string; args?: ReadonlyArray<unknown> | Record<string, unknown> }
66
- | string;
67
-
68
- export interface LibsqlResultSetLike {
69
- columns: string[];
70
- rows: Array<LibsqlRowLike>;
71
- rowsAffected: number;
72
- lastInsertRowid?: bigint | number | undefined;
73
- }
74
-
75
- export interface LibsqlRowLike {
76
- length: number;
77
- [index: number]: unknown;
78
- [name: string]: unknown;
79
- }
80
-
81
- // ---------------------------------------------------------------------------
82
- // Factory config
83
- // ---------------------------------------------------------------------------
84
-
85
- export interface D1Config {
86
- dialect: 'd1';
87
- /** A Cloudflare D1 binding (e.g. `env.DB`). */
88
- binding: D1DatabaseLike;
89
- }
90
-
91
- export interface LibsqlConfig {
92
- dialect: 'libsql';
93
- /**
94
- * A libSQL/Turso client. Build it from whichever package you installed:
95
- *
96
- * ```ts
97
- * // recommended (fetch-based, works on Workers + Node)
98
- * import { createClient } from '@tursodatabase/serverless/compat'
99
- * // or the battle-tested fallback
100
- * import { createClient } from '@libsql/client/web'
101
- *
102
- * const client = createClient({ url: env.TURSO_URL, authToken: env.TURSO_TOKEN })
103
- * ```
104
- */
105
- client: LibsqlClientLike;
106
- }
107
-
108
- export type DbConfig = D1Config | LibsqlConfig;