@shiprev/server-sdk-node 0.0.0-stage → 0.1.0-beta.1

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 (45) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +276 -2
  3. package/dist/auth/token-verifier.d.ts +56 -0
  4. package/dist/auth/token-verifier.js +257 -0
  5. package/dist/client/connection-supervisor.d.ts +148 -0
  6. package/dist/client/connection-supervisor.js +650 -0
  7. package/dist/client/shiprev-client.d.ts +139 -0
  8. package/dist/client/shiprev-client.js +400 -0
  9. package/dist/index.d.ts +16 -0
  10. package/dist/index.js +47 -0
  11. package/dist/metering/backlog/host-adapter-backlog.d.ts +10 -0
  12. package/dist/metering/backlog/host-adapter-backlog.js +27 -0
  13. package/dist/metering/backlog/journal-backlog.d.ts +14 -0
  14. package/dist/metering/backlog/journal-backlog.js +135 -0
  15. package/dist/metering/backlog/memory-backlog.d.ts +9 -0
  16. package/dist/metering/backlog/memory-backlog.js +34 -0
  17. package/dist/metering/usage-buffer.d.ts +59 -0
  18. package/dist/metering/usage-buffer.js +175 -0
  19. package/dist/mirror/degradation.d.ts +22 -0
  20. package/dist/mirror/degradation.js +67 -0
  21. package/dist/mirror/entitlement-mirror.d.ts +61 -0
  22. package/dist/mirror/entitlement-mirror.js +143 -0
  23. package/dist/nest/decorators.d.ts +15 -0
  24. package/dist/nest/decorators.js +21 -0
  25. package/dist/nest/index.d.ts +4 -0
  26. package/dist/nest/index.js +21 -0
  27. package/dist/nest/shiprev-auth.guard.d.ts +7 -0
  28. package/dist/nest/shiprev-auth.guard.js +52 -0
  29. package/dist/nest/shiprev-capability.guard.d.ts +9 -0
  30. package/dist/nest/shiprev-capability.guard.js +65 -0
  31. package/dist/nest/shiprev.module.d.ts +17 -0
  32. package/dist/nest/shiprev.module.js +57 -0
  33. package/dist/ruling/adjudicator.d.ts +15 -0
  34. package/dist/ruling/adjudicator.js +123 -0
  35. package/dist/transport/event-stream.d.ts +27 -0
  36. package/dist/transport/event-stream.js +92 -0
  37. package/dist/transport/http.transport.d.ts +69 -0
  38. package/dist/transport/http.transport.js +238 -0
  39. package/dist/transport/wire.d.ts +79 -0
  40. package/dist/transport/wire.js +8 -0
  41. package/dist/types.d.ts +252 -0
  42. package/dist/types.js +37 -0
  43. package/dist/util/decimal.d.ts +14 -0
  44. package/dist/util/decimal.js +57 -0
  45. package/package.json +96 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,277 @@
