@siremzam/sentinel 0.3.1 → 0.3.3

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 (65) hide show
  1. package/README.md +590 -178
  2. package/dist/engine-C6IASR5F.d.cts +283 -0
  3. package/dist/engine-C6IASR5F.d.ts +283 -0
  4. package/dist/index.cjs +877 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +58 -0
  7. package/dist/index.d.ts +58 -10
  8. package/dist/index.js +838 -5
  9. package/dist/index.js.map +1 -1
  10. package/dist/middleware/express.cjs +58 -0
  11. package/dist/middleware/express.cjs.map +1 -0
  12. package/dist/middleware/express.d.cts +35 -0
  13. package/dist/middleware/express.d.ts +6 -6
  14. package/dist/middleware/express.js +31 -39
  15. package/dist/middleware/express.js.map +1 -1
  16. package/dist/middleware/fastify.cjs +59 -0
  17. package/dist/middleware/fastify.cjs.map +1 -0
  18. package/dist/middleware/fastify.d.cts +29 -0
  19. package/dist/middleware/fastify.d.ts +6 -6
  20. package/dist/middleware/fastify.js +32 -39
  21. package/dist/middleware/fastify.js.map +1 -1
  22. package/dist/middleware/hono.cjs +57 -0
  23. package/dist/middleware/hono.cjs.map +1 -0
  24. package/dist/middleware/hono.d.cts +45 -0
  25. package/dist/middleware/hono.d.ts +45 -0
  26. package/dist/middleware/hono.js +32 -0
  27. package/dist/middleware/hono.js.map +1 -0
  28. package/dist/middleware/nestjs.cjs +84 -0
  29. package/dist/middleware/nestjs.cjs.map +1 -0
  30. package/dist/middleware/nestjs.d.cts +67 -0
  31. package/dist/middleware/nestjs.d.ts +9 -9
  32. package/dist/middleware/nestjs.js +51 -76
  33. package/dist/middleware/nestjs.js.map +1 -1
  34. package/dist/server.cjs +184 -0
  35. package/dist/server.cjs.map +1 -0
  36. package/dist/server.d.cts +54 -0
  37. package/dist/server.d.ts +10 -8
  38. package/dist/server.js +149 -153
  39. package/dist/server.js.map +1 -1
  40. package/package.json +28 -9
  41. package/dist/engine.d.ts +0 -70
  42. package/dist/engine.d.ts.map +0 -1
  43. package/dist/engine.js +0 -562
  44. package/dist/engine.js.map +0 -1
  45. package/dist/index.d.ts.map +0 -1
  46. package/dist/middleware/express.d.ts.map +0 -1
  47. package/dist/middleware/fastify.d.ts.map +0 -1
  48. package/dist/middleware/nestjs.d.ts.map +0 -1
  49. package/dist/policy-builder.d.ts +0 -39
  50. package/dist/policy-builder.d.ts.map +0 -1
  51. package/dist/policy-builder.js +0 -92
  52. package/dist/policy-builder.js.map +0 -1
  53. package/dist/role-hierarchy.d.ts +0 -42
  54. package/dist/role-hierarchy.d.ts.map +0 -1
  55. package/dist/role-hierarchy.js +0 -87
  56. package/dist/role-hierarchy.js.map +0 -1
  57. package/dist/serialization.d.ts +0 -52
  58. package/dist/serialization.d.ts.map +0 -1
  59. package/dist/serialization.js +0 -144
  60. package/dist/serialization.js.map +0 -1
  61. package/dist/server.d.ts.map +0 -1
  62. package/dist/types.d.ts +0 -137
  63. package/dist/types.d.ts.map +0 -1
  64. package/dist/types.js +0 -27
  65. package/dist/types.js.map +0 -1
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ createAuthServer: () => createAuthServer
24
+ });
25
+ module.exports = __toCommonJS(server_exports);
26
+ var import_node_http = require("http");
27
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
28
+ function readBody(req, maxBytes) {
29
+ return new Promise((resolve, reject) => {
30
+ const chunks = [];
31
+ let received = 0;
32
+ let settled = false;
33
+ function settle(fn) {
34
+ if (!settled) {
35
+ settled = true;
36
+ fn();
37
+ }
38
+ }
39
+ req.on("data", (chunk) => {
40
+ if (settled) return;
41
+ received += chunk.length;
42
+ if (received > maxBytes) {
43
+ req.resume();
44
+ settle(() => reject(new Error(`Request body exceeds ${maxBytes} bytes`)));
45
+ return;
46
+ }
47
+ chunks.push(chunk);
48
+ });
49
+ req.on("end", () => {
50
+ settle(() => resolve(Buffer.concat(chunks).toString("utf-8")));
51
+ });
52
+ req.on("error", (err) => {
53
+ settle(() => reject(err));
54
+ });
55
+ });
56
+ }
57
+ function sendJson(res, status, body) {
58
+ const json = JSON.stringify(body);
59
+ res.writeHead(status, {
60
+ "Content-Type": "application/json",
61
+ "Content-Length": Buffer.byteLength(json)
62
+ });
63
+ res.end(json);
64
+ }
65
+ function createAuthServer(options) {
66
+ const {
67
+ engine,
68
+ port = 3100,
69
+ host = "0.0.0.0",
70
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES
71
+ } = options;
72
+ const startTime = Date.now();
73
+ const server = (0, import_node_http.createServer)(async (req, res) => {
74
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
75
+ const method = req.method ?? "GET";
76
+ try {
77
+ if (options.authenticate) {
78
+ const authed = await options.authenticate(req);
79
+ if (authed !== true) {
80
+ sendJson(res, 401, { error: "Unauthorized" });
81
+ return;
82
+ }
83
+ }
84
+ if (method === "GET" && pathname === "/health") {
85
+ const body = {
86
+ status: "ok",
87
+ rulesLoaded: engine.getRules().length,
88
+ uptime: Date.now() - startTime
89
+ };
90
+ sendJson(res, 200, body);
91
+ return;
92
+ }
93
+ if (method === "GET" && pathname === "/rules") {
94
+ const rules = engine.getRules().map((r) => ({
95
+ id: r.id,
96
+ effect: r.effect,
97
+ roles: r.roles,
98
+ actions: r.actions,
99
+ resources: r.resources,
100
+ priority: r.priority,
101
+ description: r.description,
102
+ hasConditions: (r.conditions?.length ?? 0) > 0
103
+ }));
104
+ sendJson(res, 200, { rules });
105
+ return;
106
+ }
107
+ if (method === "POST" && pathname === "/evaluate") {
108
+ let raw;
109
+ try {
110
+ raw = await readBody(req, maxBodyBytes);
111
+ } catch (err) {
112
+ sendJson(res, 413, {
113
+ error: err instanceof Error ? err.message : "Payload too large"
114
+ });
115
+ return;
116
+ }
117
+ let body;
118
+ try {
119
+ body = JSON.parse(raw);
120
+ } catch {
121
+ sendJson(res, 400, { error: "Invalid JSON body" });
122
+ return;
123
+ }
124
+ if (!body.subject || !body.action || !body.resource) {
125
+ sendJson(res, 400, {
126
+ error: "Missing required fields: subject, action, resource"
127
+ });
128
+ return;
129
+ }
130
+ if (typeof body.action !== "string" || typeof body.resource !== "string") {
131
+ sendJson(res, 400, { error: "action and resource must be strings" });
132
+ return;
133
+ }
134
+ if (typeof body.subject !== "object" || typeof body.subject.id !== "string" || !Array.isArray(body.subject.roles)) {
135
+ sendJson(res, 400, {
136
+ error: "subject must have a string id and a roles array"
137
+ });
138
+ return;
139
+ }
140
+ const subject = options.resolveSubject ? await options.resolveSubject(body) : body.subject;
141
+ const decision = engine.evaluate(
142
+ subject,
143
+ body.action,
144
+ body.resource,
145
+ body.resourceContext ?? {},
146
+ body.tenantId
147
+ );
148
+ const response = {
149
+ allowed: decision.allowed,
150
+ effect: decision.effect,
151
+ reason: decision.reason,
152
+ matchedRuleId: decision.matchedRule?.id ?? null,
153
+ durationMs: decision.durationMs
154
+ };
155
+ sendJson(res, 200, response);
156
+ return;
157
+ }
158
+ sendJson(res, 404, { error: "Not found" });
159
+ } catch (err) {
160
+ const message = err instanceof Error ? err.message : "Internal server error";
161
+ sendJson(res, 500, { error: message });
162
+ }
163
+ });
164
+ return {
165
+ start() {
166
+ return new Promise((resolve) => {
167
+ server.listen(port, host, () => {
168
+ resolve();
169
+ });
170
+ });
171
+ },
172
+ stop() {
173
+ return new Promise((resolve, reject) => {
174
+ server.close((err) => err ? reject(err) : resolve());
175
+ });
176
+ },
177
+ httpServer: server
178
+ };
179
+ }
180
+ // Annotate the CommonJS export names for ESM import in node:
181
+ 0 && (module.exports = {
182
+ createAuthServer
183
+ });
184
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport type { AccessEngine } from \"./engine.js\";\nimport type { SchemaDefinition, Subject, ResourceContext } from \"./types.js\";\n\nconst DEFAULT_MAX_BODY_BYTES = 1024 * 1024; // 1 MB\n\n// ---------------------------------------------------------------------------\n// Standalone HTTP authorization server\n// ---------------------------------------------------------------------------\n\nexport interface ServerOptions<S extends SchemaDefinition> {\n engine: AccessEngine<S>;\n port?: number;\n host?: string;\n /**\n * Optional hook to resolve a Subject from the request body.\n * Defaults to using body.subject directly.\n */\n resolveSubject?: (body: EvalRequestBody) => Subject<S> | Promise<Subject<S>>;\n /**\n * Optional authentication hook. Return true to allow the request,\n * false to reject with 401. Called before any endpoint logic.\n * If not provided, all requests are allowed (suitable for internal networks only).\n */\n authenticate?: (req: IncomingMessage) => boolean | Promise<boolean>;\n /** Maximum request body size in bytes. Defaults to 1 MB. */\n maxBodyBytes?: number;\n}\n\nexport interface EvalRequestBody {\n subject: {\n id: string;\n roles: { role: string; tenantId?: string }[];\n attributes?: Record<string, unknown>;\n };\n action: string;\n resource: string;\n resourceContext?: ResourceContext;\n tenantId?: string;\n}\n\ninterface EvalResponseBody {\n allowed: boolean;\n effect: string;\n reason: string;\n matchedRuleId: string | null;\n durationMs: number;\n}\n\ninterface HealthResponse {\n status: \"ok\";\n rulesLoaded: number;\n uptime: number;\n}\n\nfunction readBody(req: IncomingMessage, maxBytes: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let received = 0;\n let settled = false;\n\n function settle(fn: () => void) {\n if (!settled) {\n settled = true;\n fn();\n }\n }\n\n req.on(\"data\", (chunk: Buffer) => {\n if (settled) return;\n received += chunk.length;\n if (received > maxBytes) {\n req.resume();\n settle(() => reject(new Error(`Request body exceeds ${maxBytes} bytes`)));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => {\n settle(() => resolve(Buffer.concat(chunks).toString(\"utf-8\")));\n });\n req.on(\"error\", (err) => {\n settle(() => reject(err));\n });\n });\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n const json = JSON.stringify(body);\n res.writeHead(status, {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(json),\n });\n res.end(json);\n}\n\n/**\n * Create a standalone HTTP authorization server.\n *\n * Endpoints:\n * POST /evaluate — evaluate an authorization request\n * GET /health — health check + rule count\n * GET /rules — list all loaded rules (without conditions)\n *\n * **Security**: This server has no authentication by default.\n * In production, provide an `authenticate` hook or run behind a VPN/service mesh.\n */\nexport function createAuthServer<S extends SchemaDefinition>(\n options: ServerOptions<S>,\n) {\n const {\n engine,\n port = 3100,\n host = \"0.0.0.0\",\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n } = options;\n const startTime = Date.now();\n\n const server = createServer(async (req, res) => {\n const pathname = new URL(req.url ?? \"/\", \"http://localhost\").pathname;\n const method = req.method ?? \"GET\";\n\n try {\n if (options.authenticate) {\n const authed = await options.authenticate(req);\n if (authed !== true) {\n sendJson(res, 401, { error: \"Unauthorized\" });\n return;\n }\n }\n\n if (method === \"GET\" && pathname === \"/health\") {\n const body: HealthResponse = {\n status: \"ok\",\n rulesLoaded: engine.getRules().length,\n uptime: Date.now() - startTime,\n };\n sendJson(res, 200, body);\n return;\n }\n\n if (method === \"GET\" && pathname === \"/rules\") {\n const rules = engine.getRules().map((r) => ({\n id: r.id,\n effect: r.effect,\n roles: r.roles,\n actions: r.actions,\n resources: r.resources,\n priority: r.priority,\n description: r.description,\n hasConditions: (r.conditions?.length ?? 0) > 0,\n }));\n sendJson(res, 200, { rules });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/evaluate\") {\n let raw: string;\n try {\n raw = await readBody(req, maxBodyBytes);\n } catch (err) {\n sendJson(res, 413, {\n error: err instanceof Error ? err.message : \"Payload too large\",\n });\n return;\n }\n\n let body: EvalRequestBody;\n try {\n body = JSON.parse(raw);\n } catch {\n sendJson(res, 400, { error: \"Invalid JSON body\" });\n return;\n }\n\n if (!body.subject || !body.action || !body.resource) {\n sendJson(res, 400, {\n error: \"Missing required fields: subject, action, resource\",\n });\n return;\n }\n\n if (typeof body.action !== \"string\" || typeof body.resource !== \"string\") {\n sendJson(res, 400, { error: \"action and resource must be strings\" });\n return;\n }\n\n if (\n typeof body.subject !== \"object\" ||\n typeof body.subject.id !== \"string\" ||\n !Array.isArray(body.subject.roles)\n ) {\n sendJson(res, 400, {\n error: \"subject must have a string id and a roles array\",\n });\n return;\n }\n\n const subject: Subject<S> = options.resolveSubject\n ? await options.resolveSubject(body)\n : (body.subject as unknown as Subject<S>);\n\n const decision = engine.evaluate(\n subject,\n body.action as Parameters<typeof engine.evaluate>[1],\n body.resource as Parameters<typeof engine.evaluate>[2],\n body.resourceContext ?? {},\n body.tenantId,\n );\n\n const response: EvalResponseBody = {\n allowed: decision.allowed,\n effect: decision.effect,\n reason: decision.reason,\n matchedRuleId: decision.matchedRule?.id ?? null,\n durationMs: decision.durationMs,\n };\n sendJson(res, 200, response);\n return;\n }\n\n sendJson(res, 404, { error: \"Not found\" });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal server error\";\n sendJson(res, 500, { error: message });\n }\n });\n\n return {\n start(): Promise<void> {\n return new Promise((resolve) => {\n server.listen(port, host, () => {\n resolve();\n });\n });\n },\n\n stop(): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resol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MACH,CAAC;AAAA,IACH;AAAA,IAEA,OAAsB;AACpB,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,eAAO,MAAM,CAAC,QAAS,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,MACvD,CAAC;AAAA,IACH;AAAA,IAEA,YAAY;AAAA,EACd;AACF;","names":[]}
@@ -0,0 +1,54 @@
1
+ import * as http from 'http';
2
+ import { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { R as ResourceContext, S as SchemaDefinition, A as AccessEngine, r as Subject } from './engine-C6IASR5F.cjs';
4
+
5
+ interface ServerOptions<S extends SchemaDefinition> {
6
+ engine: AccessEngine<S>;
7
+ port?: number;
8
+ host?: string;
9
+ /**
10
+ * Optional hook to resolve a Subject from the request body.
11
+ * Defaults to using body.subject directly.
12
+ */
13
+ resolveSubject?: (body: EvalRequestBody) => Subject<S> | Promise<Subject<S>>;
14
+ /**
15
+ * Optional authentication hook. Return true to allow the request,
16
+ * false to reject with 401. Called before any endpoint logic.
17
+ * If not provided, all requests are allowed (suitable for internal networks only).
18
+ */
19
+ authenticate?: (req: IncomingMessage) => boolean | Promise<boolean>;
20
+ /** Maximum request body size in bytes. Defaults to 1 MB. */
21
+ maxBodyBytes?: number;
22
+ }
23
+ interface EvalRequestBody {
24
+ subject: {
25
+ id: string;
26
+ roles: {
27
+ role: string;
28
+ tenantId?: string;
29
+ }[];
30
+ attributes?: Record<string, unknown>;
31
+ };
32
+ action: string;
33
+ resource: string;
34
+ resourceContext?: ResourceContext;
35
+ tenantId?: string;
36
+ }
37
+ /**
38
+ * Create a standalone HTTP authorization server.
39
+ *
40
+ * Endpoints:
41
+ * POST /evaluate — evaluate an authorization request
42
+ * GET /health — health check + rule count
43
+ * GET /rules — list all loaded rules (without conditions)
44
+ *
45
+ * **Security**: This server has no authentication by default.
46
+ * In production, provide an `authenticate` hook or run behind a VPN/service mesh.
47
+ */
48
+ declare function createAuthServer<S extends SchemaDefinition>(options: ServerOptions<S>): {
49
+ start(): Promise<void>;
50
+ stop(): Promise<void>;
51
+ httpServer: http.Server<typeof IncomingMessage, typeof ServerResponse>;
52
+ };
53
+
54
+ export { type EvalRequestBody, type ServerOptions, createAuthServer };
package/dist/server.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { type IncomingMessage, type ServerResponse } from "node:http";
2
- import type { AccessEngine } from "./engine.js";
3
- import type { SchemaDefinition, Subject, ResourceContext } from "./types.js";
4
- export interface ServerOptions<S extends SchemaDefinition> {
1
+ import * as http from 'http';
2
+ import { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { R as ResourceContext, S as SchemaDefinition, A as AccessEngine, r as Subject } from './engine-C6IASR5F.js';
4
+
5
+ interface ServerOptions<S extends SchemaDefinition> {
5
6
  engine: AccessEngine<S>;
6
7
  port?: number;
7
8
  host?: string;
@@ -19,7 +20,7 @@ export interface ServerOptions<S extends SchemaDefinition> {
19
20
  /** Maximum request body size in bytes. Defaults to 1 MB. */
20
21
  maxBodyBytes?: number;
21
22
  }
22
- export interface EvalRequestBody {
23
+ interface EvalRequestBody {
23
24
  subject: {
24
25
  id: string;
25
26
  roles: {
@@ -44,9 +45,10 @@ export interface EvalRequestBody {
44
45
  * **Security**: This server has no authentication by default.
45
46
  * In production, provide an `authenticate` hook or run behind a VPN/service mesh.
46
47
  */
47
- export declare function createAuthServer<S extends SchemaDefinition>(options: ServerOptions<S>): {
48
+ declare function createAuthServer<S extends SchemaDefinition>(options: ServerOptions<S>): {
48
49
  start(): Promise<void>;
49
50
  stop(): Promise<void>;
50
- httpServer: import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
51
+ httpServer: http.Server<typeof IncomingMessage, typeof ServerResponse>;
51
52
  };
52
- //# sourceMappingURL=server.d.ts.map
53
+
54
+ export { type EvalRequestBody, type ServerOptions, createAuthServer };
package/dist/server.js CHANGED
@@ -1,163 +1,159 @@
1
- import { createServer } from "node:http";
2
- const DEFAULT_MAX_BODY_BYTES = 1024 * 1024; // 1 MB
1
+ // src/server.ts
2
+ import { createServer } from "http";
3
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
3
4
  function readBody(req, maxBytes) {
4
- return new Promise((resolve, reject) => {
5
- const chunks = [];
6
- let received = 0;
7
- let settled = false;
8
- function settle(fn) {
9
- if (!settled) {
10
- settled = true;
11
- fn();
12
- }
13
- }
14
- req.on("data", (chunk) => {
15
- if (settled)
16
- return;
17
- received += chunk.length;
18
- if (received > maxBytes) {
19
- req.resume();
20
- settle(() => reject(new Error(`Request body exceeds ${maxBytes} bytes`)));
21
- return;
22
- }
23
- chunks.push(chunk);
24
- });
25
- req.on("end", () => {
26
- settle(() => resolve(Buffer.concat(chunks).toString("utf-8")));
27
- });
28
- req.on("error", (err) => {
29
- settle(() => reject(err));
30
- });
5
+ return new Promise((resolve, reject) => {
6
+ const chunks = [];
7
+ let received = 0;
8
+ let settled = false;
9
+ function settle(fn) {
10
+ if (!settled) {
11
+ settled = true;
12
+ fn();
13
+ }
14
+ }
15
+ req.on("data", (chunk) => {
16
+ if (settled) return;
17
+ received += chunk.length;
18
+ if (received > maxBytes) {
19
+ req.resume();
20
+ settle(() => reject(new Error(`Request body exceeds ${maxBytes} bytes`)));
21
+ return;
22
+ }
23
+ chunks.push(chunk);
31
24
  });
25
+ req.on("end", () => {
26
+ settle(() => resolve(Buffer.concat(chunks).toString("utf-8")));
27
+ });
28
+ req.on("error", (err) => {
29
+ settle(() => reject(err));
30
+ });
31
+ });
32
32
  }
33
33
  function sendJson(res, status, body) {
34
- const json = JSON.stringify(body);
35
- res.writeHead(status, {
36
- "Content-Type": "application/json",
37
- "Content-Length": Buffer.byteLength(json),
38
- });
39
- res.end(json);
34
+ const json = JSON.stringify(body);
35
+ res.writeHead(status, {
36
+ "Content-Type": "application/json",
37
+ "Content-Length": Buffer.byteLength(json)
38
+ });
39
+ res.end(json);
40
40
  }
41
- /**
42
- * Create a standalone HTTP authorization server.
43
- *
44
- * Endpoints:
45
- * POST /evaluate — evaluate an authorization request
46
- * GET /health health check + rule count
47
- * GET /rules — list all loaded rules (without conditions)
48
- *
49
- * **Security**: This server has no authentication by default.
50
- * In production, provide an `authenticate` hook or run behind a VPN/service mesh.
51
- */
52
- export function createAuthServer(options) {
53
- const { engine, port = 3100, host = "0.0.0.0", maxBodyBytes = DEFAULT_MAX_BODY_BYTES, } = options;
54
- const startTime = Date.now();
55
- const server = createServer(async (req, res) => {
56
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
57
- const method = req.method ?? "GET";
41
+ function createAuthServer(options) {
42
+ const {
43
+ engine,
44
+ port = 3100,
45
+ host = "0.0.0.0",
46
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES
47
+ } = options;
48
+ const startTime = Date.now();
49
+ const server = createServer(async (req, res) => {
50
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
51
+ const method = req.method ?? "GET";
52
+ try {
53
+ if (options.authenticate) {
54
+ const authed = await options.authenticate(req);
55
+ if (authed !== true) {
56
+ sendJson(res, 401, { error: "Unauthorized" });
57
+ return;
58
+ }
59
+ }
60
+ if (method === "GET" && pathname === "/health") {
61
+ const body = {
62
+ status: "ok",
63
+ rulesLoaded: engine.getRules().length,
64
+ uptime: Date.now() - startTime
65
+ };
66
+ sendJson(res, 200, body);
67
+ return;
68
+ }
69
+ if (method === "GET" && pathname === "/rules") {
70
+ const rules = engine.getRules().map((r) => ({
71
+ id: r.id,
72
+ effect: r.effect,
73
+ roles: r.roles,
74
+ actions: r.actions,
75
+ resources: r.resources,
76
+ priority: r.priority,
77
+ description: r.description,
78
+ hasConditions: (r.conditions?.length ?? 0) > 0
79
+ }));
80
+ sendJson(res, 200, { rules });
81
+ return;
82
+ }
83
+ if (method === "POST" && pathname === "/evaluate") {
84
+ let raw;
85
+ try {
86
+ raw = await readBody(req, maxBodyBytes);
87
+ } catch (err) {
88
+ sendJson(res, 413, {
89
+ error: err instanceof Error ? err.message : "Payload too large"
90
+ });
91
+ return;
92
+ }
93
+ let body;
58
94
  try {
59
- if (options.authenticate) {
60
- const authed = await options.authenticate(req);
61
- if (authed !== true) {
62
- sendJson(res, 401, { error: "Unauthorized" });
63
- return;
64
- }
65
- }
66
- if (method === "GET" && pathname === "/health") {
67
- const body = {
68
- status: "ok",
69
- rulesLoaded: engine.getRules().length,
70
- uptime: Date.now() - startTime,
71
- };
72
- sendJson(res, 200, body);
73
- return;
74
- }
75
- if (method === "GET" && pathname === "/rules") {
76
- const rules = engine.getRules().map((r) => ({
77
- id: r.id,
78
- effect: r.effect,
79
- roles: r.roles,
80
- actions: r.actions,
81
- resources: r.resources,
82
- priority: r.priority,
83
- description: r.description,
84
- hasConditions: (r.conditions?.length ?? 0) > 0,
85
- }));
86
- sendJson(res, 200, { rules });
87
- return;
88
- }
89
- if (method === "POST" && pathname === "/evaluate") {
90
- let raw;
91
- try {
92
- raw = await readBody(req, maxBodyBytes);
93
- }
94
- catch (err) {
95
- sendJson(res, 413, {
96
- error: err instanceof Error ? err.message : "Payload too large",
97
- });
98
- return;
99
- }
100
- let body;
101
- try {
102
- body = JSON.parse(raw);
103
- }
104
- catch {
105
- sendJson(res, 400, { error: "Invalid JSON body" });
106
- return;
107
- }
108
- if (!body.subject || !body.action || !body.resource) {
109
- sendJson(res, 400, {
110
- error: "Missing required fields: subject, action, resource",
111
- });
112
- return;
113
- }
114
- if (typeof body.action !== "string" || typeof body.resource !== "string") {
115
- sendJson(res, 400, { error: "action and resource must be strings" });
116
- return;
117
- }
118
- if (typeof body.subject !== "object" ||
119
- typeof body.subject.id !== "string" ||
120
- !Array.isArray(body.subject.roles)) {
121
- sendJson(res, 400, {
122
- error: "subject must have a string id and a roles array",
123
- });
124
- return;
125
- }
126
- const subject = options.resolveSubject
127
- ? await options.resolveSubject(body)
128
- : body.subject;
129
- const decision = engine.evaluate(subject, body.action, body.resource, body.resourceContext ?? {}, body.tenantId);
130
- const response = {
131
- allowed: decision.allowed,
132
- effect: decision.effect,
133
- reason: decision.reason,
134
- matchedRuleId: decision.matchedRule?.id ?? null,
135
- durationMs: decision.durationMs,
136
- };
137
- sendJson(res, 200, response);
138
- return;
139
- }
140
- sendJson(res, 404, { error: "Not found" });
95
+ body = JSON.parse(raw);
96
+ } catch {
97
+ sendJson(res, 400, { error: "Invalid JSON body" });
98
+ return;
141
99
  }
142
- catch (err) {
143
- const message = err instanceof Error ? err.message : "Internal server error";
144
- sendJson(res, 500, { error: message });
100
+ if (!body.subject || !body.action || !body.resource) {
101
+ sendJson(res, 400, {
102
+ error: "Missing required fields: subject, action, resource"
103
+ });
104
+ return;
145
105
  }
146
- });
147
- return {
148
- start() {
149
- return new Promise((resolve) => {
150
- server.listen(port, host, () => {
151
- resolve();
152
- });
153
- });
154
- },
155
- stop() {
156
- return new Promise((resolve, reject) => {
157
- server.close((err) => (err ? reject(err) : resolve()));
158
- });
159
- },
160
- httpServer: server,
161
- };
106
+ if (typeof body.action !== "string" || typeof body.resource !== "string") {
107
+ sendJson(res, 400, { error: "action and resource must be strings" });
108
+ return;
109
+ }
110
+ if (typeof body.subject !== "object" || typeof body.subject.id !== "string" || !Array.isArray(body.subject.roles)) {
111
+ sendJson(res, 400, {
112
+ error: "subject must have a string id and a roles array"
113
+ });
114
+ return;
115
+ }
116
+ const subject = options.resolveSubject ? await options.resolveSubject(body) : body.subject;
117
+ const decision = engine.evaluate(
118
+ subject,
119
+ body.action,
120
+ body.resource,
121
+ body.resourceContext ?? {},
122
+ body.tenantId
123
+ );
124
+ const response = {
125
+ allowed: decision.allowed,
126
+ effect: decision.effect,
127
+ reason: decision.reason,
128
+ matchedRuleId: decision.matchedRule?.id ?? null,
129
+ durationMs: decision.durationMs
130
+ };
131
+ sendJson(res, 200, response);
132
+ return;
133
+ }
134
+ sendJson(res, 404, { error: "Not found" });
135
+ } catch (err) {
136
+ const message = err instanceof Error ? err.message : "Internal server error";
137
+ sendJson(res, 500, { error: message });
138
+ }
139
+ });
140
+ return {
141
+ start() {
142
+ return new Promise((resolve) => {
143
+ server.listen(port, host, () => {
144
+ resolve();
145
+ });
146
+ });
147
+ },
148
+ stop() {
149
+ return new Promise((resolve, reject) => {
150
+ server.close((err) => err ? reject(err) : resolve());
151
+ });
152
+ },
153
+ httpServer: server
154
+ };
162
155
  }
156
+ export {
157
+ createAuthServer
158
+ };
163
159
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AAIpF,MAAM,sBAAsB,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,OAAO;AAmDnD,SAAS,QAAQ,CAAC,GAAoB,EAAE,QAAgB;IACtD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAa,EAAE,CAAC;QAC5B,IAAI,QAAQ,GAAG,CAAC,CAAC;QACjB,IAAI,OAAO,GAAG,KAAK,CAAC;QAEpB,SAAS,MAAM,CAAC,EAAc;YAC5B,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,OAAO,GAAG,IAAI,CAAC;gBACf,EAAE,EAAE,CAAC;YACP,CAAC;QACH,CAAC;QAED,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE;YAC/B,IAAI,OAAO;gBAAE,OAAO;YACpB,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;YACzB,IAAI,QAAQ,GAAG,QAAQ,EAAE,CAAC;gBACxB,GAAG,CAAC,MAAM,EAAE,CAAC;gBACb,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC;gBAC1E,OAAO;YACT,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EA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ACH,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC7B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE;oBAC7B,OAAO,EAAE,CAAC;gBACZ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;QAED,IAAI;YACF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACrC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YACzD,CAAC,CAAC,CAAC;QACL,CAAC;QAED,UAAU,EAAE,MAAM;KACnB,CAAC;AACJ,CAAC"}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport type { AccessEngine } from \"./engine.js\";\nimport type { SchemaDefinition, Subject, ResourceContext } from \"./types.js\";\n\nconst DEFAULT_MAX_BODY_BYTES = 1024 * 1024; // 1 MB\n\n// ---------------------------------------------------------------------------\n// Standalone HTTP authorization server\n// ---------------------------------------------------------------------------\n\nexport interface ServerOptions<S extends SchemaDefinition> {\n engine: AccessEngine<S>;\n port?: number;\n host?: string;\n /**\n * Optional hook to resolve a Subject from the request body.\n * Defaults to using body.subject directly.\n */\n resolveSubject?: (body: EvalRequestBody) => Subject<S> | Promise<Subject<S>>;\n /**\n * Optional authentication hook. Return true to allow the request,\n * false to reject with 401. Called before any endpoint logic.\n * If not provided, all requests are allowed (suitable for internal networks only).\n */\n authenticate?: (req: IncomingMessage) => boolean | Promise<boolean>;\n /** Maximum request body size in bytes. Defaults to 1 MB. */\n maxBodyBytes?: number;\n}\n\nexport interface EvalRequestBody {\n subject: {\n id: string;\n roles: { role: string; tenantId?: string }[];\n attributes?: Record<string, unknown>;\n };\n action: string;\n resource: string;\n resourceContext?: ResourceContext;\n tenantId?: string;\n}\n\ninterface EvalResponseBody {\n allowed: boolean;\n effect: string;\n reason: string;\n matchedRuleId: string | null;\n durationMs: number;\n}\n\ninterface HealthResponse {\n status: \"ok\";\n rulesLoaded: number;\n uptime: number;\n}\n\nfunction readBody(req: IncomingMessage, maxBytes: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let received = 0;\n let settled = false;\n\n function settle(fn: () => void) {\n if (!settled) {\n settled = true;\n fn();\n }\n }\n\n req.on(\"data\", (chunk: Buffer) => {\n if (settled) return;\n received += chunk.length;\n if (received > maxBytes) {\n req.resume();\n settle(() => reject(new Error(`Request body exceeds ${maxBytes} bytes`)));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => {\n settle(() => resolve(Buffer.concat(chunks).toString(\"utf-8\")));\n });\n req.on(\"error\", (err) => {\n settle(() => reject(err));\n });\n });\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n const json = JSON.stringify(body);\n res.writeHead(status, {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(json),\n });\n res.end(json);\n}\n\n/**\n * Create a standalone HTTP authorization server.\n *\n * Endpoints:\n * POST /evaluate — evaluate an authorization request\n * GET /health — health check + rule count\n * GET /rules — list all loaded rules (without conditions)\n *\n * **Security**: This server has no authentication by default.\n * In production, provide an `authenticate` hook or run behind a VPN/service mesh.\n */\nexport function createAuthServer<S extends SchemaDefinition>(\n options: ServerOptions<S>,\n) {\n const {\n engine,\n port = 3100,\n host = \"0.0.0.0\",\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n } = options;\n const startTime = Date.now();\n\n const server = createServer(async (req, res) => {\n const pathname = new URL(req.url ?? \"/\", \"http://localhost\").pathname;\n const method = req.method ?? \"GET\";\n\n try {\n if (options.authenticate) {\n const authed = await options.authenticate(req);\n if (authed !== true) {\n sendJson(res, 401, { error: \"Unauthorized\" });\n return;\n }\n }\n\n if (method === \"GET\" && pathname === \"/health\") {\n const body: HealthResponse = {\n status: \"ok\",\n rulesLoaded: engine.getRules().length,\n uptime: Date.now() - startTime,\n };\n sendJson(res, 200, body);\n return;\n }\n\n if (method === \"GET\" && pathname === \"/rules\") {\n const rules = engine.getRules().map((r) => ({\n id: r.id,\n effect: r.effect,\n roles: r.roles,\n actions: r.actions,\n resources: r.resources,\n priority: r.priority,\n description: r.description,\n hasConditions: (r.conditions?.length ?? 0) > 0,\n }));\n sendJson(res, 200, { rules });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/evaluate\") {\n let raw: string;\n try {\n raw = await readBody(req, maxBodyBytes);\n } catch (err) {\n sendJson(res, 413, {\n error: err instanceof Error ? err.message : \"Payload too large\",\n });\n return;\n }\n\n let body: EvalRequestBody;\n try {\n body = JSON.parse(raw);\n } catch {\n sendJson(res, 400, { error: \"Invalid JSON body\" });\n return;\n }\n\n if (!body.subject || !body.action || !body.resource) {\n sendJson(res, 400, {\n error: \"Missing required fields: subject, action, resource\",\n });\n return;\n }\n\n if (typeof body.action !== \"string\" || typeof body.resource !== \"string\") {\n sendJson(res, 400, { error: \"action and resource must be strings\" });\n return;\n }\n\n if (\n typeof body.subject !== \"object\" ||\n typeof body.subject.id !== \"string\" ||\n !Array.isArray(body.subject.roles)\n ) {\n sendJson(res, 400, {\n error: \"subject must have a string id and a roles array\",\n });\n return;\n }\n\n const subject: Subject<S> = options.resolveSubject\n ? await options.resolveSubject(body)\n : (body.subject as unknown as Subject<S>);\n\n const decision = engine.evaluate(\n subject,\n body.action as Parameters<typeof engine.evaluate>[1],\n body.resource as Parameters<typeof engine.evaluate>[2],\n body.resourceContext ?? {},\n body.tenantId,\n );\n\n const response: EvalResponseBody = {\n allowed: decision.allowed,\n effect: decision.effect,\n reason: decision.reason,\n matchedRuleId: decision.matchedRule?.id ?? null,\n durationMs: decision.durationMs,\n };\n sendJson(res, 200, response);\n return;\n }\n\n sendJson(res, 404, { error: \"Not found\" });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal server error\";\n sendJson(res, 500, { error: message });\n }\n });\n\n return {\n start(): Promise<void> {\n return new Promise((resolve) => {\n server.listen(port, host, () => {\n resolve();\n });\n });\n },\n\n stop(): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n },\n\n httpServer: server,\n };\n}\n"],"mappings":";AAAA,SAAS,oBAA+D;AAIxE,IAAM,yBAAyB,OAAO;AAmDtC,SAAS,SAAS,KAAsB,UAAmC;AACzE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,SAAmB,CAAC;AAC1B,QAAI,WAAW;AACf,QAAI,UAAU;AAEd,aAAS,OAAO,IAAgB;AAC9B,UAAI,CAAC,SAAS;AACZ,kBAAU;AACV,WAAG;AAAA,MACL;AAAA,IACF;AAEA,QAAI,GAAG,QAAQ,CAAC,UAAkB;AAChC,UAAI,QAAS;AACb,kBAAY,MAAM;AAClB,UAAI,WAAW,UAAU;AACvB,YAAI,OAAO;AACX,eAAO,MAAM,OAAO,IAAI,MAAM,wBAAwB,QAAQ,QAAQ,CAAC,CAAC;AACxE;AAAA,MACF;AACA,aAAO,KAAK,KAAK;AAAA,IACnB,CAAC;AACD,QAAI,GAAG,OAAO,MAAM;AAClB,aAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC;AAAA,IAC/D,CAAC;AACD,QAAI,GAAG,SAAS,CAAC,QAAQ;AACvB,aAAO,MAAM,OAAO,GAAG,CAAC;AAAA,IAC1B,CAAC;AAAA,EACH,CAAC;AACH;AAEA,SAAS,SAAS,KAAqB,QAAgB,MAAqB;AAC1E,QAAM,OAAO,KAAK,UAAU,IAAI;AAChC,MAAI,UAAU,QAAQ;AAAA,IACpB,gBAAgB;AAAA,IAChB,kBAAkB,OAAO,WAAW,IAAI;AAAA,EAC1C,CAAC;AACD,MAAI,IAAI,IAAI;AACd;AAaO,SAAS,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