@authyon/server 0.2.0-beta.0 → 0.2.0-beta.2

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