@orangecheck/me-client 0.48.0 → 0.50.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.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SessionPayload, VerifyOcOptions, RevocationCheck, SessionRequestHeaders } from '@orangecheck/auth-core';
1
+ import { RevocationCheck, SessionPayload, VerifyOcOptions, SessionRequestHeaders } from '@orangecheck/auth-core';
2
2
  export { BondClaim, SessionPayload, VerifyOcOptions, bondMeets, readBondClaim } from '@orangecheck/auth-core';
3
3
  export { A as ActivityAttestation, a as ActivityAttestationBundle, b as ActivityVerifyCheck, c as ActivityVerifyResult, V as VerifyActivityOptions, i as identity, r as refreshEnvelopeJwks, v as verifyActivityAttestation } from './identity-DfxCvxuH.js';
4
4
  export { CONNECT_CONSENT_BLURB, CONNECT_CONSENT_LABEL } from './connect-consent.js';
@@ -62,6 +62,48 @@ type RevokeTokenResult = {
62
62
  };
63
63
  declare function revokeToken(token: string | readonly string[], options?: RevokeTokenOptions): Promise<RevokeTokenResult>;
64
64
 
65
+ interface ExchangeNativeCodeInput {
66
+ code: string;
67
+ codeVerifier: string;
68
+ redirectUri: string;
69
+ audience: string;
70
+ }
71
+ interface ExchangeNativeCodeOptions {
72
+ projectKey?: string;
73
+ issuer?: string;
74
+ meOrigin?: string;
75
+ revocation?: RevocationCheck | false;
76
+ requireBond?: WithOcAuthOptions['requireBond'];
77
+ timeoutMs?: number;
78
+ }
79
+ type ExchangeNativeCodeRefusal = 'invalid_grant' | 'not_offered' | 'bad_request' | 'invalid_token' | 'no_session_handle' | 'session_ended' | 'unknown_project_key';
80
+ type ExchangeNativeCodeUnavailable = 'auth_host_unavailable' | 'rate_limited' | 'key_set_unavailable' | 'revocations_unavailable' | 'bond_policy_unavailable';
81
+ type ExchangeNativeCodeResult = {
82
+ status: 'valid';
83
+ token: string;
84
+ session: SessionPayload;
85
+ } | {
86
+ status: 'invalid';
87
+ reason: ExchangeNativeCodeRefusal;
88
+ } | {
89
+ status: 'invalid';
90
+ reason: 'bond_required';
91
+ need: {
92
+ min_sats: number;
93
+ min_days: number;
94
+ max_age_secs?: number;
95
+ };
96
+ have: {
97
+ sats_floor: number;
98
+ days_floor: number;
99
+ } | null;
100
+ back_url: string;
101
+ } | {
102
+ status: 'unavailable';
103
+ reason: ExchangeNativeCodeUnavailable;
104
+ };
105
+ declare function exchangeNativeCode(input: ExchangeNativeCodeInput, options?: ExchangeNativeCodeOptions): Promise<ExchangeNativeCodeResult>;
106
+
65
107
  type MergedUserMatch = {
66
108
  kind: 'none';
67
109
  } | {
@@ -198,4 +240,4 @@ interface HonoContextLike {
198
240
  type HonoNextLike = () => Promise<void>;
199
241
  declare function ocAuthHono(options?: WithOcAuthOptions): (c: HonoContextLike, next: HonoNextLike) => Promise<unknown>;
200
242
 
201
- export { BACK_ACCOUNT_URL, type ConnectClaimLinkRefusal, type ConnectClaimLinkResult, type ConnectDeleteRefusal, type ConnectDeleteResult, type ConnectOptions, type ConnectProvisionOptions, type ConnectProvisionRefusal, type ConnectProvisionResult, type ConnectRefused, type JtiStore, MemoryJtiStore, type MergedUserMatch, type OcHonoEnv, type OcSessionCheck, type OcSessionOptions, type OcSessionRefusal, type OcSessionUnavailable, type OcTokenCheck, type RevokeTokenOptions, type RevokeTokenRefusal, type RevokeTokenResult, type SignInRuleCheck, type SignInRuleOptions, type VerifyOcTokenOptions, type WithOcAuthOptions, type WithOcSession, _resetSessionChecksForTests, checkOcSession, checkOcToken, checkSignInRule, connectClaimLink, connectDelete, connectProvision, getOcSession, matchMergedUser, mergedHandles, ocAuthExpress, ocAuthHono, revokeToken, spendOnce, verifyOcToken, withOcAuth };
243
+ export { BACK_ACCOUNT_URL, type ConnectClaimLinkRefusal, type ConnectClaimLinkResult, type ConnectDeleteRefusal, type ConnectDeleteResult, type ConnectOptions, type ConnectProvisionOptions, type ConnectProvisionRefusal, type ConnectProvisionResult, type ConnectRefused, type ExchangeNativeCodeInput, type ExchangeNativeCodeOptions, type ExchangeNativeCodeRefusal, type ExchangeNativeCodeResult, type ExchangeNativeCodeUnavailable, type JtiStore, MemoryJtiStore, type MergedUserMatch, type OcHonoEnv, type OcSessionCheck, type OcSessionOptions, type OcSessionRefusal, type OcSessionUnavailable, type OcTokenCheck, type RevokeTokenOptions, type RevokeTokenRefusal, type RevokeTokenResult, type SignInRuleCheck, type SignInRuleOptions, type VerifyOcTokenOptions, type WithOcAuthOptions, type WithOcSession, _resetSessionChecksForTests, checkOcSession, checkOcToken, checkSignInRule, connectClaimLink, connectDelete, connectProvision, exchangeNativeCode, getOcSession, matchMergedUser, mergedHandles, ocAuthExpress, ocAuthHono, revokeToken, spendOnce, verifyOcToken, withOcAuth };
package/dist/server.js CHANGED
@@ -770,9 +770,9 @@ function spendOnce(jti, exp, store) {
770
770
  });
771
771
  }
