@jini-ai/capability-providers 0.1.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.
Files changed (54) hide show
  1. package/LICENSE +201 -0
  2. package/dist/auth.d.ts +70 -0
  3. package/dist/auth.d.ts.map +1 -0
  4. package/dist/auth.js +181 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/db.d.ts +75 -0
  7. package/dist/db.d.ts.map +1 -0
  8. package/dist/db.js +83 -0
  9. package/dist/db.js.map +1 -0
  10. package/dist/index.d.ts +22 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +22 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/payments.d.ts +98 -0
  15. package/dist/payments.d.ts.map +1 -0
  16. package/dist/payments.js +180 -0
  17. package/dist/payments.js.map +1 -0
  18. package/dist/realtime.d.ts +86 -0
  19. package/dist/realtime.d.ts.map +1 -0
  20. package/dist/realtime.js +147 -0
  21. package/dist/realtime.js.map +1 -0
  22. package/dist/storage.d.ts +70 -0
  23. package/dist/storage.d.ts.map +1 -0
  24. package/dist/storage.js +61 -0
  25. package/dist/storage.js.map +1 -0
  26. package/dist/tokens.d.ts +11 -0
  27. package/dist/tokens.d.ts.map +1 -0
  28. package/dist/tokens.js +18 -0
  29. package/dist/tokens.js.map +1 -0
  30. package/dist/unsafe-reference/auth.d.ts +22 -0
  31. package/dist/unsafe-reference/auth.d.ts.map +1 -0
  32. package/dist/unsafe-reference/auth.js +56 -0
  33. package/dist/unsafe-reference/auth.js.map +1 -0
  34. package/dist/unsafe-reference/db.d.ts +16 -0
  35. package/dist/unsafe-reference/db.d.ts.map +1 -0
  36. package/dist/unsafe-reference/db.js +49 -0
  37. package/dist/unsafe-reference/db.js.map +1 -0
  38. package/dist/unsafe-reference/index.d.ts +49 -0
  39. package/dist/unsafe-reference/index.d.ts.map +1 -0
  40. package/dist/unsafe-reference/index.js +49 -0
  41. package/dist/unsafe-reference/index.js.map +1 -0
  42. package/dist/unsafe-reference/payments.d.ts +17 -0
  43. package/dist/unsafe-reference/payments.d.ts.map +1 -0
  44. package/dist/unsafe-reference/payments.js +38 -0
  45. package/dist/unsafe-reference/payments.js.map +1 -0
  46. package/dist/unsafe-reference/realtime.d.ts +17 -0
  47. package/dist/unsafe-reference/realtime.d.ts.map +1 -0
  48. package/dist/unsafe-reference/realtime.js +34 -0
  49. package/dist/unsafe-reference/realtime.js.map +1 -0
  50. package/dist/unsafe-reference/storage.d.ts +16 -0
  51. package/dist/unsafe-reference/storage.d.ts.map +1 -0
  52. package/dist/unsafe-reference/storage.js +30 -0
  53. package/dist/unsafe-reference/storage.js.map +1 -0
  54. package/package.json +56 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Open Design contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ export interface AuthCredentials {
2
+ readonly email: string;
3
+ readonly password: string;
4
+ }
5
+ export interface AuthUser {
6
+ readonly id: string;
7
+ readonly email: string;
8
+ readonly createdAt: number;
9
+ }
10
+ export interface AuthSession {
11
+ readonly token: string;
12
+ readonly userId: string;
13
+ readonly expiresAt: number;
14
+ }
15
+ export interface AuthProvider {
16
+ /** Creates a new user. Rejects if `credentials.email` is already registered. */
17
+ signUp(credentials: AuthCredentials): Promise<AuthUser>;
18
+ /** Exchanges valid credentials for a new session. Rejects on an unknown email or wrong password. */
19
+ signIn(credentials: AuthCredentials): Promise<AuthSession>;
20
+ /** Invalidates a session token. A no-op on an already-invalid/unknown token. */
21
+ signOut(token: string): Promise<void>;
22
+ /** Resolves a session token to its user, or `null` if the token is unknown, invalidated, or expired. */
23
+ verifySession(token: string): Promise<AuthUser | null>;
24
+ }
25
+ export interface JwtAuthProviderOptions {
26
+ /** HMAC-SHA256 signing secret for session tokens. Required and explicit — never read from an environment variable inside this adapter. */
27
+ readonly secret: string;
28
+ /** Session lifetime in ms. Defaults to 1 hour, matching the in-memory reference adapter's default. */
29
+ readonly sessionTtlMs?: number;
30
+ /** Injectable clock for deterministic tests; defaults to `Date.now`. */
31
+ readonly now?: () => number;
32
+ }
33
+ /**
34
+ * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
35
+ * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
36
+ * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
37
+ * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
38
+ *
39
+ * Two deliberate, documented scope limits:
40
+ *
41
+ * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
42
+ * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
43
+ * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `source-map.md`'s
44
+ * "composition happens at the binding site, not in this package" design decision) if a host
45
+ * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
46
+ * instance verifies its *signature* successfully against any instance sharing the same
47
+ * `secret` (including a fresh instance after a restart), but `verifySession` still returns
48
+ * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
49
+ * tested explicitly below.
50
+ * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
51
+ * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
52
+ * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
53
+ * token is memory-safe under normal operation but session revocation is not honored across a
54
+ * restart of the process holding the deny-list.
55
+ */
56
+ export declare class JwtAuthProvider implements AuthProvider {
57
+ private readonly secret;
58
+ private readonly sessionTtlMs;
59
+ private readonly now;
60
+ private readonly usersByEmail;
61
+ private readonly usersById;
62
+ private readonly revokedJti;
63
+ private nextId;
64
+ constructor(options: JwtAuthProviderOptions);
65
+ signUp(credentials: AuthCredentials): Promise<AuthUser>;
66
+ signIn(credentials: AuthCredentials): Promise<AuthSession>;
67
+ signOut(token: string): Promise<void>;
68
+ verifySession(token: string): Promise<AuthUser | null>;
69
+ }
70
+ //# sourceMappingURL=auth.d.ts.map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CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;IACnC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAiC;IAC9D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAiC;IAC3D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAqB;IAChD,OAAO,CAAC,MAAM,CAAK;gBAEP,OAAO,EAAE,sBAAsB;IASrC,MAAM,CAAC,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC;IAevD,MAAM,CAAC,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC;IAmB1D,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOrC,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;CAS7D"}
package/dist/auth.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * `AuthProvider` — a swappable identity/session port. Speculative
3
+ * port-design exploration (see `source-map.md`): Zana and Tovu-Runner each
4
+ * independently built an explicit capability-provider layer with auth as one
5
+ * of the swappable capabilities (Supabase/sqlite-backed) — this is the
6
+ * engine-level shape that convergence points at, not a lift from either.
7
+ *
8
+ * This file defines the port's stable interface/type surface, plus one real,
9
+ * production-quality adapter (`JwtAuthProvider`, added 2026-07-21 — see
10
+ * `source-map.md`'s dated section): self-contained HS256 JWT session tokens
11
+ * signed with a host-supplied secret, `node:crypto` `scrypt` password
12
+ * hashing, no external auth-service dependency. The in-memory reference
13
+ * implementation (`createInMemoryAuthProvider`) is a separate, non-production
14
+ * stub that lives under `src/unsafe-reference/`, exported only from the
15
+ * separate `@jini-ai/capability-providers/unsafe-reference` entry point — see
16
+ * that directory's `index.ts` header for the full warning.
17
+ */
18
+ import { createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
19
+ const SCRYPT_KEYLEN = 64;
20
+ const SCRYPT_SALT_BYTES = 16;
21
+ const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;
22
+ function base64url(input) {
23
+ return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
24
+ }
25
+ function base64urlToBuffer(input) {
26
+ const padded = input.replace(/-/g, '+').replace(/_/g, '/');
27
+ const padLength = padded.length % 4 === 0 ? 0 : 4 - (padded.length % 4);
28
+ return Buffer.from(padded + '='.repeat(padLength), 'base64');
29
+ }
30
+ /** Hashes `password` with `scrypt` under a fresh random salt, returned as a `<saltHex>:<hashHex>` string. */
31
+ function hashPassword(password) {
32
+ const salt = randomBytes(SCRYPT_SALT_BYTES);
33
+ const hash = scryptSync(password, salt, SCRYPT_KEYLEN);
34
+ return `${salt.toString('hex')}:${hash.toString('hex')}`;
35
+ }
36
+ /**
37
+ * Verifies `password` against a `<saltHex>:<hashHex>` string previously produced by
38
+ * {@link hashPassword}. `stored` is always this class's own `hashPassword` output — nothing
39
+ * external ever writes to a user's `passwordHash` field — so both halves are trusted to be
40
+ * well-formed hex by construction; no defensive "malformed stored hash" branch is needed (there
41
+ * is no real caller path that could exercise one).
42
+ */
43
+ function verifyPassword(password, stored) {
44
+ const separatorIndex = stored.indexOf(':');
45
+ const salt = Buffer.from(stored.slice(0, separatorIndex), 'hex');
46
+ const expected = Buffer.from(stored.slice(separatorIndex + 1), 'hex');
47
+ const actual = scryptSync(password, salt, SCRYPT_KEYLEN);
48
+ return timingSafeEqual(actual, expected);
49
+ }
50
+ /** Signs `payload` as an HS256 JWT (`base64url(header).base64url(payload).base64url(hmacSha256Signature)`). */
51
+ function signSessionJwt(payload, secret) {
52
+ const header = { alg: 'HS256', typ: 'JWT' };
53
+ const signingInput = `${base64url(Buffer.from(JSON.stringify(header)))}.${base64url(Buffer.from(JSON.stringify(payload)))}`;
54
+ const signature = base64url(createHmac('sha256', secret).update(signingInput).digest());
55
+ return `${signingInput}.${signature}`;
56
+ }
57
+ /**
58
+ * Verifies an HS256 session JWT's signature and claim shape against `secret`. Deliberately does
59
+ * NOT check expiry or revocation — those are session-store concerns (`revokedJti`, `now()`) that
60
+ * `JwtAuthProvider.verifySession` layers on top, so this stays a pure "is this token
61
+ * authentically signed and well-formed" check reusable by both `verifySession` and `signOut`.
62
+ */
63
+ function verifySessionJwt(token, secret) {
64
+ const parts = token.split('.');
65
+ if (parts.length !== 3)
66
+ return { ok: false };
67
+ // Array destructuring can't narrow past noUncheckedIndexedAccess; the length check above
68
+ // guarantees all three are real strings, not undefined.
69
+ const headerPart = parts[0];
70
+ const payloadPart = parts[1];
71
+ const signaturePart = parts[2];
72
+ const expectedSignature = createHmac('sha256', secret).update(`${headerPart}.${payloadPart}`).digest();
73
+ const actualSignature = base64urlToBuffer(signaturePart);
74
+ if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) {
75
+ return { ok: false };
76
+ }
77
+ let parsed;
78
+ try {
79
+ parsed = JSON.parse(base64urlToBuffer(payloadPart).toString('utf8'));
80
+ }
81
+ catch {
82
+ return { ok: false };
83
+ }
84
+ if (!parsed ||
85
+ typeof parsed !== 'object' ||
86
+ typeof parsed.sub !== 'string' ||
87
+ typeof parsed.jti !== 'string' ||
88
+ typeof parsed.exp !== 'number') {
89
+ return { ok: false };
90
+ }
91
+ return { ok: true, payload: parsed };
92
+ }
93
+ /**
94
+ * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
95
+ * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
96
+ * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
97
+ * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
98
+ *
99
+ * Two deliberate, documented scope limits:
100
+ *
101
+ * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
102
+ * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
103
+ * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `source-map.md`'s
104
+ * "composition happens at the binding site, not in this package" design decision) if a host
105
+ * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
106
+ * instance verifies its *signature* successfully against any instance sharing the same
107
+ * `secret` (including a fresh instance after a restart), but `verifySession` still returns
108
+ * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
109
+ * tested explicitly below.
110
+ * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
111
+ * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
112
+ * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
113
+ * token is memory-safe under normal operation but session revocation is not honored across a
114
+ * restart of the process holding the deny-list.
115
+ */
116
+ export class JwtAuthProvider {
117
+ secret;
118
+ sessionTtlMs;
119
+ now;
120
+ usersByEmail = new Map();
121
+ usersById = new Map();
122
+ revokedJti = new Set();
123
+ nextId = 1;
124
+ constructor(options) {
125
+ if (!options.secret) {
126
+ throw new Error('JwtAuthProvider requires a non-empty options.secret');
127
+ }
128
+ this.secret = options.secret;
129
+ this.sessionTtlMs = options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;
130
+ this.now = options.now ?? Date.now;
131
+ }
132
+ async signUp(credentials) {
133
+ if (this.usersByEmail.has(credentials.email)) {
134
+ throw new Error(`email already registered: ${credentials.email}`);
135
+ }
136
+ const user = {
137
+ id: `user-${this.nextId++}`,
138
+ email: credentials.email,
139
+ createdAt: this.now(),
140
+ passwordHash: hashPassword(credentials.password),
141
+ };
142
+ this.usersByEmail.set(credentials.email, user);
143
+ this.usersById.set(user.id, user);
144
+ return { id: user.id, email: user.email, createdAt: user.createdAt };
145
+ }
146
+ async signIn(credentials) {
147
+ const user = this.usersByEmail.get(credentials.email);
148
+ if (!user || !verifyPassword(credentials.password, user.passwordHash)) {
149
+ throw new Error('invalid email or password');
150
+ }
151
+ const nowMs = this.now();
152
+ const expiresAt = nowMs + this.sessionTtlMs;
153
+ const token = signSessionJwt({
154
+ sub: user.id,
155
+ jti: randomBytes(16).toString('hex'),
156
+ iat: Math.floor(nowMs / 1000),
157
+ exp: Math.floor(expiresAt / 1000),
158
+ }, this.secret);
159
+ return { token, userId: user.id, expiresAt };
160
+ }
161
+ async signOut(token) {
162
+ const result = verifySessionJwt(token, this.secret);
163
+ if (result.ok) {
164
+ this.revokedJti.add(result.payload.jti);
165
+ }
166
+ }
167
+ async verifySession(token) {
168
+ const result = verifySessionJwt(token, this.secret);
169
+ if (!result.ok)
170
+ return null;
171
+ if (this.revokedJti.has(result.payload.jti))
172
+ return null;
173
+ if (result.payload.exp * 1000 <= this.now())
174
+ return null;
175
+ const user = this.usersById.get(result.payload.sub);
176
+ if (!user)
177
+ return null;
178
+ return { id: user.id, email: user.email, createdAt: user.createdAt };
179
+ }
180
+ }
181
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA8BnF,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,sBAAsB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE9C,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAa;IACtC,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAC3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CAAC,SAAS,EAAE,CAAC;IACvE,CAAC;CACF"}
package/dist/db.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * `DbProvider` — a swappable, minimal document-store port (collection +
3
+ * record id, not a query language). Speculative port-design exploration
4
+ * (see `source-map.md`) — no OD source; the capability
5
+ * `foundry/docs/jini-port/recon/r5b-consumers-matrix.md` §3.3 names as the one Zana
6
+ * (Supabase→db+auth+storage+realtime) and Tovu-Runner (ports+sqlite/memory)
7
+ * both built explicitly.
8
+ *
9
+ * This file defines the port's stable interface/type surface, plus one real,
10
+ * production-quality adapter (`SqliteDbProvider`, added 2026-07-21 — see
11
+ * `source-map.md`'s dated section) backed directly by `better-sqlite3` — the
12
+ * same driver `@jini-ai/sqlite`'s `createSqliteEventLog` uses, following that
13
+ * module's DI/schema conventions (an injected, already-open `Database`
14
+ * handle; idempotent `CREATE TABLE IF NOT EXISTS`; multi-statement writes
15
+ * wrapped in `db.transaction()`). The in-memory reference implementation
16
+ * (`createInMemoryDbProvider`) is a separate, non-production stub that lives
17
+ * under `src/unsafe-reference/`, exported only from the separate
18
+ * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
19
+ * directory's `index.ts` header for the full warning.
20
+ */
21
+ import type Database from 'better-sqlite3';
22
+ export interface DbRecord {
23
+ readonly id: string;
24
+ readonly [field: string]: unknown;
25
+ }
26
+ export interface DbQuery {
27
+ /** Exact-match filter: every key/value pair must match on a candidate record. Omitted/empty means "all records". */
28
+ readonly where?: Readonly<Record<string, unknown>>;
29
+ }
30
+ export interface DbProvider {
31
+ /** Inserts a record into `collection`. Rejects if `record.id` already exists in that collection. */
32
+ insert(collection: string, record: DbRecord): Promise<DbRecord>;
33
+ /** Looks up a record by id, or `null` if unknown. */
34
+ get(collection: string, id: string): Promise<DbRecord | null>;
35
+ /** Shallow-merges `patch` into an existing record. Returns `null` if `id` is unknown (no upsert). */
36
+ update(collection: string, id: string, patch: Readonly<Record<string, unknown>>): Promise<DbRecord | null>;
37
+ /** Deletes a record by id. A no-op if it doesn't exist. */
38
+ delete(collection: string, id: string): Promise<void>;
39
+ /** Returns every record in `collection` matching `query.where` (all records when `query` is omitted). */
40
+ query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
41
+ }
42
+ /** Alias for a `better-sqlite3` `Database` handle, matching `@jini-ai/sqlite`'s own `SqliteDb` alias (`packages/sqlite/src/db/core/types.ts`). */
43
+ type SqliteDatabase = Database.Database;
44
+ /**
45
+ * `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
46
+ * Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
47
+ * `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
48
+ * client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
49
+ * deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
50
+ * framing and the in-memory reference adapter's identical semantics, so behavior is identical
51
+ * between the two adapters for every input.
52
+ *
53
+ * Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
54
+ * — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
55
+ * re-run against an already-migrated handle) and never opens or closes a connection itself,
56
+ * mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
57
+ * convention for tests.
58
+ */
59
+ export declare class SqliteDbProvider implements DbProvider {
60
+ private readonly getStmt;
61
+ private readonly insertStmt;
62
+ private readonly updateStmt;
63
+ private readonly deleteStmt;
64
+ private readonly queryStmt;
65
+ private readonly insertTxn;
66
+ private readonly updateTxn;
67
+ constructor(db: SqliteDatabase);
68
+ insert(collection: string, record: DbRecord): Promise<DbRecord>;
69
+ get(collection: string, id: string): Promise<DbRecord | null>;
70
+ update(collection: string, id: string, patch: Readonly<Record<string, unknown>>): Promise<DbRecord | null>;
71
+ delete(collection: string, id: string): Promise<void>;
72
+ query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
73
+ }
74
+ export {};
75
+ //# sourceMappingURL=db.d.ts.map
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ACH,qBAAa,gBAAiB,YAAW,UAAU;IACjD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoD;IAC5E,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA+C;IAC1E,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA+C;IAC1E,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAuC;IAClE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA4C;IACtE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAqD;IAC/E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAIL;gBAET,EAAE,EAAE,cAAc;IAkDxB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAI/D,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAK7D,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAI1G,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrD,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,GAAE,OAAY,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;CAI1E"}
package/dist/db.js ADDED
@@ -0,0 +1,83 @@
1
+ /** Exact-match filter used by both `query()` here and the in-memory reference adapter's own `matchesWhere` — kept as an independent, self-contained copy rather than a shared import so this adapter has no dependency on `src/unsafe-reference/`. */
2
+ function matchesWhere(record, where) {
3
+ if (!where)
4
+ return true;
5
+ return Object.entries(where).every(([key, value]) => record[key] === value);
6
+ }
7
+ /**
8
+ * `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
9
+ * Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
10
+ * `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
11
+ * client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
12
+ * deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
13
+ * framing and the in-memory reference adapter's identical semantics, so behavior is identical
14
+ * between the two adapters for every input.
15
+ *
16
+ * Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
17
+ * — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
18
+ * re-run against an already-migrated handle) and never opens or closes a connection itself,
19
+ * mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
20
+ * convention for tests.
21
+ */
22
+ export class SqliteDbProvider {
23
+ getStmt;
24
+ insertStmt;
25
+ updateStmt;
26
+ deleteStmt;
27
+ queryStmt;
28
+ insertTxn;
29
+ updateTxn;
30
+ constructor(db) {
31
+ db.exec(`
32
+ CREATE TABLE IF NOT EXISTS jini_capability_db_records (
33
+ collection TEXT NOT NULL,
34
+ id TEXT NOT NULL,
35
+ data TEXT NOT NULL,
36
+ PRIMARY KEY (collection, id)
37
+ );
38
+ `);
39
+ this.getStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ? AND id = ?');
40
+ this.insertStmt = db.prepare('INSERT INTO jini_capability_db_records (collection, id, data) VALUES (?, ?, ?)');
41
+ this.updateStmt = db.prepare('UPDATE jini_capability_db_records SET data = ? WHERE collection = ? AND id = ?');
42
+ this.deleteStmt = db.prepare('DELETE FROM jini_capability_db_records WHERE collection = ? AND id = ?');
43
+ this.queryStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ?');
44
+ // Wrapped in db.transaction() for the same reason createSqliteEventLog wraps its
45
+ // dedupe-check + insert: a single atomic unit of work at the SQL level, not a JS-level race
46
+ // guard (better-sqlite3 is synchronous, so no other JS can run between the get() and run()
47
+ // calls within one process either way).
48
+ this.insertTxn = db.transaction((collection, record) => {
49
+ const existing = this.getStmt.get(collection, record.id);
50
+ if (existing) {
51
+ throw new Error(`record already exists: ${collection}/${record.id}`);
52
+ }
53
+ this.insertStmt.run(collection, record.id, JSON.stringify(record));
54
+ return record;
55
+ });
56
+ this.updateTxn = db.transaction((collection, id, patch) => {
57
+ const row = this.getStmt.get(collection, id);
58
+ if (!row)
59
+ return null;
60
+ const updated = { ...JSON.parse(row.data), ...patch, id };
61
+ this.updateStmt.run(JSON.stringify(updated), collection, id);
62
+ return updated;
63
+ });
64
+ }
65
+ async insert(collection, record) {
66
+ return this.insertTxn(collection, record);
67
+ }
68
+ async get(collection, id) {
69
+ const row = this.getStmt.get(collection, id);
70
+ return row ? JSON.parse(row.data) : null;
71
+ }
72
+ async update(collection, id, patch) {
73
+ return this.updateTxn(collection, id, patch);
74
+ }
75
+ async delete(collection, id) {
76
+ this.deleteStmt.run(collection, id);
77
+ }
78
+ async query(collection, query = {}) {
79
+ const rows = this.queryStmt.all(collection);
80
+ return rows.map((row) => JSON.parse(row.data)).filter((record) => matchesWhere(record, query.where));
81
+ }
82
+ }
83
+ //# sourceMappingURL=db.js.map
package/dist/db.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.js","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":"AAsDA,sPAAsP;AACtP,SAAS,YAAY,CAAC,MAAgB,EAAE,KAAoD;IAC1F,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,gBAAgB;IACV,OAAO,CAAoD;IAC3D,UAAU,CAA+C;IACzD,UAAU,CAA+C;IACz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