@authyon/server 0.2.0-beta.5 → 0.2.0-beta.8

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,12 +1,19 @@
1
+ import {
2
+ AuthyonError,
3
+ DEFAULT_BASE_URL,
4
+ DEFAULT_EXPIRY_SKEW_MS,
5
+ ErrorCodes,
6
+ FetchHttpAdapter,
7
+ JsonHttpClient,
8
+ LoggingHttpAdapter,
9
+ createSharedTransport
10
+ } from "./chunk-56H66KLG.js";
1
11
  import {
2
12
  AuthorizationError,
3
13
  AuthyonAbility,
4
14
  AuthyonAbilityBuilder,
5
15
  JwksTokenVerifier,
6
16
  TokenVerificationError,
7
- __privateAdd,
8
- __privateGet,
9
- __privateSet,
10
17
  authorizeRequest,
11
18
  authorizeToken,
12
19
  clientIpHeaders,
@@ -15,8 +22,14 @@ import {
15
22
  createAuthyonRules,
16
23
  createExpressAuthorizationMiddleware,
17
24
  hasPermission,
25
+ hasPermissionGroup,
18
26
  normalizeClientIp
19
- } from "./chunk-24IFDJ73.js";
27
+ } from "./chunk-NKWQMYB3.js";
28
+ import {
29
+ __privateAdd,
30
+ __privateGet,
31
+ __privateSet
32
+ } from "./chunk-77J4NURK.js";
20
33
 
21
34
  // src/client/credentialManagement.ts
