@authyon/server 0.2.0-beta.0 → 0.2.0-beta.1
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 +21 -0
- package/README.md +121 -2
- package/dist/browser.cjs +21 -0
- package/dist/browser.d.cts +2 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +4 -0
- package/dist/index.cjs +889 -68
- package/dist/index.d.cts +343 -61
- package/dist/index.d.ts +343 -61
- package/dist/index.js +876 -67
- package/package.json +58 -36
package/dist/index.cjs
CHANGED
|
@@ -20,43 +20,523 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
+
AuthorizationError: () => AuthorizationError,
|
|
24
|
+
AuthyonAbility: () => AuthyonAbility,
|
|
25
|
+
AuthyonAbilityBuilder: () => AuthyonAbilityBuilder,
|
|
23
26
|
AuthyonError: () => AuthyonError,
|
|
24
27
|
AuthyonServerClient: () => AuthyonServerClient,
|
|
28
|
+
AuthyonServerClientBuilder: () => AuthyonServerClientBuilder,
|
|
29
|
+
ErrorCodes: () => ErrorCodes,
|
|
30
|
+
FetchHttpAdapter: () => FetchHttpAdapter,
|
|
31
|
+
JwksTokenVerifier: () => JwksTokenVerifier,
|
|
32
|
+
LoggingHttpAdapter: () => LoggingHttpAdapter,
|
|
25
33
|
TenantScopedClient: () => TenantScopedClient,
|
|
26
|
-
|
|
34
|
+
TokenVerificationError: () => TokenVerificationError,
|
|
35
|
+
authorizeRequest: () => authorizeRequest,
|
|
36
|
+
authorizeToken: () => authorizeToken,
|
|
37
|
+
createAuthorizationErrorResponse: () => createAuthorizationErrorResponse,
|
|
38
|
+
createAuthyonAbility: () => createAuthyonAbility,
|
|
39
|
+
createAuthyonRules: () => createAuthyonRules,
|
|
40
|
+
createClient: () => createClient,
|
|
41
|
+
createExpressAuthorizationMiddleware: () => createExpressAuthorizationMiddleware,
|
|
42
|
+
normalizeClientIp: () => normalizeClientIp
|
|
27
43
|
});
|
|
28
44
|
module.exports = __toCommonJS(index_exports);
|
|
29
45
|
|
|
30
|
-
//
|
|
46
|
+
// ../../internal/core/config/defaults.ts
|
|
47
|
+
var DEFAULT_BASE_URL = "https://api.authyon.com";
|
|
48
|
+
var DEFAULT_EXPIRY_SKEW_MS = 3e4;
|
|
49
|
+
|
|
50
|
+
// ../../internal/core/auth/expiringTokenProvider.ts
|
|
51
|
+
var ExpiringTokenProvider = class {
|
|
52
|
+
constructor(acquire, expirySkewMs = DEFAULT_EXPIRY_SKEW_MS) {
|
|
53
|
+
this.acquire = acquire;
|
|
54
|
+
this.expirySkewMs = expirySkewMs;
|
|
55
|
+
this.token = null;
|
|
56
|
+
this.inFlight = null;
|
|
57
|
+
}
|
|
58
|
+
async getAccessToken() {
|
|
59
|
+
if (this.token && Date.now() < this.token.expiresAt - this.expirySkewMs) {
|
|
60
|
+
return this.token.accessToken;
|
|
61
|
+
}
|
|
62
|
+
if (this.inFlight) return this.inFlight;
|
|
63
|
+
this.inFlight = this.acquire().then((token) => {
|
|
64
|
+
this.token = token;
|
|
65
|
+
return token.accessToken;
|
|
66
|
+
}).finally(() => {
|
|
67
|
+
this.inFlight = null;
|
|
68
|
+
});
|
|
69
|
+
return this.inFlight;
|
|
70
|
+
}
|
|
71
|
+
clear() {
|
|
72
|
+
this.token = null;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// ../../internal/core/errors/authyonError.ts
|
|
77
|
+
var ErrorCodes = {
|
|
78
|
+
Unknown: "unknown",
|
|
79
|
+
NetworkError: "request.network_error",
|
|
80
|
+
Timeout: "request.timeout",
|
|
81
|
+
SessionMalformed: "session.malformed",
|
|
82
|
+
NotAuthenticated: "auth.not_authenticated",
|
|
83
|
+
InvalidToken: "auth.invalid_token",
|
|
84
|
+
MissingToken: "auth.missing_token",
|
|
85
|
+
EmailTaken: "user.email_taken",
|
|
86
|
+
PasswordWeak: "user.password_weak",
|
|
87
|
+
PasswordPwned: "user.password_pwned",
|
|
88
|
+
RateLimited: "rate_limited"
|
|
89
|
+
};
|
|
31
90
|
var AuthyonError = class extends Error {
|
|
32
|
-
constructor(status, body) {
|
|
91
|
+
constructor(status, body, options = {}) {
|
|
33
92
|
super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
|
|
34
93
|
this.name = "AuthyonError";
|
|
35
94
|
this.status = status;
|
|
36
95
|
this.code = body.code ?? "unknown";
|
|
37
96
|
this.title = body.title ?? "Error";
|
|
38
97
|
this.detail = body.detail;
|
|
98
|
+
this.requestId = options.requestId;
|
|
99
|
+
this.retryAfter = options.retryAfter;
|
|
100
|
+
this.cause = options.cause;
|
|
39
101
|
}
|
|
40
102
|
is(code) {
|
|
41
103
|
return this.code === code;
|
|
42
104
|
}
|
|
105
|
+
isAny(...codes) {
|
|
106
|
+
return codes.includes(this.code);
|
|
107
|
+
}
|
|
108
|
+
hasPrefix(prefix) {
|
|
109
|
+
return this.code.startsWith(prefix);
|
|
110
|
+
}
|
|
111
|
+
isStatus(...statuses) {
|
|
112
|
+
return statuses.includes(this.status);
|
|
113
|
+
}
|
|
114
|
+
/** Stable interpretation for UI decisions, retries, telemetry and support flows. */
|
|
115
|
+
interpret() {
|
|
116
|
+
const category = classifyError(this.status, this.code);
|
|
117
|
+
return {
|
|
118
|
+
category,
|
|
119
|
+
action: actionFor(category),
|
|
120
|
+
retryable: isRetryable(category),
|
|
121
|
+
...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
|
|
122
|
+
...this.requestId !== void 0 ? { requestId: this.requestId } : {}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
get category() {
|
|
126
|
+
return this.interpret().category;
|
|
127
|
+
}
|
|
128
|
+
get retryable() {
|
|
129
|
+
return this.interpret().retryable;
|
|
130
|
+
}
|
|
131
|
+
toJSON() {
|
|
132
|
+
return {
|
|
133
|
+
name: this.name,
|
|
134
|
+
message: this.message,
|
|
135
|
+
status: this.status,
|
|
136
|
+
code: this.code,
|
|
137
|
+
title: this.title,
|
|
138
|
+
detail: this.detail,
|
|
139
|
+
requestId: this.requestId,
|
|
140
|
+
retryAfter: this.retryAfter,
|
|
141
|
+
...this.interpret()
|
|
142
|
+
};
|
|
143
|
+
}
|
|
43
144
|
};
|
|
145
|
+
function classifyError(status, code) {
|
|
146
|
+
if (code === ErrorCodes.NetworkError) return "network";
|
|
147
|
+
if (code === ErrorCodes.Timeout || status === 408) return "timeout";
|
|
148
|
+
if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
|
|
149
|
+
if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
|
|
150
|
+
if (code === ErrorCodes.PasswordWeak || code === ErrorCodes.PasswordPwned) return "validation";
|
|
151
|
+
if (code === ErrorCodes.SessionMalformed) return "server";
|
|
152
|
+
if (code.startsWith("auth.") || status === 401) return "authentication";
|
|
153
|
+
if (status === 403) return "authorization";
|
|
154
|
+
if (status === 404) return "not_found";
|
|
155
|
+
if (status === 400 || status === 422) return "validation";
|
|
156
|
+
if (status >= 500) return "server";
|
|
157
|
+
return "unknown";
|
|
158
|
+
}
|
|
159
|
+
function actionFor(category) {
|
|
160
|
+
switch (category) {
|
|
161
|
+
case "network":
|
|
162
|
+
case "timeout":
|
|
163
|
+
case "rate_limit":
|
|
164
|
+
case "server":
|
|
165
|
+
return "retry";
|
|
166
|
+
case "authentication":
|
|
167
|
+
return "reauthenticate";
|
|
168
|
+
case "authorization":
|
|
169
|
+
return "request_access";
|
|
170
|
+
case "validation":
|
|
171
|
+
return "fix_input";
|
|
172
|
+
case "not_found":
|
|
173
|
+
return "not_found";
|
|
174
|
+
case "conflict":
|
|
175
|
+
return "resolve_conflict";
|
|
176
|
+
case "unknown":
|
|
177
|
+
return "contact_support";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function isRetryable(category) {
|
|
181
|
+
return category === "network" || category === "timeout" || category === "rate_limit" || category === "server";
|
|
182
|
+
}
|
|
44
183
|
|
|
45
|
-
//
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
function toQuery(params = {}) {
|
|
184
|
+
// ../../internal/core/http/query.ts
|
|
185
|
+
function appendQuery(path, params) {
|
|
186
|
+
if (!params) return path;
|
|
49
187
|
const query = new URLSearchParams();
|
|
50
|
-
for (const [key,
|
|
51
|
-
if (
|
|
188
|
+
for (const [key, value2] of Object.entries(params)) {
|
|
189
|
+
if (value2 !== void 0) query.set(key, String(value2));
|
|
190
|
+
}
|
|
191
|
+
const value = query.toString();
|
|
192
|
+
return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ../../internal/core/http/httpAdapter.ts
|
|
196
|
+
var FetchHttpAdapter = class {
|
|
197
|
+
constructor(fetchImpl = fetch.bind(globalThis)) {
|
|
198
|
+
this.fetchImpl = fetchImpl;
|
|
199
|
+
}
|
|
200
|
+
request(request) {
|
|
201
|
+
return this.fetchImpl(request.url, {
|
|
202
|
+
method: request.method,
|
|
203
|
+
headers: request.headers,
|
|
204
|
+
body: request.body,
|
|
205
|
+
signal: request.signal
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
var LoggingHttpAdapter = class {
|
|
210
|
+
constructor(adapter, options) {
|
|
211
|
+
this.adapter = adapter;
|
|
212
|
+
this.options = options;
|
|
213
|
+
}
|
|
214
|
+
async request(request) {
|
|
215
|
+
const startedAt = Date.now();
|
|
216
|
+
const eventBase = {
|
|
217
|
+
method: request.method,
|
|
218
|
+
url: sanitizeUrl(request.url)
|
|
219
|
+
};
|
|
220
|
+
this.log({ type: "request", ...eventBase, timestamp: startedAt });
|
|
221
|
+
try {
|
|
222
|
+
const response = await this.adapter.request(request);
|
|
223
|
+
this.log({
|
|
224
|
+
type: "response",
|
|
225
|
+
...eventBase,
|
|
226
|
+
status: response.status,
|
|
227
|
+
durationMs: Date.now() - startedAt,
|
|
228
|
+
requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
|
|
229
|
+
timestamp: Date.now()
|
|
230
|
+
});
|
|
231
|
+
return response;
|
|
232
|
+
} catch (error) {
|
|
233
|
+
this.log({
|
|
234
|
+
type: "error",
|
|
235
|
+
...eventBase,
|
|
236
|
+
errorName: error instanceof Error ? error.name : "UnknownError",
|
|
237
|
+
durationMs: Date.now() - startedAt,
|
|
238
|
+
timestamp: Date.now()
|
|
239
|
+
});
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
log(event) {
|
|
244
|
+
if (!this.options.enabled) return;
|
|
245
|
+
const logger = this.options.logger ?? defaultHttpLogger;
|
|
246
|
+
try {
|
|
247
|
+
logger(event);
|
|
248
|
+
} catch {
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
function defaultHttpLogger(event) {
|
|
253
|
+
console.debug("[Authyon HTTP]", event);
|
|
254
|
+
}
|
|
255
|
+
function sanitizeUrl(value) {
|
|
256
|
+
const url = new URL(value);
|
|
257
|
+
const queryKeys = /* @__PURE__ */ new Set();
|
|
258
|
+
url.searchParams.forEach((_value, key) => queryKeys.add(key));
|
|
259
|
+
url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
|
|
260
|
+
return url.toString();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ../../internal/core/http/transport.ts
|
|
264
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
265
|
+
var SharedTransportError = class extends Error {
|
|
266
|
+
constructor(code, cause) {
|
|
267
|
+
super(code === "request.timeout" ? "Request timed out" : "Network request failed");
|
|
268
|
+
this.name = "SharedTransportError";
|
|
269
|
+
this.code = code;
|
|
270
|
+
this.cause = cause;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
function createSharedTransport(options) {
|
|
274
|
+
const baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureHttp ?? false);
|
|
275
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
276
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
|
|
277
|
+
throw new Error("Authyon: `timeoutMs` must be a non-negative finite number");
|
|
278
|
+
}
|
|
279
|
+
if (options.httpAdapter && options.fetch) {
|
|
280
|
+
throw new Error("Authyon: use either `httpAdapter` or `fetch`, not both");
|
|
281
|
+
}
|
|
282
|
+
const baseAdapter = options.httpAdapter ?? new FetchHttpAdapter(options.fetch);
|
|
283
|
+
const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
|
|
284
|
+
return {
|
|
285
|
+
baseUrl,
|
|
286
|
+
async request(path, init) {
|
|
287
|
+
const controller = new AbortController();
|
|
288
|
+
const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
|
|
289
|
+
try {
|
|
290
|
+
return await httpAdapter.request({
|
|
291
|
+
url: `${baseUrl}${path}`,
|
|
292
|
+
method: init.method ?? "GET",
|
|
293
|
+
headers: normalizeHeaders(init.headers),
|
|
294
|
+
body: init.body,
|
|
295
|
+
signal: controller.signal
|
|
296
|
+
});
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
throw new SharedTransportError(
|
|
299
|
+
controller.signal.aborted ? ErrorCodes.Timeout : ErrorCodes.NetworkError,
|
|
300
|
+
cause
|
|
301
|
+
);
|
|
302
|
+
} finally {
|
|
303
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function normalizeHeaders(headers) {
|
|
309
|
+
const normalized = {};
|
|
310
|
+
new Headers(headers).forEach((value, key) => {
|
|
311
|
+
normalized[key] = value;
|
|
312
|
+
});
|
|
313
|
+
return normalized;
|
|
314
|
+
}
|
|
315
|
+
function responseMetadata(response) {
|
|
316
|
+
const retryAfterHeader = response.headers.get("retry-after");
|
|
317
|
+
const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : void 0;
|
|
318
|
+
return {
|
|
319
|
+
requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
|
|
320
|
+
retryAfter: Number.isFinite(retryAfter) ? retryAfter : void 0
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function normalizeBaseUrl(value, allowInsecureHttp) {
|
|
324
|
+
let url;
|
|
325
|
+
try {
|
|
326
|
+
url = new URL(value);
|
|
327
|
+
} catch {
|
|
328
|
+
throw new Error("Authyon: `baseUrl` must be an absolute URL");
|
|
329
|
+
}
|
|
330
|
+
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
331
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && (loopback || allowInsecureHttp))) {
|
|
332
|
+
throw new Error(
|
|
333
|
+
"Authyon: `baseUrl` must use HTTPS (HTTP is allowed only for loopback or with `allowInsecureHttp`)"
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
337
|
+
throw new Error(
|
|
338
|
+
"Authyon: `baseUrl` cannot contain credentials, query parameters, or fragments"
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
return url.toString().replace(/\/+$/, "");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// ../../internal/core/http/jsonHttpClient.ts
|
|
345
|
+
var JsonHttpClient = class {
|
|
346
|
+
constructor(transport) {
|
|
347
|
+
this.transport = transport;
|
|
348
|
+
}
|
|
349
|
+
async send(path, options = {}) {
|
|
350
|
+
const headers = { ...options.headers };
|
|
351
|
+
if (options.body !== void 0) headers["Content-Type"] = "application/json";
|
|
352
|
+
try {
|
|
353
|
+
return await this.transport.request(appendQuery(path, options.query), {
|
|
354
|
+
method: options.method ?? "GET",
|
|
355
|
+
headers,
|
|
356
|
+
body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
|
|
357
|
+
});
|
|
358
|
+
} catch (cause) {
|
|
359
|
+
if (!(cause instanceof SharedTransportError)) throw cause;
|
|
360
|
+
throw new AuthyonError(0, { code: cause.code, title: cause.message }, { cause: cause.cause });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async parse(response) {
|
|
364
|
+
if (!response.ok) {
|
|
365
|
+
let body = {};
|
|
366
|
+
try {
|
|
367
|
+
body = await response.json();
|
|
368
|
+
} catch {
|
|
369
|
+
}
|
|
370
|
+
throw new AuthyonError(response.status, body, responseMetadata(response));
|
|
371
|
+
}
|
|
372
|
+
if (response.status === 204) return void 0;
|
|
373
|
+
return await response.json();
|
|
374
|
+
}
|
|
375
|
+
async request(path, options = {}) {
|
|
376
|
+
return this.parse(await this.send(path, options));
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
// ../../internal/core/http/clientIp.ts
|
|
381
|
+
function clientIpHeaders(context) {
|
|
382
|
+
if (!context?.clientIp) return {};
|
|
383
|
+
return { "X-Forwarded-For": normalizeClientIp(context.clientIp) };
|
|
384
|
+
}
|
|
385
|
+
function normalizeClientIp(value) {
|
|
386
|
+
let ip = value.trim();
|
|
387
|
+
if (ip.startsWith("[") && ip.endsWith("]")) ip = ip.slice(1, -1);
|
|
388
|
+
if (!ip || ip.length > 45 || ip.includes(",") || /[\r\n\s]/.test(ip) || !/^[0-9a-f:.]+$/i.test(ip) || !ip.includes(".") && !ip.includes(":")) {
|
|
389
|
+
throw invalidClientIp();
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
new URL(ip.includes(":") ? `http://[${ip}]` : `http://${ip}`);
|
|
393
|
+
} catch {
|
|
394
|
+
throw invalidClientIp();
|
|
395
|
+
}
|
|
396
|
+
return ip;
|
|
397
|
+
}
|
|
398
|
+
function invalidClientIp() {
|
|
399
|
+
return new Error("Authyon: `clientIp` must be a single valid IPv4 or IPv6 address");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/security/jwksTokenVerifier.ts
|
|
403
|
+
var import_jose = require("jose");
|
|
404
|
+
var SAFE_ASYMMETRIC_ALGORITHMS = [
|
|
405
|
+
"RS256",
|
|
406
|
+
"PS256",
|
|
407
|
+
"ES256",
|
|
408
|
+
"EdDSA"
|
|
409
|
+
];
|
|
410
|
+
var TokenVerificationError = class extends Error {
|
|
411
|
+
constructor(code, options = {}) {
|
|
412
|
+
super(messageForCode(code));
|
|
413
|
+
this.code = code;
|
|
414
|
+
this.name = "TokenVerificationError";
|
|
415
|
+
if (options.cause !== void 0) Object.defineProperty(this, "cause", { value: options.cause });
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
var JwksTokenVerifier = class {
|
|
419
|
+
constructor(options) {
|
|
420
|
+
this.options = options;
|
|
421
|
+
validateOptions(options);
|
|
422
|
+
this.algorithms = [...options.algorithms ?? ["RS256"]];
|
|
423
|
+
this.acceptedTokenTypes = new Set(options.acceptedTokenTypes ?? ["JWT", "at+jwt"]);
|
|
424
|
+
this.verifyKey = options.jwks ? (0, import_jose.createLocalJWKSet)(options.jwks) : (0, import_jose.createRemoteJWKSet)(new URL(options.jwksUri), {
|
|
425
|
+
timeoutDuration: options.jwksTimeoutMs ?? 5e3,
|
|
426
|
+
cacheMaxAge: options.jwksCacheMs ?? 6e5,
|
|
427
|
+
cooldownDuration: options.jwksCooldownMs ?? 3e4
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
async verifyAccessToken(token) {
|
|
431
|
+
if (!token || token.length > 16384) {
|
|
432
|
+
throw new TokenVerificationError("token.invalid");
|
|
433
|
+
}
|
|
434
|
+
try {
|
|
435
|
+
const result = await (0, import_jose.jwtVerify)(token, this.verifyKey, {
|
|
436
|
+
algorithms: this.algorithms,
|
|
437
|
+
issuer: this.options.issuer,
|
|
438
|
+
audience: this.options.audience,
|
|
439
|
+
clockTolerance: this.options.clockToleranceSeconds ?? 5,
|
|
440
|
+
maxTokenAge: this.options.maxTokenAgeSeconds ?? 3600,
|
|
441
|
+
requiredClaims: ["iss", "aud", "sub", "exp", "iat"]
|
|
442
|
+
});
|
|
443
|
+
validateTokenType(result, this.acceptedTokenTypes);
|
|
444
|
+
validateClaims(result.payload);
|
|
445
|
+
return { claims: result.payload, protectedHeader: result.protectedHeader };
|
|
446
|
+
} catch (cause) {
|
|
447
|
+
if (cause instanceof TokenVerificationError) throw cause;
|
|
448
|
+
throw new TokenVerificationError(errorCode(cause), { cause });
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
function validateTokenType(result, acceptedTokenTypes) {
|
|
453
|
+
const type = result.protectedHeader.typ;
|
|
454
|
+
if (!type || !acceptedTokenTypes.has(type)) {
|
|
455
|
+
throw new TokenVerificationError("token.invalid_claims");
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function validateClaims(claims) {
|
|
459
|
+
if (typeof claims.sub !== "string" || !claims.sub) invalidClaims();
|
|
460
|
+
if (claims.permissions !== void 0 && !isStringArray(claims.permissions)) invalidClaims();
|
|
461
|
+
if (claims.roles !== void 0 && !isStringArray(claims.roles)) invalidClaims();
|
|
462
|
+
if (claims.scope !== void 0 && typeof claims.scope !== "string") invalidClaims();
|
|
463
|
+
}
|
|
464
|
+
function validateOptions(options) {
|
|
465
|
+
const issuer = secureUrl(options.issuer, "issuer");
|
|
466
|
+
if (Boolean(options.jwksUri) === Boolean(options.jwks)) {
|
|
467
|
+
throw new Error("Authyon: configure exactly one of `jwksUri` or `jwks`");
|
|
468
|
+
}
|
|
469
|
+
const jwks = options.jwksUri ? secureUrl(options.jwksUri, "jwksUri") : void 0;
|
|
470
|
+
if (!options.audience || Array.isArray(options.audience) && options.audience.length === 0) {
|
|
471
|
+
throw new Error("Authyon: JWT `audience` is required");
|
|
472
|
+
}
|
|
473
|
+
if (jwks && issuer.origin !== jwks.origin) {
|
|
474
|
+
throw new Error("Authyon: `issuer` and `jwksUri` must use the same trusted origin");
|
|
475
|
+
}
|
|
476
|
+
const algorithms = options.algorithms ?? ["RS256"];
|
|
477
|
+
if (algorithms.length === 0 || algorithms.some((algorithm) => !SAFE_ASYMMETRIC_ALGORITHMS.includes(algorithm))) {
|
|
478
|
+
throw new Error("Authyon: only approved asymmetric JWT algorithms are accepted");
|
|
479
|
+
}
|
|
480
|
+
if (options.acceptedTokenTypes?.length === 0 || options.acceptedTokenTypes?.some((type) => !type.trim())) {
|
|
481
|
+
throw new Error("Authyon: `acceptedTokenTypes` must contain non-empty values");
|
|
482
|
+
}
|
|
483
|
+
for (const [name, value] of [
|
|
484
|
+
["clockToleranceSeconds", options.clockToleranceSeconds],
|
|
485
|
+
["maxTokenAgeSeconds", options.maxTokenAgeSeconds],
|
|
486
|
+
["jwksTimeoutMs", options.jwksTimeoutMs],
|
|
487
|
+
["jwksCacheMs", options.jwksCacheMs],
|
|
488
|
+
["jwksCooldownMs", options.jwksCooldownMs]
|
|
489
|
+
]) {
|
|
490
|
+
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) {
|
|
491
|
+
throw new Error(`Authyon: \`${name}\` must be a non-negative finite number`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
function secureUrl(value, name) {
|
|
496
|
+
let url;
|
|
497
|
+
try {
|
|
498
|
+
url = new URL(value);
|
|
499
|
+
} catch {
|
|
500
|
+
throw new Error(`Authyon: JWT \`${name}\` must be an absolute URL`);
|
|
501
|
+
}
|
|
502
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash) {
|
|
503
|
+
throw new Error(`Authyon: JWT \`${name}\` must be a credential-free HTTPS URL`);
|
|
504
|
+
}
|
|
505
|
+
return url;
|
|
506
|
+
}
|
|
507
|
+
function errorCode(error) {
|
|
508
|
+
const code = isRecord(error) && typeof error.code === "string" ? error.code : "";
|
|
509
|
+
if (code === "ERR_JWT_EXPIRED") return "token.expired";
|
|
510
|
+
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "token.invalid_signature";
|
|
511
|
+
if (code === "ERR_JWKS_TIMEOUT") {
|
|
512
|
+
return "token.key_unavailable";
|
|
52
513
|
}
|
|
53
|
-
|
|
54
|
-
|
|
514
|
+
if (code === "ERR_JWKS_NO_MATCHING_KEY") return "token.invalid_signature";
|
|
515
|
+
if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
516
|
+
const claim = isRecord(error) && typeof error.claim === "string" ? error.claim : "";
|
|
517
|
+
return claim === "nbf" ? "token.not_active" : "token.invalid_claims";
|
|
518
|
+
}
|
|
519
|
+
return "token.invalid";
|
|
520
|
+
}
|
|
521
|
+
function messageForCode(code) {
|
|
522
|
+
if (code === "token.key_unavailable") return "Token verification key is unavailable";
|
|
523
|
+
if (code === "token.expired") return "Token has expired";
|
|
524
|
+
if (code === "token.not_active") return "Token is not active yet";
|
|
525
|
+
return "Token verification failed";
|
|
526
|
+
}
|
|
527
|
+
function invalidClaims() {
|
|
528
|
+
throw new TokenVerificationError("token.invalid_claims");
|
|
529
|
+
}
|
|
530
|
+
function isStringArray(value) {
|
|
531
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
55
532
|
}
|
|
533
|
+
function isRecord(value) {
|
|
534
|
+
return typeof value === "object" && value !== null;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/client/authyonServerClient.ts
|
|
56
538
|
var AuthyonServerClient = class {
|
|
57
539
|
constructor(options = {}) {
|
|
58
|
-
this.environmentToken = null;
|
|
59
|
-
this.environmentTokenInFlight = null;
|
|
60
540
|
// ── Discovery ──────────────────────────────────────────────────────────────
|
|
61
541
|
this.discovery = {
|
|
62
542
|
/** GET /.well-known/jwks.json — the environment's public signing keys. */
|
|
@@ -330,53 +810,55 @@ var AuthyonServerClient = class {
|
|
|
330
810
|
this.envKey = options.envKey;
|
|
331
811
|
this.clientId = options.clientId;
|
|
332
812
|
this.clientSecret = options.clientSecret;
|
|
333
|
-
this.
|
|
334
|
-
|
|
813
|
+
this.transport = createSharedTransport({
|
|
814
|
+
baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
|
|
815
|
+
allowInsecureHttp: options.allowInsecureHttp,
|
|
816
|
+
timeoutMs: options.timeoutMs,
|
|
817
|
+
httpAdapter: options.httpAdapter,
|
|
818
|
+
httpLogger: options.httpLogger,
|
|
819
|
+
fetch: options.fetch
|
|
820
|
+
});
|
|
821
|
+
this.http = new JsonHttpClient(this.transport);
|
|
822
|
+
this.environmentTokenProvider = new ExpiringTokenProvider(async () => {
|
|
823
|
+
if (!this.clientId || !this.clientSecret) {
|
|
824
|
+
throw new Error(
|
|
825
|
+
"Authyon: `clientId`/`clientSecret` are required for environment management calls (mint a pair in the console, under the environment's OAuth clients)."
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
const token = await this.environmentAuth.token({
|
|
829
|
+
clientId: this.clientId,
|
|
830
|
+
clientSecret: this.clientSecret
|
|
831
|
+
});
|
|
832
|
+
return {
|
|
833
|
+
accessToken: token.access_token,
|
|
834
|
+
expiresAt: Date.now() + token.expires_in * 1e3
|
|
835
|
+
};
|
|
836
|
+
});
|
|
335
837
|
}
|
|
336
838
|
async request(path, options = {}) {
|
|
337
839
|
const headers = { ...options.headers };
|
|
338
|
-
if (options.body !== void 0) headers["Content-Type"] = "application/json";
|
|
339
840
|
if (options.envBearer) {
|
|
340
841
|
headers.Authorization = `Bearer ${await this.getEnvironmentAccessToken()}`;
|
|
341
842
|
}
|
|
342
843
|
if (this.envKey) headers["X-Authyon-Environment"] = this.envKey;
|
|
343
|
-
|
|
344
|
-
method: options.method ?? "GET",
|
|
345
|
-
headers,
|
|
346
|
-
body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
|
|
347
|
-
});
|
|
348
|
-
if (!response.ok) {
|
|
349
|
-
let body = {};
|
|
350
|
-
try {
|
|
351
|
-
body = await response.json();
|
|
352
|
-
} catch {
|
|
353
|
-
}
|
|
354
|
-
throw new AuthyonError(response.status, body);
|
|
355
|
-
}
|
|
356
|
-
if (response.status === 204) return void 0;
|
|
357
|
-
return await response.json();
|
|
844
|
+
return this.http.request(path, { ...options, headers });
|
|
358
845
|
}
|
|
359
846
|
/** Mints (and caches) an environment access token from `clientId`/`clientSecret`. */
|
|
360
847
|
async getEnvironmentAccessToken() {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
);
|
|
848
|
+
return this.environmentTokenProvider.getAccessToken();
|
|
849
|
+
}
|
|
850
|
+
/** Discovers Authyon's trusted issuer/JWKS and creates a cached local access-token verifier. */
|
|
851
|
+
async createJwksTokenVerifier(options) {
|
|
852
|
+
const { publishableKey, issuer, ...verifierOptions } = options;
|
|
853
|
+
const configuration = await this.discovery.openidConfiguration(publishableKey);
|
|
854
|
+
if (issuer && configuration.issuer !== issuer) {
|
|
855
|
+
throw new Error("Authyon: discovered JWT issuer does not match the configured issuer");
|
|
369
856
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
};
|
|
375
|
-
return token.access_token;
|
|
376
|
-
}).finally(() => {
|
|
377
|
-
this.environmentTokenInFlight = null;
|
|
857
|
+
return new JwksTokenVerifier({
|
|
858
|
+
...verifierOptions,
|
|
859
|
+
issuer: issuer ?? configuration.issuer,
|
|
860
|
+
jwksUri: configuration.jwks_uri
|
|
378
861
|
});
|
|
379
|
-
return this.environmentTokenInFlight;
|
|
380
862
|
}
|
|
381
863
|
// ── Token verification ────────────────────────────────────────────────────
|
|
382
864
|
//
|
|
@@ -387,12 +869,22 @@ var AuthyonServerClient = class {
|
|
|
387
869
|
// endpoint with only the `X-Authyon-Environment` header (no bearer)
|
|
388
870
|
// returns 401 with `WWW-Authenticate: Bearer`.
|
|
389
871
|
/** POST /auth/introspect — lightweight token introspection (RFC 7662). */
|
|
390
|
-
introspect(token) {
|
|
391
|
-
return this.request("/auth/introspect", {
|
|
872
|
+
introspect(token, context) {
|
|
873
|
+
return this.request("/auth/introspect", {
|
|
874
|
+
method: "POST",
|
|
875
|
+
envBearer: true,
|
|
876
|
+
body: { token },
|
|
877
|
+
headers: clientIpHeaders(context)
|
|
878
|
+
});
|
|
392
879
|
}
|
|
393
880
|
/** POST /auth/validate — recommended: cross-checks DB state, catches revocation immediately. */
|
|
394
|
-
async validate(token) {
|
|
395
|
-
const raw = await this.request("/auth/validate", {
|
|
881
|
+
async validate(token, context) {
|
|
882
|
+
const raw = await this.request("/auth/validate", {
|
|
883
|
+
method: "POST",
|
|
884
|
+
envBearer: true,
|
|
885
|
+
body: { token },
|
|
886
|
+
headers: clientIpHeaders(context)
|
|
887
|
+
});
|
|
396
888
|
return { valid: raw.valid, reason: raw.reason ?? null, user: raw.profile };
|
|
397
889
|
}
|
|
398
890
|
/**
|
|
@@ -415,8 +907,6 @@ var AuthyonServerClient = class {
|
|
|
415
907
|
};
|
|
416
908
|
var TenantScopedClient = class {
|
|
417
909
|
constructor(server, credentials) {
|
|
418
|
-
this.token = null;
|
|
419
|
-
this.tokenInFlight = null;
|
|
420
910
|
this.members = {
|
|
421
911
|
/**
|
|
422
912
|
* GET /tenant/members — members of the token's tenant.
|
|
@@ -473,23 +963,16 @@ var TenantScopedClient = class {
|
|
|
473
963
|
delete: (roleId) => this.request(`/tenant/roles/${encodeURIComponent(roleId)}`, { method: "DELETE" })
|
|
474
964
|
};
|
|
475
965
|
this.server = server;
|
|
476
|
-
this.
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (this.token && Date.now() < this.token.expiresAt - EXPIRY_SKEW_MS) {
|
|
480
|
-
return this.token.accessToken;
|
|
481
|
-
}
|
|
482
|
-
if (this.tokenInFlight) return this.tokenInFlight;
|
|
483
|
-
this.tokenInFlight = this.server.tenantAuth.token(this.credentials).then((token) => {
|
|
484
|
-
this.token = {
|
|
966
|
+
this.tokenProvider = new ExpiringTokenProvider(async () => {
|
|
967
|
+
const token = await this.server.tenantAuth.token(credentials);
|
|
968
|
+
return {
|
|
485
969
|
accessToken: token.access_token,
|
|
486
970
|
expiresAt: Date.now() + token.expires_in * 1e3
|
|
487
971
|
};
|
|
488
|
-
return token.access_token;
|
|
489
|
-
}).finally(() => {
|
|
490
|
-
this.tokenInFlight = null;
|
|
491
972
|
});
|
|
492
|
-
|
|
973
|
+
}
|
|
974
|
+
async getAccessToken() {
|
|
975
|
+
return this.tokenProvider.getAccessToken();
|
|
493
976
|
}
|
|
494
977
|
async request(path, options = {}) {
|
|
495
978
|
return this.server._requestAsTenant(await this.getAccessToken(), path, options);
|
|
@@ -498,10 +981,348 @@ var TenantScopedClient = class {
|
|
|
498
981
|
function createClient(options = {}) {
|
|
499
982
|
return new AuthyonServerClient(options);
|
|
500
983
|
}
|
|
984
|
+
|
|
985
|
+
// src/client/authyonServerClientBuilder.ts
|
|
986
|
+
var AuthyonServerClientBuilder = class {
|
|
987
|
+
constructor() {
|
|
988
|
+
this.options = {};
|
|
989
|
+
}
|
|
990
|
+
withEnvironmentKey(envKey) {
|
|
991
|
+
this.options.envKey = envKey;
|
|
992
|
+
return this;
|
|
993
|
+
}
|
|
994
|
+
withEnvironmentCredentials(clientId, clientSecret) {
|
|
995
|
+
this.options.clientId = clientId;
|
|
996
|
+
this.options.clientSecret = clientSecret;
|
|
997
|
+
return this;
|
|
998
|
+
}
|
|
999
|
+
withBaseUrl(baseUrl, allowInsecureHttp = false) {
|
|
1000
|
+
this.options.baseUrl = baseUrl;
|
|
1001
|
+
this.options.allowInsecureHttp = allowInsecureHttp;
|
|
1002
|
+
return this;
|
|
1003
|
+
}
|
|
1004
|
+
withTimeout(timeoutMs) {
|
|
1005
|
+
this.options.timeoutMs = timeoutMs;
|
|
1006
|
+
return this;
|
|
1007
|
+
}
|
|
1008
|
+
withHttpAdapter(httpAdapter) {
|
|
1009
|
+
this.options.httpAdapter = httpAdapter;
|
|
1010
|
+
return this;
|
|
1011
|
+
}
|
|
1012
|
+
withHttpLogger(httpLogger) {
|
|
1013
|
+
this.options.httpLogger = httpLogger;
|
|
1014
|
+
return this;
|
|
1015
|
+
}
|
|
1016
|
+
build() {
|
|
1017
|
+
return new AuthyonServerClient({ ...this.options });
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// ../../internal/core/authorization/ability.ts
|
|
1022
|
+
var AuthyonAbility = class {
|
|
1023
|
+
constructor(rules = [], detectSubjectType = defaultSubjectType) {
|
|
1024
|
+
this.detectSubjectType = detectSubjectType;
|
|
1025
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
1026
|
+
this.currentRules = rules.map(cloneRule);
|
|
1027
|
+
}
|
|
1028
|
+
get rules() {
|
|
1029
|
+
return this.currentRules;
|
|
1030
|
+
}
|
|
1031
|
+
can(action, subject, field) {
|
|
1032
|
+
const subjectType = typeof subject === "string" ? subject : this.detectSubjectType(subject);
|
|
1033
|
+
for (let index = this.currentRules.length - 1; index >= 0; index -= 1) {
|
|
1034
|
+
const rule = this.currentRules[index];
|
|
1035
|
+
if (!matchesToken(rule.action, action, "manage")) continue;
|
|
1036
|
+
if (!matchesToken(rule.subject, subjectType, "all")) continue;
|
|
1037
|
+
if (field && rule.fields && !rule.fields.some((value) => matchesField(value, field)))
|
|
1038
|
+
continue;
|
|
1039
|
+
if (rule.conditions) {
|
|
1040
|
+
if (typeof subject === "string" || !matchesConditions(subject, rule.conditions)) continue;
|
|
1041
|
+
}
|
|
1042
|
+
return !rule.inverted;
|
|
1043
|
+
}
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
cannot(action, subject, field) {
|
|
1047
|
+
return !this.can(action, subject, field);
|
|
1048
|
+
}
|
|
1049
|
+
rulesFor(action, subject) {
|
|
1050
|
+
return this.currentRules.filter(
|
|
1051
|
+
(rule) => matchesToken(rule.action, action, "manage") && matchesToken(rule.subject, subject, "all")
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
update(rules) {
|
|
1055
|
+
this.currentRules = rules.map(cloneRule);
|
|
1056
|
+
for (const listener of this.listeners) listener(this.rules);
|
|
1057
|
+
}
|
|
1058
|
+
on(event, listener) {
|
|
1059
|
+
if (event !== "updated") return () => void 0;
|
|
1060
|
+
this.listeners.add(listener);
|
|
1061
|
+
return () => this.listeners.delete(listener);
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
var AuthyonAbilityBuilder = class {
|
|
1065
|
+
constructor() {
|
|
1066
|
+
this.rules = [];
|
|
1067
|
+
}
|
|
1068
|
+
can(action, subject, conditions, fields) {
|
|
1069
|
+
this.rules.push({ action, subject, conditions, fields });
|
|
1070
|
+
return this;
|
|
1071
|
+
}
|
|
1072
|
+
cannot(action, subject, conditions, fields, reason) {
|
|
1073
|
+
this.rules.push({ action, subject, conditions, fields, reason, inverted: true });
|
|
1074
|
+
return this;
|
|
1075
|
+
}
|
|
1076
|
+
build(options = {}) {
|
|
1077
|
+
return new AuthyonAbility(this.rules, options.detectSubjectType);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
function createAuthyonAbility(source = {}, options = {}) {
|
|
1081
|
+
return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
|
|
1082
|
+
}
|
|
1083
|
+
function createAuthyonRules(source = {}, options = {}) {
|
|
1084
|
+
const permissions = /* @__PURE__ */ new Set([
|
|
1085
|
+
...source.permissions ?? [],
|
|
1086
|
+
...source.scope?.split(/\s+/).filter(Boolean) ?? []
|
|
1087
|
+
]);
|
|
1088
|
+
const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
|
|
1089
|
+
for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
|
|
1090
|
+
rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
|
|
1091
|
+
}
|
|
1092
|
+
rules.push(...(options.rules ?? []).map(cloneRule));
|
|
1093
|
+
return rules;
|
|
1094
|
+
}
|
|
1095
|
+
function permissionToRule(permission) {
|
|
1096
|
+
const normalized = permission.trim();
|
|
1097
|
+
if (!normalized) return null;
|
|
1098
|
+
if (normalized === "*" || normalized === "*:*" || normalized === "all:manage") {
|
|
1099
|
+
return { action: "manage", subject: "all" };
|
|
1100
|
+
}
|
|
1101
|
+
const separator = normalized.lastIndexOf(":");
|
|
1102
|
+
if (separator <= 0 || separator === normalized.length - 1) return null;
|
|
1103
|
+
const subject = normalized.slice(0, separator);
|
|
1104
|
+
const action = normalized.slice(separator + 1);
|
|
1105
|
+
return {
|
|
1106
|
+
action: action === "*" ? "manage" : action,
|
|
1107
|
+
subject: subject === "*" ? "all" : subject
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
function matchesToken(value, expected, wildcard) {
|
|
1111
|
+
return (Array.isArray(value) ? value : [value]).some(
|
|
1112
|
+
(candidate) => candidate === expected || candidate === wildcard || candidate === "*"
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
function matchesField(pattern, field) {
|
|
1116
|
+
if (pattern === "*" || pattern === field) return true;
|
|
1117
|
+
return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
|
|
1118
|
+
}
|
|
1119
|
+
function matchesConditions(subject, conditions) {
|
|
1120
|
+
return Object.entries(conditions).every(([path, expected]) => {
|
|
1121
|
+
if (path === "$and" && Array.isArray(expected)) {
|
|
1122
|
+
return expected.every(
|
|
1123
|
+
(condition) => matchesConditions(subject, condition)
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
if (path === "$or" && Array.isArray(expected)) {
|
|
1127
|
+
return expected.some(
|
|
1128
|
+
(condition) => matchesConditions(subject, condition)
|
|
1129
|
+
);
|
|
1130
|
+
}
|
|
1131
|
+
return matchesValue(readPath(subject, path), expected);
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
function matchesValue(actual, expected) {
|
|
1135
|
+
if (!isRecord2(expected) || !Object.keys(expected).some((key) => key.startsWith("$"))) {
|
|
1136
|
+
return isRecord2(expected) && isRecord2(actual) ? matchesConditions(actual, expected) : Object.is(actual, expected);
|
|
1137
|
+
}
|
|
1138
|
+
return Object.entries(expected).every(([operator, operand]) => {
|
|
1139
|
+
switch (operator) {
|
|
1140
|
+
case "$eq":
|
|
1141
|
+
return Object.is(actual, operand);
|
|
1142
|
+
case "$ne":
|
|
1143
|
+
return !Object.is(actual, operand);
|
|
1144
|
+
case "$in":
|
|
1145
|
+
return Array.isArray(operand) && operand.some((value) => Object.is(actual, value));
|
|
1146
|
+
case "$nin":
|
|
1147
|
+
return Array.isArray(operand) && !operand.some((value) => Object.is(actual, value));
|
|
1148
|
+
case "$gt":
|
|
1149
|
+
return typeof actual === "number" && typeof operand === "number" && actual > operand;
|
|
1150
|
+
case "$gte":
|
|
1151
|
+
return typeof actual === "number" && typeof operand === "number" && actual >= operand;
|
|
1152
|
+
case "$lt":
|
|
1153
|
+
return typeof actual === "number" && typeof operand === "number" && actual < operand;
|
|
1154
|
+
case "$lte":
|
|
1155
|
+
return typeof actual === "number" && typeof operand === "number" && actual <= operand;
|
|
1156
|
+
case "$exists":
|
|
1157
|
+
return operand ? actual !== void 0 : actual === void 0;
|
|
1158
|
+
default:
|
|
1159
|
+
return false;
|
|
1160
|
+
}
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
function readPath(value, path) {
|
|
1164
|
+
return path.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
|
|
1165
|
+
}
|
|
1166
|
+
function defaultSubjectType(subject) {
|
|
1167
|
+
const explicit = subject.__type ?? subject.type ?? subject.kind;
|
|
1168
|
+
if (typeof explicit === "string") return explicit;
|
|
1169
|
+
const constructorName = subject.constructor?.name;
|
|
1170
|
+
return typeof constructorName === "string" ? constructorName : "Object";
|
|
1171
|
+
}
|
|
1172
|
+
function cloneRule(rule) {
|
|
1173
|
+
return {
|
|
1174
|
+
...rule,
|
|
1175
|
+
action: Array.isArray(rule.action) ? [...rule.action] : rule.action,
|
|
1176
|
+
subject: Array.isArray(rule.subject) ? [...rule.subject] : rule.subject,
|
|
1177
|
+
fields: rule.fields ? [...rule.fields] : void 0
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
function isRecord2(value) {
|
|
1181
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1182
|
+
}
|
|
1183
|
+
function isAbilityRule(value) {
|
|
1184
|
+
return value !== null;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// src/integrations/authorization.ts
|
|
1188
|
+
var AuthorizationError = class extends Error {
|
|
1189
|
+
constructor(status, code, message) {
|
|
1190
|
+
super(message);
|
|
1191
|
+
this.status = status;
|
|
1192
|
+
this.code = code;
|
|
1193
|
+
this.name = "AuthorizationError";
|
|
1194
|
+
}
|
|
1195
|
+
};
|
|
1196
|
+
async function authorizeToken(client, token, options = {}) {
|
|
1197
|
+
if (!token) throw unauthenticated();
|
|
1198
|
+
let userId;
|
|
1199
|
+
let permissions = [];
|
|
1200
|
+
let roles = [];
|
|
1201
|
+
let scope;
|
|
1202
|
+
if (options.verification === "jwks") {
|
|
1203
|
+
if (!options.jwksVerifier) {
|
|
1204
|
+
throw new Error("Authyon: `jwksVerifier` is required for JWKS verification");
|
|
1205
|
+
}
|
|
1206
|
+
let verified;
|
|
1207
|
+
try {
|
|
1208
|
+
verified = await options.jwksVerifier.verifyAccessToken(token);
|
|
1209
|
+
} catch (error) {
|
|
1210
|
+
if (!(error instanceof TokenVerificationError)) throw error;
|
|
1211
|
+
if (error.code === "token.key_unavailable") {
|
|
1212
|
+
throw new AuthorizationError(
|
|
1213
|
+
503,
|
|
1214
|
+
"authorization.unavailable",
|
|
1215
|
+
"Token verification is temporarily unavailable"
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
throw unauthenticated();
|
|
1219
|
+
}
|
|
1220
|
+
const { claims } = verified;
|
|
1221
|
+
userId = claims.sub;
|
|
1222
|
+
permissions = claims.permissions ?? [];
|
|
1223
|
+
roles = claims.roles ?? [];
|
|
1224
|
+
scope = claims.scope;
|
|
1225
|
+
} else if (options.verification === "introspect") {
|
|
1226
|
+
const identity = await client.introspect(token, { clientIp: options.clientIp });
|
|
1227
|
+
if (!identity.active) throw unauthenticated();
|
|
1228
|
+
userId = identity.sub;
|
|
1229
|
+
permissions = identity.permissions ?? [];
|
|
1230
|
+
roles = identity.roles ?? [];
|
|
1231
|
+
scope = identity.scope;
|
|
1232
|
+
} else {
|
|
1233
|
+
const identity = await client.validate(token, { clientIp: options.clientIp });
|
|
1234
|
+
if (!identity.valid || !identity.user) throw unauthenticated();
|
|
1235
|
+
userId = identity.user.id;
|
|
1236
|
+
permissions = identity.user.permissions ?? [];
|
|
1237
|
+
}
|
|
1238
|
+
const ability = createAuthyonAbility(
|
|
1239
|
+
{ permissions, roles, scope },
|
|
1240
|
+
{
|
|
1241
|
+
rules: options.rules,
|
|
1242
|
+
roleRules: options.roleRules,
|
|
1243
|
+
roles: options.roles,
|
|
1244
|
+
detectSubjectType: options.detectSubjectType
|
|
1245
|
+
}
|
|
1246
|
+
);
|
|
1247
|
+
if (options.requirement && !canAccess(ability, options.requirement)) {
|
|
1248
|
+
throw new AuthorizationError(403, "authorization.forbidden", "Permission denied");
|
|
1249
|
+
}
|
|
1250
|
+
return { token, userId, ability, permissions, roles };
|
|
1251
|
+
}
|
|
1252
|
+
function authorizeRequest(client, request, options = {}) {
|
|
1253
|
+
const clientIp = options.resolveClientIp?.(request) ?? options.clientIp;
|
|
1254
|
+
return authorizeToken(client, bearerToken(request.headers.get("authorization")), {
|
|
1255
|
+
...options,
|
|
1256
|
+
clientIp
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
function createExpressAuthorizationMiddleware(client, options = {}) {
|
|
1260
|
+
return async (request, response, next) => {
|
|
1261
|
+
try {
|
|
1262
|
+
const header = request.headers.authorization;
|
|
1263
|
+
const clientIp = resolveExpressClientIp(request, options);
|
|
1264
|
+
const context = await authorizeToken(
|
|
1265
|
+
client,
|
|
1266
|
+
bearerToken(Array.isArray(header) ? header[0] : header),
|
|
1267
|
+
{ ...options, clientIp }
|
|
1268
|
+
);
|
|
1269
|
+
request[options.requestProperty ?? "authyon"] = context;
|
|
1270
|
+
next();
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
if (options.passErrorsToNext || !(error instanceof AuthorizationError)) {
|
|
1273
|
+
next(error);
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
response.status(error.status).json({ code: error.code, message: error.message });
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
function resolveExpressClientIp(request, options) {
|
|
1281
|
+
const resolved = options.resolveClientIp?.(request) ?? (options.trustProxy ? request.ip : request.socket?.remoteAddress);
|
|
1282
|
+
return resolved ? normalizeClientIp(stripIpv4Prefix(resolved)) : void 0;
|
|
1283
|
+
}
|
|
1284
|
+
function stripIpv4Prefix(value) {
|
|
1285
|
+
return value.startsWith("::ffff:") ? value.slice(7) : value;
|
|
1286
|
+
}
|
|
1287
|
+
function createAuthorizationErrorResponse(error) {
|
|
1288
|
+
if (!(error instanceof AuthorizationError)) throw error;
|
|
1289
|
+
return Response.json({ code: error.code, message: error.message }, { status: error.status });
|
|
1290
|
+
}
|
|
1291
|
+
function canAccess(ability, requirement) {
|
|
1292
|
+
return ability.can(requirement.action, requirement.subject, requirement.field);
|
|
1293
|
+
}
|
|
1294
|
+
function bearerToken(header) {
|
|
1295
|
+
const match = header?.match(/^Bearer\s+(.+)$/i);
|
|
1296
|
+
if (!match?.[1]) throw unauthenticated();
|
|
1297
|
+
return match[1].trim();
|
|
1298
|
+
}
|
|
1299
|
+
function unauthenticated() {
|
|
1300
|
+
return new AuthorizationError(
|
|
1301
|
+
401,
|
|
1302
|
+
"authorization.unauthenticated",
|
|
1303
|
+
"A valid bearer token is required"
|
|
1304
|
+
);
|
|
1305
|
+
}
|
|
501
1306
|
// Annotate the CommonJS export names for ESM import in node:
|
|
502
1307
|
0 && (module.exports = {
|
|
1308
|
+
AuthorizationError,
|
|
1309
|
+
AuthyonAbility,
|
|
1310
|
+
AuthyonAbilityBuilder,
|
|
503
1311
|
AuthyonError,
|
|
504
1312
|
AuthyonServerClient,
|
|
1313
|
+
AuthyonServerClientBuilder,
|
|
1314
|
+
ErrorCodes,
|
|
1315
|
+
FetchHttpAdapter,
|
|
1316
|
+
JwksTokenVerifier,
|
|
1317
|
+
LoggingHttpAdapter,
|
|
505
1318
|
TenantScopedClient,
|
|
506
|
-
|
|
1319
|
+
TokenVerificationError,
|
|
1320
|
+
authorizeRequest,
|
|
1321
|
+
authorizeToken,
|
|
1322
|
+
createAuthorizationErrorResponse,
|
|
1323
|
+
createAuthyonAbility,
|
|
1324
|
+
createAuthyonRules,
|
|
1325
|
+
createClient,
|
|
1326
|
+
createExpressAuthorizationMiddleware,
|
|
1327
|
+
normalizeClientIp
|
|
507
1328
|
});
|