@iqauth/sdk 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +24 -0
  2. package/dist/browser-session.d.mts +1 -2
  3. package/dist/browser-session.d.ts +1 -2
  4. package/dist/browser-session.js +89 -68
  5. package/dist/browser-session.mjs +2 -1
  6. package/dist/browser.d.mts +1 -1
  7. package/dist/browser.d.ts +1 -1
  8. package/dist/browser.js +13 -2
  9. package/dist/browser.mjs +2 -2
  10. package/dist/{chunk-D72UL5HL.mjs → chunk-EKTNEZIH.mjs} +4 -4
  11. package/dist/{chunk-M4J6BPK7.mjs → chunk-KGEPDXHU.mjs} +10 -1
  12. package/dist/{chunk-QZB745C2.mjs → chunk-RACIPVLD.mjs} +13 -2
  13. package/dist/chunk-UNYDG2L4.mjs +209 -0
  14. package/dist/{chunk-MDUHPQMM.mjs → chunk-W3F4JYGP.mjs} +8 -180
  15. package/dist/{chunk-QEJB7WEQ.mjs → chunk-WQWBJSSS.mjs} +1 -1
  16. package/dist/cli/index.mjs +1 -1
  17. package/dist/{client-DXbHb2ul.d.ts → client-DTX4hNdS.d.ts} +16 -21
  18. package/dist/{client-Dv4v92Mj.d.mts → client-vdh2a9fJ.d.mts} +16 -21
  19. package/dist/{doctor-XCI77BQS.mjs → doctor-A5E7LSFW.mjs} +1 -1
  20. package/dist/{express-BZmF1llh.d.mts → express-A0-dWEMy.d.mts} +1 -1
  21. package/dist/{express-B4o3P8vK.d.ts → express-Bo_pJKHN.d.ts} +1 -1
  22. package/dist/express.d.mts +75 -5
  23. package/dist/express.d.ts +75 -5
  24. package/dist/express.js +300 -70
  25. package/dist/express.mjs +208 -7
  26. package/dist/fastify.js +101 -70
  27. package/dist/fastify.mjs +8 -6
  28. package/dist/hono.js +100 -70
  29. package/dist/hono.mjs +7 -6
  30. package/dist/index.d.mts +2 -3
  31. package/dist/index.d.ts +2 -3
  32. package/dist/index.js +90 -69
  33. package/dist/index.mjs +15 -13
  34. package/dist/mobile.d.mts +1 -2
  35. package/dist/mobile.d.ts +1 -2
  36. package/dist/mobile.js +89 -68
  37. package/dist/mobile.mjs +2 -1
  38. package/dist/next.d.mts +9 -0
  39. package/dist/next.d.ts +9 -0
  40. package/dist/next.js +99 -1616
  41. package/dist/next.mjs +9 -9
  42. package/dist/react.d.mts +1 -1
  43. package/dist/react.d.ts +1 -1
  44. package/dist/react.js +13 -2
  45. package/dist/react.mjs +2 -2
  46. package/dist/server/handlers.d.mts +2 -0
  47. package/dist/server/handlers.d.ts +2 -0
  48. package/dist/server/handlers.js +10 -1
  49. package/dist/server/handlers.mjs +2 -2
  50. package/dist/server.d.mts +2 -3
  51. package/dist/server.d.ts +2 -3
  52. package/dist/server.js +99 -69
  53. package/dist/server.mjs +7 -6
  54. package/dist/service.d.mts +1 -2
  55. package/dist/service.d.ts +1 -2
  56. package/dist/service.js +89 -68
  57. package/dist/service.mjs +2 -1
  58. package/dist/{signIn-D_kP3v-c.d.mts → signIn-Cd0P4y9d.d.mts} +8 -0
  59. package/dist/{signIn-BVDTIA_t.d.ts → signIn-DKakyzeu.d.ts} +8 -0
  60. package/package.json +3 -2
package/dist/hono.js CHANGED
@@ -406,8 +406,7 @@ function parseMfaResponse(data, browserSessionMode) {
406
406
  }
407
407
 
408
408
  // src/modules/tokens.ts
409
- var import_crypto = __toESM(require("crypto"));
410
- var import_jsonwebtoken = __toESM(require("jsonwebtoken"));
409
+ var import_jose = require("jose");
411
410
  var JWKS_CACHE_TTL_MS = 60 * 60 * 1e3;