22
35
  function segment(value) {
@@ -262,10 +275,6 @@ var WorkspaceInvitesClient = class {
262
275
  };
263
276
  _request3 = new WeakMap();
264
277
 
265
- // ../../internal/core/config/defaults.ts
266
- var DEFAULT_BASE_URL = "https://api.authyon.com";
267
- var DEFAULT_EXPIRY_SKEW_MS = 3e4;
268
-
269
278
  // ../../internal/core/auth/expiringTokenProvider.ts
270
279
  var _token, _inFlight;
271
280
  var ExpiringTokenProvider = class {
@@ -295,315 +304,6 @@ var ExpiringTokenProvider = class {
295
304
  _token = new WeakMap();
296
305
  _inFlight = new WeakMap();
297
306
 
298
- // ../../internal/core/errors/authyonError.ts
299
- var ErrorCodes = {
300
- Unknown: "unknown",
301
- NetworkError: "request.network_error",
302
- Timeout: "request.timeout",
303
- SessionMalformed: "session.malformed",
304
- NotAuthenticated: "auth.not_authenticated",
305
- InvalidToken: "auth.invalid_token",
306
- MissingToken: "auth.missing_token",
307
- EmailTaken: "user.email_taken",
308
- PasswordWeak: "user.password_weak",
309
- PasswordPwned: "user.password_pwned",
310
- RateLimited: "rate_limited"
311
- };
312
- var AuthyonError = class extends Error {
313
- constructor(status, body, options = {}) {
314
- super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
315
- this.name = "AuthyonError";
316
- this.status = status;
317
- this.code = body.code ?? "unknown";
318
- this.title = body.title ?? "Error";
319
- this.detail = body.detail;
320
- this.requestId = options.requestId;
321
- this.retryAfter = options.retryAfter;
322
- this.cause = options.cause;
323
- }
324
- is(code) {
325
- return this.code === code;
326
- }
327
- isAny(...codes) {
328
- return codes.includes(this.code);
329
- }
330
- hasPrefix(prefix) {
331
- return this.code.startsWith(prefix);
332
- }
333
- isStatus(...statuses) {
334
- return statuses.includes(this.status);
335
- }
336
- /** Stable interpretation for UI decisions, retries, telemetry and support flows. */
337
- interpret() {
338
- const category = classifyError(this.status, this.code);
339
- return {
340
- category,
341
- action: actionFor(category),
342
- retryable: isRetryable(category),
343
- ...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
344
- ...this.requestId !== void 0 ? { requestId: this.requestId } : {}
345
- };
346
- }
347
- get category() {
348
- return this.interpret().category;
349
- }
350
- get retryable() {
351
- return this.interpret().retryable;
352
- }
353
- toJSON() {
354
- return {
355
- name: this.name,
356
- message: this.message,
357
- status: this.status,
358
- code: this.code,
359
- title: this.title,
360
- detail: this.detail,
361
- requestId: this.requestId,
362
- retryAfter: this.retryAfter,
363
- ...this.interpret()
364
- };
365
- }
366
- };
367
- function classifyError(status, code) {
368
- if (code === ErrorCodes.NetworkError) return "network";
369
- if (code === ErrorCodes.Timeout || status === 408) return "timeout";
370
- if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
371
- if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
372
- if (code === ErrorCodes.PasswordWeak || code === ErrorCodes.PasswordPwned) return "validation";
373
- if (code === ErrorCodes.SessionMalformed) return "server";
374
- if (code.startsWith("auth.") || status === 401) return "authentication";
375
- if (status === 403) return "authorization";
376
- if (status === 404) return "not_found";
377
- if (status === 400 || status === 422) return "validation";
378
- if (status >= 500) return "server";
379
- return "unknown";
380
- }
381
- function actionFor(category) {
382
- switch (category) {
383
- case "network":
384
- case "timeout":
385
- case "rate_limit":
386
- case "server":
387
- return "retry";
388
- case "authentication":
389
- return "reauthenticate";
390
- case "authorization":
391
- return "request_access";
392
- case "validation":
393
- return "fix_input";
394
- case "not_found":
395
- return "not_found";
396
- case "conflict":
397
- return "resolve_conflict";
398
- case "unknown":
399
- return "contact_support";
400
- }
401
- }
402
- function isRetryable(category) {
403
- return category === "network" || category === "timeout" || category === "rate_limit" || category === "server";
404
- }
405
-
406
- // ../../internal/core/http/query.ts
407
- function appendQuery(path, params) {
408
- if (!params) return path;
409
- const query = new URLSearchParams();
410
- for (const [key, value2] of Object.entries(params)) {
411
- if (value2 !== void 0) query.set(key, String(value2));
412
- }
413
- const value = query.toString();
414
- return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
415
- }
416
-
417
- // ../../internal/core/http/httpAdapter.ts
418
- var FetchHttpAdapter = class {
419
- constructor(fetchImpl = fetch.bind(globalThis)) {
420
- this.fetchImpl = fetchImpl;
421
- }
422
- request(request) {
423
- return this.fetchImpl(request.url, {
424
- method: request.method,
425
- headers: request.headers,
426
- body: request.body,
427
- signal: request.signal,
428
- redirect: "error"
429
- });
430
- }
431
- };
432
- var LoggingHttpAdapter = class {
433
- constructor(adapter, options) {
434
- this.adapter = adapter;
435
- this.options = options;
436
- }
437
- async request(request) {
438
- const startedAt = Date.now();
439
- const eventBase = {
440
- method: request.method,
441
- url: sanitizeUrl(request.url)
442
- };
443
- this.log({ type: "request", ...eventBase, timestamp: startedAt });
444
- try {
445
- const response = await this.adapter.request(request);
446
- this.log({
447
- type: "response",
448
- ...eventBase,
449
- status: response.status,
450
- durationMs: Date.now() - startedAt,
451
- requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
452
- timestamp: Date.now()
453
- });
454
- return response;
455
- } catch (error) {
456
- this.log({
457
- type: "error",
458
- ...eventBase,
459
- errorName: error instanceof Error ? error.name : "UnknownError",
460
- durationMs: Date.now() - startedAt,
461
- timestamp: Date.now()
462
- });
463
- throw error;
464
- }
465
- }
466
- log(event) {
467
- if (!this.options.enabled) return;
468
- const logger = this.options.logger ?? defaultHttpLogger;
469
- try {
470
- logger(event);
471
- } catch {
472
- }
473
- }
474
- };
475
- function defaultHttpLogger(event) {
476
- console.debug("[Authyon HTTP]", event);
477
- }
478
- function sanitizeUrl(value) {
479
- const url = new URL(value);
480
- url.username = "";
481
- url.password = "";
482
- url.hash = "";
483
- url.pathname = url.pathname.replace(/(\/platform\/workspace-invites\/)[^/]+/u, "$1REDACTED");
484
- const queryKeys = /* @__PURE__ */ new Set();
485
- url.searchParams.forEach((_value, key) => queryKeys.add(key));
486
- url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
487
- return url.toString();
488
- }
489
-
490
- // ../../internal/core/http/transport.ts
491
- var DEFAULT_TIMEOUT_MS = 15e3;
492
- var SharedTransportError = class extends Error {
493
- constructor(code, cause) {
494
- super(code === "request.timeout" ? "Request timed out" : "Network request failed");
495
- this.name = "SharedTransportError";
496
- this.code = code;
497
- this.cause = cause;
498
- }
499
- };
500
- function createSharedTransport(options) {
501
- const baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureHttp ?? false);
502
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
503
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
504
- throw new Error("Authyon: `timeoutMs` must be a non-negative finite number");
505
- }
506
- if (options.httpAdapter && options.fetch) {
507
- throw new Error("Authyon: use either `httpAdapter` or `fetch`, not both");
508
- }
509
- const baseAdapter = options.httpAdapter ?? new FetchHttpAdapter(options.fetch);
510
- const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
511
- return {
512
- baseUrl,
513
- async request(path, init) {
514
- const controller = new AbortController();
515
- const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
516
- try {
517
- return await httpAdapter.request({
518
- url: `${baseUrl}${path}`,
519
- method: init.method ?? "GET",
520
- headers: normalizeHeaders(init.headers),
521
- body: init.body,
522
- signal: controller.signal
523
- });
524
- } catch (cause) {
525
- throw new SharedTransportError(
526
- controller.signal.aborted ? ErrorCodes.Timeout : ErrorCodes.NetworkError,
527
- cause
528
- );
529
- } finally {
530
- if (timeout !== void 0) clearTimeout(timeout);
531
- }
532
- }
533
- };
534
- }
535
- function normalizeHeaders(headers) {
536
- const normalized = {};
537
- new Headers(headers).forEach((value, key) => {
538
- normalized[key] = value;
539
- });
540
- return normalized;
541
- }
542
- function responseMetadata(response) {
543
- const retryAfterHeader = response.headers.get("retry-after");
544
- const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : void 0;
545
- return {
546
- requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
547
- retryAfter: Number.isFinite(retryAfter) ? retryAfter : void 0
548
- };
549
- }
550
- function normalizeBaseUrl(value, allowInsecureHttp) {
551
- let url;
552
- try {
553
- url = new URL(value);
554
- } catch {
555
- throw new Error("Authyon: `baseUrl` must be an absolute URL");
556
- }
557
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
558
- if (url.protocol !== "https:" && !(url.protocol === "http:" && (loopback || allowInsecureHttp))) {
559
- throw new Error(
560
- "Authyon: `baseUrl` must use HTTPS (HTTP is allowed only for loopback or with `allowInsecureHttp`)"
561
- );
562
- }
563
- if (url.username || url.password || url.search || url.hash) {
564
- throw new Error(
565
- "Authyon: `baseUrl` cannot contain credentials, query parameters, or fragments"
566
- );
567
- }
568
- return url.toString().replace(/\/+$/, "");
569
- }
570
-
571
- // ../../internal/core/http/jsonHttpClient.ts
572
- var JsonHttpClient = class {
573
- constructor(transport) {
574
- this.transport = transport;
575
- }
576
- async send(path, options = {}) {
577
- const headers = { ...options.headers };
578
- if (options.body !== void 0) headers["Content-Type"] = "application/json";
579
- try {
580
- return await this.transport.request(appendQuery(path, options.query), {
581
- method: options.method ?? "GET",
582
- headers,
583
- body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
584
- });
585
- } catch (cause) {
586
- if (!(cause instanceof SharedTransportError)) throw cause;
587
- throw new AuthyonError(0, { code: cause.code, title: cause.message }, { cause: cause.cause });
588
- }
589
- }
590
- async parse(response) {
591
- if (!response.ok) {
592
- let body = {};
593
- try {
594
- body = await response.json();
595
- } catch {
596
- }
597
- throw new AuthyonError(response.status, body, responseMetadata(response));
598
- }
599
- if (response.status === 204) return void 0;
600
- return await response.json();
601
- }
602
- async request(path, options = {}) {
603
- return this.parse(await this.send(path, options));
604
- }
605
- };
606
-
607
307
  // src/client/authyonServerClient.ts
608
308
  var _clientSecret;
609
309
  var AuthyonServerClient = class {
@@ -642,6 +342,14 @@ var AuthyonServerClient = class {
642
342
  client_id: credentials.clientId,
643
343
  client_secret: credentials.clientSecret
644
344
  }
345
+ }),
346
+ /** POST /tenant/auth/validate — validates an already-minted tenant-client bearer token. */
347
+ validate: (accessToken, context) => this.request("/tenant/auth/validate", {
348
+ method: "POST",
349
+ headers: {
350
+ ...clientIpHeaders(context),
351
+ Authorization: `Bearer ${accessToken}`
352
+ }
645
353
  })
