@softistx/janus-kit 0.0.0-stage → 0.6.16

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.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The refusal of a URL already connected with other options, from
3
+ * `@softistx/redis` 0.24+ and `@softistx/mongo` 0.30+ (code `URI_CONFLICT`).
4
+ * Earlier versions refuse with a `TypeError`, which callers test beside this;
5
+ * the peer ranges accept both. Matched on `code`, so neither package's error
6
+ * class is imported.
7
+ */
8
+ export declare function isUriConflict(cause: unknown): boolean;
9
+ //# sourceMappingURL=uri-conflict.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uri-conflict.d.ts","sourceRoot":"","sources":["../../src/shared/uri-conflict.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKrD"}
package/docs/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @softistx/janus-kit — documentation
2
+
3
+ The [README](../README.md) shows the whole kit in one example; these pages give
4
+ the detail.
5
+
6
+ | Page | Read it when |
7
+ | --- | --- |
8
+ | [The configuration](guide/configuration.md) | You are writing `defineConfig`: where PostgreSQL or MongoDB and Redis are, the `auth` and `access` functions, telemetry |
9
+ | [Health and closing](guide/lifecycle.md) | You are wiring a health route, shutting down, or handing the kit a connection you opened |
10
+ | [Troubleshooting](troubleshooting.md) | You have an error message and want its cause and its fix |
11
+ | [Roadmap](roadmap.md) | You want to know what is coming, what shipped, and what is deliberately not planned |
@@ -0,0 +1,264 @@
1
+ # The configuration
2
+
3
+ This page covers every key of `defineConfig`:
4
+ - `postgres` on `@softistx/janus-kit/drizzle`, or `mongo` on
5
+ `@softistx/janus-kit/mongo`: where users, logins and relations are kept;
6
+ - `redis`, where sessions and one-time tokens are kept instead;
7
+ - `auth` and `access`, the two functions that build the instances;
8
+ - `telemetry`.
9
+
10
+ `defineConfig` checks the configuration and answers it, frozen. It connects to
11
+ nothing and reads no environment variable, so read them where your other
12
+ settings are read, and pass the values:
13
+
14
+ ```ts
15
+ // src/janus.ts
16
+ import { janus, scryptHasher } from '@softistx/janus';
17
+ import { connectKit, defineConfig } from '@softistx/janus-kit/drizzle';
18
+ import { User } from './users';
19
+
20
+ export const config = defineConfig({
21
+ postgres: { url: process.env.JANUS_DATABASE_URL! },
22
+ auth: (adapters) =>
23
+ janus({ user: User, password: { login: 'email' }, hasher: scryptHasher(), ...adapters }),
24
+ });
25
+
26
+ export const kit = await connectKit(config);
27
+ ```
28
+
29
+ What is wrong with it throws a `TypeError` there, where the application
30
+ starts. `connectKit` runs the same checks again, as `connectKit: …`, for a
31
+ configuration built without `defineConfig`: a missing URL must not reach Bun's
32
+ `SQL`, which would read `DATABASE_URL` instead. An unreachable database, or
33
+ one without the tables, is `connectKit`'s `Error`: `defineConfig` has not
34
+ connected yet.
35
+
36
+ ## `postgres`
37
+
38
+ Required. Users, logins, relations, and sessions and tokens unless `redis`
39
+ holds them.
40
+
41
+ ```ts
42
+ postgres: { url: process.env.JANUS_DATABASE_URL! } // opened and closed by the kit
43
+ postgres: { db } // a Drizzle instance you opened, never closed by the kit
44
+ ```
45
+
46
+ With `url`, the kit opens it over Bun's `SQL`, as `drizzle-orm/bun-sql`. It
47
+ must be a `postgres://` or `postgresql://` URL: Bun's `SQL` would open
48
+ `mysql://` or `sqlite://` as another database, so `defineConfig` refuses
49
+ them, naming the scheme and never the URL. The
50
+ recommended URL is **a database of Janus's own**, which is backed up and
51
+ restored alone: [`@softistx/janus-drizzle`'s guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-drizzle/docs/guide/database.md)
52
+ shows how to create it, and its tables.
53
+
54
+ With `db`, any Drizzle PostgreSQL instance works: node-postgres, postgres.js,
55
+ Bun's `SQL`, PGlite in tests.
56
+
57
+ **`tables`** is what your schema file's `defineJanusTables(…)` returned. Pass it
58
+ when the tables are in a PostgreSQL schema of their own:
59
+
60
+ ```ts
61
+ // src/db/schema.ts
62
+ import { defineJanusTables } from '@softistx/janus-drizzle';
63
+ import { pgSchema } from 'drizzle-orm/pg-core';
64
+
65
+ export const janus = pgSchema('janus');
66
+ export const janusTables = defineJanusTables({ schema: janus });
67
+ export const { users, logins, sessions, tokens, relations } = janusTables;
68
+ ```
69
+
70
+ ```ts
71
+ postgres: { db, tables: { users, logins, sessions, tokens, relations } }
72
+ ```
73
+
74
+ Pass the tables you migrated, not the whole `janusTables`: the kit checks (and
75
+ wires) `social_links` and `passkeys` when `tables` defines them, so
76
+ `janusTables` would fail at connect on a database that did not migrate them.
77
+ It never checks `invitations`, whether `tables` defines it or not. `api_keys`
78
+ is checked only with [`apiKeys: true`](#apikeys), and then `tables` must define
79
+ `apiKeys`.
80
+
81
+ Without it, the kit looks for `users`, `logins`, `sessions`, `tokens` and
82
+ `relations` in the connection's `search_path`, `public` by default.
83
+
84
+ **`connectKit` checks that the five tables exist**, and refuses to start
85
+ otherwise. `social_links` and `passkeys` are opt-in: each is checked only when
86
+ `postgres.tables` defines it. `invitations` is never checked, because the kit
87
+ wires no invitation store. `api_keys` is checked with `apiKeys: true` only.
88
+
89
+ ```
90
+ connectKit: Janus's tables are missing from this database: "users", "logins", "sessions", "tokens", "relations". Apply the migration drizzle-kit generated from defineJanusTables(), to the database `postgres` names.
91
+ ```
92
+
93
+ ## `apiKeys`
94
+
95
+ `true` opts in to API keys, on `/drizzle` and `/mongo` alike. Absent (or
96
+ `false`), nothing API-key related is checked, created or required, and
97
+ `adapters` has no `apiKeyStore`.
98
+
99
+ ```ts
100
+ import { connectKit, defineConfig } from '@softistx/janus-kit/drizzle';
101
+
102
+ const kit = await connectKit(
103
+ defineConfig({
104
+ postgres: { url: process.env.JANUS_DATABASE_URL! },
105
+ apiKeys: true,
106
+ auth: (adapters) =>
107
+ janus({
108
+ user, password: { login: 'email' }, hasher,
109
+ ...adapters,
110
+ apiKeys: { store: adapters.apiKeyStore, prefix: 'sl_', lifetimes: ['30d'] },
111
+ }),
112
+ }),
113
+ );
114
+ ```
115
+
116
+ - **PostgreSQL:** the migration holds `api_keys` (`defineJanusTables()` defines
117
+ it), and `postgres.tables`, when you pass it, defines `apiKeys`: `defineConfig`
118
+ throws a `TypeError` otherwise. A missing table fails `connectKit` naming
119
+ `"api_keys"`. `collectExpired()` deletes lapsed keys there.
120
+ - **MongoDB:** run `syncMongoApiKeys(db)` where you deploy, beside
121
+ `syncMongoAdapter(db)`. A missing collection or index fails `connectKit`
122
+ naming `apiKeys`. A TTL index drops lapsed keys.
123
+ - **The prefix and the lifetimes are yours**: you write the `apiKeys` block of
124
+ `janus()`, with `adapters.apiKeyStore` as its `store`.
125
+
126
+ ## `mongo`
127
+
128
+ Required on `@softistx/janus-kit/mongo`, in place of `postgres`. Users,
129
+ relations, and sessions and tokens unless `redis` holds them.
130
+
131
+ ```ts
132
+ import { connectKit, defineConfig } from '@softistx/janus-kit/mongo';
133
+
134
+ mongo: { url: process.env.JANUS_MONGO_URL! } // opened and closed by the kit
135
+ mongo: { url, clientOptions: { serverSelectionTimeoutMS: 15_000 } }
136
+ mongo: { db } // a Db you opened, never closed by the kit
137
+ ```
138
+
139
+ With `url`, the kit calls `@softistx/mongo`'s `connectMongo` with
140
+ `{ serverSelectionTimeoutMS: 5_000, ...clientOptions }`. It must be a
141
+ `mongodb://` or `mongodb+srv://` URL, and **its path names the database**:
142
+ `mongodb://db.internal/janus`. Without a path, the driver uses `test`. A URL the driver cannot parse is a `TypeError`,
143
+ at once. Five seconds, where the driver waits thirty, makes a MongoDB that does not answer
144
+ fail at startup, and a request during an outage, as fast as Redis does
145
+ without its offline queue; raise it to ride out a replica-set election.
146
+ `clientOptions` is the driver's `MongoClientOptions`, and cannot be given
147
+ beside a `db`, whose client is already open with its own.
148
+
149
+ Use a replica set: `@softistx/janus-mongo` writes a relation change of more than
150
+ one tuple in a transaction, which a standalone `mongod` refuses.
151
+
152
+ **`connectKit` compares the four collections** with `@softistx/janus-mongo`'s
153
+ definitions by running `syncMongoAdapter(db, { dryRun: true })`, which writes
154
+ nothing. **A missing collection or index refuses to start**, naming each:
155
+
156
+ ```
157
+ connectKit: Janus's collections are not in sync with @softistx/janus-mongo: users (missing), sessions (missing), tokens (missing), relations (missing). Run syncMongoAdapter(db), a deployment step, against the database `mongo` names.
158
+ ```
159
+
160
+ A table missing in PostgreSQL fails the first query; a collection missing in
161
+ MongoDB is created by the first write, **without the unique index on
162
+ logins**, and two users could then share one. That is why the check is
163
+ stricter here. When the missing collection is `apiKeys`, the message names
164
+ `syncMongoApiKeys(db)`, or both calls when another collection is also missing.
165
+
166
+ A validator, an option or an index's options that differ **only warn**, with
167
+ the code `JANUS_KIT_COLLECTIONS_DRIFTED`: they differ in either direction, and
168
+ in a rolling deploy or a rollback the previous release meets the next one's
169
+ collections and must still start. Run `syncMongoAdapter(db)` where you deploy, as the migrations
170
+ of `/drizzle`: it needs the `dbAdmin` role, which the application's user
171
+ should not hold.
172
+
173
+ ## `redis`
174
+
175
+ Optional. Sessions and one-time tokens in Redis, which expires them itself.
176
+ Users and relations stay in the database.
177
+
178
+ ```ts
179
+ redis: { url: process.env.REDIS_URL! } // opened and closed by the kit
180
+ redis: { url: process.env.REDIS_URL!, prefix: 'clinic:janus:', clientOptions: { tls: true } }
181
+ redis: { connection } // from connectRedis, never closed by the kit
182
+ ```
183
+
184
+ With `url`, the kit calls `@softistx/redis`'s `connectRedis` with
185
+ `{ enableOfflineQueue: false, ...clientOptions }`. Without the offline queue,
186
+ a call during an outage fails at once, and a route answers 503, instead of
187
+ waiting about 31 seconds for Bun's client to give up. `clientOptions` is Bun's
188
+ `RedisOptions`, and cannot be given beside a `connection`, already open with
189
+ its own.
190
+
191
+ `prefix` starts every key, `janus:` by default. Two applications sharing one
192
+ Redis each take their own.
193
+
194
+ The one-time tokens include `signIn`'s password counts, which throttle
195
+ guessing per login, and the counts of e-mailed requests (`mail.throttle`):
196
+ **a flushed Redis forgets them**, and every login may try
197
+ ten passwords again, every address ask for five e-mails again — as a flush signs everybody out. Keep `FLUSHDB` for tests.
198
+
199
+ Absent, sessions and tokens stay in the database. On PostgreSQL, schedule
200
+ `kit.auth.collectExpired()` then: PostgreSQL has no TTL, and the call deletes
201
+ lapsed sessions and lapsed tokens — the sign-in throttle's counts, one per
202
+ login tried and per window, and the mail throttle's — in one statement each.
203
+ Both tables are indexed on `expires_at` once the
204
+ [To 0.9](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-drizzle/docs/guide/migrations.md#to-09-an-index-on-tokensexpires_at)
205
+ migration is applied. On MongoDB, a TTL index removes them,
206
+ and `collectExpired()` answers `UNSUPPORTED`.
207
+
208
+ ## `auth`
209
+
210
+ Required. It receives `{ store, relations }` and answers your `janus()`
211
+ instance. Spread it:
212
+
213
+ ```ts
214
+ auth: (adapters) =>
215
+ janus({
216
+ users: {
217
+ patient: { schema: Patient, password: { login: 'email' } },
218
+ staff: { schema: Staff, password: { login: 'username' } },
219
+ },
220
+ hasher: scryptHasher(),
221
+ ...adapters,
222
+ }),
223
+ ```
224
+
225
+ `store` is users from PostgreSQL, and sessions and tokens from Redis when it is
226
+ wired. `relations` is the relation store: passed to `janus()`, deleting a user
227
+ deletes every tuple naming them. `kit.auth` is what you returned, with its
228
+ types: `kit.auth.staff.signIn` takes a `username`.
229
+
230
+ ## `access`
231
+
232
+ Optional. It receives `{ relations, auth }`, `auth` being the instance above,
233
+ and answers your `permissions()` instance:
234
+
235
+ ```ts
236
+ access: ({ relations, auth }) =>
237
+ permissions({
238
+ model: defineModel({
239
+ subjects: auth.types, // 'patient' | 'staff'
240
+ types: {
241
+ record: {
242
+ related: { doctors: ['staff'], patients: ['patient'] },
243
+ permits: { view: ['doctors', 'patients'] },
244
+ },
245
+ },
246
+ }),
247
+ store: relations,
248
+ }),
249
+ ```
250
+
251
+ Absent, the kit has no `access`, and `kit.access` does not compile.
252
+
253
+ ## `telemetry`
254
+
255
+ Optional. `true` wraps `auth` with `@softistx/janus-telemetry`'s `instrumentJanus`
256
+ and `access` with `instrumentPermissions`: a span per flow and per check, and
257
+ the security events. The instances answer the same, with the same types.
258
+
259
+ `@softistx/janus-telemetry` is an optional peer, loaded only then. Install it, and
260
+ `@softistx/telemetry`, which it runs on:
261
+
262
+ ```sh
263
+ bun add @softistx/janus-telemetry @softistx/telemetry
264
+ ```
@@ -0,0 +1,59 @@
1
+ # Health and closing
2
+
3
+ This page covers:
4
+ - `kit.ping()`, for a health route;
5
+ - `kit.close()`, and who closes what;
6
+ - `kit.db` and `kit.redis`, the connections the kit holds.
7
+
8
+ ## `kit.ping(options?)`
9
+
10
+ ```ts
11
+ const health = await kit.ping({ timeoutMs: 1_000 }); // 2 s by default
12
+ // { ok: true, postgres: { ok: true, latencyMs: 1.2 }, redis: { ok: true, latencyMs: 0.4 } }
13
+ ```
14
+
15
+ It sends `select 1` to PostgreSQL — or `ping` to MongoDB, reported as
16
+ `mongo` — and `PING` to Redis, at once, each within `timeoutMs`. `redis` is there only when Redis is wired. **It never throws**: a
17
+ database that does not answer is `{ ok: false, error }`, and `ok` at the top
18
+ is `false`, so a health route always has something to report:
19
+
20
+ ```ts
21
+ app.get('/health', async (c) => {
22
+ const health = await kit.ping();
23
+ return c.json({ ok: health.ok }, health.ok ? 200 : 503);
24
+ });
25
+ ```
26
+
27
+ Do not send `error` to the client: it is the driver's, and may name a host.
28
+ A probe that outlasts `timeoutMs` is `{ ok: false, error }` with the error
29
+ `ping: no answer in 2000ms`.
30
+
31
+ ## `kit.close()`
32
+
33
+ ```ts
34
+ await kit.close();
35
+ // or, for a script or a test:
36
+ await using kit = await connectKit(config);
37
+ ```
38
+
39
+ It closes what the kit opened, Redis first, then the database, and nothing it
40
+ was handed: a `postgres.db`, a `mongo.db` or a `redis.connection` from the configuration
41
+ stays open, since it is not the kit's to close. It is idempotent. It tries
42
+ every connection, then rejects with the error of the one that failed to
43
+ close, or an `AggregateError` when several did.
44
+
45
+ After it, every call through `kit.auth` that reaches a connection the kit
46
+ opened fails with `STORE_FAILED`, and `kit.ping()` answers `ok: false` for
47
+ it. A connection you handed in keeps answering.
48
+
49
+ `@softistx/redis` and `@softistx/mongo` share one client per URL: the client closes
50
+ with the last connection to it, so a connection your application opened to
51
+ the same URL keeps it open.
52
+
53
+ ## `kit.db` and `kit.redis`
54
+
55
+ `kit.db` is the Drizzle instance, or the MongoDB `Db`, over Janus's database, for a query of your
56
+ own: an admin page, a report. Read, never write: a row written behind the
57
+ stores skips their invariants.
58
+
59
+ `kit.redis` is the `@softistx/redis` connection, or `undefined` without Redis.
@@ -0,0 +1,47 @@
1
+ # Roadmap
2
+
3
+ Where `@softistx/janus-kit` is heading. It shows a direction, not a commitment:
4
+ there are no dates here, and the only number is the version something shipped
5
+ in.
6
+
7
+ ## Now
8
+
9
+ Nothing yet.
10
+
11
+ ## Next
12
+
13
+ Nothing yet.
14
+
15
+ ## Later
16
+
17
+ Nothing yet.
18
+
19
+ ## Not planned
20
+
21
+ - **Running migrations, or `syncMongoAdapter`.** Janus's tables are created
22
+ by your drizzle-kit migrations, as your own are, and its collections by
23
+ `syncMongoAdapter` where you deploy: both need rights the application's
24
+ user should not hold. The kit checks, and creates nothing.
25
+ - **Building `janus()` or `permissions()` from configuration keys.** You write
26
+ them, in `auth` and `access`, so their types are inferred where you wrote
27
+ them.
28
+ - **Node.** The kit opens PostgreSQL over Bun's `SQL` and Redis over Bun's
29
+ `RedisClient`. On Node, wire the adapters yourself.
30
+
31
+ ## Shipped
32
+
33
+ - **API keys** (0.6.0) — `apiKeys: true` opts in on `/drizzle` and `/mongo`: `connectKit` checks the `api_keys` table or collection at connect and wires the store as `adapters.apiKeyStore`.
34
+
35
+ - **Social login** (0.3.0) — the linked-accounts store comes wired with the
36
+ others: on MongoDB the `socialLinks` collection is checked and wired, and
37
+ on PostgreSQL the `social_links` table is wired when the `tables` you pass
38
+ define it. [#359](https://github.com/softistx/nxgt-janus/issues/359)
39
+
40
+ - **Moved to `@softistx` on GitHub Packages** (0.2.0) — formerly
41
+ the `@nxgt` scope on npm; same names under the new scope, published privately.
42
+
43
+ - **The first release, v0.1.0**: PostgreSQL through `@softistx/janus-drizzle`, at
44
+ `@softistx/janus-kit/drizzle`, and MongoDB through `@softistx/janus-mongo`, at
45
+ `@softistx/janus-kit/mongo`; sessions and one-time tokens in Redis through
46
+ `@softistx/janus-redis`, telemetry through `@softistx/janus-telemetry`, a health
47
+ check and a close.