412
411
  var DEFAULT_TOKEN_ISSUER = [
413
412
  "https://auth.dispositioniq.com",
@@ -420,6 +419,24 @@ var DEFAULT_TOKEN_AUDIENCE = [
420
419
  "iqvalidate"
421
420
  ];
422
421
  var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
422
+ function decodeProtectedHeader(token) {
423
+ const parts = token.split(".");
424
+ if (parts.length < 2) return null;
425
+ try {
426
+ const padded = parts[0] + "=".repeat((4 - parts[0].length % 4) % 4);
427
+ const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
428
+ let json;
429
+ if (typeof atob === "function") {
430
+ json = atob(b64);
431
+ } else {
432
+ const { Buffer: Buffer2 } = require("buffer");
433
+ json = Buffer2.from(b64, "base64").toString("utf8");
434
+ }
435
+ return JSON.parse(json);
436
+ } catch {
437
+ return null;
438
+ }
439
+ }
423
440
  var TokensModule = class {
424
441
  constructor(baseUrl, options = {}) {
425
442
  this.jwksCache = null;
@@ -430,49 +447,49 @@ var TokensModule = class {
430
447
  this.defaultClockTolerance = options.clockTolerance ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;
431
448
  }
432
449
  /**
433
- * Verify a JWT access token using RS256 via JWKS from /.well-known/jwks.json.
434
- * Caches JWKS keys for 1 hour. Retries once on unknown `kid`.
435
- *
436
- * @remarks Validates against /.well-known/jwks.json. Issuer, audience, and
437
- * clock tolerance default to client config but can be overridden per call.
450
+ * Verify a JWT access token using RS256/ES256 via JWKS from
451
+ * `/.well-known/jwks.json`. Backed by `jose` (Web Crypto) so it runs on
452
+ * Node, browser, and edge runtimes alike — no `node:crypto` dependency.
453
+ * Caches JWKS for 1 hour and refetches once on unknown `kid`.
438
454
  */
439
455
  async verify(token, options = {}) {
440
- const decoded = import_jsonwebtoken.default.decode(token, { complete: true });
441
- if (!decoded || typeof decoded === "string") {
456
+ const header = decodeProtectedHeader(token);
457
+ if (!header) {
442
458
  throw new IQAuthError("TOKEN_INVALID", "Unable to decode token");
443
459
  }
444
- const kid = decoded.header.kid;
460
+ const kid = header.kid;
445
461
  if (!kid) {
446
462
  throw new IQAuthError("TOKEN_INVALID", "Token missing kid header");
447
463
  }
448
- let publicKey = await this.getPublicKey(kid);
449
- if (!publicKey) {
450
- await this.refreshJwks();
451
- publicKey = await this.getPublicKey(kid);
464
+ let cache = await this.ensureCache();
465
+ if (!cache.byKid.has(kid)) {
466
+ this.jwksCache = null;
467
+ cache = await this.ensureCache();
452
468
  }
453
- if (!publicKey) {
469
+ if (!cache.byKid.has(kid)) {
454
470
  throw new IQAuthError("TOKEN_INVALID", `Unknown key ID: ${kid}`);
455
471
  }
456
472
  const issuer = options.issuer ?? this.defaultIssuer;
457
473
  const audience = options.audience ?? this.defaultAudience;
458
474
  const clockTolerance = options.clockTolerance ?? this.defaultClockTolerance;
459
- const algorithms = options.algorithms ?? ["RS256"];
475
+ const algorithms = options.algorithms ?? ["RS256", "ES256"];
476
+ const verifyOptions = {
477
+ algorithms,
478
+ clockTolerance,
479
+ issuer,
480
+ audience
481
+ };
460
482
  try {
461
- const verifyOptions = {
462
- algorithms,
463
- clockTolerance,
464
- // The jsonwebtoken types insist on tuple types for arrays; runtime
465
- // accepts plain string[] so we cast to satisfy the compiler.
466
- issuer,
467
- audience
468
- };
469
- const verified = import_jsonwebtoken.default.verify(token, publicKey, verifyOptions);
470
- return verified;
483
+ const { payload } = await (0, import_jose.jwtVerify)(token, cache.verifier, verifyOptions);
484
+ return payload;
471
485
  } catch (err) {
486
+ if (err instanceof import_jose.errors.JWTExpired) {
487
+ throw new IQAuthError("TOKEN_EXPIRED", "Token has expired");
488
+ }
489
+ if (err instanceof import_jose.errors.JOSEError) {
490
+ throw new IQAuthError("TOKEN_INVALID", err.message);
491
+ }
472
492
  if (err instanceof Error) {
473
- if (err.name === "TokenExpiredError") {
474
- throw new IQAuthError("TOKEN_EXPIRED", "Token has expired");
475
- }
476
493
  throw new IQAuthError("TOKEN_INVALID", err.message);
477
494
  }
478
495
  throw new IQAuthError("TOKEN_INVALID", "Token verification failed");
@@ -480,29 +497,40 @@ var TokensModule = class {
480
497
  }
481
498
  /**
482
499
  * Decode a JWT without verification. Returns null if malformed.
483
- *
484
- * @remarks Local decode only — no network call
485
500
  */
486
501
  decode(token) {
487
- const decoded = import_jsonwebtoken.default.decode(token);
488
- return decoded;
502
+ try {
503
+ const parts = token.split(".");
504
+ if (parts.length < 2) return null;
505
+ const payload = parts[1];
506
+ const padded = payload + "=".repeat((4 - payload.length % 4) % 4);
507
+ const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
508
+ let json;
509
+ if (typeof atob === "function") {
510
+ json = atob(b64);
511
+ } else {
512
+ const { Buffer: Buffer2 } = require("buffer");
513
+ json = Buffer2.from(b64, "base64").toString("utf8");
514
+ }
515
+ try {
516
+ json = decodeURIComponent(escape(json));
517
+ } catch {
518
+ }
519
+ const claims = JSON.parse(json);
520
+ if (!claims || typeof claims !== "object") return null;
521
+ return claims;
522
+ } catch {
523
+ return null;
524
+ }
489
525
  }
490
- /**
491
- * Check if a token is expired based on the `exp` claim.
492
- *
493
- * @remarks Local check only — no network call
494
- */
526
+ /** Check if a token is expired based on the `exp` claim. */
495
527
  isExpired(token) {
496
528
  const claims = this.decode(token);
497
529
  if (!claims?.exp) return true;
498
530
  const now = Math.floor(Date.now() / 1e3);
499
531
  return claims.exp <= now;
500
532
  }
501
- /**
502
- * Get the claims from a token without verification.
503
- *
504
- * @remarks Local decode only — no network call
505
- */
533
+ /** Get the claims from a token without verification. */
506
534
  getClaims(token) {
507
535
  const claims = this.decode(token);
508
536
  if (!claims) {
@@ -510,11 +538,15 @@ var TokensModule = class {
510
538
  }
511
539
  return claims;
512
540
  }
513
- async getPublicKey(kid) {
514
- if (!this.jwksCache || Date.now() - this.jwksCache.fetchedAt > JWKS_CACHE_TTL_MS) {
515
- await this.refreshJwks();
541
+ async ensureCache() {
542
+ if (this.jwksCache && Date.now() - this.jwksCache.fetchedAt <= JWKS_CACHE_TTL_MS) {
543
+ return this.jwksCache;
544
+ }
545
+ await this.refreshJwks();
546
+ if (!this.jwksCache) {
547
+ throw new IQAuthError("INTERNAL_ERROR", "JWKS cache unavailable after refresh");
516
548
  }
517
- return this.jwksCache?.keys.get(kid) ?? null;
549
+ return this.jwksCache;
518
550
  }
519
551
  async refreshJwks() {
520
552
  if (this.inFlightRefresh) {
@@ -541,35 +573,24 @@ var TokensModule = class {
541
573
  "Malformed JWKS response: expected { keys: [...] }"
542
574
  );
543
575
  }
544
- const keys = /* @__PURE__ */ new Map();
576
+ const byKid = /* @__PURE__ */ new Set();
545
577
  for (const key of jwks.keys) {
546
- if (!key || typeof key.kid !== "string" || typeof key.n !== "string" || typeof key.e !== "string") {
578
+ if (!key || typeof key.kid !== "string" || typeof key.n !== "string" && typeof key.x !== "string" || key.kty === "RSA" && (typeof key.n !== "string" || typeof key.e !== "string")) {
547
579
  throw new IQAuthError(
548
580
  "INTERNAL_ERROR",
549
581
  "Malformed JWKS response: key missing required fields"
550
582
  );
551
583
  }
552
- const pem = this.jwkToPem(key);
553
- keys.set(key.kid, pem);
584
+ byKid.add(key.kid);
554
585
  }
555
- this.jwksCache = { keys, fetchedAt: Date.now() };
586
+ const verifier = (0, import_jose.createLocalJWKSet)({ keys: jwks.keys });
587
+ this.jwksCache = { raw: jwks.keys, byKid, verifier, fetchedAt: Date.now() };
556
588
  } finally {
557
589
  this.inFlightRefresh = null;
558
590
  }
559
591
  })();
560
592
  return this.inFlightRefresh;
561
593
  }
562
- jwkToPem(jwk) {
563
- const keyObject = import_crypto.default.createPublicKey({
564
- key: {
565
- kty: jwk.kty,
566
- n: jwk.n,
567
- e: jwk.e
568
- },
569
- format: "jwk"
570
- });
571
- return keyObject.export({ type: "spki", format: "pem" });
572
- }
573
594
  /** @internal Exposed for testing — clears JWKS cache */
574
595
  clearCache() {
575
596
  this.jwksCache = null;
@@ -777,7 +798,7 @@ var PermissionsModule = class {
777
798
  };
778
799
 
779
800
  // src/modules/oidc.ts
780
- var import_crypto2 = __toESM(require("crypto"));
801
+ var import_crypto = __toESM(require("crypto"));
781
802
  var InMemoryOidcStateStore = class {
782
803
  constructor() {
783
804
  this.map = /* @__PURE__ */ new Map();
@@ -858,12 +879,12 @@ var OidcModule = class {
858
879
  * ready to redirect the user to.
859
880
  */
860
881
  async createAuthRequest(params) {
861
- const codeVerifier = base64UrlEncode(import_crypto2.default.randomBytes(32));
882
+ const codeVerifier = base64UrlEncode(import_crypto.default.randomBytes(32));
862
883
  const codeChallenge = base64UrlEncode(
863
- import_crypto2.default.createHash("sha256").update(codeVerifier).digest()
884
+ import_crypto.default.createHash("sha256").update(codeVerifier).digest()
864
885
  );
865
- const state = base64UrlEncode(import_crypto2.default.randomBytes(16));
866
- const nonce = base64UrlEncode(import_crypto2.default.randomBytes(16));
886
+ const state = base64UrlEncode(import_crypto.default.randomBytes(16));
887
+ const nonce = base64UrlEncode(import_crypto.default.randomBytes(16));
867
888
  await this.stateStore.set(state, {
868
889
  codeVerifier,
869
890
  state,
@@ -1811,7 +1832,7 @@ function assertPublishableKey(raw, opts) {
1811
1832
  if (!isValidIssuerUrl(decoded.iss)) {
1812
1833
  throw new IQAuthError(
1813
1834
  "CONFIG_INVALID",
1814
- `${ctx}IQAuth publishable key encodes an invalid issuer (iss=${JSON.stringify(decoded.iss)}). Expected a fully-qualified URL like "https://auth.example.com" (scheme required). Regenerate the key from the IQAuth admin console, or set IQAUTH_ISSUER to the correct issuer URL as a temporary workaround.`
1835
+ `${ctx}IQAuth publishable key encodes an invalid issuer (iss=${JSON.stringify(decoded.iss)}). Expected a fully-qualified URL like "https://auth.example.com" (scheme required). Regenerate the key from the IQAuth admin console \u2014 the new key will encode a valid issuer URL.`
1815
1836
  );
1816
1837
  }
1817
1838
  return { mode: shapeMatch[1], iss: decoded.iss, appId: decoded.appId, tenantId: decoded.tenantId, kid: decoded.kid, raw };
@@ -2013,6 +2034,15 @@ async function handleSignout(config, input) {
2013
2034
  } catch {
2014
2035
  }
2015
2036
  }
2037
+ if (input.endSsoSession !== false && input.ssoCookieHeader) {
2038
+ try {
2039
+ await cfg.fetchImpl(`${cfg.issuer}/oidc/sso-logout`, {
2040
+ method: "POST",
2041
+ headers: { Cookie: input.ssoCookieHeader }
2042
+ });
2043
+ } catch {
2044
+ }
2045
+ }
2016
2046
  return {
2017
2047
  status: 200,
2018
2048
  body: { success: true, data: { signedOut: true } },
@@ -2083,7 +2113,7 @@ function iqAuth(options) {
2083
2113
  if (path === `${mount}/signout`) {
2084
2114
  const auth2 = c.req.header("authorization");
2085
2115
  const accessToken = auth2 && auth2.replace(/^Bearer /i, "") || readCookieFromHeader(cookieHeader, accessCookie);
2086
- return honoResponse(await handleSignout(helperConfig, { accessToken }));
2116
+ return honoResponse(await handleSignout(helperConfig, { accessToken, ssoCookieHeader: cookieHeader }));
2087
2117
  }
2088
2118
  }
2089
2119
  if (isPublic(path)) return next();
package/dist/hono.mjs CHANGED
@@ -1,15 +1,16 @@
1
+ import {
2
+ IQAuthClient
3
+ } from "./chunk-W3F4JYGP.mjs";
1
4
  import {
2
5
  handleCallback,
3
6
  handleRefresh,
4
7
  handleSignout,
5
8
  serializeCookie
6
- } from "./chunk-M4J6BPK7.mjs";
9
+ } from "./chunk-KGEPDXHU.mjs";
7
10
  import {
8
11
  assertPublishableKey
9
- } from "./chunk-QEJB7WEQ.mjs";
10
- import {
11
- IQAuthClient
12
- } from "./chunk-MDUHPQMM.mjs";
12
+ } from "./chunk-WQWBJSSS.mjs";
13
+ import "./chunk-UNYDG2L4.mjs";
13
14
  import {
14
15
  IQAuthError
15
16
  } from "./chunk-6I6RM4MN.mjs";
@@ -78,7 +79,7 @@ function iqAuth(options) {
78
79
  if (path === `${mount}/signout`) {
79
80
  const auth2 = c.req.header("authorization");
80
81
  const accessToken = auth2 && auth2.replace(/^Bearer /i, "") || readCookieFromHeader(cookieHeader, accessCookie);
81
- return honoResponse(await handleSignout(helperConfig, { accessToken }));
82
+ return honoResponse(await handleSignout(helperConfig, { accessToken, ssoCookieHeader: cookieHeader }));
82
83
  }
83
84
  }
84
85
  if (isPublic(path)) return next();
package/dist/index.d.mts CHANGED
@@ -1,6 +1,5 @@
1
- export { o as ApiKeysModule, l as AppsModule, A as AuthModule, B as BrandingModule, r as ClientsModule, C as CreateAppRequest, m as CreateAppResponse, h as DEFAULT_CLOCK_TOLERANCE_SECONDS, g as DEFAULT_TOKEN_AUDIENCE, D as DEFAULT_TOKEN_ISSUER, E as EntitlementsModule, G as GdprModule, H as HierarchyModule, I as IQAuthClient, a as InMemoryOidcStateStore, p as InvitesModule, M as MembershipsModule, u as MfaModule, d as OidcAuthRequest, e as OidcCallbackResult, O as OidcModule, f as OidcModuleOptions, b as OidcStateStore, c as OidcStoredRequest, n as PermissionGroupsModule, P as PermissionsModule, t as PinModule, R as RolesModule, s as ScopeModule, S as SessionsModule, q as SourcesModule, k as TenantsModule, i as TokenVerifyOptions, T as TokensModule, j as TokensModuleOptions, U as UsersModule, V as VendorsModule, W as WebhooksModule } from './client-Dv4v92Mj.mjs';
1
+ export { o as ApiKeysModule, l as AppsModule, A as AuthModule, B as BrandingModule, r as ClientsModule, C as CreateAppRequest, m as CreateAppResponse, h as DEFAULT_CLOCK_TOLERANCE_SECONDS, g as DEFAULT_TOKEN_AUDIENCE, D as DEFAULT_TOKEN_ISSUER, E as EntitlementsModule, G as GdprModule, H as HierarchyModule, I as IQAuthClient, a as InMemoryOidcStateStore, p as InvitesModule, M as MembershipsModule, u as MfaModule, d as OidcAuthRequest, e as OidcCallbackResult, O as OidcModule, f as OidcModuleOptions, b as OidcStateStore, c as OidcStoredRequest, n as PermissionGroupsModule, P as PermissionsModule, t as PinModule, R as RolesModule, s as ScopeModule, S as SessionsModule, q as SourcesModule, k as TenantsModule, i as TokenVerifyOptions, T as TokensModule, j as TokensModuleOptions, U as UsersModule, V as VendorsModule, W as WebhooksModule } from './client-vdh2a9fJ.mjs';
2
2
  export { a as ErrorCode, E as ErrorCodes, I as IQAuthError } from './errors-CDdl24MP.mjs';
3
- export { i as iqAuthMiddleware } from './express-BZmF1llh.mjs';
3
+ export { i as iqAuthMiddleware } from './express-A0-dWEMy.mjs';
4
4
  export { K as KeyMode, c as ParsedPublishableKey, P as PublishableKeyPayload, a as assertPublishableKey, e as encodePublishableKey, i as isPublishableKey, b as isSecretKey, p as parsePublishableKey } from './publishableKey-BaR0HoAH.mjs';
5
5
  export { an as AcceptInviteRequest, aa as AddGroupPermissionRequest, ad as AddUserOverrideRequest, v as ApiErrorResponse, ag as ApiKeyInfo, aj as ApiKeyIntrospection, w as ApiResponse, A as ApiSuccessResponse, _ as AppInfo, Z as AppManifest, a0 as AppSyncResult, a4 as AssignRoleRequest, aM as AvailableScopesTree, a_ as BackupCodeCountResult, aZ as BackupCodesResult, p as BrandingAsset, B as BrandingConfig, r as BrandingDomainMapping, aB as Client, ah as CreateApiKeyRequest, ai as CreateApiKeyResult, aC as CreateClientRequest, al as CreateInviteRequest, aJ as CreateMembershipRequest, a2 as CreateRoleRequest, az as CreateSourceRequest, C as CreateTenantRequest, aw as CreateVendorRequest, ap as CreateWebhookRequest, aq as CreateWebhookResult, ae as EffectivePermission, aY as EmailEnrollResult, at as Entitlement, N as ExpressMiddlewareOptions, aR as GdprExportData, au as GrantEntitlementRequest, a9 as GroupPermission, aG as HierarchyClient, aH as HierarchyLink, aF as HierarchySource, aE as HierarchyVendor, c as IQAuthBrowserSessionClientConfig, a as IQAuthClientConfig, I as IQAuthEnvironment, V as IQAuthNextFunction, Q as IQAuthRequestLike, R as IQAuthResponseLike, W as IQAuthRetryConfig, b as IQAuthTokenClientConfig, X as IQAuthVerifyConfig, ab as InheritanceRelation, ak as Invitation, l as InviteTenantUserRequest, m as InviteTenantUserResult, am as InviteValidation, s as JwksKey, t as JwksResponse, J as JwtClaims, L as LoginResult, aI as Membership, aL as MembershipWithDetails, aU as MfaAvailableMethods, y as MfaEnrollment, x as MfaMethod, F as MfaPolicy, D as MfaVerifyResult, M as MigrateUserRequest, O as OidcDiscovery, u as OidcTokenResponse, E as PasswordPolicy, af as PermissionCheckResult, a8 as PermissionGroup, $ as PermissionNodeInfo, Y as PermissionNodeManifest, aT as PinLoginResult, aS as PinStatus, P as PromoteToVendorRequest, k as PromoteToVendorResult, H as ProvisionUserRequest, K as ProvisionUserResponse, a1 as Role, S as ScopeContext, aQ as ScopeSwitchResult, aN as ScopeTreeClient, aO as ScopeTreeSource, aP as ScopeTreeVendor, h as Session, g as SessionAuthenticatedLoginResult, d as SessionUser, aX as SmsEnrollResult, ay as Source, e as Tenant, i as TenantInfo, a7 as TenantUser, n as TenantUserRoleUpdate, f as TokenAuthenticatedLoginResult, T as TokenPair, aV as TotpEnrollResult, z as TotpEnrollmentResult, aW as TotpVerifyResult, o as UpdateBrandingRequest, aD as UpdateClientRequest, aK as UpdateMembershipRequest, a3 as UpdateRoleRequest, aA as UpdateSourceRequest, j as UpdateTenantRequest, ax as UpdateVendorRequest, q as UploadAssetRequest, a6 as UserGroupAssignment, ac as UserPermissionOverride, G as UserPermissions, U as UserProfile, a5 as UserRoleAssignment, av as Vendor, ar as WebhookDelivery, ao as WebhookEndpoint, as as WebhookTestResult } from './types-Cxl3bQHt.mjs';
6
- import 'jsonwebtoken';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- export { o as ApiKeysModule, l as AppsModule, A as AuthModule, B as BrandingModule, r as ClientsModule, C as CreateAppRequest, m as CreateAppResponse, h as DEFAULT_CLOCK_TOLERANCE_SECONDS, g as DEFAULT_TOKEN_AUDIENCE, D as DEFAULT_TOKEN_ISSUER, E as EntitlementsModule, G as GdprModule, H as HierarchyModule, I as IQAuthClient, a as InMemoryOidcStateStore, p as InvitesModule, M as MembershipsModule, u as MfaModule, d as OidcAuthRequest, e as OidcCallbackResult, O as OidcModule, f as OidcModuleOptions, b as OidcStateStore, c as OidcStoredRequest, n as PermissionGroupsModule, P as PermissionsModule, t as PinModule, R as RolesModule, s as ScopeModule, S as SessionsModule, q as SourcesModule, k as TenantsModule, i as TokenVerifyOptions, T as TokensModule, j as TokensModuleOptions, U as UsersModule, V as VendorsModule, W as WebhooksModule } from './client-DXbHb2ul.js';
1
+ export { o as ApiKeysModule, l as AppsModule, A as AuthModule, B as BrandingModule, r as ClientsModule, C as CreateAppRequest, m as CreateAppResponse, h as DEFAULT_CLOCK_TOLERANCE_SECONDS, g as DEFAULT_TOKEN_AUDIENCE, D as DEFAULT_TOKEN_ISSUER, E as EntitlementsModule, G as GdprModule, H as HierarchyModule, I as IQAuthClient, a as InMemoryOidcStateStore, p as InvitesModule, M as MembershipsModule, u as MfaModule, d as OidcAuthRequest, e as OidcCallbackResult, O as OidcModule, f as OidcModuleOptions, b as OidcStateStore, c as OidcStoredRequest, n as PermissionGroupsModule, P as PermissionsModule, t as PinModule, R as RolesModule, s as ScopeModule, S as SessionsModule, q as SourcesModule, k as TenantsModule, i as TokenVerifyOptions, T as TokensModule, j as TokensModuleOptions, U as UsersModule, V as VendorsModule, W as WebhooksModule } from './client-DTX4hNdS.js';
2
2
  export { a as ErrorCode, E as ErrorCodes, I as IQAuthError } from './errors-CDdl24MP.js';
3
- export { i as iqAuthMiddleware } from './express-B4o3P8vK.js';
3
+ export { i as iqAuthMiddleware } from './express-Bo_pJKHN.js';
4
4
  export { K as KeyMode, c as ParsedPublishableKey, P as PublishableKeyPayload, a as assertPublishableKey, e as encodePublishableKey, i as isPublishableKey, b as isSecretKey, p as parsePublishableKey } from './publishableKey-BaR0HoAH.js';
5
5
  export { an as AcceptInviteRequest, aa as AddGroupPermissionRequest, ad as AddUserOverrideRequest, v as ApiErrorResponse, ag as ApiKeyInfo, aj as ApiKeyIntrospection, w as ApiResponse, A as ApiSuccessResponse, _ as AppInfo, Z as AppManifest, a0 as AppSyncResult, a4 as AssignRoleRequest, aM as AvailableScopesTree, a_ as BackupCodeCountResult, aZ as BackupCodesResult, p as BrandingAsset, B as BrandingConfig, r as BrandingDomainMapping, aB as Client, ah as CreateApiKeyRequest, ai as CreateApiKeyResult, aC as CreateClientRequest, al as CreateInviteRequest, aJ as CreateMembershipRequest, a2 as CreateRoleRequest, az as CreateSourceRequest, C as CreateTenantRequest, aw as CreateVendorRequest, ap as CreateWebhookRequest, aq as CreateWebhookResult, ae as EffectivePermission, aY as EmailEnrollResult, at as Entitlement, N as ExpressMiddlewareOptions, aR as GdprExportData, au as GrantEntitlementRequest, a9 as GroupPermission, aG as HierarchyClient, aH as HierarchyLink, aF as HierarchySource, aE as HierarchyVendor, c as IQAuthBrowserSessionClientConfig, a as IQAuthClientConfig, I as IQAuthEnvironment, V as IQAuthNextFunction, Q as IQAuthRequestLike, R as IQAuthResponseLike, W as IQAuthRetryConfig, b as IQAuthTokenClientConfig, X as IQAuthVerifyConfig, ab as InheritanceRelation, ak as Invitation, l as InviteTenantUserRequest, m as InviteTenantUserResult, am as InviteValidation, s as JwksKey, t as JwksResponse, J as JwtClaims, L as LoginResult, aI as Membership, aL as MembershipWithDetails, aU as MfaAvailableMethods, y as MfaEnrollment, x as MfaMethod, F as MfaPolicy, D as MfaVerifyResult, M as MigrateUserRequest, O as OidcDiscovery, u as OidcTokenResponse, E as PasswordPolicy, af as PermissionCheckResult, a8 as PermissionGroup, $ as PermissionNodeInfo, Y as PermissionNodeManifest, aT as PinLoginResult, aS as PinStatus, P as PromoteToVendorRequest, k as PromoteToVendorResult, H as ProvisionUserRequest, K as ProvisionUserResponse, a1 as Role, S as ScopeContext, aQ as ScopeSwitchResult, aN as ScopeTreeClient, aO as ScopeTreeSource, aP as ScopeTreeVendor, h as Session, g as SessionAuthenticatedLoginResult, d as SessionUser, aX as SmsEnrollResult, ay as Source, e as Tenant, i as TenantInfo, a7 as TenantUser, n as TenantUserRoleUpdate, f as TokenAuthenticatedLoginResult, T as TokenPair, aV as TotpEnrollResult, z as TotpEnrollmentResult, aW as TotpVerifyResult, o as UpdateBrandingRequest, aD as UpdateClientRequest, aK as UpdateMembershipRequest, a3 as UpdateRoleRequest, aA as UpdateSourceRequest, j as UpdateTenantRequest, ax as UpdateVendorRequest, q as UploadAssetRequest, a6 as UserGroupAssignment, ac as UserPermissionOverride, G as UserPermissions, U as UserProfile, a5 as UserRoleAssignment, av as Vendor, ar as WebhookDelivery, ao as WebhookEndpoint, as as WebhookTestResult } from './types-Cxl3bQHt.js';
6
- import 'jsonwebtoken';
package/dist/index.js CHANGED
@@ -478,8 +478,7 @@ function parseMfaResponse(data, browserSessionMode) {
478
478
  }
479
479
 
480
480
  // src/modules/tokens.ts
481
- var import_crypto = __toESM(require("crypto"));
482
- var import_jsonwebtoken = __toESM(require("jsonwebtoken"));
481
+ var import_jose = require("jose");
483
482
  var JWKS_CACHE_TTL_MS = 60 * 60 * 1e3;
484
483
  var DEFAULT_TOKEN_ISSUER = [
485
484
  "https://auth.dispositioniq.com",
@@ -492,6 +491,24 @@ var DEFAULT_TOKEN_AUDIENCE = [
492
491
  "iqvalidate"
493
492
  ];
494
493
  var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
494
+ function decodeProtectedHeader(token) {
495
+ const parts = token.split(".");
496
+ if (parts.length < 2) return null;
497
+ try {
498
+ const padded = parts[0] + "=".repeat((4 - parts[0].length % 4) % 4);
499
+ const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
500
+ let json;
501
+ if (typeof atob === "function") {
502
+ json = atob(b64);
503
+ } else {
504
+ const { Buffer: Buffer2 } = require("buffer");
505
+ json = Buffer2.from(b64, "base64").toString("utf8");
506
+ }
507
+ return JSON.parse(json);
508
+ } catch {
509
+ return null;
510
+ }
511
+ }
495
512
  var TokensModule = class {
496
513
  constructor(baseUrl, options = {}) {
497
514
  this.jwksCache = null;
@@ -502,49 +519,49 @@ var TokensModule = class {
502
519
  this.defaultClockTolerance = options.clockTolerance ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;
503
520
  }
504
521
  /**
505
- * Verify a JWT access token using RS256 via JWKS from /.well-known/jwks.json.
506
- * Caches JWKS keys for 1 hour. Retries once on unknown `kid`.
507
- *
508
- * @remarks Validates against /.well-known/jwks.json. Issuer, audience, and
509
- * clock tolerance default to client config but can be overridden per call.
522
+ * Verify a JWT access token using RS256/ES256 via JWKS from
523
+ * `/.well-known/jwks.json`. Backed by `jose` (Web Crypto) so it runs on
524
+ * Node, browser, and edge runtimes alike — no `node:crypto` dependency.
525
+ * Caches JWKS for 1 hour and refetches once on unknown `kid`.
510
526
  */
511
527
  async verify(token, options = {}) {
512
- const decoded = import_jsonwebtoken.default.decode(token, { complete: true });
513
- if (!decoded || typeof decoded === "string") {
528
+ const header = decodeProtectedHeader(token);
529
+ if (!header) {
514
530
  throw new IQAuthError("TOKEN_INVALID", "Unable to decode token");
515
531
  }
516
- const kid = decoded.header.kid;
532
+ const kid = header.kid;
517
533
  if (!kid) {
518
534
  throw new IQAuthError("TOKEN_INVALID", "Token missing kid header");
519
535
  }
520
- let publicKey = await this.getPublicKey(kid);
521
- if (!publicKey) {
522
- await this.refreshJwks();
523
- publicKey = await this.getPublicKey(kid);
536
+ let cache = await this.ensureCache();
537
+ if (!cache.byKid.has(kid)) {
538
+ this.jwksCache = null;
539
+ cache = await this.ensureCache();
524
540
  }
525
- if (!publicKey) {
541
+ if (!cache.byKid.has(kid)) {
526
542
  throw new IQAuthError("TOKEN_INVALID", `Unknown key ID: ${kid}`);
527
543
  }
528
544
  const issuer = options.issuer ?? this.defaultIssuer;
529
545
  const audience = options.audience ?? this.defaultAudience;
530
546
  const clockTolerance = options.clockTolerance ?? this.defaultClockTolerance;
531
- const algorithms = options.algorithms ?? ["RS256"];
547
+ const algorithms = options.algorithms ?? ["RS256", "ES256"];
548
+ const verifyOptions = {
549
+ algorithms,
550
+ clockTolerance,
551
+ issuer,
552
+ audience
553
+ };
532
554
  try {
533
- const verifyOptions = {
534
- algorithms,
535
- clockTolerance,
536
- // The jsonwebtoken types insist on tuple types for arrays; runtime
537
- // accepts plain string[] so we cast to satisfy the compiler.
538
- issuer,
539
- audience
540
- };
541
- const verified = import_jsonwebtoken.default.verify(token, publicKey, verifyOptions);
542
- return verified;
555
+ const { payload } = await (0, import_jose.jwtVerify)(token, cache.verifier, verifyOptions);
556
+ return payload;
543
557
  } catch (err) {
558
+ if (err instanceof import_jose.errors.JWTExpired) {
559
+ throw new IQAuthError("TOKEN_EXPIRED", "Token has expired");
560
+ }
561
+ if (err instanceof import_jose.errors.JOSEError) {
562
+ throw new IQAuthError("TOKEN_INVALID", err.message);
563
+ }
544
564
  if (err instanceof Error) {
545
- if (err.name === "TokenExpiredError") {
546
- throw new IQAuthError("TOKEN_EXPIRED", "Token has expired");
547
- }
548
565
  throw new IQAuthError("TOKEN_INVALID", err.message);
549
566
  }
550
567
  throw new IQAuthError("TOKEN_INVALID", "Token verification failed");
@@ -552,29 +569,40 @@ var TokensModule = class {
552
569
  }
553
570
  /**
554
571
  * Decode a JWT without verification. Returns null if malformed.
555
- *
556
- * @remarks Local decode only — no network call
557
572
  */
558
573
  decode(token) {
559
- const decoded = import_jsonwebtoken.default.decode(token);
560
- return decoded;
574
+ try {
575
+ const parts = token.split(".");
576
+ if (parts.length < 2) return null;
577
+ const payload = parts[1];
578
+ const padded = payload + "=".repeat((4 - payload.length % 4) % 4);
579
+ const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
580
+ let json;
581
+ if (typeof atob === "function") {
582
+ json = atob(b64);
583
+ } else {
584
+ const { Buffer: Buffer2 } = require("buffer");
585
+ json = Buffer2.from(b64, "base64").toString("utf8");
586
+ }
587
+ try {
588
+ json = decodeURIComponent(escape(json));
589
+ } catch {
590
+ }
591
+ const claims = JSON.parse(json);
592
+ if (!claims || typeof claims !== "object") return null;
593
+ return claims;
594
+ } catch {
595
+ return null;
596
+ }
561
597
  }
562
- /**
563
- * Check if a token is expired based on the `exp` claim.
564
- *
565
- * @remarks Local check only — no network call
566
- */
598
+ /** Check if a token is expired based on the `exp` claim. */
567
599
  isExpired(token) {
568
600
  const claims = this.decode(token);
569
601
  if (!claims?.exp) return true;
570
602
  const now = Math.floor(Date.now() / 1e3);
571
603
  return claims.exp <= now;
572
604
  }
573
- /**
574
- * Get the claims from a token without verification.
575
- *
576
- * @remarks Local decode only — no network call
577
- */
605
+ /** Get the claims from a token without verification. */
578
606
  getClaims(token) {
579
607
  const claims = this.decode(token);
580
608
  if (!claims) {
@@ -582,11 +610,15 @@ var TokensModule = class {
582
610
  }
583
611
  return claims;
584
612
  }
585
- async getPublicKey(kid) {
586
- if (!this.jwksCache || Date.now() - this.jwksCache.fetchedAt > JWKS_CACHE_TTL_MS) {
587
- await this.refreshJwks();
613
+ async ensureCache() {
614
+ if (this.jwksCache && Date.now() - this.jwksCache.fetchedAt <= JWKS_CACHE_TTL_MS) {
615
+ return this.jwksCache;
616
+ }
617
+ await this.refreshJwks();
618
+ if (!this.jwksCache) {
619
+ throw new IQAuthError("INTERNAL_ERROR", "JWKS cache unavailable after refresh");
588
620
  }
589
- return this.jwksCache?.keys.get(kid) ?? null;
621
+ return this.jwksCache;
590
622
  }
591
623
  async refreshJwks() {
592
624
  if (this.inFlightRefresh) {
@@ -613,35 +645,24 @@ var TokensModule = class {
613
645
  "Malformed JWKS response: expected { keys: [...] }"
614
646
  );
615
647
  }
616
- const keys = /* @__PURE__ */ new Map();
648
+ const byKid = /* @__PURE__ */ new Set();
617
649
  for (const key of jwks.keys) {
618
- if (!key || typeof key.kid !== "string" || typeof key.n !== "string" || typeof key.e !== "string") {
650
+ if (!key || typeof key.kid !== "string" || typeof key.n !== "string" && typeof key.x !== "string" || key.kty === "RSA" && (typeof key.n !== "string" || typeof key.e !== "string")) {
619
651
  throw new IQAuthError(
620
652
  "INTERNAL_ERROR",
621
653
  "Malformed JWKS response: key missing required fields"
622
654
  );
623
655
  }
624
- const pem = this.jwkToPem(key);
625
- keys.set(key.kid, pem);
656
+ byKid.add(key.kid);
626
657
  }
627
- this.jwksCache = { keys, fetchedAt: Date.now() };
658
+ const verifier = (0, import_jose.createLocalJWKSet)({ keys: jwks.keys });
659
+ this.jwksCache = { raw: jwks.keys, byKid, verifier, fetchedAt: Date.now() };
628
660
  } finally {
629
661
  this.inFlightRefresh = null;
630
662
  }
631
663
  })();
632
664
  return this.inFlightRefresh;
633
665
  }
634
- jwkToPem(jwk) {
635
- const keyObject = import_crypto.default.createPublicKey({
636
- key: {
637
- kty: jwk.kty,
638
- n: jwk.n,
639
- e: jwk.e
640
- },
641
- format: "jwk"
642
- });
643
- return keyObject.export({ type: "spki", format: "pem" });
644
- }
645
666
  /** @internal Exposed for testing — clears JWKS cache */
646
667
  clearCache() {
647
668
  this.jwksCache = null;
@@ -849,7 +870,7 @@ var PermissionsModule = class {
849
870
  };
850
871
 
851
872
  // src/modules/oidc.ts
852
- var import_crypto2 = __toESM(require("crypto"));
873
+ var import_crypto = __toESM(require("crypto"));
853
874
  var InMemoryOidcStateStore = class {
854
875
  constructor() {
855
876
  this.map = /* @__PURE__ */ new Map();
@@ -930,12 +951,12 @@ var OidcModule = class {
930
951
  * ready to redirect the user to.
931
952
  */
932
953
  async createAuthRequest(params) {
933
- const codeVerifier = base64UrlEncode(import_crypto2.default.randomBytes(32));
954
+ const codeVerifier = base64UrlEncode(import_crypto.default.randomBytes(32));
934
955
  const codeChallenge = base64UrlEncode(
935
- import_crypto2.default.createHash("sha256").update(codeVerifier).digest()
956
+ import_crypto.default.createHash("sha256").update(codeVerifier).digest()
936
957
  );
937
- const state = base64UrlEncode(import_crypto2.default.randomBytes(16));
938
- const nonce = base64UrlEncode(import_crypto2.default.randomBytes(16));
958
+ const state = base64UrlEncode(import_crypto.default.randomBytes(16));
959
+ const nonce = base64UrlEncode(import_crypto.default.randomBytes(16));
939
960
  await this.stateStore.set(state, {
940
961
  codeVerifier,
941
962
  state,
@@ -1913,7 +1934,7 @@ function assertPublishableKey(raw, opts) {
1913
1934
  if (!isValidIssuerUrl(decoded.iss)) {
1914
1935
  throw new IQAuthError(
1915
1936
  "CONFIG_INVALID",
1916
- `${ctx}IQAuth publishable key encodes an invalid issuer (iss=${JSON.stringify(decoded.iss)}). Expected a fully-qualified URL like "https://auth.example.com" (scheme required). Regenerate the key from the IQAuth admin console, or set IQAUTH_ISSUER to the correct issuer URL as a temporary workaround.`
1937
+ `${ctx}IQAuth publishable key encodes an invalid issuer (iss=${JSON.stringify(decoded.iss)}). Expected a fully-qualified URL like "https://auth.example.com" (scheme required). Regenerate the key from the IQAuth admin console \u2014 the new key will encode a valid issuer URL.`
1917
1938
  );
1918
1939
  }
1919
1940
  return { mode: shapeMatch[1], iss: decoded.iss, appId: decoded.appId, tenantId: decoded.tenantId, kid: decoded.kid, raw };
package/dist/index.mjs CHANGED
@@ -1,22 +1,12 @@
1
1
  import {
2
2
  iqAuthMiddleware
3
- } from "./chunk-D72UL5HL.mjs";
4
- import {
5
- assertPublishableKey,
6
- encodePublishableKey,
7
- isPublishableKey,
8
- isSecretKey,
9
- parsePublishableKey
10
- } from "./chunk-QEJB7WEQ.mjs";
3
+ } from "./chunk-EKTNEZIH.mjs";
11
4
  import {
12
5
  ApiKeysModule,
13
6
  AppsModule,
14
7
  AuthModule,
15
8
  BrandingModule,
16
9
  ClientsModule,
17
- DEFAULT_CLOCK_TOLERANCE_SECONDS,
18
- DEFAULT_TOKEN_AUDIENCE,
19
- DEFAULT_TOKEN_ISSUER,
20
10
  EntitlementsModule,
21
11
  GdprModule,
22
12
  HierarchyModule,
@@ -34,11 +24,23 @@ import {
34
24
  SessionsModule,
35
25
  SourcesModule,
36
26
  TenantsModule,
37
- TokensModule,
38
27
  UsersModule,
39
28
  VendorsModule,
40
29
  WebhooksModule
41
- } from "./chunk-MDUHPQMM.mjs";
30
+ } from "./chunk-W3F4JYGP.mjs";
31
+ import {
32
+ assertPublishableKey,
33
+ encodePublishableKey,
34
+ isPublishableKey,
35
+ isSecretKey,
36
+ parsePublishableKey
37
+ } from "./chunk-WQWBJSSS.mjs";
38
+ import {
39
+ DEFAULT_CLOCK_TOLERANCE_SECONDS,
40
+ DEFAULT_TOKEN_AUDIENCE,
41
+ DEFAULT_TOKEN_ISSUER,
42
+ TokensModule
43
+ } from "./chunk-UNYDG2L4.mjs";
42
44
  import {
43
45
  ErrorCodes,
44
46
  IQAuthError