646
354
  };
647
355
  this.workspaceInvites = new WorkspaceInvitesClient(
@@ -760,7 +468,11 @@ var AuthyonServerClient = class {
760
468
  create: (tenantId, input) => this.request(`/env/tenants/${segment(tenantId)}/credentials`, {
761
469
  method: "POST",
762
470
  envBearer: true,
763
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
471
+ body: {
472
+ description: input.description,
473
+ ...lifetimeBody(input),
474
+ ...permissionsBody(input)
475
+ }
764
476
  }),
765
477
  /** Returns a new secret once while keeping the same client id. */
766
478
  rotate: (tenantId, credentialId) => this.request(
@@ -791,7 +503,18 @@ var AuthyonServerClient = class {
791
503
  envBearer: true,
792
504
  body: input
793
505
  }),
794
- /** DELETE /env/tenants/{tenantId} — delete a tenant. */
506
+ /** PUT /env/tenants/{tenantId}/metadata - replace public and private metadata. */
507
+ updateMetadata: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/metadata`, {
508
+ method: "PUT",
509
+ envBearer: true,
510
+ body: input
511
+ }),
512
+ /** POST /env/tenants/{tenantId}/disable — disable without removing tenant data. */
513
+ disable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/disable`, {
514
+ method: "POST",
515
+ envBearer: true
516
+ }),
517
+ /** DELETE /env/tenants/{tenantId} — logically delete (disable) a tenant. */
795
518
  delete: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
796
519
  method: "DELETE",
797
520
  envBearer: true
@@ -926,6 +649,7 @@ var AuthyonServerClient = class {
926
649
  this.envKey = options.envKey;
927
650
  this.clientId = options.clientId;
928
651
  __privateSet(this, _clientSecret, options.clientSecret);
652
+ this.clientIp = options.clientIp;
929
653
  this.transport = createSharedTransport({
930
654
  baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
931
655
  allowInsecureHttp: options.allowInsecureHttp,
@@ -952,7 +676,10 @@ var AuthyonServerClient = class {
952
676
  });
953
677
  }
954
678
  async request(path, options = {}) {
955
- const headers = { ...options.headers };
679
+ const headers = {
680
+ ...clientIpHeaders({ clientIp: this.clientIp }),
681
+ ...options.headers
682
+ };
956
683
  if (options.envBearer) {
957
684
  headers.Authorization = `Bearer ${await this.getEnvironmentAccessToken()}`;
958
685
  }
@@ -1103,8 +830,8 @@ var TenantScopedClient = class {
1103
830
  return this.server._requestAsTenant(await this.getAccessToken(), path, options);
1104
831
  }
1105
832
  /** POST /tenant/auth/validate — validates this tenant client's current bearer token. */
1106
- validate() {
1107
- return this.request("/tenant/auth/validate", { method: "POST" });
833
+ async validate(context) {
834
+ return this.server.tenantAuth.validate(await this.getAccessToken(), context);
1108
835
  }
1109
836
  };
1110
837
  function createClient(options = {}) {
@@ -1126,6 +853,10 @@ var AuthyonServerClientBuilder = class {
1126
853
  __privateGet(this, _options).clientSecret = clientSecret;
1127
854
  return this;
1128
855
  }
856
+ withClientIp(clientIp) {
857
+ __privateGet(this, _options).clientIp = clientIp;
858
+ return this;
859
+ }
1129
860
  withBaseUrl(baseUrl, allowInsecureHttp = false) {
1130
861
  __privateGet(this, _options).baseUrl = baseUrl;
1131
862
  __privateGet(this, _options).allowInsecureHttp = allowInsecureHttp;
@@ -1172,5 +903,6 @@ export {
1172
903
  createClient,
1173
904
  createExpressAuthorizationMiddleware,
1174
905
  hasPermission,
906
+ hasPermissionGroup,
1175
907
  normalizeClientIp
1176
908
  };
package/dist/next.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ReactNode } from 'react';
2
- import { R as RequestAuthorizationOptions, A as AuthyonServerClient, a as AbilitySubject, b as AuthorizationError } from './authorization-NQe6R3am.cjs';
2
+ import { R as RequestAuthorizationOptions, A as AbilitySubject, a as AuthorizationError } from './authorization-DPlRA9qM.cjs';
3
+ import { A as AuthyonServerClient } from './authyonServerClient-D8r47VSq.cjs';
3
4
  import 'jose';
4
5
 
5
6
  interface ServerPermissionGuardFallbackContext {
package/dist/next.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ReactNode } from 'react';
2
- import { R as RequestAuthorizationOptions, A as AuthyonServerClient, a as AbilitySubject, b as AuthorizationError } from './authorization-NQe6R3am.js';
2
+ import { R as RequestAuthorizationOptions, A as AbilitySubject, a as AuthorizationError } from './authorization-BZTzR6iu.js';
3
+ import { A as AuthyonServerClient } from './authyonServerClient-D8r47VSq.js';
3
4
  import 'jose';
4
5
 
5
6
  interface ServerPermissionGuardFallbackContext {
package/dist/next.js CHANGED
@@ -2,7 +2,8 @@ import {
2
2
  AuthorizationError,
3
3
  authorizeRequest,
4
4
  authorizeToken
5
- } from "./chunk-24IFDJ73.js";
5
+ } from "./chunk-NKWQMYB3.js";
6
+ import "./chunk-77J4NURK.js";
6
7
 
7
8
  // src/next.ts
8
9
  async function PermissionGuard({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authyon/server",
3
- "version": "0.2.0-beta.5",
3
+ "version": "0.2.0-beta.8",
4
4
  "description": "Authyon SDK for backends — server-to-server organization/member management and access-token verification.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,6 +27,13 @@
27
27
  "require": "./dist/index.cjs",
28
28
  "default": "./dist/index.js"
29
29
  },
30
+ "./bff": {
31
+ "types": "./dist/bff.d.ts",
32
+ "browser": "./dist/browser.js",
33
+ "import": "./dist/bff.js",
34
+ "require": "./dist/bff.cjs",
35
+ "default": "./dist/bff.js"
36
+ },
30
37
  "./next": {
31
38
  "types": "./dist/next.d.ts",
32
39
  "import": "./dist/next.js",
@@ -43,7 +50,7 @@
43
50
  "provenance": true
44
51
  },
45
52
  "scripts": {
46
- "build": "tsup src/index.ts src/browser.ts src/next.ts --format esm,cjs --dts --clean",
53
+ "build": "tsup src/index.ts src/browser.ts src/next.ts src/bff.ts --format esm,cjs --dts --clean",
47
54
  "typecheck": "tsc --noEmit",
48
55
  "prepack": "npm run build"
49
56
  },
@@ -66,6 +73,7 @@
66
73
  }
67
74
  },
68
75
  "devDependencies": {
76
+ "@types/node": "^22.20.2",
69
77
  "@types/react": "^19.2.18",
70
78
  "tsup": "^8.0.0",
71
79
  "typescript": "^5.5.0"