@orangecheck/me-client 0.38.3 → 0.40.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.
package/dist/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { getOcSession as getOcSession$1, SAFE_METHODS, integratorRevocationCheck, bondMeets, readBondClaim } from '@orangecheck/auth-core';
2
- export { bondMeets, readBondClaim, verifyOcToken } from '@orangecheck/auth-core';
1
+ import { verifyOcToken as verifyOcToken$1, getOcSession as getOcSession$1, SAFE_METHODS, integratorRevocationCheck, bondMeets, readBondClaim } from '@orangecheck/auth-core';
2
+ export { bondMeets, readBondClaim } from '@orangecheck/auth-core';
3
3
 
4
4
  var __defProp = Object.defineProperty;
5
5
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -568,7 +568,204 @@ var identity = {
568
568
  refreshEnvelopeJwks
569
569
  };
570
570
 
571
+ // src/connect.ts
572
+ var ORIGIN = "https://ochk.io";
573
+ var DEFAULT_TIMEOUT_MS = 5e3;
574
+ var MAX_TIMEOUT_MS = 3e4;
575
+ var DID_OC = /^did:oc:[0-9a-f]{32}$/;
576
+ var BASE_KEYS = ["apiKey", "userId", "timeoutMs"];
577
+ var PROVISION_KEYS = /* @__PURE__ */ new Set([...BASE_KEYS, "consent", "email", "emailVerified"]);
578
+ var USER_KEYS = new Set(BASE_KEYS);
579
+ var PROVISION_REASONS = /* @__PURE__ */ new Set([
580
+ "account_deleted",
581
+ "daily_limit",
582
+ "rate_limited",
583
+ "invalid_api_key",
584
+ "app_suspended",
585
+ "bad_request"
586
+ ]);
587
+ var DELETE_REASONS = /* @__PURE__ */ new Set([
588
+ "unknown_user",
589
+ "holds_earnings",
590
+ "not_deletable",
591
+ "rate_limited",
592
+ "invalid_api_key",
593
+ "bad_request"
594
+ ]);
595
+ var CLAIM_LINK_REASONS = /* @__PURE__ */ new Set([
596
+ "unknown_user",
597
+ "already_claimed",
598
+ "rate_limited",
599
+ "invalid_api_key",
600
+ "app_suspended",
601
+ "bad_request"
602
+ ]);
603
+ var DELETE_RESULTS = /* @__PURE__ */ new Set(["deleted", "detached", "already_deleted"]);
604
+ function fail(message) {
605
+ throw new TypeError(`@orangecheck/me-client: ${message}`);
606
+ }
607
+ function checkCall(name, options, known) {
608
+ if (typeof document !== "undefined") {
609
+ fail(`${name} runs on your server only: in a browser your API key would be exposed`);
610
+ }
611
+ if (options === null || typeof options !== "object") fail(`${name}: options must be an object`);
612
+ const unknown = Object.keys(options).filter((k) => !known.has(k));
613
+ if (unknown.length > 0) {
614
+ const only = [...known].join(", ");
615
+ fail(`${name}: unknown option ${unknown.join(", ")}. It reads only ${only}.`);
616
+ }
617
+ const o = Object.assign(/* @__PURE__ */ Object.create(null), options);
618
+ if (typeof o.apiKey !== "string" || o.apiKey.trim() === "") {
619
+ fail(`${name}: apiKey is required (your Connect API key)`);
620
+ }
621
+ const id = o.userId;
622
+ if (typeof id !== "string" || id.length < 1 || id.length > 256) {
623
+ fail(`${name}: userId must be your user's id, 1 to 256 characters`);
624
+ }
625
+ const t = o.timeoutMs;
626
+ if (t !== void 0 && !(typeof t === "number" && t > 0 && t <= MAX_TIMEOUT_MS)) {
627
+ fail(`${name}: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);
628
+ }
629
+ return o;
630
+ }
631
+ async function post(path, apiKey, body, timeoutMs) {
632
+ const controller = new AbortController();
633
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
634
+ try {
635
+ const res = await fetch(`${ORIGIN}${path}`, {
636
+ method: "POST",
637
+ // These endpoints never redirect, so a redirect is an error: the key and
638
+ // the body go to ochk.io and nowhere else.
639
+ redirect: "error",
640
+ headers: {
641
+ "content-type": "application/json",
642
+ authorization: `Bearer ${apiKey}`
643
+ },
644
+ body: JSON.stringify(body),
645
+ signal: controller.signal
646
+ });
647
+ let parsed = null;
648
+ try {
649
+ parsed = await res.json();
650
+ } catch {
651
+ parsed = null;
652
+ }
653
+ const ok = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
654
+ return { status: res.status, body: ok ? parsed : null };
655
+ } catch {
656
+ return { status: 0, body: null };
657
+ } finally {
658
+ clearTimeout(timer);
659
+ }
660
+ }
661
+ function refused(answer, known) {
662
+ const raw = answer.body?.reason;
663
+ const said = raw === "missing_api_key" ? "invalid_api_key" : raw;
664
+ const reason = typeof said === "string" && known.has(said) ? said : "unavailable";
665
+ return { ok: false, reason, status: answer.status };
666
+ }
667
+ function connectProvision(options) {
668
+ const o = checkCall("connectProvision", options, PROVISION_KEYS);
669
+ if (o.consent !== void 0 && o.consent !== true) {
670
+ fail(
671
+ "connectProvision: consent must be true or left out. An unticked box means no call at all; a call without consent makes an account nobody asked for"
672
+ );
673
+ }
674
+ const { email, emailVerified } = o;
675
+ if (email !== void 0 && (typeof email !== "string" || email === "")) {
676
+ fail("connectProvision: email must be a non-empty string");
677
+ }
678
+ if (emailVerified !== void 0 && typeof emailVerified !== "boolean") {
679
+ fail("connectProvision: emailVerified must be a boolean");
680
+ }
681
+ if (emailVerified !== void 0 && email === void 0) {
682
+ fail("connectProvision: emailVerified describes email, so pass email too");
683
+ }
684
+ const body = { user_id: o.userId };
685
+ if (o.consent === true) body.consent = true;
686
+ if (email !== void 0) body.email = email;
687
+ if (emailVerified !== void 0) body.email_verified = emailVerified;
688
+ return call("/api/connect/provision", o, body).then(
689
+ (answer) => {
690
+ const b = answer.body;
691
+ if (answer.status !== 200) return refused(answer, PROVISION_REASONS);
692
+ const good = b?.ok === true && typeof b.did_oc === "string" && DID_OC.test(b.did_oc) && typeof b.is_new === "boolean";
693
+ return good ? { ok: true, did_oc: b.did_oc, is_new: b.is_new } : { ok: false, reason: "unavailable", status: 200 };
694
+ }
695
+ );
696
+ }
697
+ function connectClaimLink(options) {
698
+ const o = checkCall("connectClaimLink", options, USER_KEYS);
699
+ return call("/api/connect/claim-link", o, { user_id: o.userId }).then(
700
+ (answer) => {
701
+ const b = answer.body;
702
+ if (answer.status !== 200) return refused(answer, CLAIM_LINK_REASONS);
703
+ const good = b?.ok === true && isClaimUrl(b.url) && typeof b.expires_at === "string" && b.expires_at !== "";
704
+ return good ? { ok: true, url: b.url, expires_at: b.expires_at } : { ok: false, reason: "unavailable", status: 200 };
705
+ }
706
+ );
707
+ }
708
+ function connectDelete(options) {
709
+ const o = checkCall("connectDelete", options, USER_KEYS);
710
+ return call("/api/connect/delete", o, { user_id: o.userId }).then(
711
+ (answer) => {
712
+ const b = answer.body;
713
+ if (answer.status !== 200) return refused(answer, DELETE_REASONS);
714
+ return b?.ok === true && typeof b.result === "string" && DELETE_RESULTS.has(b.result) ? { ok: true, result: b.result } : { ok: false, reason: "unavailable", status: 200 };
715
+ }
716
+ );
717
+ }
718
+ function call(path, o, body) {
719
+ return post(path, o.apiKey, body, o.timeoutMs ?? DEFAULT_TIMEOUT_MS);
720
+ }
721
+ function isClaimUrl(v) {
722
+ if (typeof v !== "string") return false;
723
+ try {
724
+ const url = new URL(v);
725
+ return url.protocol === "https:" && url.hostname === "ochk.app" && url.port === "" && url.username === "" && url.password === "";
726
+ } catch {
727
+ return false;
728
+ }
729
+ }
730
+
731
+ // src/connect-consent.ts
732
+ var CONNECT_CONSENT_LABEL = "Also create my orangecheck account";
733
+ var CONNECT_CONSENT_BLURB = "It stays with orangecheck until you claim it at ochk.app. Then you can use it on other sites, or delete it.";
734
+
571
735
  // src/server.ts
736
+ function lacksHandle(session, requireHandle) {
737
+ if (requireHandle === false) return false;
738
+ const { aud, rh } = session;
739
+ if (aud === void 0) return false;
740
+ return typeof rh !== "string" || rh.length === 0;
741
+ }
742
+ function checkRequireHandle(requireHandle) {
743
+ if (requireHandle !== void 0 && typeof requireHandle !== "boolean") {
744
+ throw new TypeError("@orangecheck/me-client: requireHandle must be true or false");
745
+ }
746
+ }
747
+ var warnedHandle = false;
748
+ function warnNoHandle(session) {
749
+ if (warnedHandle) return;
750
+ warnedHandle = true;
751
+ console.warn(
752
+ `[@orangecheck/me-client] a sign-in token bound to ${JSON.stringify(session.aud)} carries no revocation handle (rh), so sign out everywhere could not end it, and it was refused (no_session_handle). Tokens from the ochk.app sign-in popup carry one. Pass requireHandle: false only to accept tokens minted some other way.`
753
+ );
754
+ }
755
+ async function verifyOcToken(token, options = {}) {
756
+ if (options === null || typeof options !== "object") {
757
+ throw new TypeError("@orangecheck/me-client: options must be an object");
758
+ }
759
+ const { requireHandle, ...core } = options;
760
+ checkRequireHandle(requireHandle);
761
+ const session = await verifyOcToken$1(token, core);
762
+ if (!session) return null;
763
+ if (lacksHandle(session, requireHandle)) {
764
+ warnNoHandle(session);
765
+ return null;
766
+ }
767
+ return session;
768
+ }
572
769
  var sessionChecks = /* @__PURE__ */ new Map();
573
770
  var warnedUnchecked = false;
574
771
  function revocationFor(options) {
@@ -597,6 +794,7 @@ function revocationFor(options) {
597
794
  function _resetSessionChecksForTests() {
598
795
  sessionChecks.clear();
599
796
  warnedUnchecked = false;
797
+ warnedHandle = false;
600
798
  }
601
799
  async function getOcSession(headers, options = {}) {
602
800
  const checked = await checkOcSession(headers, options);
@@ -610,6 +808,10 @@ async function checkOcSession(headers, options = {}) {
610
808
  if (options.audience === void 0) warnIfAudienceMissing(headers);
611
809
  return { status: "signed_out" };
612
810
  }
811
+ if (lacksHandle(session, options.requireHandle)) {
812
+ warnNoHandle(session);
813
+ return { status: "signed_out", reason: "no_session_handle" };
814
+ }
613
815
  const check = revocationFor(options);
614
816
  if (check) {
615
817
  const state = await check.status(session);
@@ -621,6 +823,7 @@ async function checkOcSession(headers, options = {}) {
621
823
  return { status: "signed_in", session };
622
824
  }
623
825
  var UNAVAILABLE = { status: 503, body: { ok: false, reason: "revocations_unavailable" } };
826
+ var refusedFor = (checked) => checked.status === "signed_out" ? checked.reason : void 0;
624
827
  var warnedAudience = false;
625
828
  function warnIfAudienceMissing(headers) {
626
829
  if (warnedAudience) return;
@@ -655,6 +858,7 @@ var KNOWN_OPTIONS = /* @__PURE__ */ new Set([
655
858
  "projectKey",
656
859
  "meOrigin",
657
860
  "revocation",
861
+ "requireHandle",
658
862
  "required",
659
863
  "requireBond"
660
864
  ]);
@@ -669,6 +873,7 @@ function checkOptions(options) {
669
873
  `@orangecheck/me-client: unknown option ${unknown.join(", ")}. It reads only ${[...KNOWN_OPTIONS].join(", ")}.`
670
874
  );
671
875
  }
876
+ checkRequireHandle(options.requireHandle);
672
877
  const bond = options.requireBond;
673
878
  if (bond === void 0) return;
674
879
  if (bond === null || typeof bond !== "object") {
@@ -751,10 +956,9 @@ async function bondNeed(options) {
751
956
  if (options.projectKey) return projectRequirement(options);
752
957
  return null;
753
958
  }
754
- async function refusal(session, options) {
755
- if (!session && options.required) {
756
- return { status: 401, body: { ok: false, reason: "unauthenticated" } };
757
- }
959
+ async function refusal(session, options, why) {
960
+ const unauthenticated = { status: 401, body: { ok: false, reason: why ?? "unauthenticated" } };
961
+ if (!session && options.required) return unauthenticated;
758
962
  if (!session && !options.requireBond) return null;
759
963
  const need = await bondNeed(options);
760
964
  if (need === UNKNOWN_PROJECT) {
@@ -763,9 +967,7 @@ async function refusal(session, options) {
763
967
  if (need === void 0) {
764
968
  return { status: 503, body: { ok: false, reason: "bond_policy_unavailable" } };
765
969
  }
766
- if (!session) {
767
- return need ? { status: 401, body: { ok: false, reason: "unauthenticated" } } : null;
768
- }
970
+ if (!session) return need ? unauthenticated : null;
769
971
  if (need && !bondMeets(session, need)) {
770
972
  const have = readBondClaim(session);
771
973
  return {
@@ -800,8 +1002,8 @@ function withOcAuth(handler, options = {}) {
800
1002
  const session = checked.status === "signed_in" ? checked.session : null;
801
1003
  const withSession = req;
802
1004
  withSession.ocSession = session;
803
- const refused = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options);
804
- if (refused) return res.status(refused.status).json(refused.body);
1005
+ const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1006
+ if (refused2) return res.status(refused2.status).json(refused2.body);
805
1007
  return handler(withSession, res);
806
1008
  };
807
1009
  }
@@ -820,9 +1022,9 @@ function ocAuthExpress(options = {}) {
820
1022
  );
821
1023
  const session = checked.status === "signed_in" ? checked.session : null;
822
1024
  req.ocSession = session;
823
- const refused = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options);
824
- if (refused) {
825
- res.status(refused.status).json(refused.body);
1025
+ const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1026
+ if (refused2) {
1027
+ res.status(refused2.status).json(refused2.body);
826
1028
  return;
827
1029
  }
828
1030
  next();
@@ -842,12 +1044,12 @@ function ocAuthHono(options = {}) {
842
1044
  });
843
1045
  const session = checked.status === "signed_in" ? checked.session : null;
844
1046
  c.set("ocSession", session);
845
- const refused = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options);
846
- if (refused) return c.json(refused.body, refused.status);
1047
+ const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1048
+ if (refused2) return c.json(refused2.body, refused2.status);
847
1049
  await next();
848
1050
  };
849
1051
  }
850
1052
 
851
- export { BACK_ACCOUNT_URL, _resetSessionChecksForTests, checkOcSession, getOcSession, identity, ocAuthExpress, ocAuthHono, refreshEnvelopeJwks, verifyActivityAttestation, withOcAuth };
1053
+ export { BACK_ACCOUNT_URL, CONNECT_CONSENT_BLURB, CONNECT_CONSENT_LABEL, _resetSessionChecksForTests, checkOcSession, connectClaimLink, connectDelete, connectProvision, getOcSession, identity, ocAuthExpress, ocAuthHono, refreshEnvelopeJwks, verifyActivityAttestation, verifyOcToken, withOcAuth };
852
1054
  //# sourceMappingURL=server.mjs.map
853
1055
  //# sourceMappingURL=server.mjs.map