@marichi-labs-tech/rbac-sdk 0.1.0 → 0.2.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/dist/index.d.ts +36 -7
- package/dist/index.js +114 -13
- package/package.json +4 -3
package/dist/index.d.ts
CHANGED
|
@@ -53,15 +53,25 @@ interface RoleView {
|
|
|
53
53
|
customized: boolean;
|
|
54
54
|
grants: Grant[];
|
|
55
55
|
}
|
|
56
|
+
/** A change RBAC reported on the invalidation stream: one org's roles, or everything. */
|
|
57
|
+
type InvalidationEvent = {
|
|
58
|
+
type: "org";
|
|
59
|
+
orgId: string;
|
|
60
|
+
} | {
|
|
61
|
+
type: "all";
|
|
62
|
+
};
|
|
63
|
+
interface SubscribeOptions {
|
|
64
|
+
/**
|
|
65
|
+
* Called after the SDK cache is cleared for each org or all event. Not awaited, so handlers may overlap;
|
|
66
|
+
* a throw or rejection is logged and the stream carries on. Events missed while disconnected are not replayed.
|
|
67
|
+
*/
|
|
68
|
+
onEvent?: (event: InvalidationEvent) => void | Promise<void>;
|
|
69
|
+
}
|
|
56
70
|
type GrantInput = string | {
|
|
57
71
|
permission: string;
|
|
58
72
|
scope?: string | null;
|
|
59
73
|
params?: Record<string, ParamValue>;
|
|
60
74
|
};
|
|
61
|
-
interface MessageSubscriber {
|
|
62
|
-
subscribe(channel: string): unknown;
|
|
63
|
-
on(event: "message", fn: (channel: string, message: string) => void): unknown;
|
|
64
|
-
}
|
|
65
75
|
declare class RbacClient implements RbacChecker {
|
|
66
76
|
private readonly opts;
|
|
67
77
|
private readonly cache;
|
|
@@ -72,6 +82,12 @@ declare class RbacClient implements RbacChecker {
|
|
|
72
82
|
private readonly timeoutMs;
|
|
73
83
|
private readonly doFetch;
|
|
74
84
|
private readonly now;
|
|
85
|
+
private streamOn;
|
|
86
|
+
private streamAbort?;
|
|
87
|
+
private streamRetry?;
|
|
88
|
+
private streamWatchdog?;
|
|
89
|
+
private streamAttempt;
|
|
90
|
+
private onEvent?;
|
|
75
91
|
constructor(opts: RbacClientOptions);
|
|
76
92
|
/** Counters since construction, for the product's own metrics. */
|
|
77
93
|
stats(): ClientStats;
|
|
@@ -114,9 +130,22 @@ declare class RbacClient implements RbacChecker {
|
|
|
114
130
|
reset: (orgId: string, actorRoleIds: string[], roleId: string) => Promise<RoleView>;
|
|
115
131
|
delete: (orgId: string, actorRoleIds: string[], roleId: string) => Promise<void>;
|
|
116
132
|
};
|
|
117
|
-
/**
|
|
118
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Keeps one stream to RBAC open (GET /v1/invalidations/stream) and drops cached role maps as RBAC
|
|
135
|
+
* reports changes. Reconnects on its own; every (re)connect clears the cache, since events sent
|
|
136
|
+
* while disconnected are not replayed. Idempotent: a call while subscribed is ignored, options included.
|
|
137
|
+
* `onEvent` hears each org and all event after the cache is cleared. Call close() on shutdown.
|
|
138
|
+
*/
|
|
139
|
+
subscribe(options?: SubscribeOptions): void;
|
|
140
|
+
/** Stops the invalidation stream and its reconnects. */
|
|
141
|
+
close(): void;
|
|
119
142
|
invalidate(orgId?: string): void;
|
|
143
|
+
private connectStream;
|
|
144
|
+
private armWatchdog;
|
|
145
|
+
private readStream;
|
|
146
|
+
private onStreamEvent;
|
|
147
|
+
/** The caller's handler must never break the stream, so its failures are only logged. */
|
|
148
|
+
private emit;
|
|
120
149
|
private rolesQuery;
|
|
121
150
|
private rolesPath;
|
|
122
151
|
private mutateRole;
|
|
@@ -229,4 +258,4 @@ interface AdminSignatureHeaders {
|
|
|
229
258
|
declare function signAdminRequest(o: SignAdminRequestOptions): AdminSignatureHeaders;
|
|
230
259
|
|
|
231
260
|
export { RbacClient, RbacForbiddenError, RbacRequestError, RbacUnavailableError, createMockRbac, permissionsHandler, requirePermission, signAdminRequest };
|
|
232
|
-
export type { AdminSignatureHeaders, ClientStats, GrantInput, MockRbacOptions, Next, PermissionView, RbacChecker, RbacClientOptions, RbacContext, RbacResponse, RoleView, SignAdminRequestOptions, Subject, SubjectOf };
|
|
261
|
+
export type { AdminSignatureHeaders, ClientStats, GrantInput, InvalidationEvent, MockRbacOptions, Next, PermissionView, RbacChecker, RbacClientOptions, RbacContext, RbacResponse, RoleView, SignAdminRequestOptions, Subject, SubjectOf, SubscribeOptions };
|
package/dist/index.js
CHANGED
|
@@ -66,7 +66,9 @@ var RbacRequestError = class extends Error {
|
|
|
66
66
|
// src/client.ts
|
|
67
67
|
var NOT_FOUND_TTL_MS = 3e4;
|
|
68
68
|
var MAX_PAGES = 1e3;
|
|
69
|
-
var
|
|
69
|
+
var STREAM_WATCHDOG_MS = 6e4;
|
|
70
|
+
var BACKOFF_START_MS = 1e3;
|
|
71
|
+
var BACKOFF_CAP_MS = 3e4;
|
|
70
72
|
var RbacClient = class {
|
|
71
73
|
constructor(opts) {
|
|
72
74
|
this.opts = opts;
|
|
@@ -85,6 +87,12 @@ var RbacClient = class {
|
|
|
85
87
|
timeoutMs;
|
|
86
88
|
doFetch;
|
|
87
89
|
now;
|
|
90
|
+
streamOn = false;
|
|
91
|
+
streamAbort;
|
|
92
|
+
streamRetry;
|
|
93
|
+
streamWatchdog;
|
|
94
|
+
streamAttempt = 0;
|
|
95
|
+
onEvent;
|
|
88
96
|
// ---- checks (local after the first fetch of an org) ----
|
|
89
97
|
/** Counters since construction, for the product's own metrics. */
|
|
90
98
|
stats() {
|
|
@@ -175,19 +183,31 @@ var RbacClient = class {
|
|
|
175
183
|
}
|
|
176
184
|
};
|
|
177
185
|
// ---- cache invalidation ----
|
|
178
|
-
/**
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
this.opts.logger?.warn("
|
|
186
|
+
/**
|
|
187
|
+
* Keeps one stream to RBAC open (GET /v1/invalidations/stream) and drops cached role maps as RBAC
|
|
188
|
+
* reports changes. Reconnects on its own; every (re)connect clears the cache, since events sent
|
|
189
|
+
* while disconnected are not replayed. Idempotent: a call while subscribed is ignored, options included.
|
|
190
|
+
* `onEvent` hears each org and all event after the cache is cleared. Call close() on shutdown.
|
|
191
|
+
*/
|
|
192
|
+
subscribe(options = {}) {
|
|
193
|
+
if (this.streamOn) {
|
|
194
|
+
if (options.onEvent && options.onEvent !== this.onEvent) {
|
|
195
|
+
this.opts.logger?.warn("rbac subscribe() called while already subscribed; its onEvent is ignored");
|
|
188
196
|
}
|
|
189
|
-
|
|
190
|
-
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this.onEvent = options.onEvent;
|
|
200
|
+
this.streamOn = true;
|
|
201
|
+
this.streamAttempt = 0;
|
|
202
|
+
void this.connectStream();
|
|
203
|
+
}
|
|
204
|
+
/** Stops the invalidation stream and its reconnects. */
|
|
205
|
+
close() {
|
|
206
|
+
this.streamOn = false;
|
|
207
|
+
this.onEvent = void 0;
|
|
208
|
+
clearTimeout(this.streamRetry);
|
|
209
|
+
clearTimeout(this.streamWatchdog);
|
|
210
|
+
this.streamAbort?.abort();
|
|
191
211
|
}
|
|
192
212
|
invalidate(orgId) {
|
|
193
213
|
if (orgId === void 0) {
|
|
@@ -199,6 +219,87 @@ var RbacClient = class {
|
|
|
199
219
|
}
|
|
200
220
|
}
|
|
201
221
|
// ---- internals ----
|
|
222
|
+
async connectStream() {
|
|
223
|
+
const ac = new AbortController();
|
|
224
|
+
this.streamAbort = ac;
|
|
225
|
+
this.armWatchdog(ac);
|
|
226
|
+
try {
|
|
227
|
+
const res = await this.doFetch(`${this.baseUrl}/v1/invalidations/stream`, {
|
|
228
|
+
headers: { authorization: `Bearer ${this.opts.apiKey}`, accept: "text/event-stream" },
|
|
229
|
+
signal: ac.signal
|
|
230
|
+
});
|
|
231
|
+
if (res.status !== 200 || !res.body) {
|
|
232
|
+
const why = res.status === 401 || res.status === 403 ? "API key rejected" : "unexpected response";
|
|
233
|
+
this.opts.logger?.warn(`RBAC invalidation stream: ${why} (HTTP ${res.status}); retrying`);
|
|
234
|
+
await res.body?.cancel().catch(() => void 0);
|
|
235
|
+
} else {
|
|
236
|
+
await this.readStream(res.body, ac);
|
|
237
|
+
}
|
|
238
|
+
} catch (err) {
|
|
239
|
+
if (this.streamOn) this.opts.logger?.warn("RBAC invalidation stream disconnected; retrying", err);
|
|
240
|
+
} finally {
|
|
241
|
+
if (this.streamAbort === ac) clearTimeout(this.streamWatchdog);
|
|
242
|
+
}
|
|
243
|
+
if (!this.streamOn || this.streamAbort !== ac) return;
|
|
244
|
+
const delay = Math.random() * Math.min(BACKOFF_CAP_MS, BACKOFF_START_MS * 2 ** this.streamAttempt);
|
|
245
|
+
this.streamAttempt++;
|
|
246
|
+
this.streamRetry = setTimeout(() => void this.connectStream(), delay);
|
|
247
|
+
this.streamRetry.unref?.();
|
|
248
|
+
}
|
|
249
|
+
armWatchdog(ac) {
|
|
250
|
+
clearTimeout(this.streamWatchdog);
|
|
251
|
+
this.streamWatchdog = setTimeout(() => ac.abort(), STREAM_WATCHDOG_MS);
|
|
252
|
+
this.streamWatchdog.unref?.();
|
|
253
|
+
}
|
|
254
|
+
async readStream(body, ac) {
|
|
255
|
+
const reader = body.getReader();
|
|
256
|
+
const decoder = new TextDecoder();
|
|
257
|
+
let buf = "";
|
|
258
|
+
for (; ; ) {
|
|
259
|
+
const { done, value } = await reader.read();
|
|
260
|
+
if (done) return;
|
|
261
|
+
this.armWatchdog(ac);
|
|
262
|
+
buf += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
|
263
|
+
let end;
|
|
264
|
+
while ((end = buf.indexOf("\n\n")) >= 0) {
|
|
265
|
+
this.onStreamEvent(buf.slice(0, end));
|
|
266
|
+
buf = buf.slice(end + 2);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
onStreamEvent(block) {
|
|
271
|
+
const data = block.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\n");
|
|
272
|
+
if (!data) return;
|
|
273
|
+
let m;
|
|
274
|
+
try {
|
|
275
|
+
m = JSON.parse(data);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
this.opts.logger?.warn("ignoring malformed rbac invalidation message", err);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (m.type === "ready") {
|
|
281
|
+
this.streamAttempt = 0;
|
|
282
|
+
this.invalidate();
|
|
283
|
+
} else if (m.type === "org" && typeof m.orgId === "string") {
|
|
284
|
+
this.invalidate(m.orgId);
|
|
285
|
+
this.emit({ type: "org", orgId: m.orgId });
|
|
286
|
+
} else if (m.type === "all") {
|
|
287
|
+
this.invalidate();
|
|
288
|
+
this.emit({ type: "all" });
|
|
289
|
+
} else this.opts.logger?.warn("ignoring unknown rbac invalidation event");
|
|
290
|
+
}
|
|
291
|
+
/** The caller's handler must never break the stream, so its failures are only logged. */
|
|
292
|
+
emit(event) {
|
|
293
|
+
const handler = this.onEvent;
|
|
294
|
+
if (!handler) return;
|
|
295
|
+
const fail = (err) => this.opts.logger?.warn("rbac onEvent handler failed", err);
|
|
296
|
+
try {
|
|
297
|
+
const result = handler(event);
|
|
298
|
+
if (result) Promise.resolve(result).catch(fail);
|
|
299
|
+
} catch (err) {
|
|
300
|
+
fail(err);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
202
303
|
rolesQuery(orgId, limit, cursor) {
|
|
203
304
|
return `${this.rolesPath(orgId)}?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`;
|
|
204
305
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marichi-labs-tech/rbac-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -17,14 +17,15 @@
|
|
|
17
17
|
"exports": {
|
|
18
18
|
".": {
|
|
19
19
|
"types": "./dist/index.d.ts",
|
|
20
|
-
"import": "./dist/index.js"
|
|
20
|
+
"import": "./dist/index.js",
|
|
21
|
+
"default": "./dist/index.js"
|
|
21
22
|
}
|
|
22
23
|
},
|
|
23
24
|
"files": [
|
|
24
25
|
"dist"
|
|
25
26
|
],
|
|
26
27
|
"dependencies": {
|
|
27
|
-
"@marichi-labs-tech/rbac-manifest-schema": "0.
|
|
28
|
+
"@marichi-labs-tech/rbac-manifest-schema": "0.2.0"
|
|
28
29
|
},
|
|
29
30
|
"scripts": {
|
|
30
31
|
"build": "tsup",
|