@orangecheck/me-client 0.40.1 → 0.42.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,4 +1,4 @@
1
- import { verifyOcToken as verifyOcToken$1, getOcSession as getOcSession$1, SAFE_METHODS, integratorRevocationCheck, bondMeets, readBondClaim } from '@orangecheck/auth-core';
1
+ import { verifyOcToken as verifyOcToken$1, checkOcToken as checkOcToken$1, readOcSessionToken, SAFE_METHODS, integratorRevocationCheck, bondMeets, readBondClaim } from '@orangecheck/auth-core';
2
2
  export { bondMeets, readBondClaim } from '@orangecheck/auth-core';
3
3
 
4
4
  var __defProp = Object.defineProperty;
@@ -732,6 +732,110 @@ function isClaimUrl(v) {
732
732
  var CONNECT_CONSENT_LABEL = "Also create my orangecheck account";
733
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
734
 
735
+ // src/tokens.ts
736
+ var DEFAULT_ISSUER2 = "https://ochk.io";
737
+ var DEFAULT_TIMEOUT_MS2 = 5e3;
738
+ var MAX_TIMEOUT_MS2 = 3e4;
739
+ var MAX_TOKENS = 8;
740
+ var MAX_TOKEN_LENGTH = 4096;
741
+ function fail2(message) {
742
+ throw new TypeError(`@orangecheck/me-client: ${message}`);
743
+ }
744
+ var nowSeconds = () => Math.floor(Date.now() / 1e3);
745
+ var MemoryJtiStore = class {
746
+ constructor() {
747
+ this.spent = /* @__PURE__ */ new Map();
748
+ }
749
+ add(jti, exp) {
750
+ const now = nowSeconds();
751
+ for (const [k, until] of this.spent) if (until <= now) this.spent.delete(k);
752
+ if (this.spent.has(jti)) return false;
753
+ this.spent.set(jti, exp);
754
+ return true;
755
+ }
756
+ };
757
+ function spendOnce(jti, exp, store) {
758
+ if (typeof jti !== "string" || jti === "") fail2("spendOnce: jti must be one non-empty string");
759
+ if (typeof exp !== "number" || !Number.isFinite(exp)) {
760
+ fail2("spendOnce: exp must be the token's expiry, in seconds");
761
+ }
762
+ if (store === null || typeof store !== "object" || typeof store.add !== "function") {
763
+ fail2("spendOnce: store must have add(jti, exp)");
764
+ }
765
+ if (exp <= nowSeconds()) return Promise.resolve(false);
766
+ return Promise.resolve().then(() => store.add(jti, exp)).then((spent) => {
767
+ if (typeof spent !== "boolean") fail2("spendOnce: store.add must answer true or false");
768
+ return spent;
769
+ });
770
+ }
771
+ var REVOKE_OPTIONS = /* @__PURE__ */ new Set(["issuer", "timeoutMs"]);
772
+ function issuerOrigin(issuer) {
773
+ if (typeof issuer !== "string") fail2("revokeToken: issuer must be a URL");
774
+ const refuse = () => fail2(`revokeToken: issuer must be one https origin (http only on this machine), such as https://ochk.io, got ${issuer}`);
775
+ if (/[?#@\\]/.test(issuer)) refuse();
776
+ let url;
777
+ try {
778
+ url = new URL(issuer);
779
+ } catch {
780
+ return refuse();
781
+ }
782
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
783
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) refuse();
784
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "" || url.username !== "" || url.password !== "") {
785
+ refuse();
786
+ }
787
+ return url.origin;
788
+ }
789
+ function revokeToken(token, options = {}) {
790
+ if (options === null || typeof options !== "object") fail2("revokeToken: options must be an object");
791
+ const unknown = Object.keys(options).filter((k) => !REVOKE_OPTIONS.has(k));
792
+ if (unknown.length > 0) {
793
+ fail2(`revokeToken: unknown option ${unknown.join(", ")}. It reads only ${[...REVOKE_OPTIONS].join(", ")}.`);
794
+ }
795
+ const tokens = typeof token === "string" ? [token] : Array.isArray(token) ? [...token] : null;
796
+ if (!tokens || tokens.length < 1 || tokens.length > MAX_TOKENS || !tokens.every((t) => typeof t === "string" && t.length > 0 && t.length <= MAX_TOKEN_LENGTH)) {
797
+ fail2(`revokeToken: pass one token, or 1 to ${MAX_TOKENS}, each a non-empty string of at most ${MAX_TOKEN_LENGTH} characters`);
798
+ }
799
+ const origin = issuerOrigin(options.issuer ?? DEFAULT_ISSUER2);
800
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
801
+ if (typeof timeoutMs !== "number" || !(timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS2)) {
802
+ fail2(`revokeToken: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS2}`);
803
+ }
804
+ return post2(`${origin}/api/auth/revoke`, tokens, timeoutMs);
805
+ }
806
+ async function post2(url, tokens, timeoutMs) {
807
+ const controller = new AbortController();
808
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
809
+ try {
810
+ const res = await fetch(url, {
811
+ method: "POST",
812
+ // The endpoint never redirects, so a redirect is an error: the tokens go
813
+ // to the auth host and nowhere else.
814
+ redirect: "error",
815
+ headers: { "content-type": "application/json" },
816
+ body: JSON.stringify({ tokens }),
817
+ signal: controller.signal
818
+ });
819
+ let body = null;
820
+ try {
821
+ body = await res.json();
822
+ } catch {
823
+ body = null;
824
+ }
825
+ const b = body !== null && typeof body === "object" ? body : null;
826
+ if (res.status === 200) {
827
+ return b?.ok === true && Number.isSafeInteger(b.revoked) && b.revoked >= 0 ? { ok: true, revoked: b.revoked } : { ok: false, reason: "unavailable", status: 200 };
828
+ }
829
+ if (res.status === 429) return { ok: false, reason: "rate_limited", status: 429 };
830
+ if (res.status === 400) return { ok: false, reason: "bad_request", status: 400 };
831
+ return { ok: false, reason: "unavailable", status: res.status };
832
+ } catch {
833
+ return { ok: false, reason: "unavailable", status: 0 };
834
+ } finally {
835
+ clearTimeout(timer);
836
+ }
837
+ }
838
+
735
839
  // src/server.ts
736
840
  function lacksHandle(session, requireHandle) {
737
841
  if (requireHandle === false) return false;
@@ -766,6 +870,21 @@ async function verifyOcToken(token, options = {}) {
766
870
  }
767
871
  return session;
768
872
  }
873
+ async function checkOcToken(token, options = {}) {
874
+ if (options === null || typeof options !== "object") {
875
+ throw new TypeError("@orangecheck/me-client: options must be an object");
876
+ }
877
+ const { requireHandle, ...core } = options;
878
+ checkRequireHandle(requireHandle);
879
+ const checked = await checkOcToken$1(token, core);
880
+ if (checked.status === "unavailable") return { status: "unavailable", reason: "key_set_unavailable" };
881
+ if (checked.status === "invalid") return { status: "invalid" };
882
+ if (lacksHandle(checked.session, requireHandle)) {
883
+ warnNoHandle(checked.session);
884
+ return { status: "invalid", reason: "no_session_handle" };
885
+ }
886
+ return { status: "valid", session: checked.session };
887
+ }
769
888
  var sessionChecks = /* @__PURE__ */ new Map();
770
889
  var warnedUnchecked = false;
771
890
  function revocationFor(options) {
@@ -803,11 +922,15 @@ async function getOcSession(headers, options = {}) {
803
922
  async function checkOcSession(headers, options = {}) {
804
923
  checkOptions(options);
805
924
  const { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience } = options;
806
- const session = await getOcSession$1(headers, { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience });
807
- if (!session) {
925
+ const token = readOcSessionToken(headers);
926
+ if (!token) return { status: "signed_out" };
927
+ const verified = await checkOcToken$1(token, { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience });
928
+ if (verified.status === "unavailable") return { status: "unavailable", reason: "key_set_unavailable" };
929
+ if (verified.status === "invalid") {
808
930
  if (options.audience === void 0) warnIfAudienceMissing(headers);
809
931
  return { status: "signed_out" };
810
932
  }
933
+ const session = verified.session;
811
934
  if (lacksHandle(session, options.requireHandle)) {
812
935
  warnNoHandle(session);
813
936
  return { status: "signed_out", reason: "no_session_handle" };
@@ -817,12 +940,15 @@ async function checkOcSession(headers, options = {}) {
817
940
  const state = await check.status(session);
818
941
  if (state === "revoked") return { status: "signed_out" };
819
942
  if (state === "unverified" && !SAFE_METHODS.has((options.method ?? "").toUpperCase())) {
820
- return { status: "unavailable" };
943
+ return { status: "unavailable", reason: "revocations_unavailable" };
821
944
  }
822
945
  }
823
946
  return { status: "signed_in", session };
824
947
  }
825
- var UNAVAILABLE = { status: 503, body: { ok: false, reason: "revocations_unavailable" } };
948
+ var unavailable = (checked) => ({
949
+ status: 503,
950
+ body: { ok: false, reason: checked.reason ?? "revocations_unavailable" }
951
+ });
826
952
  var refusedFor = (checked) => checked.status === "signed_out" ? checked.reason : void 0;
827
953
  var warnedAudience = false;
828
954
  function warnIfAudienceMissing(headers) {
@@ -1002,7 +1128,7 @@ function withOcAuth(handler, options = {}) {
1002
1128
  const session = checked.status === "signed_in" ? checked.session : null;
1003
1129
  const withSession = req;
1004
1130
  withSession.ocSession = session;
1005
- const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1131
+ const refused2 = checked.status === "unavailable" ? unavailable(checked) : await refusal(session, options, refusedFor(checked));
1006
1132
  if (refused2) return res.status(refused2.status).json(refused2.body);
1007
1133
  return handler(withSession, res);
1008
1134
  };
@@ -1022,7 +1148,7 @@ function ocAuthExpress(options = {}) {
1022
1148
  );
1023
1149
  const session = checked.status === "signed_in" ? checked.session : null;
1024
1150
  req.ocSession = session;
1025
- const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1151
+ const refused2 = checked.status === "unavailable" ? unavailable(checked) : await refusal(session, options, refusedFor(checked));
1026
1152
  if (refused2) {
1027
1153
  res.status(refused2.status).json(refused2.body);
1028
1154
  return;
@@ -1044,12 +1170,12 @@ function ocAuthHono(options = {}) {
1044
1170
  });
1045
1171
  const session = checked.status === "signed_in" ? checked.session : null;
1046
1172
  c.set("ocSession", session);
1047
- const refused2 = checked.status === "unavailable" ? UNAVAILABLE : await refusal(session, options, refusedFor(checked));
1173
+ const refused2 = checked.status === "unavailable" ? unavailable(checked) : await refusal(session, options, refusedFor(checked));
1048
1174
  if (refused2) return c.json(refused2.body, refused2.status);
1049
1175
  await next();
1050
1176
  };
1051
1177
  }
1052
1178
 
1053
- export { BACK_ACCOUNT_URL, CONNECT_CONSENT_BLURB, CONNECT_CONSENT_LABEL, _resetSessionChecksForTests, checkOcSession, connectClaimLink, connectDelete, connectProvision, getOcSession, identity, ocAuthExpress, ocAuthHono, refreshEnvelopeJwks, verifyActivityAttestation, verifyOcToken, withOcAuth };
1179
+ export { BACK_ACCOUNT_URL, CONNECT_CONSENT_BLURB, CONNECT_CONSENT_LABEL, MemoryJtiStore, _resetSessionChecksForTests, checkOcSession, checkOcToken, connectClaimLink, connectDelete, connectProvision, getOcSession, identity, ocAuthExpress, ocAuthHono, refreshEnvelopeJwks, revokeToken, spendOnce, verifyActivityAttestation, verifyOcToken, withOcAuth };
1054
1180
  //# sourceMappingURL=server.mjs.map
1055
1181
  //# sourceMappingURL=server.mjs.map