@shiprev/server-sdk-node 0.0.0-stage → 0.1.0-beta.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.
- package/LICENSE +202 -0
- package/README.md +253 -2
- package/dist/auth/token-verifier.d.ts +42 -0
- package/dist/auth/token-verifier.js +230 -0
- package/dist/client/connection-supervisor.d.ts +117 -0
- package/dist/client/connection-supervisor.js +547 -0
- package/dist/client/shiprev-client.d.ts +106 -0
- package/dist/client/shiprev-client.js +267 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +47 -0
- package/dist/metering/backlog/host-adapter-backlog.d.ts +10 -0
- package/dist/metering/backlog/host-adapter-backlog.js +27 -0
- package/dist/metering/backlog/journal-backlog.d.ts +14 -0
- package/dist/metering/backlog/journal-backlog.js +135 -0
- package/dist/metering/backlog/memory-backlog.d.ts +9 -0
- package/dist/metering/backlog/memory-backlog.js +34 -0
- package/dist/metering/usage-buffer.d.ts +59 -0
- package/dist/metering/usage-buffer.js +175 -0
- package/dist/mirror/entitlement-mirror.d.ts +47 -0
- package/dist/mirror/entitlement-mirror.js +109 -0
- package/dist/nest/decorators.d.ts +15 -0
- package/dist/nest/decorators.js +21 -0
- package/dist/nest/index.d.ts +4 -0
- package/dist/nest/index.js +21 -0
- package/dist/nest/shiprev-auth.guard.d.ts +7 -0
- package/dist/nest/shiprev-auth.guard.js +52 -0
- package/dist/nest/shiprev-capability.guard.d.ts +9 -0
- package/dist/nest/shiprev-capability.guard.js +65 -0
- package/dist/nest/shiprev.module.d.ts +17 -0
- package/dist/nest/shiprev.module.js +57 -0
- package/dist/ruling/adjudicator.d.ts +15 -0
- package/dist/ruling/adjudicator.js +131 -0
- package/dist/transport/event-stream.d.ts +27 -0
- package/dist/transport/event-stream.js +92 -0
- package/dist/transport/http.transport.d.ts +64 -0
- package/dist/transport/http.transport.js +218 -0
- package/dist/transport/wire.d.ts +79 -0
- package/dist/transport/wire.js +8 -0
- package/dist/types.d.ts +191 -0
- package/dist/types.js +25 -0
- package/dist/util/decimal.d.ts +14 -0
- package/dist/util/decimal.js +57 -0
- package/package.json +98 -4
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,254 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @shiprev/server-sdk-node
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
85
|
+
## NestJS
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { Module } from '@nestjs/common';
|
|
91
|
+
import { ShipRevModule } from '@shiprev/server-sdk-node/nest';
|
|
92
|
+
|
|
93
|
+
@Module({
|
|
94
|
+
imports: [
|
|
95
|
+
ShipRevModule.forRoot({
|
|
96
|
+
base_url: process.env.SHIPREV_BASE_URL!,
|
|
97
|
+
api_key: process.env.SHIPREV_API_KEY!,
|
|
98
|
+
}),
|
|
99
|
+
],
|
|
100
|
+
})
|
|
101
|
+
export class AppModule {}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`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:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
108
|
+
import { ShipRevModule } from '@shiprev/server-sdk-node/nest';
|
|
109
|
+
|
|
110
|
+
ShipRevModule.forRootAsync({
|
|
111
|
+
imports: [ConfigModule],
|
|
112
|
+
inject: [ConfigService],
|
|
113
|
+
useFactory: (config: ConfigService) => ({
|
|
114
|
+
base_url: config.getOrThrow<string>('SHIPREV_BASE_URL'),
|
|
115
|
+
api_key: config.getOrThrow<string>('SHIPREV_API_KEY'),
|
|
116
|
+
}),
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The subpath also resolves under `"moduleResolution": "node"`, the default of new NestJS projects.
|
|
121
|
+
|
|
122
|
+
Protect routes with the guards, in this order:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { Controller, Post, UseGuards } from '@nestjs/common';
|
|
126
|
+
import { ShipRevClient } from '@shiprev/server-sdk-node';
|
|
127
|
+
import {
|
|
128
|
+
InjectShipRevClient,
|
|
129
|
+
RequireCapability,
|
|
130
|
+
ShipRevAuthGuard,
|
|
131
|
+
ShipRevCapabilityGuard,
|
|
132
|
+
} from '@shiprev/server-sdk-node/nest';
|
|
133
|
+
|
|
134
|
+
@Controller('reports')
|
|
135
|
+
@UseGuards(ShipRevAuthGuard, ShipRevCapabilityGuard)
|
|
136
|
+
export class ReportsController {
|
|
137
|
+
constructor(@InjectShipRevClient() private readonly shiprev: ShipRevClient) {}
|
|
138
|
+
|
|
139
|
+
@Post('export')
|
|
140
|
+
@RequireCapability('report_exports', 'write', 1)
|
|
141
|
+
async export() {
|
|
142
|
+
// ...
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
- `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`.
|
|
148
|
+
- `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.
|
|
149
|
+
- `@InjectShipRevClient()` injects the client (token `SHIPREV_CLIENT`).
|
|
150
|
+
|
|
151
|
+
## Token verification
|
|
152
|
+
|
|
153
|
+
`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:
|
|
154
|
+
|
|
155
|
+
| Check | Refused with `TokenRejectedError`, `reason` |
|
|
156
|
+
| :--------------------------------------------------------- | :------------------------------------------ |
|
|
157
|
+
| `exp` is present and numeric | `missing_expiry` |
|
|
158
|
+
| no `purpose` claim (email verification and the like) | `not_a_session_token` |
|
|
159
|
+
| the client knows what to expect | `not_ready` |
|
|
160
|
+
| `aud` and `scope` are both `public` | `audience_mismatch` |
|
|
161
|
+
| `iss` equals the issuer of the client's service token | `issuer_mismatch` |
|
|
162
|
+
| `pid` equals the application of the client's service token | `project_mismatch` |
|
|
163
|
+
|
|
164
|
+
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.
|
|
165
|
+
|
|
166
|
+
## Rulings and `operation`
|
|
167
|
+
|
|
168
|
+
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'`.
|
|
169
|
+
|
|
170
|
+
`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.
|
|
171
|
+
|
|
172
|
+
A `Ruling` is `{ allowed, source, reason?, remaining?, limit?, adjudicated_at }`. `source` says where it came from:
|
|
173
|
+
|
|
174
|
+
| `source` | When |
|
|
175
|
+
| :--------------- | :----------------------------------------------------------------------------------------------- |
|
|
176
|
+
| `realtime` | Online, ruled from the mirror |
|
|
177
|
+
| `authoritative` | Online, the mirror did not know the organization or capability; the instance ruled |
|
|
178
|
+
| `degraded` | Offline, ruled from the last snapshot |
|
|
179
|
+
| `client_default` | No basis for a ruling: invalid request, cold start offline, or online with nothing in the mirror |
|
|
180
|
+
|
|
181
|
+
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 only the `ALLOW_AND_BILL` overage policy allows locally; any other policy is refused with `reason: 'quota_exhausted'`. A capability the mirror does not hold is refused with `reason: 'capability_not_granted'` (which `adjudicateAsync()` turns into a question to the instance).
|
|
182
|
+
|
|
183
|
+
`guardWrite(options, action)` runs `action` only when a `write` ruling allows it, and otherwise throws `DisconnectedWriteError`.
|
|
184
|
+
|
|
185
|
+
## Usage reporting
|
|
186
|
+
|
|
187
|
+
`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:
|
|
188
|
+
|
|
189
|
+
| Field | Meaning |
|
|
190
|
+
| :---------------- | :-------------------------------------------------------------------------------------- |
|
|
191
|
+
| `usage_event_id` | Your unique ID for the event. The service drops repeats, so a retried event counts once |
|
|
192
|
+
| `organization_id` | Buyer organization that consumed |
|
|
193
|
+
| `capability_key` | Metered capability |
|
|
194
|
+
| `quantity` | A finite number; anything else throws `RangeError` at `reportUsage()` |
|
|
195
|
+
| `occurred_at` | ISO 8601 timestamp of the consumption |
|
|
196
|
+
| `idempotency_key` | Optional |
|
|
197
|
+
| `properties` | Optional, `Record<string, unknown>` |
|
|
198
|
+
|
|
199
|
+
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.
|
|
200
|
+
|
|
201
|
+
`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.
|
|
202
|
+
|
|
203
|
+
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.
|
|
204
|
+
|
|
205
|
+
## Connection
|
|
206
|
+
|
|
207
|
+
From `start()` to `stop()` the client keeps itself connected; the host calls nothing in between.
|
|
208
|
+
|
|
209
|
+
- **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.
|
|
210
|
+
- **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.
|
|
211
|
+
- **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.
|
|
212
|
+
- **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()`.
|
|
213
|
+
|
|
214
|
+
Every timer is unref'd: the client never keeps your process alive, and `stop()` closes the stream and clears every timer.
|
|
215
|
+
|
|
216
|
+
## Disconnected semantics
|
|
217
|
+
|
|
218
|
+
`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 }`.
|
|
219
|
+
|
|
220
|
+
| State | Meaning | Reads | Writes |
|
|
221
|
+
| :------------- | :-------------------------- | :--------------------------------- | :------------------------------------ |
|
|
222
|
+
| `LIVE` | Online, mirror loaded | Ruled from the mirror | Ruled from the mirror |
|
|
223
|
+
| `DISCONNECTED` | Offline, last snapshot kept | **Fail open**: allowed, `degraded` | **Fail closed**: `disconnected_write` |
|
|
224
|
+
| `COLD_OFFLINE` | Offline, nothing loaded | `presets.cold_start` decides | **Fail closed**: `disconnected_write` |
|
|
225
|
+
| `COLD` | Not started, or stopped | | |
|
|
226
|
+
|
|
227
|
+
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.
|
|
228
|
+
|
|
229
|
+
`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`).
|
|
230
|
+
|
|
231
|
+
## Persistence modes
|
|
232
|
+
|
|
233
|
+
`backlog.mode` chooses where undeliverable usage waits:
|
|
234
|
+
|
|
235
|
+
| Mode | Survives a restart | Notes |
|
|
236
|
+
| :------------- | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
237
|
+
| `memory` | No | Default. Events waiting in the backlog are lost if the process exits |
|
|
238
|
+
| `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 |
|
|
239
|
+
| `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 |
|
|
240
|
+
|
|
241
|
+
## Development
|
|
242
|
+
|
|
243
|
+
```bash
|
|
244
|
+
pnpm --filter @shiprev/server-sdk-node build
|
|
245
|
+
pnpm --filter @shiprev/server-sdk-node test
|
|
246
|
+
pnpm --filter @shiprev/server-sdk-node lint
|
|
247
|
+
pnpm --filter @shiprev/server-sdk-node test:nest9 # Nest specs and type check against NestJS 9; needs the npm registry
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
Packages are named by product line plus language suffix, `@shiprev/server-sdk-<lang>`; other languages will be added under the same prefix.
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
[Apache-2.0](./LICENSE).
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
export declare class TokenVerifier {
|
|
13
|
+
private readonly transport;
|
|
14
|
+
private readonly publicKeyCache;
|
|
15
|
+
constructor(transport: HttpTransport);
|
|
16
|
+
/**
|
|
17
|
+
* Refreshes the local in-memory public key cache from the JWKS endpoint
|
|
18
|
+
*/
|
|
19
|
+
refreshKeys(): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Directly caches a key in memory (e.g. for testing or preloading)
|
|
22
|
+
*/
|
|
23
|
+
setPublicKey(kid: string, pem: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* Verifies an RS256 JWT token locally, extracting the subject and isolation keys.
|
|
26
|
+
* If the kid is unknown in cache, it triggers a single JWKS refresh.
|
|
27
|
+
*
|
|
28
|
+
* With `expectations` (or `null`, meaning they are not known yet), the token must also be a buyer
|
|
29
|
+
* session token of that issuer and application; the checks run after the signature, in the order
|
|
30
|
+
* exp · purpose · aud/scope · iss · pid, and refusals are `TokenRejectedError`. Without the
|
|
31
|
+
* argument only the signature and, when present, the expiry are checked.
|
|
32
|
+
*/
|
|
33
|
+
verifyToken(token: string, expectations?: TokenExpectations | null): Promise<TokenClaims>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reads the expectations from a machine token's payload without verifying it (the client obtained
|
|
37
|
+
* it from the instance itself). Returns `null` when the value is not a decodable JWT or lacks `iss`
|
|
38
|
+
* or `pid`.
|
|
39
|
+
*/
|
|
40
|
+
export declare function expectationsFromMachineToken(token: string): TokenExpectations | null;
|
|
41
|
+
/** The `exp` of a JWT in milliseconds, or `undefined` when it cannot be read. */
|
|
42
|
+
export declare function expiryOfToken(token: string): number | undefined;
|