1
- # Temporary Holding Version
1
+ # @shiprev/server-sdk-node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Server SDK you install inside your own Node.js or NestJS service to connect it to a ShipRev instance. It verifies the access tokens ShipRev issues to your users, rules on capabilities locally from a mirror of the application's entitlements, reports metered usage in batches, and makes two-phase reservations for expensive work.
4
+
5
+ It runs on your request path. What it does when it cannot reach the instance (a dropped connection, a cold start) is specified below and is part of the contract, not an implementation detail.
6
+
7
+ > **Beta.** Versions `0.1.x` are published under the `beta` dist-tag. The interface may still change before `1.0`; pin an exact version.
8
+
9
+ ## Requirements
10
+
11
+ - Node.js 20 or later.
12
+ - A running ShipRev instance reachable from your service, and an **SDK-scoped API key** for your application (created in the operator console, or with `POST /mgt/v1/credentials` and `scope: "SDK"`).
13
+ - For the NestJS bindings only: `@nestjs/common` and `@nestjs/core` (9, 10 or 11) and `reflect-metadata`. They are optional peer dependencies; a plain Node.js service does not need them, because the main entry point never loads NestJS.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @shiprev/server-sdk-node@beta
19
+ # or
20
+ pnpm add @shiprev/server-sdk-node@beta
21
+ ```
22
+
23
+ ## Quick start (plain Node.js)
24
+
25
+ ```ts
26
+ import { createClient } from '@shiprev/server-sdk-node';
27
+
28
+ const shiprev = createClient({
29
+ base_url: process.env.SHIPREV_BASE_URL!, // e.g. https://shiprev.example.com
30
+ api_key: process.env.SHIPREV_API_KEY!, // SDK-scoped key of your application
31
+ });
32
+
33
+ // Fetches the signing keys, exchanges the API key for a service token, opens the push stream,
34
+ // and loads the entitlement snapshot of every buyer organization of the application.
35
+ const { state } = await shiprev.start();
36
+ if (state !== 'LIVE') {
37
+ // start() never throws: the client keeps reconnecting in the background (see "Connection").
38
+ }
39
+
40
+ // Who is calling: verify the session token your user got from the ShipRev portal.
41
+ const claims = await shiprev.verifyToken(bearerToken);
42
+
43
+ // May they do it: a local ruling, no network I/O.
44
+ const ruling = shiprev.adjudicate({
45
+ organization_id: claims.organization_id,
46
+ capability_key: 'report_exports',
47
+ quantity: 1,
48
+ operation: 'write',
49
+ });
50
+
51
+ if (ruling.allowed) {
52
+ // ... do the work, then report what was consumed.
53
+ await shiprev.reportUsage({
54
+ usage_event_id: crypto.randomUUID(),
55
+ organization_id: claims.organization_id,
56
+ capability_key: 'report_exports',
57
+ quantity: 1,
58
+ occurred_at: new Date().toISOString(),
59
+ });
60
+ }
61
+
62
+ // On shutdown: flush buffered usage.
63
+ await shiprev.stop();
64
+ ```
65
+
66
+ A runnable version of this flow is the `examples/server-sdk-quickstart` example in the ShipRev repository.
67
+
68
+ ## Configuration
69
+
70
+ `createClient(options)` and `new ShipRevClient(options)` take the same `ShipRevClientOptions`:
71
+
72
+ | Option | Default | Meaning |
73
+ | :--------------------------- | :--------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
74
+ | `base_url` | (required) | Base URL of the instance's core service; may include a path prefix. Trailing slashes are ignored |
75
+ | `api_key` | (required) | SDK-scoped API key of the application |
76
+ | `presets.cold_start` | `'deny'` | Ruling for **reads** when the mirror is empty and the instance is unreachable: `'allow'` or `'deny'` |
77
+ | `presets.connect_timeout_ms` | `5000` | Timeout of every request to the instance |
78
+ | `presets.reservation_ttl_s` | (service) | Default time-to-live of a reservation when `reserve()` does not pass one |
79
+ | `buffer.batch_size` | `100` | Usage events sent per request; reaching it triggers a flush |
80
+ | `buffer.flush_interval_ms` | `5000` | Background flush interval. `0` disables the timer; the timer never keeps the process alive |
81
+ | `backlog` | memory | Where usage waits while it cannot be delivered; see [Persistence modes](#persistence-modes) |
82
+ | `on_flush_failure` | | `(events, error) => void`, called when a batch could not be delivered (the events go to the backlog) |
83
+ | `on_rejected` | | `(rejected) => void`, called with the events the service refused, each with a `reason` |
84
+ | `on_level_change` | | `(organization_id, level) => void`, called when an organization's effective level changes; see [Degradation levels](#degradation-levels) |
85
+
86
+ ## NestJS
87
+
88
+ The NestJS bindings live in the `@shiprev/server-sdk-node/nest` subpath. `ShipRevModule` is a global module that provides one started client and two guards.
89
+
90
+ ```ts
91
+ import { Module } from '@nestjs/common';
92
+ import { ShipRevModule } from '@shiprev/server-sdk-node/nest';
93
+
94
+ @Module({
95
+ imports: [
96
+ ShipRevModule.forRoot({
97
+ base_url: process.env.SHIPREV_BASE_URL!,
98
+ api_key: process.env.SHIPREV_API_KEY!,
99
+ }),
100
+ ],
101
+ })
102
+ export class AppModule {}
103
+ ```
104
+
105
+ `forRoot` and `forRootAsync` start the client in the background, so the host boots even when the instance is unreachable. `forRootAsync({ imports, inject, useFactory })` builds the options from other providers: `imports` lists the modules that export them, `inject` the providers passed to `useFactory`, in order:
106
+
107
+ ```ts
108
+ import { ConfigModule, ConfigService } from '@nestjs/config';
109
+ import { ShipRevModule } from '@shiprev/server-sdk-node/nest';
110
+
111
+ ShipRevModule.forRootAsync({
112
+ imports: [ConfigModule],
113
+ inject: [ConfigService],
114
+ useFactory: (config: ConfigService) => ({
115
+ base_url: config.getOrThrow<string>('SHIPREV_BASE_URL'),
116
+ api_key: config.getOrThrow<string>('SHIPREV_API_KEY'),
117
+ }),
118
+ });
119
+ ```
120
+
121
+ The subpath also resolves under `"moduleResolution": "node"`, the default of new NestJS projects.
122
+
123
+ Protect routes with the guards, in this order:
124
+
125
+ ```ts
126
+ import { Controller, Post, UseGuards } from '@nestjs/common';
127
+ import { ShipRevClient } from '@shiprev/server-sdk-node';
128
+ import {
129
+ InjectShipRevClient,
130
+ RequireCapability,
131
+ ShipRevAuthGuard,
132
+ ShipRevCapabilityGuard,
133
+ } from '@shiprev/server-sdk-node/nest';
134
+
135
+ @Controller('reports')
136
+ @UseGuards(ShipRevAuthGuard, ShipRevCapabilityGuard)
137
+ export class ReportsController {
138
+ constructor(@InjectShipRevClient() private readonly shiprev: ShipRevClient) {}
139
+
140
+ @Post('export')
141
+ @RequireCapability('report_exports', 'write', 1)
142
+ async export() {
143
+ // ...
144
+ }
145
+ }
146
+ ```
147
+
148
+ - `ShipRevAuthGuard` reads `Authorization: Bearer <token>`, verifies it with `verifyToken()`, and sets the claims on `request.authClaims` and `request.user`. A missing, malformed, badly signed, expired or rejected token (see [Token verification](#token-verification)) is a `401`.
149
+ - `ShipRevCapabilityGuard` reads `@RequireCapability(capabilityKey, operation = 'read', quantity = 1)` from the handler or the controller and rules with `adjudicateAsync()`. The organization comes only from the verified claims (`organization_id` on `request.authClaims`, or on `request.user`); a header, route parameter or body field is never read, because the caller controls those. Claims without an organization are a `403` with reason `missing_organization`, before any ruling. A refusal is a `403`; the ruling is set on `request.ruling`. Routes without `@RequireCapability` pass.
150
+ - `@InjectShipRevClient()` injects the client (token `SHIPREV_CLIENT`).
151
+
152
+ ## Token verification
153
+
154
+ `verifyToken(token)` accepts only the session tokens the ShipRev portal issues to the buyer end users of **your** application on **your** instance. After the format, the RS256 signature against the instance's keys and the expiry, it checks, in this order:
155
+
156
+ | Check | Refused with `TokenRejectedError`, `reason` |
157
+ | :--------------------------------------------------------- | :------------------------------------------ |
158
+ | `exp` is present and numeric | `missing_expiry` |
159
+ | no `purpose` claim (email verification and the like) | `not_a_session_token` |
160
+ | the client knows what to expect | `not_ready` |
161
+ | `aud` and `scope` are both `public` | `audience_mismatch` |
162
+ | `iss` equals the issuer of the client's service token | `issuer_mismatch` |
163
+ | `pid` equals the application of the client's service token | `project_mismatch` |
164
+
165
+ The expected issuer and application come from the service token the client obtains in `start()`; there is nothing to configure. Until the client has obtained one (never reached the instance), every token is refused with `not_ready`. Once known, the expectations are kept while the client is disconnected, and verification keeps working offline for every signing key already fetched. `TokenRejectedError` is exported from the main entry; its message never contains the token.
166
+
167
+ A token whose `kid` is not among the cached signing keys triggers one refetch of the instance's keys, but not within 30 seconds of the last successful fetch: inside that window it is refused (`Unknown key ID`) without any request, so forged tokens with random key IDs cannot multiply your traffic into requests to the instance. A failed fetch does not start the window. After the instance rotates its signing key, tokens signed with the new key may therefore be refused for up to 30 seconds after the previous fetch.
168
+
169
+ ## Rulings and `operation`
170
+
171
+ Every ruling names its `operation`: `'read'` or `'write'`. It is required, because the two fail in opposite directions when the instance is unreachable: reads keep working from the last known entitlements, writes stop. Anything that consumes quota, changes state or costs money is a `write`. A missing or unknown `operation`, or a negative or non-finite `quantity`, is refused with `reason: 'invalid_request'`.
172
+
173
+ `adjudicate(options)` is synchronous and does no I/O. `adjudicateAsync(options)` returns the same ruling, except that when the client is online and the mirror does not know the organization or capability, it asks the instance (`POST /sdk/v1/adjudicate`) and, on an allow, loads that organization into the mirror.
174
+
175
+ A `Ruling` is `{ allowed, source, reason?, remaining?, limit?, adjudicated_at }`. `source` says where it came from:
176
+
177
+ | `source` | When |
178
+ | :--------------- | :----------------------------------------------------------------------------------------------- |
179
+ | `realtime` | Online, ruled from the mirror |
180
+ | `authoritative` | Online, the mirror did not know the organization or capability; the instance ruled |
181
+ | `degraded` | Offline, ruled from the last snapshot |
182
+ | `client_default` | No basis for a ruling: invalid request, cold start offline, or online with nothing in the mirror |
183
+
184
+ Online rulings from the mirror compare `quantity` exactly against the remaining allowance, which the snapshot carries as fixed-point decimal strings. Beyond the remaining allowance nothing is allowed locally, whatever the overage policy: whether credits (and, for `ALLOW_AND_BILL`, the wallet's overdraft limit) cover the write is state of the instance, so the local answer is a refusal with `reason: 'quota_exhausted'`, which `adjudicateAsync()` turns into a question to the instance and returns its ruling. When no ruling can be had the write stays refused. A capability the mirror does not hold is refused with `reason: 'capability_not_granted'` (which `adjudicateAsync()` turns into a question to the instance).
185
+
186
+ `guardWrite(options, action)` runs `action` only when a `write` ruling allows it, and otherwise throws `DisconnectedWriteError`.
187
+
188
+ ## Usage reporting
189
+
190
+ `reportUsage(event)` appends to an in-memory buffer; the buffer is sent to `POST /sdk/v1/usage-events` when it reaches `buffer.batch_size`, on the flush timer, on `flush()`, and on `stop()`. Each event is:
191
+
192
+ | Field | Meaning |
193
+ | :---------------- | :-------------------------------------------------------------------------------------- |
194
+ | `usage_event_id` | Your unique ID for the event. The service drops repeats, so a retried event counts once |
195
+ | `organization_id` | Buyer organization that consumed |
196
+ | `capability_key` | Metered capability |
197
+ | `quantity` | A finite number; anything else throws `RangeError` at `reportUsage()` |
198
+ | `occurred_at` | ISO 8601 timestamp of the consumption |
199
+ | `idempotency_key` | Optional |
200
+ | `properties` | Optional, `Record<string, unknown>` |
201
+
202
+ Before sending the buffer, each flush first drains what is waiting in the backlog. Events the service refuses are reported to `on_rejected` and are not retried.
203
+
204
+ `await flush()` (and `await stop()`) resolves only when every event reported before the call has been accepted, refused (`on_rejected`), or moved to the backlog because it could not be delivered (offline, no service token, or a failed request; `on_flush_failure` is called for a failed buffer batch). If another flush is in flight, for example the one that follows a reconnection, the call waits for it and then makes its own pass. A flush started by `flush()` sends the whole backlog, batch by batch, stopping at the first failed batch; a timer tick skips while a flush is in flight and sends at most one backlog batch.
205
+
206
+ For work whose cost is only known afterwards, reserve first and settle later: `reserve({ organization_id, capability_key, amount, ttl_seconds? })`, then `confirm(reservationId, actualAmount?)` (without an amount, the reserved amount is confirmed) or `release(reservationId)`. Reservations need a service token, which `start()` obtains; without one they throw.
207
+
208
+ ## Connection
209
+
210
+ From `start()` to `stop()` the client keeps itself connected; the host calls nothing in between.
211
+
212
+ - **Push stream.** The client holds `GET /sdk/v1/events` open. When the instance announces that an organization's entitlements changed (a plan change, a top-up, an operator's rule change), the client refreshes that organization in the mirror without a restart; when the instance asks for a full resynchronization, it reloads the whole snapshot. The mirror is never refreshed on a timer.
213
+ - **Service token.** Renewed at 80 % of its lifetime; the new token takes over the push stream without a gap. A `401` on any request renews the token once (one renewal shared by concurrent requests) and retries that request once. If the instance refuses the API key itself (revoked or expired), the client retries every 30 seconds.
214
+ - **Online signal.** The push stream is the only signal: the client is `LIVE` while the stream is open and not silent for three heartbeat intervals (45 seconds with the instance's default), and the mirror was loaded after the stream opened. A single failed request does not change the state. A stream that ends or fails is reopened at once; if that fails the client is `DISCONNECTED` and retries after 1, 2, 4, 8, 16 and then every 30 seconds (each ±20 %). A stopped service process is noticed at once; a silent network outage within the heartbeat window.
215
+ - **Recovery.** Back online, the client reloads the whole snapshot, returns to `LIVE`, and delivers the usage backlog before new events. A client that started `COLD_OFFLINE` recovers the same way, without a new `start()`.
216
+
217
+ Every timer is unref'd: the client never keeps your process alive, and `stop()` closes the stream and clears every timer.
218
+
219
+ ## Disconnected semantics
220
+
221
+ `start()` moves the client to `LIVE` when it has the signing keys, a service token, a ready push stream and the snapshot. When only the push stream is unavailable it ends in `DISCONNECTED` with the snapshot loaded; when no snapshot could be loaded, in `COLD_OFFLINE`. It does not throw. `state()` reports `{ state, snapshot_revision, last_sync_at }`.
222
+
223
+ | State | Meaning | Reads | Writes |
224
+ | :------------- | :-------------------------- | :--------------------------------- | :------------------------------------ |
225
+ | `LIVE` | Online, mirror loaded | Ruled from the mirror | Ruled from the mirror |
226
+ | `DISCONNECTED` | Offline, last snapshot kept | **Fail open**: allowed, `degraded` | **Fail closed**: `disconnected_write` |
227
+ | `COLD_OFFLINE` | Offline, nothing loaded | `presets.cold_start` decides | **Fail closed**: `disconnected_write` |
228
+ | `COLD` | Not started, or stopped | | |
229
+
230
+ Writes are refused whenever the push stream is down, even if other requests to the instance still succeed: without the stream the mirror may be stale, and a stale mirror must not approve consumption. While offline, usage events are not lost: flushes move them into the backlog, and the first flush back online delivers the backlog before new events.
231
+
232
+ `setOnline(false)` closes the push stream and suspends reconnection until `setOnline(true)`, which sets `LIVE` at once and resumes; on a started client the next connection attempt then corrects the state. Both are for fault injection and tests. `loadSnapshot(snapshot)` seeds the mirror without the network (a `COLD_OFFLINE` client becomes `DISCONNECTED`).
233
+
234
+ ## Degradation levels
235
+
236
+ Every organization entry of the snapshot carries two fields the instance computes: `degradation_level`, one of `NONE`, `RESTRICT_NEW`, `RESTRICT_USAGE`, `RESTRICT_READ` and `SUSPENDED` (strictly increasing), and `valid_until`, the time until which the entry may be used without a newer answer. An instance sets the level from its own rules (for example a buyer's unpaid invoices); at `SUSPENDED` the entry's `items` is empty, so nothing is granted. Instances that predate the fields leave them out.
237
+
238
+ `effectiveLevel(organizationId)` combines them with the connection, synchronously and without I/O, into `{ level, source, expired }` (`undefined` when the mirror does not hold the organization):
239
+
240
+ | The client observes | `level` | `source` | `expired` |
241
+ | :----------------------------------------------------- | :----------------------------------------------------- | :----------- | :-------- |
242
+ | `LIVE` (the instance answers) | The entry's level | `'answer'` | `false` |
243
+ | Not `LIVE`, before the entry's `valid_until` | The entry's level | `'degraded'` | `false` |
244
+ | Not `LIVE`, at or after `valid_until` (or none usable) | The entry's level, raised to `RESTRICT_USAGE` at least | `'degraded'` | `true` |
245
+
246
+ A level the client does not know (another string, or not a string) reads as `RESTRICT_USAGE`, never looser. The level does not change `adjudicate()`, `adjudicateAsync()` or `guardWrite()`: a disconnected write is refused whatever the level; what a level blocks in your service is your decision.
247
+
248
+ While `LIVE`, once half of an entry's validity has passed without a newer entry, the client pulls that organization once to renew it (never more than once per entry, never on a fixed period).
249
+
250
+ `refresh(organizationId, { timeout_ms? })` pulls one organization now, sharing a pull already in flight for it, and resolves with the answer's level (`source: 'answer'`); when the pull fails or does not finish within `timeout_ms` (default `presets.connect_timeout_ms`) it resolves with `effectiveLevel()` as it stands. Use it before refusing an action on a level, so that a change at the instance applies within the action.
251
+
252
+ `sendUsage(events)` sends one batch at once, outside the buffer and the backlog, and resolves with `{ accepted_count, duplicates_dropped, rejected }`. Quantities may be decimal strings, sent unchanged. It throws `UsageDeliveryError` when the batch did not get through (network error, timeout, `5xx`); any other refusal throws as it came. Sending the same batch again is safe, as events are deduplicated by `usage_event_id`. It is for callers that keep their own durable queue; everyone else uses `reportUsage()`.
253
+
254
+ ## Persistence modes
255
+
256
+ `backlog.mode` chooses where undeliverable usage waits:
257
+
258
+ | Mode | Survives a restart | Notes |
259
+ | :------------- | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
260
+ | `memory` | No | Default. Events waiting in the backlog are lost if the process exits |
261
+ | `journal` | Yes | Append-only file at `backlog.journal_path` (default `.shiprev-usage-journal.log` in the working directory), replayed on start; corrupt lines are skipped |
262
+ | `host_adapter` | Your choice | Pass `backlog.adapter`, any `BacklogAdapter` (`enqueue`, `peek`, `ack`, `nack`, `size`) backed by your own store, e.g. Redis or your database |
263
+
264
+ ## Development
265
+
266
+ ```bash
267
+ pnpm --filter @shiprev/server-sdk-node build
268
+ pnpm --filter @shiprev/server-sdk-node test
269
+ pnpm --filter @shiprev/server-sdk-node lint
270
+ pnpm --filter @shiprev/server-sdk-node test:nest9 # Nest specs and type check against NestJS 9; needs the npm registry
271
+ ```
272
+
273
+ Packages are named by product line plus language suffix, `@shiprev/server-sdk-<lang>`; other languages will be added under the same prefix.
274
+
275
+ ## License
276
+
277
+ [Apache-2.0](./LICENSE).
@@ -0,0 +1,56 @@
1
+ import { HttpTransport } from '../transport/http.transport';
2
+ import { JwksKey, TokenClaims } from '../types';
3
+ /**
4
+ * What a buyer session token must carry to be accepted, learned from this client's own machine
5
+ * token: the instance that issued it and the application it belongs to.
6
+ */
7
+ export interface TokenExpectations {
8
+ issuer: string;
9
+ projectId: string;
10
+ }
11
+ export declare function jwkToPem(jwk: JwksKey): string;
12
+ /**
13
+ * After a successful JWKS fetch, a token with an unknown `kid` does not trigger another fetch for
14
+ * this long; it is refused instead. Without it, an anonymous caller could turn every forged token
15
+ * carrying a random `kid` into one request to the instance. A key rotated in during this window is
16
+ * accepted at most this long after the previous fetch.
17
+ */
18
+ export declare const JWKS_REFRESH_COOLDOWN_MS = 30000;
19
+ export declare class TokenVerifier {
20
+ private readonly transport;
21
+ private readonly publicKeyCache;
22
+ /** `Date.now()` of the last successful JWKS fetch; failed fetches do not set it. */
23
+ private lastRefreshAt;
24
+ private inFlightRefresh;
25
+ constructor(transport: HttpTransport);
26
+ /**
27
+ * Refreshes the local in-memory public key cache from the JWKS endpoint. Always fetches (no
28
+ * cooldown); concurrent calls share one request. A success starts the unknown-`kid` cooldown.
29
+ */
30
+ refreshKeys(): Promise<void>;
31
+ private fetchKeys;
32
+ private inRefreshCooldown;
33
+ /**
34
+ * Directly caches a key in memory (e.g. for testing or preloading)
35
+ */
36
+ setPublicKey(kid: string, pem: string): void;
37
+ /**
38
+ * Verifies an RS256 JWT token locally, extracting the subject and isolation keys.
39
+ * If the kid is unknown in cache, it triggers a single JWKS refresh, unless the last successful
40
+ * refresh is less than `JWKS_REFRESH_COOLDOWN_MS` old, in which case the token is refused at once.
41
+ *
42
+ * With `expectations` (or `null`, meaning they are not known yet), the token must also be a buyer
43
+ * session token of that issuer and application; the checks run after the signature, in the order
44
+ * exp · purpose · aud/scope · iss · pid, and refusals are `TokenRejectedError`. Without the
45
+ * argument only the signature and, when present, the expiry are checked.
46
+ */
47
+ verifyToken(token: string, expectations?: TokenExpectations | null): Promise<TokenClaims>;
48
+ }
49
+ /**
50
+ * Reads the expectations from a machine token's payload without verifying it (the client obtained
51
+ * it from the instance itself). Returns `null` when the value is not a decodable JWT or lacks `iss`
52
+ * or `pid`.
53
+ */
54
+ export declare function expectationsFromMachineToken(token: string): TokenExpectations | null;
55
+ /** The `exp` of a JWT in milliseconds, or `undefined` when it cannot be read. */
56
+ export declare function expiryOfToken(token: string): number | undefined;