@drmhse/authos-node 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,24 @@
1
+ import { RequestHandler, Request } from 'express';
2
+ import { a as VerifiedToken, A as AuthOSNodeOptions, R as RequireAuthOptions, d as RequirePermissionOptions } from './types-C4aDSNcp.mjs';
3
+ import '@drmhse/sso-sdk';
4
+
5
+ declare global {
6
+ namespace Express {
7
+ interface Request {
8
+ auth?: VerifiedToken;
9
+ }
10
+ }
11
+ }
12
+ /**
13
+ * Create Express middleware for AuthOS authentication
14
+ */
15
+ declare function createAuthMiddleware(options: AuthOSNodeOptions): {
16
+ requireAuth: (authOptions?: RequireAuthOptions) => RequestHandler;
17
+ requirePermission: (permission: string, permOptions?: RequirePermissionOptions) => RequestHandler;
18
+ requireAnyPermission: (permissions: string[], permOptions?: RequirePermissionOptions) => RequestHandler;
19
+ requireAllPermissions: (permissions: string[], permOptions?: RequirePermissionOptions) => RequestHandler;
20
+ requirePlatformOwner: (permOptions?: RequirePermissionOptions) => RequestHandler;
21
+ requireOrganization: (getOrgSlug: string | ((req: Request) => string), permOptions?: RequirePermissionOptions) => RequestHandler;
22
+ };
23
+
24
+ export { createAuthMiddleware };
@@ -0,0 +1,24 @@
1
+ import { RequestHandler, Request } from 'express';
2
+ import { a as VerifiedToken, A as AuthOSNodeOptions, R as RequireAuthOptions, d as RequirePermissionOptions } from './types-C4aDSNcp.js';
3
+ import '@drmhse/sso-sdk';
4
+
5
+ declare global {
6
+ namespace Express {
7
+ interface Request {
8
+ auth?: VerifiedToken;
9
+ }
10
+ }
11
+ }
12
+ /**
13
+ * Create Express middleware for AuthOS authentication
14
+ */
15
+ declare function createAuthMiddleware(options: AuthOSNodeOptions): {
16
+ requireAuth: (authOptions?: RequireAuthOptions) => RequestHandler;
17
+ requirePermission: (permission: string, permOptions?: RequirePermissionOptions) => RequestHandler;
18
+ requireAnyPermission: (permissions: string[], permOptions?: RequirePermissionOptions) => RequestHandler;
19
+ requireAllPermissions: (permissions: string[], permOptions?: RequirePermissionOptions) => RequestHandler;
20
+ requirePlatformOwner: (permOptions?: RequirePermissionOptions) => RequestHandler;
21
+ requireOrganization: (getOrgSlug: string | ((req: Request) => string), permOptions?: RequirePermissionOptions) => RequestHandler;
22
+ };
23
+
24
+ export { createAuthMiddleware };
@@ -0,0 +1,395 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n.default = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
24
+
25
+ // src/jwks.ts
26
+ var jwksCache = /* @__PURE__ */ new Map();
27
+ var DEFAULT_CACHE_TTL = 60 * 60 * 1e3;
28
+ function base64UrlDecode(input) {
29
+ const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
30
+ const pad = base64.length % 4;
31
+ const padded = pad ? base64 + "=".repeat(4 - pad) : base64;
32
+ return Buffer.from(padded, "base64");
33
+ }
34
+ function jwkToPem(jwk) {
35
+ if (jwk.kty !== "RSA" || !jwk.n || !jwk.e) {
36
+ throw new Error("Only RSA keys are supported");
37
+ }
38
+ const n = base64UrlDecode(jwk.n);
39
+ const e = base64UrlDecode(jwk.e);
40
+ const nInt = encodeASN1Integer(n);
41
+ const eInt = encodeASN1Integer(e);
42
+ const rsaPublicKey = encodeASN1Sequence(Buffer.concat([nInt, eInt]));
43
+ const bitString = Buffer.concat([
44
+ Buffer.from([3]),
45
+ encodeASN1Length(rsaPublicKey.length + 1),
46
+ Buffer.from([0]),
47
+ // no unused bits
48
+ rsaPublicKey
49
+ ]);
50
+ const algorithmIdentifier = Buffer.from([
51
+ 48,
52
+ 13,
53
+ // SEQUENCE
54
+ 6,
55
+ 9,
56
+ // OID
57
+ 42,
58
+ 134,
59
+ 72,
60
+ 134,
61
+ 247,
62
+ 13,
63
+ 1,
64
+ 1,
65
+ 1,
66
+ // 1.2.840.113549.1.1.1
67
+ 5,
68
+ 0
69
+ // NULL
70
+ ]);
71
+ const subjectPublicKeyInfo = encodeASN1Sequence(
72
+ Buffer.concat([algorithmIdentifier, bitString])
73
+ );
74
+ const base64Key = subjectPublicKeyInfo.toString("base64");
75
+ const lines = base64Key.match(/.{1,64}/g) || [];
76
+ return `-----BEGIN PUBLIC KEY-----
77
+ ${lines.join("\n")}
78
+ -----END PUBLIC KEY-----`;
79
+ }
80
+ function encodeASN1Length(length) {
81
+ if (length < 128) {
82
+ return Buffer.from([length]);
83
+ }
84
+ const bytes = [];
85
+ let len = length;
86
+ while (len > 0) {
87
+ bytes.unshift(len & 255);
88
+ len = len >> 8;
89
+ }
90
+ return Buffer.from([128 | bytes.length, ...bytes]);
91
+ }
92
+ function encodeASN1Integer(value) {
93
+ const needsPadding = value[0] & 128;
94
+ const content = needsPadding ? Buffer.concat([Buffer.from([0]), value]) : value;
95
+ return Buffer.concat([
96
+ Buffer.from([2]),
97
+ // INTEGER tag
98
+ encodeASN1Length(content.length),
99
+ content
100
+ ]);
101
+ }
102
+ function encodeASN1Sequence(content) {
103
+ return Buffer.concat([
104
+ Buffer.from([48]),
105
+ // SEQUENCE tag
106
+ encodeASN1Length(content.length),
107
+ content
108
+ ]);
109
+ }
110
+ async function fetchJWKS(baseURL) {
111
+ const url = `${baseURL.replace(/\/$/, "")}/.well-known/jwks.json`;
112
+ const response = await fetch(url);
113
+ if (!response.ok) {
114
+ throw new Error(`Failed to fetch JWKS: ${response.status} ${response.statusText}`);
115
+ }
116
+ return response.json();
117
+ }
118
+ async function getJWKS(baseURL, cacheTTL) {
119
+ const cached = jwksCache.get(baseURL);
120
+ const now = Date.now();
121
+ if (cached && now - cached.fetchedAt < cacheTTL) {
122
+ return cached.jwks;
123
+ }
124
+ const jwks = await fetchJWKS(baseURL);
125
+ jwksCache.set(baseURL, { jwks, fetchedAt: now });
126
+ return jwks;
127
+ }
128
+ function findKey(jwks, kid) {
129
+ return jwks.keys.find((key) => key.kid === kid) || null;
130
+ }
131
+ var TokenVerificationError = class extends Error {
132
+ constructor(message, code) {
133
+ super(message);
134
+ this.code = code;
135
+ this.name = "TokenVerificationError";
136
+ }
137
+ };
138
+ function parseJWT(token) {
139
+ const parts = token.split(".");
140
+ if (parts.length !== 3) {
141
+ throw new TokenVerificationError("Invalid JWT format", "INVALID_TOKEN_FORMAT");
142
+ }
143
+ try {
144
+ const header = JSON.parse(base64UrlDecode(parts[0]).toString("utf8"));
145
+ const payload = JSON.parse(base64UrlDecode(parts[1]).toString("utf8"));
146
+ return { header, payload };
147
+ } catch {
148
+ throw new TokenVerificationError("Invalid JWT encoding", "INVALID_TOKEN_FORMAT");
149
+ }
150
+ }
151
+ function createTokenVerifier(options) {
152
+ const { baseURL, jwksCacheTTL = DEFAULT_CACHE_TTL } = options;
153
+ async function verifyToken(token, verifyOptions = {}) {
154
+ const { audience, issuer, clockTolerance = 0 } = verifyOptions;
155
+ const { header, payload } = parseJWT(token);
156
+ if (header.alg !== "RS256") {
157
+ throw new TokenVerificationError(
158
+ `Unsupported algorithm: ${header.alg}. Only RS256 is supported.`,
159
+ "INVALID_ALGORITHM"
160
+ );
161
+ }
162
+ const kid = header.kid;
163
+ if (!kid) {
164
+ throw new TokenVerificationError("Token missing kid header", "MISSING_KID");
165
+ }
166
+ const jwks = await getJWKS(baseURL, jwksCacheTTL);
167
+ const jwk = findKey(jwks, kid);
168
+ if (!jwk) {
169
+ const freshJwks = await fetchJWKS(baseURL);
170
+ jwksCache.set(baseURL, { jwks: freshJwks, fetchedAt: Date.now() });
171
+ const freshJwk = findKey(freshJwks, kid);
172
+ if (!freshJwk) {
173
+ throw new TokenVerificationError(
174
+ `No matching key found for kid: ${kid}`,
175
+ "KEY_NOT_FOUND"
176
+ );
177
+ }
178
+ return verifyWithKey(token, freshJwk, payload, { audience, issuer, clockTolerance });
179
+ }
180
+ return verifyWithKey(token, jwk, payload, { audience, issuer, clockTolerance });
181
+ }
182
+ return { verifyToken };
183
+ }
184
+ function verifyWithKey(token, jwk, payload, options) {
185
+ const { audience, issuer, clockTolerance } = options;
186
+ const pem = jwkToPem(jwk);
187
+ const parts = token.split(".");
188
+ const signatureInput = `${parts[0]}.${parts[1]}`;
189
+ const signature = base64UrlDecode(parts[2]);
190
+ const verifier = crypto__namespace.createVerify("RSA-SHA256");
191
+ verifier.update(signatureInput);
192
+ if (!verifier.verify(pem, signature)) {
193
+ throw new TokenVerificationError("Invalid token signature", "INVALID_SIGNATURE");
194
+ }
195
+ const now = Math.floor(Date.now() / 1e3);
196
+ if (payload.exp && payload.exp + clockTolerance < now) {
197
+ throw new TokenVerificationError("Token has expired", "TOKEN_EXPIRED");
198
+ }
199
+ if (payload.iat && payload.iat - clockTolerance > now) {
200
+ throw new TokenVerificationError("Token is not yet valid", "TOKEN_NOT_YET_VALID");
201
+ }
202
+ if (audience) {
203
+ const tokenAud = payload.aud;
204
+ const validAud = Array.isArray(tokenAud) ? tokenAud.includes(audience) : tokenAud === audience;
205
+ if (!validAud) {
206
+ throw new TokenVerificationError("Invalid token audience", "INVALID_AUDIENCE");
207
+ }
208
+ }
209
+ if (issuer) {
210
+ const tokenIss = payload.iss;
211
+ if (tokenIss !== issuer) {
212
+ throw new TokenVerificationError("Invalid token issuer", "INVALID_ISSUER");
213
+ }
214
+ }
215
+ return { claims: payload, token };
216
+ }
217
+
218
+ // src/express/middleware.ts
219
+ function extractBearerToken(req) {
220
+ const authHeader = req.headers.authorization;
221
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
222
+ return null;
223
+ }
224
+ return authHeader.slice(7);
225
+ }
226
+ function createAuthMiddleware(options) {
227
+ const verifier = createTokenVerifier(options);
228
+ function requireAuth(authOptions = {}) {
229
+ const { getToken, ...verifyOptions } = authOptions;
230
+ return async (req, res, next) => {
231
+ try {
232
+ const token = getToken ? getToken(req) : extractBearerToken(req);
233
+ if (!token) {
234
+ res.status(401).json({
235
+ error: "Unauthorized",
236
+ message: "Missing authentication token",
237
+ code: "MISSING_TOKEN"
238
+ });
239
+ return;
240
+ }
241
+ const verified = await verifier.verifyToken(token, verifyOptions);
242
+ req.auth = verified;
243
+ next();
244
+ } catch (err) {
245
+ if (err instanceof TokenVerificationError) {
246
+ res.status(401).json({
247
+ error: "Unauthorized",
248
+ message: err.message,
249
+ code: err.code
250
+ });
251
+ return;
252
+ }
253
+ console.error("Auth middleware error:", err);
254
+ res.status(500).json({
255
+ error: "Internal Server Error",
256
+ message: "Authentication verification failed"
257
+ });
258
+ }
259
+ };
260
+ }
261
+ function requirePermission(permission, permOptions = {}) {
262
+ const { message = "Insufficient permissions" } = permOptions;
263
+ return (req, res, next) => {
264
+ if (!req.auth) {
265
+ res.status(401).json({
266
+ error: "Unauthorized",
267
+ message: "Authentication required",
268
+ code: "NOT_AUTHENTICATED"
269
+ });
270
+ return;
271
+ }
272
+ const permissions = req.auth.claims.permissions || [];
273
+ const hasPermission = permissions.includes(permission);
274
+ if (!hasPermission) {
275
+ res.status(403).json({
276
+ error: "Forbidden",
277
+ message,
278
+ code: "PERMISSION_DENIED",
279
+ required: permission
280
+ });
281
+ return;
282
+ }
283
+ next();
284
+ };
285
+ }
286
+ function requireAnyPermission(permissions, permOptions = {}) {
287
+ const { message = "Insufficient permissions" } = permOptions;
288
+ return (req, res, next) => {
289
+ if (!req.auth) {
290
+ res.status(401).json({
291
+ error: "Unauthorized",
292
+ message: "Authentication required",
293
+ code: "NOT_AUTHENTICATED"
294
+ });
295
+ return;
296
+ }
297
+ const userPermissions = req.auth.claims.permissions || [];
298
+ const hasAny = permissions.some((p) => userPermissions.includes(p));
299
+ if (!hasAny) {
300
+ res.status(403).json({
301
+ error: "Forbidden",
302
+ message,
303
+ code: "PERMISSION_DENIED",
304
+ required: permissions
305
+ });
306
+ return;
307
+ }
308
+ next();
309
+ };
310
+ }
311
+ function requireAllPermissions(permissions, permOptions = {}) {
312
+ const { message = "Insufficient permissions" } = permOptions;
313
+ return (req, res, next) => {
314
+ if (!req.auth) {
315
+ res.status(401).json({
316
+ error: "Unauthorized",
317
+ message: "Authentication required",
318
+ code: "NOT_AUTHENTICATED"
319
+ });
320
+ return;
321
+ }
322
+ const userPermissions = req.auth.claims.permissions || [];
323
+ const hasAll = permissions.every((p) => userPermissions.includes(p));
324
+ if (!hasAll) {
325
+ const missing = permissions.filter((p) => !userPermissions.includes(p));
326
+ res.status(403).json({
327
+ error: "Forbidden",
328
+ message,
329
+ code: "PERMISSION_DENIED",
330
+ required: permissions,
331
+ missing
332
+ });
333
+ return;
334
+ }
335
+ next();
336
+ };
337
+ }
338
+ function requirePlatformOwner(permOptions = {}) {
339
+ const { message = "Platform owner access required" } = permOptions;
340
+ return (req, res, next) => {
341
+ if (!req.auth) {
342
+ res.status(401).json({
343
+ error: "Unauthorized",
344
+ message: "Authentication required",
345
+ code: "NOT_AUTHENTICATED"
346
+ });
347
+ return;
348
+ }
349
+ if (!req.auth.claims.is_platform_owner) {
350
+ res.status(403).json({
351
+ error: "Forbidden",
352
+ message,
353
+ code: "NOT_PLATFORM_OWNER"
354
+ });
355
+ return;
356
+ }
357
+ next();
358
+ };
359
+ }
360
+ function requireOrganization(getOrgSlug, permOptions = {}) {
361
+ const { message = "Organization access required" } = permOptions;
362
+ return (req, res, next) => {
363
+ if (!req.auth) {
364
+ res.status(401).json({
365
+ error: "Unauthorized",
366
+ message: "Authentication required",
367
+ code: "NOT_AUTHENTICATED"
368
+ });
369
+ return;
370
+ }
371
+ const requiredOrg = typeof getOrgSlug === "function" ? getOrgSlug(req) : getOrgSlug;
372
+ const userOrg = req.auth.claims.org;
373
+ if (!userOrg || userOrg !== requiredOrg) {
374
+ res.status(403).json({
375
+ error: "Forbidden",
376
+ message,
377
+ code: "WRONG_ORGANIZATION",
378
+ required: requiredOrg
379
+ });
380
+ return;
381
+ }
382
+ next();
383
+ };
384
+ }
385
+ return {
386
+ requireAuth,
387
+ requirePermission,
388
+ requireAnyPermission,
389
+ requireAllPermissions,
390
+ requirePlatformOwner,
391
+ requireOrganization
392
+ };
393
+ }
394
+
395
+ exports.createAuthMiddleware = createAuthMiddleware;