772
772
  var REVOKE_OPTIONS = /* @__PURE__ */ new Set(["issuer", "timeoutMs"]);
773
- function issuerOrigin(issuer) {
774
- if (typeof issuer !== "string") fail2("revokeToken: issuer must be a URL");
775
- const refuse = () => fail2(`revokeToken: issuer must be one https origin (http only on this machine), such as https://ochk.io, got ${issuer}`);
773
+ function issuerOrigin(issuer, where = "revokeToken") {
774
+ if (typeof issuer !== "string") fail2(`${where}: issuer must be a URL`);
775
+ const refuse = () => fail2(`${where}: issuer must be one https origin (http only on this machine), such as https://ochk.io, got ${issuer}`);
776
776
  if (/[?#@\\]/.test(issuer)) refuse();
777
777
  let url;
778
778
  try {
@@ -837,6 +837,128 @@ async function post2(url, tokens, timeoutMs) {
837
837
  }
838
838
  }
839
839
 
840
+ // src/native.ts
841
+ var DEFAULT_ISSUER3 = "https://ochk.io";
842
+ var DEFAULT_TIMEOUT_MS3 = 5e3;
843
+ var MAX_TIMEOUT_MS3 = 3e4;
844
+ var MAX_FIELD_LENGTH = 512;
845
+ var OPTIONS = /* @__PURE__ */ new Set([
846
+ "projectKey",
847
+ "issuer",
848
+ "meOrigin",
849
+ "revocation",
850
+ "requireBond",
851
+ "timeoutMs"
852
+ ]);
853
+ var FIELDS = ["code", "codeVerifier", "redirectUri", "audience"];
854
+ function fail3(message) {
855
+ throw new TypeError(`@orangecheck/me-client: exchangeNativeCode: ${message}`);
856
+ }
857
+ async function exchangeNativeCode(input, options = {}) {
858
+ if (input === null || typeof input !== "object") fail3("input must be an object");
859
+ if ("projectKey" in input) {
860
+ fail3("projectKey is your own key: pass it in options, or set OC_PROJECT_KEY, never from the request");
861
+ }
862
+ const extra = Object.keys(input).filter((k) => !FIELDS.includes(k));
863
+ if (extra.length > 0) fail3(`unknown input ${extra.join(", ")}. It reads only ${FIELDS.join(", ")}.`);
864
+ for (const f of FIELDS) {
865
+ const v = input[f];
866
+ if (typeof v !== "string" || v.length === 0 || v.length > MAX_FIELD_LENGTH) {
867
+ fail3(`${f} must be a non-empty string of at most ${MAX_FIELD_LENGTH} characters`);
868
+ }
869
+ }
870
+ if (input.audience === "*") fail3("audience must be your site's origin, not '*'");
871
+ if (options === null || typeof options !== "object") fail3("options must be an object");
872
+ const unknown = Object.keys(options).filter((k) => !OPTIONS.has(k));
873
+ if (unknown.length > 0) fail3(`unknown option ${unknown.join(", ")}. It reads only ${[...OPTIONS].join(", ")}.`);
874
+ const projectKey = options.projectKey ?? (typeof process !== "undefined" ? process.env?.OC_PROJECT_KEY?.trim() : void 0);
875
+ if (typeof projectKey !== "string" || projectKey.length === 0 || projectKey.length > MAX_FIELD_LENGTH) {
876
+ fail3("needs your project key: options.projectKey, or OC_PROJECT_KEY");
877
+ }
878
+ const issuer = issuerOrigin(options.issuer ?? DEFAULT_ISSUER3, "exchangeNativeCode");
879
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
880
+ if (typeof timeoutMs !== "number" || !(timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS3)) {
881
+ fail3(`timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS3}`);
882
+ }
883
+ const answer = await post3(`${issuer}/api/auth/native/token`, input, projectKey, timeoutMs);
884
+ if (answer.status !== "token") return answer;
885
+ const token = answer.token;
886
+ const verified = await checkOcToken(token, { audience: input.audience, issuer });
887
+ if (verified.status === "unavailable") return { status: "unavailable", reason: "key_set_unavailable" };
888
+ if (verified.status === "invalid") return { status: "invalid", reason: verified.reason ?? "invalid_token" };
889
+ const where = options.meOrigin ? { meOrigin: options.meOrigin } : {};
890
+ const checked = await checkOcSession(
891
+ { authorization: `Bearer ${token}` },
892
+ {
893
+ audience: input.audience,
894
+ issuer,
895
+ projectKey,
896
+ method: "POST",
897
+ ...where,
898
+ ...options.revocation !== void 0 ? { revocation: options.revocation } : {}
899
+ }
900
+ );
901
+ if (checked.status === "unavailable") {
902
+ return { status: "unavailable", reason: checked.reason ?? "revocations_unavailable" };
903
+ }
904
+ if (checked.status === "signed_out") return { status: "invalid", reason: checked.reason ?? "session_ended" };
905
+ const rule = await checkSignInRule(checked.session, {
906
+ projectKey,
907
+ ...where,
908
+ ...options.requireBond ? { requireBond: options.requireBond } : {}
909
+ });
910
+ if (!rule.ok) {
911
+ const b = rule.body;
912
+ if (b.reason === "bond_required" && b.need && b.back_url) {
913
+ return { status: "invalid", reason: "bond_required", need: b.need, have: b.have ?? null, back_url: b.back_url };
914
+ }
915
+ if (b.reason === "unknown_project_key") return { status: "invalid", reason: "unknown_project_key" };
916
+ return { status: "unavailable", reason: "bond_policy_unavailable" };
917
+ }
918
+ return { status: "valid", token, session: checked.session };
919
+ }
920
+ async function post3(url, input, projectKey, timeoutMs) {
921
+ const unavailable2 = { status: "unavailable", reason: "auth_host_unavailable" };
922
+ const controller = new AbortController();
923
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
924
+ try {
925
+ const res = await fetch(url, {
926
+ method: "POST",
927
+ // The endpoint never redirects: the code goes to the auth host and nowhere else.
928
+ redirect: "error",
929
+ headers: { "content-type": "application/json" },
930
+ body: JSON.stringify({
931
+ grant_type: "authorization_code",
932
+ code: input.code,
933
+ code_verifier: input.codeVerifier,
934
+ redirect_uri: input.redirectUri,
935
+ project: projectKey
936
+ }),
937
+ signal: controller.signal
938
+ });
939
+ let body = null;
940
+ try {
941
+ const json = await res.json();
942
+ if (json !== null && typeof json === "object") body = json;
943
+ } catch {
944
+ body = null;
945
+ }
946
+ if (res.status === 200) {
947
+ return body?.ok === true && typeof body.token === "string" && body.token.length > 0 ? { status: "token", token: body.token } : unavailable2;
948
+ }
949
+ if (res.status === 400) {
950
+ return { status: "invalid", reason: body?.reason === "invalid_grant" ? "invalid_grant" : "bad_request" };
951
+ }
952
+ if (res.status === 404) return { status: "invalid", reason: "not_offered" };
953
+ if (res.status === 429) return { status: "unavailable", reason: "rate_limited" };
954
+ return unavailable2;
955
+ } catch {
956
+ return unavailable2;
957
+ } finally {
958
+ clearTimeout(timer);
959
+ }
960
+ }
961
+
840
962
  // src/merged.ts
841
963
  var MERGED_HANDLES_MAX = 16;
842
964
  function mergedHandles(session) {
@@ -1259,6 +1381,7 @@ exports.checkSignInRule = checkSignInRule;
1259
1381
  exports.connectClaimLink = connectClaimLink;
1260
1382
  exports.connectDelete = connectDelete;
1261
1383
  exports.connectProvision = connectProvision;
1384
+ exports.exchangeNativeCode = exchangeNativeCode;
1262
1385
  exports.getOcSession = getOcSession;
1263
1386
  exports.identity = identity;
1264
1387
  exports.matchMergedUser = matchMergedUser;