@cboxdk/id-js 0.17.0 → 0.19.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 (40) hide show
  1. package/README.md +315 -3
  2. package/dist/{chunk-WYTGLCMF.js → chunk-2E25IPBA.js} +4 -3
  3. package/dist/chunk-2E25IPBA.js.map +1 -0
  4. package/dist/chunk-QQW63PGU.js +25 -0
  5. package/dist/chunk-QQW63PGU.js.map +1 -0
  6. package/dist/{chunk-ASOQN47M.js → chunk-SEUD4TE4.js} +3 -23
  7. package/dist/chunk-SEUD4TE4.js.map +1 -0
  8. package/dist/{chunk-G3CD7X4U.js → chunk-YGLMLIKL.js} +197 -9
  9. package/dist/chunk-YGLMLIKL.js.map +1 -0
  10. package/dist/{client-CdwdigzG.d.ts → client-BT-jOm0p.d.cts} +154 -2
  11. package/dist/{client-CEXddiCR.d.cts → client-xlEJalu8.d.ts} +154 -2
  12. package/dist/errors-D61xljZE.d.cts +87 -0
  13. package/dist/errors-D61xljZE.d.ts +87 -0
  14. package/dist/index.cjs +267 -17
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +84 -92
  17. package/dist/index.d.ts +84 -92
  18. package/dist/index.js +66 -13
  19. package/dist/index.js.map +1 -1
  20. package/dist/management.cjs +5092 -0
  21. package/dist/management.cjs.map +1 -0
  22. package/dist/management.d.cts +13454 -0
  23. package/dist/management.d.ts +13454 -0
  24. package/dist/management.js +5054 -0
  25. package/dist/management.js.map +1 -0
  26. package/dist/nextjs.cjs +136 -5
  27. package/dist/nextjs.cjs.map +1 -1
  28. package/dist/nextjs.d.cts +3 -2
  29. package/dist/nextjs.d.ts +3 -2
  30. package/dist/nextjs.js +4 -3
  31. package/dist/nextjs.js.map +1 -1
  32. package/dist/server.d.cts +1 -1
  33. package/dist/server.d.ts +1 -1
  34. package/dist/server.js +3 -2
  35. package/dist/{types-BYZldock.d.cts → types-CC1bz68x.d.cts} +30 -1
  36. package/dist/{types-BYZldock.d.ts → types-CC1bz68x.d.ts} +30 -1
  37. package/package.json +9 -2
  38. package/dist/chunk-ASOQN47M.js.map +0 -1
  39. package/dist/chunk-G3CD7X4U.js.map +0 -1
  40. package/dist/chunk-WYTGLCMF.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -106,12 +106,12 @@ function createLegacyVerifier(options) {
106
106
  );
107
107
  };
108
108
  }
