@entro314labs/entro-auth-capydb 0.0.0-stage → 1.8.0-beta.11

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/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # Entro Auth CapyDB Adapter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Database adapter and K/V storage for running [Entro Auth](../../README.md) on [CapyDB](https://capydb.dev).
4
+
5
+ It is the Entro Auth Drizzle adapter on a `@capydb/drizzle` client, plus what a CapyDB cell needs: every auth query can run inside a transaction that carries a row-level-security context, and reads are retried when a scale-to-zero pause cut the connection.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ # the database adapter
11
+ pnpm add @entro314labs/entro-auth-capydb @capydb/drizzle drizzle-orm@rc postgres
12
+ # the K/V storage (`@entro314labs/entro-auth-capydb/kv`), with or without the adapter
13
+ pnpm add @entro314labs/entro-auth-capydb @capydb/kv @upstash/redis
14
+ ```
15
+
16
+ The two are separate entry points and neither needs the other's packages.
17
+
18
+ ## Usage
19
+
20
+ ```ts
21
+ import { createDb } from "@capydb/drizzle";
22
+ import { capydbAdapter } from "@entro314labs/entro-auth-capydb";
23
+ import { entroAuth } from "@entro314labs/entro-auth";
24
+ import * as schema from "./auth-schema";
25
+
26
+ const db = createDb({ relations: schema.authRelations });
27
+
28
+ export const auth = entroAuth({
29
+ database: capydbAdapter(db, {
30
+ schema,
31
+ // Only when the auth tables have row-level security enabled.
32
+ rls: { claims: { app_role: "system" } },
33
+ }),
34
+ });
35
+ ```
36
+
37
+ Generate `auth-schema.ts` with `npx @entro314labs/entro-auth-cli@latest generate`.
38
+
39
+ See [the adapter docs](../../docs/content/docs/adapters/capydb.mdx) for row-level security, K/V storage and the rules that follow from the transaction pooler.
40
+
41
+ ## License
42
+
43
+ MIT
@@ -0,0 +1,67 @@
1
+ import { AuthContext } from "@capydb/drizzle";
2
+ import { DrizzleAdapterConfig } from "@entro314labs/entro-auth-drizzle-adapter";
3
+ import { EntroAuthOptions } from "@entro314labs/entro-auth-core";
4
+ import { DBAdapter } from "@entro314labs/entro-auth-core/db/adapter";
5
+ import { AnyRelations } from "drizzle-orm";
6
+ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
7
+ /** A CapyDB Drizzle client, as `createDb()` from `@capydb/drizzle` returns it. */
8
+ export type CapydbDatabase = PostgresJsDatabase<AnyRelations>;
9
+ type Resolvable<T extends object> = T | (() => T);
10
+ /**
11
+ * The row-level-security context Entro Auth's own queries run under.
12
+ *
13
+ * - `claims` sets `request.jwt.claims`, for databases whose policies read
14
+ * `auth.jwt()` / `auth.uid()` (`capydb migrate rls --mode supabase-compat`).
15
+ * - `context` sets the `app.*` settings, for databases converted to the plain
16
+ * GUC convention.
17
+ *
18
+ * Give a function to compute the value per operation.
19
+ */
20
+ export type CapydbRlsConfig = {
21
+ claims: Resolvable<Record<string, unknown>>;
22
+ } | {
23
+ context: Resolvable<AuthContext>;
24
+ };
25
+ export interface CapydbAdapterConfig extends Omit<DrizzleAdapterConfig, "provider" | "transaction"> {
26
+ /**
27
+ * Run every auth query inside a transaction that carries this
28
+ * row-level-security context. Required when the auth tables have row-level
29
+ * security enabled; leave it out when they do not.
30
+ *
31
+ * The context is applied with `set_config(..., true)`, so it cannot outlive
32
+ * the transaction on the pooled endpoint.
33
+ */
34
+ rls?: CapydbRlsConfig | undefined;
35
+ }
36
+ /**
37
+ * Entro Auth database adapter for CapyDB.
38
+ *
39
+ * It is the Drizzle adapter on a `@capydb/drizzle` client, with what a CapyDB
40
+ * cell needs on top:
41
+ *
42
+ * - with `rls`, every operation runs in a transaction that carries the given
43
+ * row-level-security context, and a core transaction is a single such block
44
+ * - reads are retried when a scale-to-zero pause cut the connection. Writes
45
+ * are not, because a write can be applied before the connection drops.
46
+ *
47
+ * Call auth APIs outside your own `withAuthContext` / `withSupabaseJwtClaims`
48
+ * blocks: `@capydb/drizzle` refuses a block opened inside another one.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * import { createDb } from "@capydb/drizzle";
53
+ * import { capydbAdapter } from "@entro314labs/entro-auth-capydb";
54
+ * import * as schema from "./auth-schema";
55
+ *
56
+ * const db = createDb({ relations: schema.authRelations });
57
+ *
58
+ * export const auth = entroAuth({
59
+ * database: capydbAdapter(db, {
60
+ * schema,
61
+ * rls: { claims: { app_role: "system" } },
62
+ * }),
63
+ * });
64
+ * ```
65
+ */
66
+ export declare const capydbAdapter: (db: CapydbDatabase, config: CapydbAdapterConfig) => (options: EntroAuthOptions) => DBAdapter<EntroAuthOptions>;
67
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1,84 @@
1
+ import { retryOnPause, withAuthContext, withSupabaseJwtClaims } from "@capydb/drizzle";
2
+ import { getCurrentDBAdapterAsyncLocalStorage } from "@entro314labs/entro-auth-core/context";
3
+ import { drizzleAdapter } from "@entro314labs/entro-auth-drizzle-adapter";
4
+ // src/capydb-adapter.ts
5
+ function resolve(value) {
6
+ return typeof value === "function" ? value() : value;
7
+ }
8
+ /**
9
+ * Entro Auth database adapter for CapyDB.
10
+ *
11
+ * It is the Drizzle adapter on a `@capydb/drizzle` client, with what a CapyDB
12
+ * cell needs on top:
13
+ *
14
+ * - with `rls`, every operation runs in a transaction that carries the given
15
+ * row-level-security context, and a core transaction is a single such block
16
+ * - reads are retried when a scale-to-zero pause cut the connection. Writes
17
+ * are not, because a write can be applied before the connection drops.
18
+ *
19
+ * Call auth APIs outside your own `withAuthContext` / `withSupabaseJwtClaims`
20
+ * blocks: `@capydb/drizzle` refuses a block opened inside another one.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { createDb } from "@capydb/drizzle";
25
+ * import { capydbAdapter } from "@entro314labs/entro-auth-capydb";
26
+ * import * as schema from "./auth-schema";
27
+ *
28
+ * const db = createDb({ relations: schema.authRelations });
29
+ *
30
+ * export const auth = entroAuth({
31
+ * database: capydbAdapter(db, {
32
+ * schema,
33
+ * rls: { claims: { app_role: "system" } },
34
+ * }),
35
+ * });
36
+ * ```
37
+ */
38
+ const capydbAdapter = (db, config) => {
39
+ const { rls, ...drizzleConfig } = config;
40
+ const transact = (callback) => {
41
+ if (!rls) return db.transaction(callback);
42
+ return "claims" in rls ? withSupabaseJwtClaims(db, resolve(rls.claims), callback) : withAuthContext(db, resolve(rls.context), callback);
43
+ };
44
+ const scopedDb = new Proxy(db, { get(target, property) {
45
+ if (property === "transaction") return transact;
46
+ const value = Reflect.get(target, property, target);
47
+ return typeof value === "function" ? value.bind(target) : value;
48
+ } });
49
+ const createAdapter = drizzleAdapter(scopedDb, {
50
+ ...drizzleConfig,
51
+ provider: "pg",
52
+ transaction: true
53
+ });
54
+ return (options) => {
55
+ const adapter = createAdapter(options);
56
+ const direct = { ...adapter };
57
+ /**
58
+ * Runs one operation in its own context block, or directly without `rls`.
59
+ *
60
+ * Inside a transaction core has open, the operation joins it: a cell's
61
+ * pooled client holds one connection, so a second transaction could
62
+ * never start while the first one waits for it.
63
+ */
64
+ const write = async (operation) => {
65
+ const open = (await getCurrentDBAdapterAsyncLocalStorage()).getStore();
66
+ if (open?.isTransactionActive) return operation(open.adapter);
67
+ return rls ? adapter.transaction(operation) : operation(direct);
68
+ };
69
+ const read = (operation) => retryOnPause(() => write(operation));
70
+ return Object.assign(adapter, {
71
+ findOne: (data) => read((scoped) => scoped.findOne(data)),
72
+ findMany: (data) => read((scoped) => scoped.findMany(data)),
73
+ count: (data) => read((scoped) => scoped.count(data)),
74
+ create: (data) => write((scoped) => scoped.create(data)),
75
+ update: (data) => write((scoped) => scoped.update(data)),
76
+ updateMany: (data) => write((scoped) => scoped.updateMany(data)),
77
+ delete: (data) => write((scoped) => scoped.delete(data)),
78
+ deleteMany: (data) => write((scoped) => scoped.deleteMany(data)),
79
+ consumeOne: (data) => write((scoped) => scoped.consumeOne(data)),
80
+ incrementOne: (data) => write((scoped) => scoped.incrementOne(data))
81
+ });
82
+ };
83
+ };
84
+ export { capydbAdapter };
package/dist/kv.d.mts ADDED
@@ -0,0 +1,29 @@
1
+ import { SecondaryStorage } from "@entro314labs/entro-auth-core/db";
2
+ import { Redis } from "@upstash/redis";
3
+ export interface CapydbKvStorageConfig {
4
+ /**
5
+ * The K/V client. By default one is created from `CAPYKV_REST_URL` and
6
+ * `CAPYKV_REST_TOKEN`, with automatic JSON deserialization off so values
7
+ * come back exactly as Entro Auth stored them.
8
+ */
9
+ client?: Redis | undefined;
10
+ /**
11
+ * Prefix for every key this storage writes.
12
+ * @default "entro-auth:"
13
+ */
14
+ keyPrefix?: string | undefined;
15
+ }
16
+ /**
17
+ * Entro Auth secondary storage on CapyDB K/V, for sessions, verification
18
+ * values and rate limiting.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { capydbKvStorage } from "@entro314labs/entro-auth-capydb/kv";
23
+ *
24
+ * export const auth = entroAuth({
25
+ * secondaryStorage: capydbKvStorage(),
26
+ * });
27
+ * ```
28
+ */
29
+ export declare function capydbKvStorage(config?: CapydbKvStorageConfig): SecondaryStorage;
package/dist/kv.mjs ADDED
@@ -0,0 +1,49 @@
1
+ import { createKv } from "@capydb/kv";
2
+ // src/kv.ts
3
+ /**
4
+ * Entro Auth secondary storage on CapyDB K/V, for sessions, verification
5
+ * values and rate limiting.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { capydbKvStorage } from "@entro314labs/entro-auth-capydb/kv";
10
+ *
11
+ * export const auth = entroAuth({
12
+ * secondaryStorage: capydbKvStorage(),
13
+ * });
14
+ * ```
15
+ */
16
+ function capydbKvStorage(config = {}) {
17
+ const client = config.client ?? createKv({ automaticDeserialization: false });
18
+ const keyPrefix = config.keyPrefix ?? "entro-auth:";
19
+ const prefixed = (key) => keyPrefix + key;
20
+ /**
21
+ * A client with automatic deserialization on parses JSON values; hand them
22
+ * back as the strings Entro Auth stored.
23
+ */
24
+ const asStored = (value) => value === null || typeof value === "string" ? value : JSON.stringify(value);
25
+ return {
26
+ async get(key) {
27
+ return asStored(await client.get(prefixed(key)));
28
+ },
29
+ async getAndDelete(key) {
30
+ return asStored(await client.getdel(prefixed(key)));
31
+ },
32
+ async increment(key, ttl) {
33
+ if (!Number.isInteger(ttl) || ttl <= 0) throw new TypeError(`capydbKvStorage: increment needs a positive whole number of seconds as ttl, got ${ttl}`);
34
+ const [, count] = await client.multi().set(prefixed(key), 0, {
35
+ ex: ttl,
36
+ nx: true
37
+ }).incr(prefixed(key)).exec();
38
+ return count;
39
+ },
40
+ async set(key, value, ttl) {
41
+ if (ttl !== void 0 && ttl > 0) await client.set(prefixed(key), value, { ex: Math.ceil(ttl) });
42
+ else await client.set(prefixed(key), value);
43
+ },
44
+ async delete(key) {
45
+ await client.del(prefixed(key));
46
+ }
47
+ };
48
+ }
49
+ export { capydbKvStorage };
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@entro314labs/entro-auth-capydb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.8.0-beta.11",
4
+ "description": "CapyDB adapter and K/V storage for Entro Auth",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/entro314-labs/entro-auth.git",
10
+ "directory": "packages/capydb"
11
+ },
12
+ "keywords": [
13
+ "auth",
14
+ "capydb",
15
+ "postgres",
16
+ "drizzle",
17
+ "adapter",
18
+ "typescript",
19
+ "entro-auth"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "sideEffects": false,
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "main": "./dist/index.mjs",
29
+ "module": "./dist/index.mjs",
30
+ "types": "./dist/index.d.mts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.mts",
34
+ "dev-source": "./src/index.ts",
35
+ "default": "./dist/index.mjs"
36
+ },
37
+ "./kv": {
38
+ "types": "./dist/kv.d.mts",
39
+ "dev-source": "./src/kv.ts",
40
+ "default": "./dist/kv.mjs"
41
+ }
42
+ },
43
+ "dependencies": {
44
+ "@entro314labs/entro-auth-drizzle-adapter": "1.8.0-beta.11"
45
+ },
46
+ "peerDependencies": {
47
+ "@capydb/drizzle": ">=1.11.0 <2",
48
+ "@capydb/kv": ">=2.0.0 <3",
49
+ "@entro314labs/entro-auth-core": "^1.8.0-beta.11",
50
+ "@upstash/redis": ">=1.34.0 <2",
51
+ "drizzle-orm": ">=1.0.0-rc.6 <2.0.0",
52
+ "postgres": ">=4"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@capydb/drizzle": {
56
+ "optional": true
57
+ },
58
+ "@capydb/kv": {
59
+ "optional": true
60
+ },
61
+ "@upstash/redis": {
62
+ "optional": true
63
+ },
64
+ "drizzle-orm": {
65
+ "optional": true
66
+ },
67
+ "postgres": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "devDependencies": {
72
+ "@capydb/drizzle": "^1.11.2",
73
+ "@capydb/kv": "^2.0.2",
74
+ "@entro314labs/entro-auth-core": "1.8.0-beta.11",
75
+ "@entro314labs/entro-auth-test-utils": "1.8.0-beta.11",
76
+ "@types/pg": "^8.20.0",
77
+ "@upstash/redis": "^1.34.0",
78
+ "drizzle-kit": "1.0.0-rc.6",
79
+ "drizzle-orm": "1.0.0-rc.6",
80
+ "@entro314labs/entro-auth": "1.8.0-beta.11",
81
+ "kysely": "^0.28.17 || ^0.29.0",
82
+ "pg": "^8.21.0",
83
+ "postgres": "^4.1.1",
84
+ "tsdown": "0.23.1",
85
+ "typescript": "^6.0.3"
86
+ },
87
+ "scripts": {
88
+ "build": "tsdown",
89
+ "dev": "tsdown --watch",
90
+ "lint:package": "publint run --strict --pack false",
91
+ "lint:types": "attw --profile esm-only --pack .",
92
+ "typecheck": "tsc --noEmit",
93
+ "test": "vitest",
94
+ "coverage": "vitest run --coverage --coverage.provider=istanbul"
95
+ }
6
96
  }