@jini-ai/capability-providers 0.1.2 → 0.4.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 (75) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +174 -0
  3. package/dist/adapters/blob-storage/index.d.ts +67 -0
  4. package/dist/adapters/blob-storage/index.js +62 -0
  5. package/dist/adapters/jwt-auth/index.d.ts +53 -0
  6. package/dist/adapters/jwt-auth/index.js +182 -0
  7. package/dist/adapters/sqlite/index.d.ts +56 -0
  8. package/dist/adapters/sqlite/index.js +83 -0
  9. package/dist/adapters/stripe/index.d.ts +94 -0
  10. package/dist/adapters/stripe/index.js +167 -0
  11. package/dist/adapters/ws/index.d.ts +95 -0
  12. package/dist/adapters/ws/index.js +161 -0
  13. package/dist/auth.d.ts +22 -47
  14. package/dist/auth.js +10 -173
  15. package/dist/db.d.ts +11 -48
  16. package/dist/db.js +15 -79
  17. package/dist/index.d.ts +54 -1
  18. package/dist/index.js +54 -1
  19. package/dist/payments.d.ts +21 -74
  20. package/dist/payments.js +13 -175
  21. package/dist/realtime.d.ts +24 -73
  22. package/dist/realtime.js +14 -140
  23. package/dist/storage.d.ts +23 -49
  24. package/dist/storage.js +13 -57
  25. package/dist/tokens.js +6 -6
  26. package/dist/unsafe-reference/auth.d.ts +1 -1
  27. package/dist/unsafe-reference/auth.js +3 -3
  28. package/dist/unsafe-reference/db.d.ts +2 -2
  29. package/dist/unsafe-reference/index.d.ts +1 -1
  30. package/dist/unsafe-reference/index.js +1 -1
  31. package/dist/unsafe-reference/payments.d.ts +3 -1
  32. package/dist/unsafe-reference/payments.js +6 -5
  33. package/dist/unsafe-reference/realtime.d.ts +1 -1
  34. package/dist/unsafe-reference/realtime.js +4 -4
  35. package/dist/unsafe-reference/storage.d.ts +3 -1
  36. package/dist/unsafe-reference/storage.js +7 -6
  37. package/dist/visitor-auth/definitions.d.ts +32 -0
  38. package/dist/visitor-auth/definitions.js +57 -0
  39. package/dist/visitor-auth/index.d.ts +17 -0
  40. package/dist/visitor-auth/index.js +17 -0
  41. package/dist/visitor-auth/lifecycle.d.ts +101 -0
  42. package/dist/visitor-auth/lifecycle.js +326 -0
  43. package/dist/visitor-auth/ports.d.ts +134 -0
  44. package/dist/visitor-auth/ports.js +2 -0
  45. package/dist/visitor-auth/registry.d.ts +38 -0
  46. package/dist/visitor-auth/registry.js +78 -0
  47. package/dist/visitor-auth/tokens.d.ts +10 -0
  48. package/dist/visitor-auth/tokens.js +9 -0
  49. package/package.json +66 -9
  50. package/dist/auth.d.ts.map +0 -1
  51. package/dist/auth.js.map +0 -1
  52. package/dist/db.d.ts.map +0 -1
  53. package/dist/db.js.map +0 -1
  54. package/dist/index.d.ts.map +0 -1
  55. package/dist/index.js.map +0 -1
  56. package/dist/payments.d.ts.map +0 -1
  57. package/dist/payments.js.map +0 -1
  58. package/dist/realtime.d.ts.map +0 -1
  59. package/dist/realtime.js.map +0 -1
  60. package/dist/storage.d.ts.map +0 -1
  61. package/dist/storage.js.map +0 -1
  62. package/dist/tokens.d.ts.map +0 -1
  63. package/dist/tokens.js.map +0 -1
  64. package/dist/unsafe-reference/auth.d.ts.map +0 -1
  65. package/dist/unsafe-reference/auth.js.map +0 -1
  66. package/dist/unsafe-reference/db.d.ts.map +0 -1
  67. package/dist/unsafe-reference/db.js.map +0 -1
  68. package/dist/unsafe-reference/index.d.ts.map +0 -1
  69. package/dist/unsafe-reference/index.js.map +0 -1
  70. package/dist/unsafe-reference/payments.d.ts.map +0 -1
  71. package/dist/unsafe-reference/payments.js.map +0 -1
  72. package/dist/unsafe-reference/realtime.d.ts.map +0 -1
  73. package/dist/unsafe-reference/realtime.js.map +0 -1
  74. package/dist/unsafe-reference/storage.d.ts.map +0 -1
  75. package/dist/unsafe-reference/storage.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,95 @@