109
- async function isSignedByCboxId(body, header, secret, toleranceSeconds) {
110
- if (!header) {
109
+ async function isSignedByCboxId(body, header2, secret, toleranceSeconds) {
110
+ if (!header2) {
111
111
  return false;
112
112
  }
113
113
  const parts = {};
114
- for (const piece of header.split(",")) {
114
+ for (const piece of header2.split(",")) {
115
115
  const [key2, value] = piece.split("=", 2);
116
116
  if (key2 && value) {
117
117
  parts[key2.trim()] = value.trim();
@@ -174,6 +174,7 @@ function assertSecureIssuer(issuer) {
174
174
  }
175
175
 
176
176
  // src/frontend.ts
177
+ var SECOND_FACTOR_KINDS = /* @__PURE__ */ new Set(["totp", "sms", "recovery_code"]);
177
178
  var CboxIdFrontend = class {
178
179
  issuer;
179
180
  publishableKey;
@@ -188,7 +189,7 @@ var CboxIdFrontend = class {
188
189
  * fetches of the same immutable document is a waste the SDK should absorb rather than
189
190
  * ask every consumer to.
190
191
  */
191
- configPromise = null;
192
+ configPromises = /* @__PURE__ */ new Map();
192
193
  constructor(options) {
193
194
  if (!options.issuer) {
194
195
  throw new ConfigurationError("issuer is required.");
@@ -215,13 +216,20 @@ var CboxIdFrontend = class {
215
216
  * Fetched once per client instance. The document is small and changes when somebody
216
217
  * edits it in the console, so a long-lived page picks changes up on its next full load
217
218
  * rather than mid-session — which is the right trade for something that decides layout.
219
+ * Each `organization` is fetched and cached on its own.
218
220
  */
219
- async config() {
220
- this.configPromise ??= this.get("/frontend/v1/config", {}, isFrontendConfig).catch((error) => {
221
- this.configPromise = null;
222
- throw error;
223
- });
224
- return this.configPromise;
221
+ async config(options = {}) {
222
+ const organization2 = options.organization ?? "";
223
+ let pending = this.configPromises.get(organization2);
224
+ if (pending === void 0) {
225
+ const path = organization2 === "" ? "/frontend/v1/config" : `/frontend/v1/config?${new URLSearchParams({ organization: organization2 }).toString()}`;
226
+ pending = this.get(path, {}, isFrontendConfig).catch((error) => {
227
+ this.configPromises.delete(organization2);
228
+ throw error;
229
+ });
230
+ this.configPromises.set(organization2, pending);
231
+ }
232
+ return pending;
225
233
  }
226
234
  /**
227
235
  * Who is signed in, given an access token your app already holds.
@@ -283,8 +291,12 @@ var CboxIdFrontend = class {
283
291
  if (body.status === "ok" && typeof body.login_ticket === "string") {
284
292
  return { status: "ok", loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 };
285
293
  }
286
- if ((body.status === "mfa_required" || body.status === "otp_required") && typeof body.mfa_token === "string") {
287
- return { status: body.status, mfaToken: body.mfa_token };
294
+ if (body.status === "mfa_required" && typeof body.mfa_token === "string") {
295
+ const factors = Array.isArray(body.factors) ? body.factors.filter((f) => typeof f === "string" && SECOND_FACTOR_KINDS.has(f)) : void 0;
296
+ return { status: "mfa_required", mfaToken: body.mfa_token, ...factors ? { factors } : {} };
297
+ }
298
+ if (body.status === "otp_required" && typeof body.mfa_token === "string") {
299
+ return { status: "otp_required", mfaToken: body.mfa_token };
288
300
  }
289
301
  if (body.status === "sso_required") {
290
302
  return { status: "sso_required" };
@@ -301,6 +313,11 @@ var CboxIdFrontend = class {
301
313
  *
302
314
  * A wrong code costs an attempt, not the sign-in: five are allowed before the token
303
315
  * dies and the person starts from the password again.
316
+ *
317
+ * `method` says which challenge the code answers: `'mfa'` for an authenticator or
318
+ * recovery code, `'otp'` for an emailed code (`otp_required`), `'sms'` for a code sent
319
+ * with {@link sendSmsCode}. A texted code is six digits like an authenticator's, so the
320
+ * server cannot tell them apart by shape — answering one as the other is refused.
304
321
  */
305
322
  async submitSecondFactor(mfaToken, code, method = "mfa") {
306
323
  const response = await this.post("/frontend/v1/sign-in/factor", { mfa_token: mfaToken, code, method });
@@ -312,6 +329,41 @@ var CboxIdFrontend = class {
312
329
  }
313
330
  return body.status === "ok" && typeof body.login_ticket === "string" ? { status: "ok", loginTicket: body.login_ticket, expiresIn: body.expires_in ?? 60 } : { status: "invalid" };
314
331
  }
332
+ /**
333
+ * Text the person a sign-in code, when `mfa_required` listed `'sms'` in `factors`.
334
+ * Then finish with `submitSecondFactor(mfaToken, code, 'sms')`.
335
+ *
336
+ * Only call it when the person asks ("Text me a code"), never on page load: each send
337
+ * spends one of the token's five attempts — that is what bounds how many texts one
338
+ * proved password can cause — and every text costs the customer money.
339
+ *
340
+ * ```ts
341
+ * if (result.status === 'mfa_required' && result.factors?.includes('sms')) {
342
+ * const sent = await frontend.sendSmsCode(result.mfaToken)
343
+ * if (sent.status === 'sent') showCodeField(`We texted ${sent.to}`)
344
+ * }
345
+ * ```
346
+ */
347
+ async sendSmsCode(mfaToken) {
348
+ const response = await this.post("/frontend/v1/sign-in/factor/sms", { mfa_token: mfaToken });
349
+ let body;
350
+ try {
351
+ body = await response.json();
352
+ } catch {
353
+ throw new FrontendApiError("Cbox ID returned a body that is not JSON.", "malformed", response.status);
354
+ }
355
+ if (body.status === "sent" && typeof body.to === "string") {
356
+ return { status: "sent", to: body.to, expiresIn: typeof body.expires_in === "number" ? body.expires_in : 300 };
357
+ }
358
+ if (body.status === "rate_limited" || response.status === 429) {
359
+ const retryAfter = typeof body.retry_after === "number" ? body.retry_after : Number(response.headers.get("Retry-After") ?? "");
360
+ return { status: "rate_limited", retryAfter: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0 };
361
+ }
362
+ if (body.status === "unavailable") {
363
+ return { status: "unavailable" };
364
+ }
365
+ return { status: "invalid" };
366
+ }
315
367
  /**
316
368
  * The WebAuthn options for a passkey sign-in, and the handle that carries the challenge.
317
369
  *
@@ -607,6 +659,14 @@ function hasRole(source, role) {
607
659
  function hasPermission(source, permission) {
608
660
  return permissions(source).includes(permission);
609
661
  }
662
+ var FEATURE_FLAGS_SCOPE = "feature_flags";
663
+ function featureFlags(source) {
664
+ const claim = claimsOf(source)["feature_flags"];
665
+ return Array.isArray(claim) ? stringList(claim) : null;
666
+ }
667
+ function hasFeature(source, key) {
668
+ return featureFlags(source)?.includes(key) ?? false;
669
+ }
610
670
  var MAX_ACTOR_DEPTH = 8;
611
671
  function parseActor(claim, depth) {
612
672
  if (claim === void 0 || claim === null) {
@@ -633,6 +693,43 @@ function isUser(source) {
633
693
  }
634
694
 
635
695
  // src/vault.ts
696
+ function withConnectReturn(connectUrl, options = {}) {
697
+ const url = new URL(connectUrl);
698
+ if (options.clientId) url.searchParams.set("client_id", options.clientId);
699
+ if (options.returnTo) url.searchParams.set("return_to", options.returnTo);
700
+ return url.toString();
701
+ }
702
+ function pipeConnectUrl(issuer, provider, options = {}) {
703
+ return withConnectReturn(
704
+ `${issuer.replace(/\/$/, "")}/account/connected-services/${encodeURIComponent(provider)}/connect`,
705
+ options
706
+ );
707
+ }
708
+ var PipeLeaseError = class extends CboxIdError {
709
+ constructor(message, error, status, connectUrl = null, retryAfter = null) {
710
+ super(message);
711
+ this.error = error;
712
+ this.status = status;
713
+ this.connectUrl = connectUrl;
714
+ this.retryAfter = retryAfter;
715
+ }
716
+ error;
717
+ status;
718
+ connectUrl;
719
+ retryAfter;
720
+ /** `connectUrl` with your `client_id` and `return_to` on it, or null when there is none. */
721
+ connectUrlWith(options) {
722
+ return this.connectUrl === null ? null : withConnectReturn(this.connectUrl, options);
723
+ }
724
+ };
725
+ var PipeNotConnectedError = class extends PipeLeaseError {
726
+ };
727
+ var PipeReauthorizationRequiredError = class extends PipeLeaseError {
728
+ };
729
+ var PipeTemporarilyUnavailableError = class extends PipeLeaseError {
730
+ };
731
+ var PipeLeaseDeniedError = class extends PipeLeaseError {
732
+ };
636
733
  var VaultClient = class {
637
734
  constructor(issuer, token, timeoutMs = 1e4) {
638
735
  this.token = token;
@@ -688,11 +785,69 @@ var VaultClient = class {
688
785
  return { secretId: r.secret_id, provider: r.provider, secret: r.secret, expiresAt: r.expires_at };
689
786
  });
690
787
  }
788
+ /**
789
+ * Lease a fresh access token for a person's connected account at `provider` (Pipes,
790
+ * scope `vault.lease`). The token is refreshed first when it is about to expire, so
791
+ * you never handle a refresh token.
792
+ *
793
+ * With a client-credentials token, name the person in `userId`. With a token issued to
794
+ * your app FOR a person, leave it out — the lease is theirs.
795
+ *
796
+ * ```ts
797
+ * try {
798
+ * const { accessToken } = await vault.leasePipeToken('github', { userId, purpose: 'list-repos' })
799
+ * } catch (e) {
800
+ * if (e instanceof PipeNotConnectedError || e instanceof PipeReauthorizationRequiredError) {
801
+ * return redirect(e.connectUrlWith({ clientId, returnTo }))
802
+ * }
803
+ * throw e
804
+ * }
805
+ * ```
806
+ */
807
+ async leasePipeToken(provider, options) {
808
+ const path = `/pipes/${encodeURIComponent(provider)}/token`;
809
+ const response = await this.send("POST", path, {
810
+ purpose: options.purpose,
811
+ ...options.userId !== void 0 ? { user_id: options.userId } : {}
812
+ });
813
+ let body = {};
814
+ try {
815
+ const parsed = await response.json();
816
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
817
+ body = parsed;
818
+ }
819
+ } catch {
820
+ }
821
+ if (!response.ok) {
822
+ throw pipeLeaseError(response, body);
823
+ }
824
+ if (typeof body.access_token !== "string") {
825
+ throw new PipeLeaseError("The pipe lease answered without an access token.", null, response.status);
826
+ }
827
+ return {
828
+ accessToken: body.access_token,
829
+ tokenType: "Bearer",
830
+ provider: String(body.provider ?? provider),
831
+ userId: String(body.user_id ?? ""),
832
+ connectionId: String(body.connection_id ?? ""),
833
+ scopes: Array.isArray(body.scopes) ? body.scopes.filter((s) => typeof s === "string") : [],
834
+ expiresAt: typeof body.expires_at === "string" ? body.expires_at : null,
835
+ leaseExpiresAt: String(body.lease_expires_at ?? ""),
836
+ metadata: isStringRecord(body.metadata) ? body.metadata : {}
837
+ };
838
+ }
691
839
  async json(method, path, body) {
692
840
  const response = await this.request(method, path, body);
693
841
  return await response.json();
694
842
  }
695
843
  async request(method, path, body) {
844
+ const response = await this.send(method, path, body);
845
+ if (!response.ok) {
846
+ throw new AuthenticationError(`Vault ${method} ${path} failed with status ${response.status}.`);
847
+ }
848
+ return response;
849
+ }
850
+ async send(method, path, body) {
696
851
  const controller = new AbortController();
697
852
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
698
853
  try {
@@ -707,16 +862,35 @@ var VaultClient = class {
707
862
  if (body) {
708
863
  init.body = JSON.stringify(body);
709
864
  }
710
- const response = await fetch(`${this.base}${path}`, init);
711
- if (!response.ok) {
712
- throw new AuthenticationError(`Vault ${method} ${path} failed with status ${response.status}.`);
713
- }
714
- return response;
865
+ return await fetch(`${this.base}${path}`, init);
715
866
  } finally {
716
867
  clearTimeout(timer);
717
868
  }
718
869
  }
719
870
  };
871
+ function pipeLeaseError(response, body) {
872
+ const error = typeof body.error === "string" ? body.error : null;
873
+ const message = typeof body.message === "string" && body.message !== "" ? body.message : `The pipe lease failed with status ${response.status}.`;
874
+ const connectUrl = typeof body.connect_url === "string" && body.connect_url !== "" ? body.connect_url : null;
875
+ const header2 = response.headers.get("retry-after")?.trim() ?? "";
876
+ const retryAfter = /^\d+$/.test(header2) ? Number(header2) : null;
877
+ if (response.status === 404 && connectUrl !== null) {
878
+ return new PipeNotConnectedError(message, error, 404, connectUrl, retryAfter);
879
+ }
880
+ if (response.status === 409 && connectUrl !== null) {
881
+ return new PipeReauthorizationRequiredError(message, error, 409, connectUrl, retryAfter);
882
+ }
883
+ if (response.status === 503) {
884
+ return new PipeTemporarilyUnavailableError(message, error, 503, connectUrl, retryAfter);
885
+ }
886
+ if (response.status === 403 && error !== "insufficient_scope") {
887
+ return new PipeLeaseDeniedError(message, error, 403, connectUrl, retryAfter);
888
+ }
889
+ return new PipeLeaseError(message, error, response.status, connectUrl, retryAfter);
890
+ }
891
+ function isStringRecord(value) {
892
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((v) => typeof v === "string");
893
+ }
720
894
 
721
895
  // src/webhook.ts
722
896
  function timingSafeEqual2(a, b) {
@@ -766,6 +940,58 @@ async function verifyWebhook(options) {
766
940
  );
767
941
  return timingSafeEqual2(expected, signature);
768
942
  }
943
+ function header(headers, name) {
944
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
945
+ return headers.get(name) ?? void 0;
946
+ }
947
+ const record = headers;
948
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name);
949
+ const value = key === void 0 ? void 0 : record[key];
950
+ return Array.isArray(value) ? value.join(" ") : value;
951
+ }
952
+ function base64ToBytes(value) {
953
+ try {
954
+ const binary = atob(value);
955
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
956
+ } catch {
957
+ return null;
958
+ }
959
+ }
960
+ function toBase64(bytes) {
961
+ let binary = "";
962
+ for (const byte of new Uint8Array(bytes)) {
963
+ binary += String.fromCharCode(byte);
964
+ }
965
+ return btoa(binary);
966
+ }
967
+ async function verifyStandardWebhook(options) {
968
+ const { payload, headers, secret } = options;
969
+ const toleranceSeconds = options.toleranceSeconds ?? 300;
970
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
971
+ const id = header(headers, "webhook-id");
972
+ const timestamp = header(headers, "webhook-timestamp");
973
+ const signatures = header(headers, "webhook-signature");
974
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) {
975
+ return false;
976
+ }
977
+ if (Math.abs(now - Number(timestamp)) > toleranceSeconds) {
978
+ return false;
979
+ }
980
+ const keyBytes = secret.startsWith("whsec_") ? base64ToBytes(secret.slice("whsec_".length)) : new TextEncoder().encode(secret);
981
+ if (keyBytes === null || keyBytes.length === 0) {
982
+ return false;
983
+ }
984
+ const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
985
+ const expected = toBase64(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${payload}`)));
986
+ let valid = false;
987
+ for (const candidate of signatures.split(" ")) {
988
+ const [version, signature] = candidate.split(",", 2);
989
+ if (version === "v1" && signature !== void 0 && timingSafeEqual2(expected, signature)) {
990
+ valid = true;
991
+ }
992
+ }
993
+ return valid;
994
+ }
769
995
 
770
996
  // src/client.ts
771
997
  var CboxIdClient = class {
@@ -934,6 +1160,7 @@ var CboxIdClient = class {
934
1160
  organization: organization(claims),
935
1161
  roles: roles(claims),
936
1162
  permissions: permissions(claims),
1163
+ featureFlags: featureFlags(claims),
937
1164
  actor: actor(claims),
938
1165
  sessionId: sessionId(claims),
939
1166
  // Only present when the instance emitted the claim (exactOptionalPropertyTypes).
@@ -1113,6 +1340,18 @@ var CboxIdClient = class {
1113
1340
  * registered. `organization` picks which of the person's organizations the keys act in;
1114
1341
  * omitted, the page uses the one they are in.
1115
1342
  */
1343
+ /**
1344
+ * The hosted page where the signed-in person connects their account at `provider`
1345
+ * (Pipes) — `/account/connected-services/{provider}/connect`, preselected to this app.
1346
+ * They come back to `returnTo` with `?provider=…&status=connected|cancelled|failed`,
1347
+ * honoured only on an origin the app registered.
1348
+ */
1349
+ pipeConnectUrl(provider, returnTo) {
1350
+ return pipeConnectUrl(this.config.issuer, provider, {
1351
+ clientId: this.config.clientId,
1352
+ ...returnTo !== void 0 ? { returnTo } : {}
1353
+ });
1354
+ }
1116
1355
  apiKeysUrl(options = {}) {
1117
1356
  const params = new URLSearchParams({ client_id: options.clientId ?? this.config.clientId });
1118
1357
  if (options.returnTo) {
@@ -1641,8 +1880,14 @@ exports.CboxIdClient = CboxIdClient;
1641
1880
  exports.CboxIdError = CboxIdError;
1642
1881
  exports.CboxIdFrontend = CboxIdFrontend;
1643
1882
  exports.ConfigurationError = ConfigurationError;
1883
+ exports.FEATURE_FLAGS_SCOPE = FEATURE_FLAGS_SCOPE;
1644
1884
  exports.FrontendApiError = FrontendApiError;
1645
1885
  exports.InvalidStateError = InvalidStateError;
1886
+ exports.PipeLeaseDeniedError = PipeLeaseDeniedError;
1887
+ exports.PipeLeaseError = PipeLeaseError;
1888
+ exports.PipeNotConnectedError = PipeNotConnectedError;
1889
+ exports.PipeReauthorizationRequiredError = PipeReauthorizationRequiredError;
1890
+ exports.PipeTemporarilyUnavailableError = PipeTemporarilyUnavailableError;
1646
1891
  exports.VaultClient = VaultClient;
1647
1892
  exports.actor = actor;
1648
1893
  exports.buildManifest = buildManifest;
@@ -1650,15 +1895,20 @@ exports.challenge = challenge;
1650
1895
  exports.createLegacyVerifier = createLegacyVerifier;
1651
1896
  exports.createVerifier = createVerifier;
1652
1897
  exports.defineAuthz = defineAuthz;
1898
+ exports.featureFlags = featureFlags;
1899
+ exports.hasFeature = hasFeature;
1653
1900
  exports.hasPermission = hasPermission;
1654
1901
  exports.hasRole = hasRole;
1655
1902
  exports.isSupportSession = isSupportSession;
1656
1903
  exports.organization = organization;
1657
1904
  exports.permissions = permissions;
1905
+ exports.pipeConnectUrl = pipeConnectUrl;
1658
1906
  exports.publishManifest = publishManifest;
1659
1907
  exports.randomToken = randomToken;
1660
1908
  exports.roles = roles;
1661
1909
  exports.sessionId = sessionId;
1910
+ exports.verifyStandardWebhook = verifyStandardWebhook;
1662
1911
  exports.verifyWebhook = verifyWebhook;
1912
+ exports.withConnectReturn = withConnectReturn;
1663
1913
  //# sourceMappingURL=index.cjs.map
1664
1914
  //# sourceMappingURL=index.cjs.map