@marichi-labs-tech/rbac-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,232 @@
1
+ import { ParamValue, CheckResult, Grant, DenyReason, ParamDef } from '@marichi-labs-tech/rbac-manifest-schema';
2
+ export { CheckResult, DenyReason, Grant, ParamValue } from '@marichi-labs-tech/rbac-manifest-schema';
3
+
4
+ interface Subject {
5
+ orgId: string;
6
+ roleIds: string[];
7
+ }
8
+ interface RbacClientOptions {
9
+ url: string;
10
+ apiKey: string;
11
+ /** Must equal the product ID from the admin panel. */
12
+ product: string;
13
+ /** How long an expired cache entry may be served while RBAC is unreachable. Default 5 minutes. */
14
+ maxStaleMs?: number;
15
+ /** Per-request timeout for calls to RBAC. A timeout counts as unreachable (stale or 503). Default 5 s. */
16
+ timeoutMs?: number;
17
+ fetch?: typeof fetch;
18
+ now?: () => number;
19
+ logger?: {
20
+ warn(...args: unknown[]): void;
21
+ };
22
+ }
23
+ interface ClientStats {
24
+ checks: number;
25
+ allowed: number;
26
+ denied: number;
27
+ cacheHits: number;
28
+ cacheMisses: number;
29
+ staleServed: number;
30
+ }
31
+ interface PermissionView {
32
+ key: string;
33
+ scope: string | null;
34
+ params: Record<string, ParamValue>;
35
+ }
36
+ /** The check surface shared by RbacClient and createMockRbac. */
37
+ interface RbacChecker {
38
+ resolve(subject: Subject, perm: string): Promise<CheckResult>;
39
+ can(subject: Subject, perm: string): Promise<boolean>;
40
+ assert(subject: Subject, perm: string): Promise<void>;
41
+ scope(subject: Subject, perm: string): Promise<string | null>;
42
+ param(subject: Subject, perm: string, name: string): Promise<ParamValue | null>;
43
+ permissions(subject: Subject): Promise<PermissionView[]>;
44
+ }
45
+ interface RoleView {
46
+ id: string;
47
+ orgId: string;
48
+ key: string;
49
+ name: string;
50
+ description: string;
51
+ source: "template" | "custom";
52
+ templateKey: string | null;
53
+ customized: boolean;
54
+ grants: Grant[];
55
+ }
56
+ type GrantInput = string | {
57
+ permission: string;
58
+ scope?: string | null;
59
+ params?: Record<string, ParamValue>;
60
+ };
61
+ interface MessageSubscriber {
62
+ subscribe(channel: string): unknown;
63
+ on(event: "message", fn: (channel: string, message: string) => void): unknown;
64
+ }
65
+ declare class RbacClient implements RbacChecker {
66
+ private readonly opts;
67
+ private readonly cache;
68
+ private readonly counters;
69
+ private readonly inflight;
70
+ private readonly baseUrl;
71
+ private readonly maxStaleMs;
72
+ private readonly timeoutMs;
73
+ private readonly doFetch;
74
+ private readonly now;
75
+ constructor(opts: RbacClientOptions);
76
+ /** Counters since construction, for the product's own metrics. */
77
+ stats(): ClientStats;
78
+ resolve(subject: Subject, perm: string): Promise<CheckResult>;
79
+ private decide;
80
+ can(subject: Subject, perm: string): Promise<boolean>;
81
+ assert(subject: Subject, perm: string): Promise<void>;
82
+ scope(subject: Subject, perm: string): Promise<string | null>;
83
+ param(subject: Subject, perm: string, name: string): Promise<ParamValue | null>;
84
+ /** Everything the subject may do in this product, for the frontend. */
85
+ permissions(subject: Subject): Promise<PermissionView[]>;
86
+ ensureOrg(orgId: string, name: string): Promise<{
87
+ org: unknown;
88
+ adminRoleId: string;
89
+ roles: RoleView[];
90
+ }>;
91
+ canAssign(orgId: string, actorRoleIds: string[], roleIds: string[]): Promise<boolean>;
92
+ readonly roles: {
93
+ /** One page of roles; pass the previous `nextCursor` to continue. */
94
+ page: (orgId: string, actorRoleIds: string[], opts?: {
95
+ cursor?: string;
96
+ limit?: number;
97
+ }) => Promise<{
98
+ items: RoleView[];
99
+ nextCursor: string | null;
100
+ }>;
101
+ /** Every role, following the cursor (100 per request, at most 1,000 requests). */
102
+ list: (orgId: string, actorRoleIds: string[]) => Promise<RoleView[]>;
103
+ get: (orgId: string, actorRoleIds: string[], roleId: string) => Promise<RoleView>;
104
+ create: (orgId: string, actorRoleIds: string[], input: {
105
+ name: string;
106
+ description?: string;
107
+ grants: GrantInput[];
108
+ }) => Promise<RoleView>;
109
+ update: (orgId: string, actorRoleIds: string[], roleId: string, patch: {
110
+ name?: string;
111
+ description?: string;
112
+ }) => Promise<RoleView>;
113
+ setGrants: (orgId: string, actorRoleIds: string[], roleId: string, grants: GrantInput[]) => Promise<RoleView>;
114
+ reset: (orgId: string, actorRoleIds: string[], roleId: string) => Promise<RoleView>;
115
+ delete: (orgId: string, actorRoleIds: string[], roleId: string) => Promise<void>;
116
+ };
117
+ /** Listens on a dedicated Redis connection for org/all invalidations published by RBAC. */
118
+ subscribe(sub: MessageSubscriber): Promise<void>;
119
+ invalidate(orgId?: string): void;
120
+ private rolesQuery;
121
+ private rolesPath;
122
+ private mutateRole;
123
+ /** The org's role map, or null when RBAC says the org does not exist. */
124
+ private roleMap;
125
+ private refresh;
126
+ private send;
127
+ private request;
128
+ }
129
+
130
+ /** RBAC could not be reached (or refused our credentials) and no usable cached entry exists. Fail closed. */
131
+ declare class RbacUnavailableError extends Error {
132
+ readonly cause?: unknown | undefined;
133
+ readonly status = 503;
134
+ constructor(message: string, cause?: unknown | undefined);
135
+ }
136
+ /** The permission is not granted. */
137
+ declare class RbacForbiddenError extends Error {
138
+ readonly reason: DenyReason;
139
+ readonly permission: string;
140
+ readonly status = 403;
141
+ constructor(reason: DenyReason, permission: string);
142
+ }
143
+ /** RBAC answered with an error (validation failure, escalation_denied, not found, ...). */
144
+ declare class RbacRequestError extends Error {
145
+ readonly status: number;
146
+ readonly code: string;
147
+ readonly details?: unknown | undefined;
148
+ constructor(status: number, code: string, message: string, details?: unknown | undefined);
149
+ }
150
+
151
+ /** The part of a response these handlers use. Express (and similar) responses satisfy it as is. */
152
+ interface RbacResponse {
153
+ status(code: number): RbacResponse;
154
+ json(body: unknown): unknown;
155
+ }
156
+ type Next = (err?: unknown) => void;
157
+ type SubjectOf<Req> = (req: Req) => Subject | null | undefined;
158
+ /** What requirePermission puts on `req.rbac` for the handler that follows. */
159
+ interface RbacContext {
160
+ scope: string | null;
161
+ params: Record<string, ParamValue>;
162
+ }
163
+ declare global {
164
+ namespace Express {
165
+ interface Request {
166
+ rbac?: RbacContext;
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * 401 when the request has no subject, 403 when the permission is not granted,
172
+ * 503 when RBAC is unreachable beyond the stale window (fail closed).
173
+ * On allow, sets `req.rbac = { scope, params }`.
174
+ */
175
+ declare function requirePermission<Req extends object>(client: RbacChecker, perm: string, subjectOf: SubjectOf<Req>): (req: Req & {
176
+ rbac?: RbacContext;
177
+ }, res: RbacResponse, next: Next) => Promise<void>;
178
+ /** Handler for `GET /api/me/permissions`. */
179
+ declare function permissionsHandler<Req extends object>(client: RbacChecker, subjectOf: SubjectOf<Req>): (req: Req, res: RbacResponse, next: Next) => Promise<void>;
180
+
181
+ interface MockRbacOptions {
182
+ product: string;
183
+ /** Declare scopes (narrowest first) and params for permissions that use them. Others are plain on/off. */
184
+ permissions?: Record<string, {
185
+ scopes?: string[];
186
+ params?: Record<string, ParamDef>;
187
+ }>;
188
+ /** roleId -> grants (shorthand like "invoices:read@team", or grant objects). */
189
+ roles: Record<string, (string | {
190
+ permission: string;
191
+ scope?: string | null;
192
+ params?: Record<string, ParamValue>;
193
+ })[]>;
194
+ /** Omit to treat every org as existing and active. */
195
+ orgs?: Record<string, {
196
+ status?: "active" | "suspended";
197
+ enabled?: boolean;
198
+ }>;
199
+ }
200
+ /** A no-network stand-in for RbacClient's check methods that uses the same decision code. */
201
+ declare function createMockRbac(opts: MockRbacOptions): RbacChecker;
202
+
203
+ interface SignAdminRequestOptions {
204
+ /** `ADMIN_ACTOR_SIGNING_SECRET`, shared with RBAC. Never sent over the wire. */
205
+ signingSecret: string;
206
+ method: string;
207
+ /** The path and query exactly as RBAC receives them: already percent-encoded, with no proxy prefix stripping or rewriting. */
208
+ url: string;
209
+ /** The staff member making the call. */
210
+ actor: string;
211
+ /** Milliseconds since the epoch. Defaults to `Date.now`. */
212
+ now?: () => number;
213
+ nonce?: string;
214
+ /** The exact string that will be sent as the request body. Default: no body. */
215
+ body?: string;
216
+ }
217
+ interface AdminSignatureHeaders {
218
+ "x-admin-actor": string;
219
+ "x-admin-timestamp": string;
220
+ "x-admin-nonce": string;
221
+ "x-admin-content-sha256": string;
222
+ "x-admin-signature": string;
223
+ }
224
+ /**
225
+ * Signs an admin request for RBAC. Send these headers with `Authorization: Bearer rba_...`.
226
+ * The canonical string is the same one the service verifies: timestamp, nonce, upper-case method,
227
+ * url, actor and the SHA-256 of the body joined by newlines.
228
+ */
229
+ declare function signAdminRequest(o: SignAdminRequestOptions): AdminSignatureHeaders;
230
+
231
+ 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 };
package/dist/index.js ADDED
@@ -0,0 +1,440 @@
1
+ // src/client.ts
2
+ import {
3
+ decideFromRoleMap,
4
+ splitKey,
5
+ toFullKey
6
+ } from "@marichi-labs-tech/rbac-manifest-schema";
7
+
8
+ // src/cache.ts
9
+ var OrgCache = class {
10
+ entries = /* @__PURE__ */ new Map();
11
+ /** Bumped by every invalidation; a fetch that started earlier must not be cached. */
12
+ generation = 0;
13
+ get currentGeneration() {
14
+ return this.generation;
15
+ }
16
+ get(orgId) {
17
+ return this.entries.get(orgId);
18
+ }
19
+ set(orgId, entry) {
20
+ this.entries.set(orgId, entry);
21
+ }
22
+ drop(orgId) {
23
+ this.generation++;
24
+ this.entries.delete(orgId);
25
+ }
26
+ clear() {
27
+ this.generation++;
28
+ this.entries.clear();
29
+ }
30
+ };
31
+
32
+ // src/errors.ts
33
+ var RbacUnavailableError = class extends Error {
34
+ constructor(message, cause) {
35
+ super(message);
36
+ this.cause = cause;
37
+ this.name = "RbacUnavailableError";
38
+ }
39
+ cause;
40
+ status = 503;
41
+ };
42
+ var RbacForbiddenError = class extends Error {
43
+ constructor(reason, permission) {
44
+ super(`Forbidden: ${permission} (${reason})`);
45
+ this.reason = reason;
46
+ this.permission = permission;
47
+ this.name = "RbacForbiddenError";
48
+ }
49
+ reason;
50
+ permission;
51
+ status = 403;
52
+ };
53
+ var RbacRequestError = class extends Error {
54
+ constructor(status, code, message, details) {
55
+ super(message);
56
+ this.status = status;
57
+ this.code = code;
58
+ this.details = details;
59
+ this.name = "RbacRequestError";
60
+ }
61
+ status;
62
+ code;
63
+ details;
64
+ };
65
+
66
+ // src/client.ts
67
+ var NOT_FOUND_TTL_MS = 3e4;
68
+ var MAX_PAGES = 1e3;
69
+ var INVALIDATE_CHANNEL = "rbac:invalidate";
70
+ var RbacClient = class {
71
+ constructor(opts) {
72
+ this.opts = opts;
73
+ this.baseUrl = opts.url.replace(/\/+$/, "");
74
+ this.maxStaleMs = opts.maxStaleMs ?? 5 * 6e4;
75
+ this.timeoutMs = opts.timeoutMs ?? 5e3;
76
+ this.doFetch = opts.fetch ?? fetch;
77
+ this.now = opts.now ?? Date.now;
78
+ }
79
+ opts;
80
+ cache = new OrgCache();
81
+ counters = { checks: 0, allowed: 0, denied: 0, cacheHits: 0, cacheMisses: 0, staleServed: 0 };
82
+ inflight = /* @__PURE__ */ new Map();
83
+ baseUrl;
84
+ maxStaleMs;
85
+ timeoutMs;
86
+ doFetch;
87
+ now;
88
+ // ---- checks (local after the first fetch of an org) ----
89
+ /** Counters since construction, for the product's own metrics. */
90
+ stats() {
91
+ return { ...this.counters };
92
+ }
93
+ async resolve(subject, perm) {
94
+ const result = await this.decide(subject, perm);
95
+ this.counters.checks++;
96
+ if (result.allowed) this.counters.allowed++;
97
+ else this.counters.denied++;
98
+ return result;
99
+ }
100
+ async decide(subject, perm) {
101
+ const full = toFullKey(this.opts.product, perm);
102
+ const parts = splitKey(full);
103
+ if (!parts || parts.product !== this.opts.product) return { allowed: false, reason: "invalid_permission" };
104
+ const map = await this.roleMap(subject.orgId);
105
+ if (!map) return { allowed: false, reason: "org_not_found" };
106
+ return decideFromRoleMap(map, full, subject.roleIds);
107
+ }
108
+ async can(subject, perm) {
109
+ return (await this.resolve(subject, perm)).allowed;
110
+ }
111
+ async assert(subject, perm) {
112
+ const r = await this.resolve(subject, perm);
113
+ if (!r.allowed) throw new RbacForbiddenError(r.reason, perm);
114
+ }
115
+ async scope(subject, perm) {
116
+ const r = await this.resolve(subject, perm);
117
+ return r.allowed ? r.scope : null;
118
+ }
119
+ async param(subject, perm, name) {
120
+ const r = await this.resolve(subject, perm);
121
+ if (!r.allowed) return null;
122
+ return Object.hasOwn(r.params, name) ? r.params[name] : null;
123
+ }
124
+ /** Everything the subject may do in this product, for the frontend. */
125
+ async permissions(subject) {
126
+ const map = await this.roleMap(subject.orgId);
127
+ if (!map) return [];
128
+ const out = [];
129
+ for (const key of Object.keys(map.permissions).sort()) {
130
+ const r = decideFromRoleMap(map, key, subject.roleIds);
131
+ if (r.allowed) out.push({ key, scope: r.scope, params: r.params });
132
+ }
133
+ return out;
134
+ }
135
+ // ---- org lifecycle and role management (calls RBAC) ----
136
+ async ensureOrg(orgId, name) {
137
+ const body = await this.request(
138
+ "PUT",
139
+ `/v1/orgs/${encodeURIComponent(orgId)}`,
140
+ { name }
141
+ );
142
+ this.invalidate(orgId);
143
+ return body;
144
+ }
145
+ async canAssign(orgId, actorRoleIds, roleIds) {
146
+ const res = await this.request(
147
+ "POST",
148
+ `/v1/authz/orgs/${encodeURIComponent(orgId)}/can-assign`,
149
+ { actorRoleIds, roleIds }
150
+ );
151
+ return res.allowed === true;
152
+ }
153
+ roles = {
154
+ /** One page of roles; pass the previous `nextCursor` to continue. */
155
+ page: (orgId, actorRoleIds, opts = {}) => this.request("GET", this.rolesQuery(orgId, opts.limit ?? 50, opts.cursor), void 0, actorRoleIds),
156
+ /** Every role, following the cursor (100 per request, at most 1,000 requests). */
157
+ list: async (orgId, actorRoleIds) => {
158
+ const all = [];
159
+ let cursor;
160
+ for (let page = 0; page < MAX_PAGES; page++) {
161
+ const res = await this.roles.page(orgId, actorRoleIds, { limit: 100, ...cursor ? { cursor } : {} });
162
+ all.push(...res.items);
163
+ if (!res.nextCursor) return all;
164
+ cursor = res.nextCursor;
165
+ }
166
+ throw new RbacRequestError(0, "too_many_pages", `More than ${MAX_PAGES} pages of roles; use roles.page`);
167
+ },
168
+ get: (orgId, actorRoleIds, roleId) => this.request("GET", this.rolesPath(orgId, roleId), void 0, actorRoleIds),
169
+ create: (orgId, actorRoleIds, input) => this.mutateRole("POST", orgId, this.rolesPath(orgId), input, actorRoleIds),
170
+ update: (orgId, actorRoleIds, roleId, patch) => this.mutateRole("PATCH", orgId, this.rolesPath(orgId, roleId), patch, actorRoleIds),
171
+ setGrants: (orgId, actorRoleIds, roleId, grants) => this.mutateRole("PUT", orgId, `${this.rolesPath(orgId, roleId)}/grants`, { grants }, actorRoleIds),
172
+ reset: (orgId, actorRoleIds, roleId) => this.mutateRole("POST", orgId, `${this.rolesPath(orgId, roleId)}/reset`, void 0, actorRoleIds),
173
+ delete: async (orgId, actorRoleIds, roleId) => {
174
+ await this.mutateRole("DELETE", orgId, this.rolesPath(orgId, roleId), void 0, actorRoleIds);
175
+ }
176
+ };
177
+ // ---- cache invalidation ----
178
+ /** Listens on a dedicated Redis connection for org/all invalidations published by RBAC. */
179
+ async subscribe(sub) {
180
+ sub.on("message", (channel, message) => {
181
+ if (channel !== INVALIDATE_CHANNEL) return;
182
+ try {
183
+ const m = JSON.parse(message);
184
+ if (m.type === "org" && typeof m.orgId === "string") this.invalidate(m.orgId);
185
+ else if (m.type === "all") this.invalidate();
186
+ } catch (err) {
187
+ this.opts.logger?.warn("ignoring malformed rbac invalidation message", err);
188
+ }
189
+ });
190
+ await sub.subscribe(INVALIDATE_CHANNEL);
191
+ }
192
+ invalidate(orgId) {
193
+ if (orgId === void 0) {
194
+ this.cache.clear();
195
+ this.inflight.clear();
196
+ } else {
197
+ this.cache.drop(orgId);
198
+ this.inflight.delete(orgId);
199
+ }
200
+ }
201
+ // ---- internals ----
202
+ rolesQuery(orgId, limit, cursor) {
203
+ return `${this.rolesPath(orgId)}?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`;
204
+ }
205
+ rolesPath(orgId, roleId) {
206
+ const base = `/v1/orgs/${encodeURIComponent(orgId)}/roles`;
207
+ return roleId === void 0 ? base : `${base}/${encodeURIComponent(roleId)}`;
208
+ }
209
+ async mutateRole(method, orgId, path, body, actor) {
210
+ const res = await this.request(method, path, body, actor);
211
+ this.invalidate(orgId);
212
+ return res;
213
+ }
214
+ /** The org's role map, or null when RBAC says the org does not exist. */
215
+ async roleMap(orgId) {
216
+ const entry = this.cache.get(orgId);
217
+ if (entry && this.now() < entry.expiresAt) {
218
+ this.counters.cacheHits++;
219
+ return entry.kind === "map" ? entry.map : null;
220
+ }
221
+ const existing = this.inflight.get(orgId);
222
+ if (existing) return existing;
223
+ this.counters.cacheMisses++;
224
+ const p = this.refresh(orgId, entry).finally(() => {
225
+ if (this.inflight.get(orgId) === p) this.inflight.delete(orgId);
226
+ });
227
+ this.inflight.set(orgId, p);
228
+ return p;
229
+ }
230
+ async refresh(orgId, stale) {
231
+ const generation = this.cache.currentGeneration;
232
+ try {
233
+ const res = await this.send("GET", `/v1/authz/orgs/${encodeURIComponent(orgId)}/role-permissions`);
234
+ if (res.status === 404) {
235
+ const body = await safeJson(res);
236
+ if (body?.error === "org_not_found") {
237
+ if (this.cache.currentGeneration === generation) {
238
+ this.cache.set(orgId, { kind: "org_not_found", expiresAt: this.now() + NOT_FOUND_TTL_MS });
239
+ }
240
+ return null;
241
+ }
242
+ }
243
+ if (res.status === 401 || res.status === 403) {
244
+ throw new RbacUnavailableError(`RBAC rejected the API key (HTTP ${res.status})`);
245
+ }
246
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
247
+ const map = await res.json();
248
+ if (this.cache.currentGeneration === generation) {
249
+ this.cache.set(orgId, { kind: "map", map, expiresAt: this.now() + map.ttl * 1e3 });
250
+ }
251
+ return map;
252
+ } catch (err) {
253
+ if (err instanceof RbacUnavailableError) throw err;
254
+ const stillValid = this.cache.currentGeneration === generation;
255
+ if (stillValid && stale && stale.kind === "map" && this.now() - stale.expiresAt <= this.maxStaleMs) {
256
+ this.counters.staleServed++;
257
+ this.opts.logger?.warn(`RBAC unreachable; serving stale role map for org ${orgId}`, err);
258
+ return stale.map;
259
+ }
260
+ throw new RbacUnavailableError("RBAC is unreachable and no usable cached role map exists", err);
261
+ }
262
+ }
263
+ send(method, path, body, actorRoleIds) {
264
+ const headers = { authorization: `Bearer ${this.opts.apiKey}` };
265
+ if (body !== void 0) headers["content-type"] = "application/json";
266
+ if (actorRoleIds) headers["x-actor-role-ids"] = actorRoleIds.join(",");
267
+ return this.doFetch(`${this.baseUrl}${path}`, {
268
+ method,
269
+ headers,
270
+ // Without a deadline a server that never answers would hang every check for this org,
271
+ // and neither the stale fallback nor the 503 would ever apply. Covers reading the body too.
272
+ signal: AbortSignal.timeout(this.timeoutMs),
273
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
274
+ });
275
+ }
276
+ async request(method, path, body, actorRoleIds) {
277
+ let res;
278
+ try {
279
+ res = await this.send(method, path, body, actorRoleIds);
280
+ } catch (err) {
281
+ throw new RbacUnavailableError("RBAC is unreachable", err);
282
+ }
283
+ if (res.status >= 500) throw new RbacUnavailableError(`RBAC failed (HTTP ${res.status})`);
284
+ if (!res.ok) {
285
+ const e = await safeJson(res);
286
+ throw new RbacRequestError(res.status, e?.error ?? "request_failed", e?.message ?? `HTTP ${res.status}`, e?.details);
287
+ }
288
+ if (res.status === 204) return void 0;
289
+ return await res.json();
290
+ }
291
+ };
292
+ async function safeJson(res) {
293
+ try {
294
+ return await res.json();
295
+ } catch {
296
+ return void 0;
297
+ }
298
+ }
299
+
300
+ // src/middleware.ts
301
+ function requirePermission(client, perm, subjectOf) {
302
+ return async (req, res, next) => {
303
+ const subject = subjectOf(req);
304
+ if (!subject) {
305
+ res.status(401).json({ error: "unauthenticated" });
306
+ return;
307
+ }
308
+ try {
309
+ const r = await client.resolve(subject, perm);
310
+ if (!r.allowed) {
311
+ res.status(403).json({ error: "forbidden", reason: r.reason });
312
+ return;
313
+ }
314
+ req.rbac = { scope: r.scope, params: r.params };
315
+ next();
316
+ } catch (err) {
317
+ if (err instanceof RbacUnavailableError) {
318
+ res.status(503).json({ error: "authz_unavailable" });
319
+ return;
320
+ }
321
+ next(err);
322
+ }
323
+ };
324
+ }
325
+ function permissionsHandler(client, subjectOf) {
326
+ return async (req, res, next) => {
327
+ const subject = subjectOf(req);
328
+ if (!subject) {
329
+ res.status(401).json({ error: "unauthenticated" });
330
+ return;
331
+ }
332
+ try {
333
+ res.json({ permissions: await client.permissions(subject) });
334
+ } catch (err) {
335
+ if (err instanceof RbacUnavailableError) {
336
+ res.status(503).json({ error: "authz_unavailable" });
337
+ return;
338
+ }
339
+ next(err);
340
+ }
341
+ };
342
+ }
343
+
344
+ // src/mock.ts
345
+ import {
346
+ decideFromRoleMap as decideFromRoleMap2,
347
+ expandGrant,
348
+ parseGrant,
349
+ splitKey as splitKey2,
350
+ toFullKey as toFullKey2
351
+ } from "@marichi-labs-tech/rbac-manifest-schema";
352
+ function createMockRbac(opts) {
353
+ const { product } = opts;
354
+ const defs = /* @__PURE__ */ new Map();
355
+ const add = (key, scopes = [], params = {}) => {
356
+ const parts = splitKey2(key);
357
+ if (!parts) return;
358
+ defs.set(key, { key, product, feature: parts.feature, action: parts.action, scopes, params, deprecated: false });
359
+ };
360
+ for (const [k, v] of Object.entries(opts.permissions ?? {})) add(toFullKey2(product, k), v.scopes, v.params);
361
+ const roleGrants = {};
362
+ for (const [id, list] of Object.entries(opts.roles)) {
363
+ roleGrants[id] = list.map((g) => parseGrant(product, g));
364
+ for (const g of roleGrants[id]) if (!g.permission.endsWith("*") && !defs.has(g.permission)) add(g.permission);
365
+ }
366
+ const active = [...defs.values()];
367
+ const expanded = Object.fromEntries(
368
+ Object.entries(roleGrants).map(([id, gs]) => [id, gs.flatMap((g) => expandGrant(g, active))])
369
+ );
370
+ const mapFor = (orgId) => {
371
+ const org = opts.orgs?.[orgId];
372
+ if (opts.orgs && !org) return null;
373
+ return {
374
+ orgId,
375
+ orgStatus: org?.status ?? "active",
376
+ productEnabled: org?.enabled ?? true,
377
+ ttl: 300,
378
+ permissions: Object.fromEntries(active.map((d) => [d.key, { scopes: d.scopes, params: d.params }])),
379
+ roles: expanded
380
+ };
381
+ };
382
+ const resolve = async (s, perm) => {
383
+ const full = toFullKey2(product, perm);
384
+ const parts = splitKey2(full);
385
+ if (!parts || parts.product !== product) return { allowed: false, reason: "invalid_permission" };
386
+ const map = mapFor(s.orgId);
387
+ if (!map) return { allowed: false, reason: "org_not_found" };
388
+ return decideFromRoleMap2(map, full, s.roleIds);
389
+ };
390
+ return {
391
+ resolve,
392
+ can: async (s, p) => (await resolve(s, p)).allowed,
393
+ async assert(s, p) {
394
+ const r = await resolve(s, p);
395
+ if (!r.allowed) throw new RbacForbiddenError(r.reason, p);
396
+ },
397
+ async scope(s, p) {
398
+ const r = await resolve(s, p);
399
+ return r.allowed ? r.scope : null;
400
+ },
401
+ async param(s, p, name) {
402
+ const r = await resolve(s, p);
403
+ return r.allowed && Object.hasOwn(r.params, name) ? r.params[name] : null;
404
+ },
405
+ async permissions(s) {
406
+ const out = [];
407
+ for (const d of active) {
408
+ const r = await resolve(s, d.key);
409
+ if (r.allowed) out.push({ key: d.key, scope: r.scope, params: r.params });
410
+ }
411
+ return out.sort((a, b) => a.key.localeCompare(b.key));
412
+ }
413
+ };
414
+ }
415
+
416
+ // src/admin-signature.ts
417
+ import { createHash, createHmac, randomBytes } from "crypto";
418
+ function signAdminRequest(o) {
419
+ const timestamp = String(Math.floor((o.now ?? Date.now)() / 1e3));
420
+ const nonce = o.nonce ?? randomBytes(24).toString("base64url");
421
+ const contentSha256 = createHash("sha256").update(o.body ?? "").digest("hex");
422
+ const canonical = [timestamp, nonce, o.method.toUpperCase(), o.url, o.actor, contentSha256].join("\n");
423
+ return {
424
+ "x-admin-actor": o.actor,
425
+ "x-admin-timestamp": timestamp,
426
+ "x-admin-nonce": nonce,
427
+ "x-admin-content-sha256": contentSha256,
428
+ "x-admin-signature": createHmac("sha256", o.signingSecret).update(canonical).digest("hex")
429
+ };
430
+ }
431
+ export {
432
+ RbacClient,
433
+ RbacForbiddenError,
434
+ RbacRequestError,
435
+ RbacUnavailableError,
436
+ createMockRbac,
437
+ permissionsHandler,
438
+ requirePermission,
439
+ signAdminRequest
440
+ };
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@marichi-labs-tech/rbac-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Marichi-Labs-Tech/rbac.git",
9
+ "directory": "packages/rbac-sdk"
10
+ },
11
+ "publishConfig": {
12
+ "registry": "https://registry.npmjs.org",
13
+ "access": "public"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "dependencies": {
27
+ "@marichi-labs-tech/rbac-manifest-schema": "0.1.0"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup",
31
+ "typecheck": "tsc --noEmit"
32
+ }
6
33
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.