1
+ # @jini-ai/capability-providers
2
+
3
+ ## 0.4.0 — 2026-10-02
4
+
5
+ ### BREAKING
6
+
7
+ - Published capability helpers use required/optional argument objects and retain isolated provider entries.
8
+ - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
9
+
10
+ ## Unreleased
11
+
12
+ ### Fixed
13
+
14
+ - Align capability and visitor-auth token declarations with core's `token({ id })` factory,
15
+ preserving token IDs. Omit absent Stripe error metadata fields for exact optional property types.
16
+ - Correct payment-description options and native `Reflect.get`/`URLSearchParams.has` calls in tests
17
+ while retaining their original assertions.
18
+
19
+ ### Integration reconciliation
20
+
21
+ - Existing `.`, `./visitor-auth`, `./unsafe-reference` and five adapter subpaths already have export
22
+ and runtime metadata. No dependencies, exports or versions need changing.
23
+ - Retain the prior **BREAKING** required/optional object conversion for non-DB provider APIs.
24
+ DB port/adapter conversion remains reserved for the active DB lane.
25
+ - Make Stripe Basic auth work without Node Buffer and inject its fallback timestamp clock.
26
+ Strengthen package-wide production-source neutrality checks. Verification deferred by owner directive.
27
+
28
+
29
+ - **BREAKING:** Convert the clean existing public APIs and provider methods to required argument objects plus separate optional settings. Inject transport, time, identity and filesystem dependencies through ports. No compatibility wrappers or version bump. Conversion of pre-existing dirty source files and their coupled APIs is deferred; see API-CONVERSION.md.
30
+
31
+ ## 0.1.2
32
+
33
+ ### Patch Changes
34
+
35
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
36
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
37
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
38
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
39
+ resolution are separate algorithms. Verified against a real external consumer (whose
40
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
41
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
42
+ specifier, which already worked) for the same reason — `main` was previously absent.
43
+
44
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
45
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
46
+ this changes nothing for a consumer already on a modern resolver.
47
+
48
+ - Updated dependencies
49
+ - @jini-ai/core@0.1.2
50
+ - @jini-ai/platform@0.1.2
51
+
52
+ ## 0.1.1
53
+
54
+ ### Patch Changes
55
+
56
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
57
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
58
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
59
+ support, i.e. Node >=22.12, for this to resolve).
60
+
61
+ `@jini-ai/agent-runtime`:
62
+
63
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
64
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
65
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
66
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
67
+ behavior unchanged.
68
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
69
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
70
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
71
+ untyped sink and silently lost every streamed token with no compile or runtime error.
72
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
73
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
74
+ `{ toolUseId, content, isError }`.
75
+
76
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
77
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
78
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
79
+ isolation.
80
+
81
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
82
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
83
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
84
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
85
+ entire chat UI from ~40 bytes of malformed input.
86
+
87
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
88
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
89
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
90
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
91
+ anywhere in this package or its hosts before this).
92
+
93
+ - Updated dependencies
94
+ - @jini-ai/core@0.1.1
95
+ - @jini-ai/platform@0.1.1
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # `@jini-ai/capability-providers`
2
+
3
+ ## Integration update (2026-10-01)
4
+
5
+ The existing exports and entry runtimes cover all reported subpaths: `.`, `./visitor-auth`,
6
+ `./unsafe-reference`, and the five `./adapters/*` entries. No new exports or dependencies are needed.
7
+ The non-DB APIs use required/optional argument objects; the remaining DB conversion belongs to the
8
+ active DB lane and remains deferred across the port and both implementations together.
9
+
10
+ ```ts
11
+ const stripe = new StripePaymentsProvider(
12
+ { secretKey },
13
+ { fetchFn, apiBase, now: () => Date.now() },
14
+ );
15
+ await stripe.getCharge({ id });
16
+ await stripe.charge(
17
+ { amountCents: 1000, currency: 'usd', customerRef },
18
+ { description: 'Order payment' },
19
+ );
20
+ ```
21
+
22
+ Provider tokens use core's `token({ id })` factory and retain their existing IDs.
23
+ Stripe error metadata includes `stripeType` and `stripeCode` only when supplied by the response.
24
+
25
+ The universal Stripe adapter now uses UTF-8 plus native base64 encoding for Basic auth and an
26
+ injected clock when a response omits `created`. Successful response timestamps and HTTP payloads
27
+ retain their existing meaning. Neutrality guards inspect every production source extension and
28
+ reject application references in comments as well as imports.
29
+ Verification is not run (owner directive); see INTEGRATION-REPORT.md.
30
+
31
+
32
+ The 2026-10-01 breaking argument conversion is documented in [API-CONVERSION.md](./API-CONVERSION.md). Required values use the first object; optional settings use the second. Pre-existing dirty APIs remain deferred and are explicitly listed there.
33
+
34
+
35
+ Five swappable "capability" ports an application-shaped host tends to need — authentication, blob
36
+ storage, payments, a document store, and realtime pub/sub — expressed as narrow TypeScript
37
+ interfaces plus typed `@jini-ai/core` DI tokens. The root entry point is **interfaces and tokens
38
+ only**: no concrete implementation, no vendor SDK, nothing to install beyond the two workspace
39
+ dependencies. Concrete adapters live behind explicit `./adapters/*` subpaths so that importing a
40
+ port never drags in a vendor client or a native binary.
41
+
42
+ Be honest with yourself about maturity before adopting: this is deliberate port-design exploration,
43
+ built without a current in-repo consumer. The interfaces are small and stable-shaped, but they have
44
+ not been pressure-tested by a real product yet. See the archived provenance ledger for the full
45
+ scope note.
46
+
47
+ ## Install
48
+
49
+ ```sh
50
+ npm install @jini-ai/capability-providers
51
+
52
+ # only if you import ./adapters/ws
53
+ npm install ws
54
+
55
+ # only if you import ./adapters/sqlite (native compiled addon)
56
+ npm install better-sqlite3
57
+ ```
58
+
59
+ `ws` and `better-sqlite3` are **optional peer dependencies**. Nothing on the root barrel references
60
+ either one, in code or in the emitted `.d.ts`, so installing this package for its ports costs you
61
+ nothing extra. `@jini-ai/core` and `@jini-ai/platform` are regular dependencies.
62
+
63
+ ## What you get
64
+
65
+ **The five ports** (root entry point):
66
+ - `AuthProvider` with `AuthCredentials`, `AuthUser`, `AuthSession`
67
+ - `StorageProvider` with `StorageObjectMeta`, `StoragePutOptions`
68
+ - `PaymentsProvider` with `ChargeInput`, `Charge`, `ChargeStatus`
69
+ - `DbProvider` with `DbRecord`, `DbQuery`
70
+ - `RealtimeProvider` with `RealtimeHandler`, `RealtimeUnsubscribe`
71
+
72
+ **The DI tokens** (root entry point) — `AuthProviderToken`, `StorageProviderToken`,
73
+ `PaymentsProviderToken`, `DbProviderToken`, `RealtimeProviderToken`. Bind whichever implementation
74
+ you want at composition time; a pack declaring one of these in its `deps` gets it typed.
75
+
76
+ **Real adapters** (each behind its own subpath):
77
+ - `./adapters/jwt-auth` — `JwtAuthProvider` / `JwtAuthProviderOptions`. Self-signed HS256 session
78
+ tokens using only `node:crypto` — no external auth service. Real `scrypt` password hashing with a
79
+ per-user salt and constant-time comparison. **User storage is in-process memory, not durable**;
80
+ pair it with a real store at the binding site.
81
+ - `./adapters/blob-storage` — `BlobStorageProvider` / `BlobStorageProviderOptions`. Delegates to an
82
+ injected `@jini-ai/platform` `BlobStorage` (`LocalBlobStorage` or `S3BlobStorage`), scoped to one
83
+ namespace. `StoragePutOptions.contentType` is echoed back but not durably persisted.
84
+ - `./adapters/stripe` — `StripePaymentsProvider` / `StripePaymentsProviderOptions` /
85
+ `StripePaymentsProviderError`. Real Stripe REST calls; the secret key is an explicit constructor
86
+ argument, never read from an environment variable inside the adapter.
87
+ - `./adapters/sqlite` — `SqliteDbProvider`, constructed from a `better-sqlite3` `Database` you own
88
+ and open. Creates its own `jini_capability_db_records` table.
89
+ - `./adapters/ws` — `WebSocketRealtimeProvider`, `createWebSocketRealtimeProvider`, and the
90
+ `RealtimeWebSocketLike` / `RealtimeWebSocketServerLike` seams for injecting a fake server in tests.
91
+
92
+ **`./unsafe-reference` — read this before importing it.** Five in-memory stubs
93
+ (`createInMemoryAuthProvider`, `createInMemoryStorageProvider`, `createInMemoryPaymentsProvider`,
94
+ `createInMemoryDbProvider`, `createInMemoryRealtimeProvider`) whose only purpose is proving each port
95
+ is genuinely implementable and unit-testable. They are **not production adapters and are not meant to
96
+ become them**: the auth stub stores passwords in plaintext and issues predictable incrementing
97
+ `user-N`/`session-N` ids; the payments stub deterministically succeeds every charge; none of them has
98
+ a tenant/ACL dimension, a quota, or a size bound. Do not wire them into anything touching real
99
+ credentials, payments, or user data — not behind a feature flag, not "just for now", not in a demo
100
+ that might get deployed. They live at a separate import path precisely so they cannot arrive by
101
+ accident alongside the ports.
102
+
103
+ ## Usage
104
+
105
+ ```ts
106
+ import { bindings, definePack, createDaemon } from '@jini-ai/core';
107
+ import {
108
+ AuthProviderToken,
109
+ DbProviderToken,
110
+ RealtimeProviderToken,
111
+ type AuthProvider,
112
+ } from '@jini-ai/capability-providers';
113
+ import { JwtAuthProvider } from '@jini-ai/capability-providers/adapters/jwt-auth';
114
+ import { SqliteDbProvider } from '@jini-ai/capability-providers/adapters/sqlite';
115
+ import { createWebSocketRealtimeProvider } from '@jini-ai/capability-providers/adapters/ws';
116
+ import Database from 'better-sqlite3';
117
+
118
+ const auth: AuthProvider = new JwtAuthProvider({ secret: process.env.SESSION_SECRET! });
119
+ const db = new SqliteDbProvider(new Database('/var/lib/example/app.sqlite'));
120
+ const { provider: realtime } = createWebSocketRealtimeProvider({ wsOptions: { port: 8080 } });
121
+
122
+ const bound = bindings()
123
+ .bind(AuthProviderToken, auth)
124
+ .bind(DbProviderToken, db)
125
+ .bind(RealtimeProviderToken, realtime);
126
+
127
+ const accountPack = definePack({
128
+ name: 'account',
129
+ deps: [AuthProviderToken],
130
+ services: (c) => ({ auth: c.get(AuthProviderToken) }),
131
+ });
132
+
133
+ const daemon = createDaemon({ packs: [accountPack] as const, bindings: bound });
134
+ const session = await daemon.services.account.auth.signIn({
135
+ email: 'a@example.com',
136
+ password: 'hunter2',
137
+ });
138
+ ```
139
+
140
+ ## Entry points
141
+
142
+ | subpath | what's behind it | extra dep it pulls in |
143
+ |---|---|---|
144
+ | `.` | The five port interfaces, their data types, and the five DI tokens. No implementations. | none |
145
+ | `./unsafe-reference` | Non-production in-memory stubs. See the warning above. | none |
146
+ | `./adapters/jwt-auth` | `JwtAuthProvider` (HS256 sessions, `scrypt` hashing, in-memory users). | none (`node:crypto`) |
147
+ | `./adapters/blob-storage` | `BlobStorageProvider` over an injected `@jini-ai/platform` `BlobStorage`. | none |
148
+ | `./adapters/stripe` | `StripePaymentsProvider` (real Stripe REST). | none (`fetch`) |
149
+ | `./adapters/sqlite` | `SqliteDbProvider` over a caller-owned `Database` handle. | `better-sqlite3` (native) |
150
+ | `./adapters/ws` | `WebSocketRealtimeProvider` + `createWebSocketRealtimeProvider`. | `ws` |
151
+
152
+ ## What's swappable
153
+
154
+ Everything, by design — that is the package's whole reason to exist. Each of the five interfaces is a
155
+ port you can implement against any vendor (Supabase, Auth0, S3, Postgres, Pusher) and bind through
156
+ the matching token with no change at the consumer. Within the shipped adapters, the injectable seams
157
+ are real too: `StripePaymentsProvider` takes `fetchFn`/`apiBase`, `JwtAuthProvider` takes `now` and
158
+ `sessionTtlMs`, `BlobStorageProvider` takes the `BlobStorage` instance, `SqliteDbProvider` takes the
159
+ open database handle, and `WebSocketRealtimeProvider` accepts an injected server object so tests need
160
+ no real socket. Composition — pairing, say, `JwtAuthProvider` with a durable user store — happens at
161
+ the binding site, deliberately not inside this package.
162
+
163
+ ## Runtime
164
+
165
+ `jini.runtime: "universal"` for the root entry point and `./unsafe-reference`. Per-entry:
166
+ `./adapters/stripe` is universal (`fetch` only); `./adapters/ws`, `./adapters/sqlite`,
167
+ `./adapters/blob-storage`, and `./adapters/jwt-auth` are Node-only.
168
+ ESM only — ships `"type": "module"` with no CommonJS `require` build.
169
+
170
+ ## Provenance
171
+
172
+ See the archived provenance ledger for per-file provenance and scope decisions (note that it
173
+ predates the adapters/ports split described above; trust the exports map and this file for the
174
+ current layout). Apache-2.0, inherited from Open Design — see the repo `NOTICE`.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * `@jini-ai/capability-providers/adapters/blob-storage` — the one real,
3
+ * production-quality `StorageProvider` adapter this package ships, delegating
4
+ * to an injected `@jini-ai/platform` `BlobStorage` instance (`LocalBlobStorage`
5
+ * or `S3BlobStorage`).
6
+ *
7
+ * Lives at this separate entry point (not the package's main
8
+ * `@jini-ai/capability-providers` barrel) so importing the port
9
+ * interface/types/DI tokens never pulls `@jini-ai/platform` — and its `undici`
10
+ * dependency — into a consumer that only wanted the `StorageProvider`
11
+ * interface to implement itself. Import from here only when you actually want
12
+ * this concrete adapter.
13
+ *
14
+ * The in-memory reference implementation (`createInMemoryStorageProvider`) is a
15
+ * separate, non-production stub under `src/unsafe-reference/` — see that
16
+ * directory's `index.ts` header for the full warning.
17
+ */
18
+ import type { BlobStorage } from '@jini-ai/platform';
19
+ import type { StorageObjectMeta, StorageProvider, StoragePutOptions } from '../../storage.js';
20
+ export interface BlobStorageProviderOptions {
21
+ /**
22
+ * The `BlobStorage` namespace this provider scopes every `StorageProvider` key under (see
23
+ * `BlobStorage`'s own module doc: "a tenant id, a workspace id, a project id, whatever the
24
+ * host application scopes storage by"). `StorageProvider`'s `key` maps 1:1 onto `BlobStorage`'s
25
+ * `relpath` within this fixed namespace — this adapter does not expose namespace switching,
26
+ * matching `StorageProvider`'s single flat `key` surface (bind a separate `BlobStorageProvider`
27
+ * per namespace if a host needs more than one).
28
+ */
29
+ readonly namespace: string;
30
+ }
31
+ /**
32
+ * `StorageProvider` adapter that delegates to an injected `BlobStorage` instance
33
+ * (`@jini-ai/platform`'s real, tested port — `LocalBlobStorage` or `S3BlobStorage`). A thin
34
+ * method-shape mapping, not a reimplementation: every operation is one `BlobStorage` call plus
35
+ * field renaming (`path`→`key`, `mtimeMs`→`updatedAt`).
36
+ *
37
+ * Known limitation: `BlobFileMeta` (the metadata `BlobStorage` actually persists) has no
38
+ * `contentType` field, so `StoragePutOptions.contentType` cannot be durably stored — `put()`
39
+ * echoes it straight back in the `StorageObjectMeta` it returns (matching the option the caller
40
+ * just passed), but a later `get`-equivalent lookup (`list()`) can never recover it, since
41
+ * nothing under `../platform` persists it. `StorageObjectMeta.contentType` is optional
42
+ * specifically so an adapter is free to omit it when the backing store can't carry it — this is
43
+ * a deliberate, documented adapter-level gap, not a `StorageProvider` interface change.
44
+ */
45
+ export declare class BlobStorageProvider implements StorageProvider {
46
+ private readonly blobStorage;
47
+ private readonly options;
48
+ constructor({ blobStorage, namespace }: {
49
+ blobStorage: BlobStorage;
50
+ namespace: string;
51
+ });
52
+ put({ key, data }: {
53
+ key: string;
54
+ data: Uint8Array;
55
+ }, options?: StoragePutOptions): Promise<StorageObjectMeta>;
56
+ get({ key }: {
57
+ key: string;
58
+ }): Promise<Uint8Array | null>;
59
+ delete({ key }: {
60
+ key: string;
61
+ }): Promise<void>;
62
+ list(_required: Record<string, never>, { prefix }?: {
63
+ prefix?: string;
64
+ }): Promise<StorageObjectMeta[]>;
65
+ private toObjectMeta;
66
+ }
67
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,62 @@
1
+ import { StorageError as BlobStorageError } from '@jini-ai/platform';
2
+ /**
3
+ * `StorageProvider` adapter that delegates to an injected `BlobStorage` instance
4
+ * (`@jini-ai/platform`'s real, tested port — `LocalBlobStorage` or `S3BlobStorage`). A thin
5
+ * method-shape mapping, not a reimplementation: every operation is one `BlobStorage` call plus
6
+ * field renaming (`path`→`key`, `mtimeMs`→`updatedAt`).
7
+ *
8
+ * Known limitation: `BlobFileMeta` (the metadata `BlobStorage` actually persists) has no
9
+ * `contentType` field, so `StoragePutOptions.contentType` cannot be durably stored — `put()`
10
+ * echoes it straight back in the `StorageObjectMeta` it returns (matching the option the caller
11
+ * just passed), but a later `get`-equivalent lookup (`list()`) can never recover it, since
12
+ * nothing under `../platform` persists it. `StorageObjectMeta.contentType` is optional
13
+ * specifically so an adapter is free to omit it when the backing store can't carry it — this is
14
+ * a deliberate, documented adapter-level gap, not a `StorageProvider` interface change.
15
+ */
16
+ export class BlobStorageProvider {
17
+ blobStorage;
18
+ options;
19
+ constructor({ blobStorage, namespace }) {
20
+ this.blobStorage = blobStorage;
21
+ const options = { namespace };
22
+ this.options = options;
23
+ if (!options.namespace) {
24
+ throw new Error('BlobStorageProvider requires a non-empty options.namespace');
25
+ }
26
+ }
27
+ async put({ key, data }, options = {}) {
28
+ const meta = await this.blobStorage.writeFile(this.options.namespace, key, Buffer.from(data));
29
+ return this.toObjectMeta(meta, options.contentType);
30
+ }
31
+ async get({ key }) {
32
+ try {
33
+ return await this.blobStorage.readFile(this.options.namespace, key);
34
+ }
35
+ catch (err) {
36
+ if (err instanceof BlobStorageError && err.code === 'NOT_FOUND')
37
+ return null;
38
+ throw err;
39
+ }
40
+ }
41
+ async delete({ key }) {
42
+ // `BlobStorage.deleteFile` is already documented idempotent (missing files don't throw),
43
+ // matching `StorageProvider.delete`'s "no-op if it doesn't exist" contract directly.
44
+ await this.blobStorage.deleteFile(this.options.namespace, key);
45
+ }
46
+ async list(_required, { prefix = '' } = {}) {
47
+ const files = await this.blobStorage.listFiles(this.options.namespace);
48
+ return files
49
+ .filter((file) => file.path.startsWith(prefix))
50
+ .map((file) => this.toObjectMeta(file))
51
+ .sort((a, b) => a.key.localeCompare(b.key));
52
+ }
53
+ toObjectMeta(meta, contentType) {
54
+ return {
55
+ key: meta.path,
56
+ size: meta.size,
57
+ updatedAt: meta.mtimeMs,
58
+ ...(contentType !== undefined ? { contentType } : {}),
59
+ };
60
+ }
61
+ }
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ import type { AuthCredentials, AuthProvider, AuthSession, AuthUser } from '../../auth.js';
2
+ export interface JwtAuthProviderOptions {
3
+ /** HMAC-SHA256 signing secret for session tokens. Required and explicit — never read from an environment variable inside this adapter. */
4
+ readonly secret: string;
5
+ }
6
+ export interface JwtAuthProviderOptionalArgs {
7
+ /** Session lifetime in ms. Defaults to 1 hour, matching the in-memory reference adapter's default. */
8
+ readonly sessionTtlMs?: number;
9
+ /** Injectable clock for deterministic tests; defaults to `Date.now`. */
10
+ readonly now?: () => number;
11
+ }
12
+ /**
13
+ * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
14
+ * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
15
+ * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
16
+ * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
17
+ *
18
+ * Two deliberate, documented scope limits:
19
+ *
20
+ * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
21
+ * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
22
+ * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `archived provenance ledger`'s
23
+ * "composition happens at the binding site, not in this package" design decision) if a host
24
+ * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
25
+ * instance verifies its *signature* successfully against any instance sharing the same
26
+ * `secret` (including a fresh instance after a restart), but `verifySession` still returns
27
+ * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
28
+ * tested explicitly below.
29
+ * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
30
+ * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
31
+ * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
32
+ * token is memory-safe under normal operation but session revocation is not honored across a
33
+ * restart of the process holding the deny-list.
34
+ */
35
+ export declare class JwtAuthProvider implements AuthProvider {
36
+ private readonly secret;
37
+ private readonly sessionTtlMs;
38
+ private readonly now;
39
+ private readonly usersByEmail;
40
+ private readonly usersById;
41
+ private readonly revokedJti;
42
+ private nextId;
43
+ constructor(options: JwtAuthProviderOptions, optional?: JwtAuthProviderOptionalArgs);
44
+ signUp(credentials: AuthCredentials): Promise<AuthUser>;
45
+ signIn(credentials: AuthCredentials): Promise<AuthSession>;
46
+ signOut({ token }: {
47
+ token: string;
48
+ }): Promise<void>;
49
+ verifySession({ token }: {
50
+ token: string;
51
+ }): Promise<AuthUser | null>;
52
+ }
53
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `@jini-ai/capability-providers/adapters/jwt-auth` — the one real,
3
+ * production-quality `AuthProvider` adapter this package ships: self-contained
4
+ * HS256 JWT session tokens signed with a host-supplied secret, `node:crypto`
5
+ * `scrypt` password hashing, no external auth-service dependency (no
6
+ * Auth0/Clerk/Supabase Auth call).
7
+ *
8
+ * Lives at this separate entry point (not the package's main
9
+ * `@jini-ai/capability-providers` barrel) so importing the port
10
+ * interface/types/DI tokens never drags `node:crypto` in — that single import
11
+ * is what made the whole root barrel Node-only, unusable from a browser or edge
12
+ * runtime that only wanted the `AuthProvider` interface to implement itself.
13
+ * Import from here only when you actually want this concrete adapter.
14
+ *
15
+ * The in-memory reference implementation (`createInMemoryAuthProvider`) is a
16
+ * separate, non-production stub under `src/unsafe-reference/` — see that
17
+ * directory's `index.ts` header for the full warning.
18
+ */
19
+ import { createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
20
+ const SCRYPT_KEYLEN = 64;
21
+ const SCRYPT_SALT_BYTES = 16;
22
+ const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;
23
+ function base64url(input) {
24
+ return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
25
+ }
26
+ function base64urlToBuffer(input) {
27
+ const padded = input.replace(/-/g, '+').replace(/_/g, '/');
28
+ const padLength = padded.length % 4 === 0 ? 0 : 4 - (padded.length % 4);
29
+ return Buffer.from(padded + '='.repeat(padLength), 'base64');
30
+ }
31
+ /** Hashes `password` with `scrypt` under a fresh random salt, returned as a `<saltHex>:<hashHex>` string. */
32
+ function hashPassword(password) {
33
+ const salt = randomBytes(SCRYPT_SALT_BYTES);
34
+ const hash = scryptSync(password, salt, SCRYPT_KEYLEN);
35
+ return `${salt.toString('hex')}:${hash.toString('hex')}`;
36
+ }
37
+ /**
38
+ * Verifies `password` against a `<saltHex>:<hashHex>` string previously produced by
39
+ * {@link hashPassword}. `stored` is always this class's own `hashPassword` output — nothing
40
+ * external ever writes to a user's `passwordHash` field — so both halves are trusted to be
41
+ * well-formed hex by construction; no defensive "malformed stored hash" branch is needed (there
42
+ * is no real caller path that could exercise one).
43
+ */
44
+ function verifyPassword(password, stored) {
45
+ const separatorIndex = stored.indexOf(':');
46
+ const salt = Buffer.from(stored.slice(0, separatorIndex), 'hex');
47
+ const expected = Buffer.from(stored.slice(separatorIndex + 1), 'hex');
48
+ const actual = scryptSync(password, salt, SCRYPT_KEYLEN);
49
+ return timingSafeEqual(actual, expected);
50
+ }
51
+ /** Signs `payload` as an HS256 JWT (`base64url(header).base64url(payload).base64url(hmacSha256Signature)`). */
52
+ function signSessionJwt(payload, secret) {
53
+ const header = { alg: 'HS256', typ: 'JWT' };
54
+ const signingInput = `${base64url(Buffer.from(JSON.stringify(header)))}.${base64url(Buffer.from(JSON.stringify(payload)))}`;
55
+ const signature = base64url(createHmac('sha256', secret).update(signingInput).digest());
56
+ return `${signingInput}.${signature}`;
57
+ }
58
+ /**
59
+ * Verifies an HS256 session JWT's signature and claim shape against `secret`. Deliberately does
60
+ * NOT check expiry or revocation — those are session-store concerns (`revokedJti`, `now()`) that
61
+ * `JwtAuthProvider.verifySession` layers on top, so this stays a pure "is this token
62
+ * authentically signed and well-formed" check reusable by both `verifySession` and `signOut`.
63
+ */
64
+ function verifySessionJwt(token, secret) {
65
+ const parts = token.split('.');
66
+ if (parts.length !== 3)
67
+ return { ok: false };
68
+ // Array destructuring can't narrow past noUncheckedIndexedAccess; the length check above
69
+ // guarantees all three are real strings, not undefined.
70
+ const headerPart = parts[0];
71
+ const payloadPart = parts[1];
72
+ const signaturePart = parts[2];
73
+ const expectedSignature = createHmac('sha256', secret).update(`${headerPart}.${payloadPart}`).digest();
74
+ const actualSignature = base64urlToBuffer(signaturePart);
75
+ if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) {
76
+ return { ok: false };
77
+ }
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(base64urlToBuffer(payloadPart).toString('utf8'));
81
+ }
82
+ catch {
83
+ return { ok: false };
84
+ }
85
+ if (!parsed ||
86
+ typeof parsed !== 'object' ||
87
+ typeof parsed.sub !== 'string' ||
88
+ typeof parsed.jti !== 'string' ||
89
+ typeof parsed.exp !== 'number') {
90
+ return { ok: false };
91
+ }
92
+ return { ok: true, payload: parsed };
93
+ }
94
+ /**
95
+ * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
96
+ * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
97
+ * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
98
+ * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
99
+ *
100
+ * Two deliberate, documented scope limits:
101
+ *
102
+ * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
103
+ * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
104
+ * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `archived provenance ledger`'s
105
+ * "composition happens at the binding site, not in this package" design decision) if a host
106
+ * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
107
+ * instance verifies its *signature* successfully against any instance sharing the same
108
+ * `secret` (including a fresh instance after a restart), but `verifySession` still returns
109
+ * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
110
+ * tested explicitly below.
111
+ * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
112
+ * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
113
+ * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
114
+ * token is memory-safe under normal operation but session revocation is not honored across a
115
+ * restart of the process holding the deny-list.
116
+ */
117
+ export class JwtAuthProvider {
118
+ secret;
119
+ sessionTtlMs;
120
+ now;
121
+ usersByEmail = new Map();
122
+ usersById = new Map();
123
+ revokedJti = new Set();
124
+ nextId = 1;
125
+ constructor(options, optional = {}) {
126
+ if (!options.secret) {
127
+ throw new Error('JwtAuthProvider requires a non-empty options.secret');
128
+ }
129
+ this.secret = options.secret;
130
+ this.sessionTtlMs = optional.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;
131
+ this.now = optional.now ?? Date.now;
132
+ }
133
+ async signUp(credentials) {
134
+ if (this.usersByEmail.has(credentials.email)) {
135
+ throw new Error(`email already registered: ${credentials.email}`);
136
+ }
137
+ const user = {
138
+ id: `user-${this.nextId++}`,
139
+ email: credentials.email,
140
+ createdAt: this.now(),
141
+ passwordHash: hashPassword(credentials.password),
142
+ };
143
+ this.usersByEmail.set(credentials.email, user);
144
+ this.usersById.set(user.id, user);
145
+ return { id: user.id, email: user.email, createdAt: user.createdAt };
146
+ }
147
+ async signIn(credentials) {
148
+ const user = this.usersByEmail.get(credentials.email);
149
+ if (!user || !verifyPassword(credentials.password, user.passwordHash)) {
150
+ throw new Error('invalid email or password');
151
+ }
152
+ const nowMs = this.now();
153
+ const expiresAt = nowMs + this.sessionTtlMs;
154
+ const token = signSessionJwt({
155
+ sub: user.id,
156
+ jti: randomBytes(16).toString('hex'),
157
+ iat: Math.floor(nowMs / 1000),
158
+ exp: Math.floor(expiresAt / 1000),
159
+ }, this.secret);
160
+ return { token, userId: user.id, expiresAt };
161
+ }
162
+ async signOut({ token }) {
163
+ const result = verifySessionJwt(token, this.secret);
164
+ if (result.ok) {
165
+ this.revokedJti.add(result.payload.jti);
166
+ }
167
+ }
168
+ async verifySession({ token }) {
169
+ const result = verifySessionJwt(token, this.secret);
170
+ if (!result.ok)
171
+ return null;
172
+ if (this.revokedJti.has(result.payload.jti))
173
+ return null;
174
+ if (result.payload.exp * 1000 <= this.now())
175
+ return null;
176
+ const user = this.usersById.get(result.payload.sub);
177
+ if (!user)
178
+ return null;
179
+ return { id: user.id, email: user.email, createdAt: user.createdAt };
180
+ }
181
+ }
182
+ //# sourceMappingURL=index.js.map