herald-auth-web 0.6.8 → 0.7.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/index.d.ts +53 -2
- package/dist/index.global.js +5 -5
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +86 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -313,7 +313,7 @@ type BrowserTokenResponse = {
|
|
|
313
313
|
tokenType: string;
|
|
314
314
|
};
|
|
315
315
|
type CredentialClass = 'first_party' | 'custom_user_ui' | 'mcp';
|
|
316
|
-
type CredentialScope = 'feature_read' | 'profile_read' | 'profile_write_nickname' | 'change_password' | 'change_email' | 'delete_account' | 'totp_manage' | 'passkey_manage' | 'logout' | 'points_read' | 'points_transactions_read' | 'purchase_read' | 'purchase_initiate' | 'purchase_status_read' | 'invoice_read' | 'invoice_apply' | 'subscription_read' | 'subscription_cancel' | 'openid' | 'mcp_profile_read' | 'mcp_points_read' | 'mcp_transactions_read' | 'mcp_subscriptions_read';
|
|
316
|
+
type CredentialScope = 'feature_read' | 'profile_read' | 'profile_write_nickname' | 'change_password' | 'change_email' | 'delete_account' | 'totp_manage' | 'passkey_manage' | 'phone_manage' | 'logout' | 'points_read' | 'points_transactions_read' | 'purchase_read' | 'purchase_initiate' | 'purchase_status_read' | 'invoice_read' | 'invoice_apply' | 'subscription_read' | 'subscription_cancel' | 'openid' | 'mcp_profile_read' | 'mcp_points_read' | 'mcp_transactions_read' | 'mcp_subscriptions_read';
|
|
317
317
|
type StatusResponse = {
|
|
318
318
|
authenticated: boolean;
|
|
319
319
|
clientAppId: string;
|
|
@@ -413,6 +413,26 @@ interface EmailOtpConflict {
|
|
|
413
413
|
agreements: ConsentAgreement[];
|
|
414
414
|
}
|
|
415
415
|
type EmailOtpSendResult = EmailOtpSent | EmailOtpConflict;
|
|
416
|
+
/** A real send: the code was issued and is valid for `expiresInSeconds`. */
|
|
417
|
+
interface SmsOtpSent {
|
|
418
|
+
kind: 'sent';
|
|
419
|
+
message: string;
|
|
420
|
+
expiresInSeconds: number;
|
|
421
|
+
/** Backend-derived masked form (`138****8000`); the raw number never crosses the API. */
|
|
422
|
+
maskedPhone: string;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* A 409 control-flow outcome — NOT an error. `phone_not_registered` means no
|
|
426
|
+
* account in the realm matches the number: no code is sent and none is created
|
|
427
|
+
* (DEC-phone-login-001). SMS OTP has no auto-register consent branch.
|
|
428
|
+
*/
|
|
429
|
+
interface SmsOtpConflict {
|
|
430
|
+
kind: 'conflict';
|
|
431
|
+
/** `phone_not_registered` (backend `sms_otp.rs`). */
|
|
432
|
+
code: string;
|
|
433
|
+
message: string;
|
|
434
|
+
}
|
|
435
|
+
type SmsOtpSendResult = SmsOtpSent | SmsOtpConflict;
|
|
416
436
|
type LoginResult = LoginSuccess | LoginRequiresSecondFactor | LoginConsentRequired | LoginOauthRedirect;
|
|
417
437
|
/** Result of `passkey.loginBegin` (1FA or 2FA). `options` is the WebAuthn
|
|
418
438
|
* `PublicKeyCredentialRequestOptions` JSON returned by the server. */
|
|
@@ -607,6 +627,17 @@ interface EmailOtpVerifyPayload {
|
|
|
607
627
|
code: string;
|
|
608
628
|
agreements?: ConsentAgreement[];
|
|
609
629
|
}
|
|
630
|
+
interface SmsOtpSendPayload {
|
|
631
|
+
/** Any writing form (bare / +86 / 0086 / separators); the server normalizes. */
|
|
632
|
+
phone: string;
|
|
633
|
+
turnstileToken?: string;
|
|
634
|
+
}
|
|
635
|
+
interface SmsOtpVerifyPayload {
|
|
636
|
+
/** Must match the number the code was sent to (server re-normalizes). */
|
|
637
|
+
phone: string;
|
|
638
|
+
code: string;
|
|
639
|
+
turnstileToken?: string;
|
|
640
|
+
}
|
|
610
641
|
interface AuthDeps {
|
|
611
642
|
realmId: string;
|
|
612
643
|
clientId: string;
|
|
@@ -654,6 +685,26 @@ declare function createAuth(deps: AuthDeps): {
|
|
|
654
685
|
send(payload: EmailOtpSendPayload): Promise<EmailOtpSendResult>;
|
|
655
686
|
verify(payload: EmailOtpVerifyPayload): Promise<LoginResult>;
|
|
656
687
|
};
|
|
688
|
+
loginWithSmsOtp: {
|
|
689
|
+
/**
|
|
690
|
+
* Send a passwordless SMS login code. The single 409 control-flow
|
|
691
|
+
* outcome — `phone_not_registered` (no account matches; no code is sent
|
|
692
|
+
* and none is created, DEC-phone-login-001) — resolves as
|
|
693
|
+
* `{ kind: 'conflict' }` instead of throwing. SMS OTP has no
|
|
694
|
+
* auto-register consent branch, unlike `loginWithEmailOtp.send`. All
|
|
695
|
+
* other HTTP failures throw `HeraldError`.
|
|
696
|
+
*/
|
|
697
|
+
send(payload: SmsOtpSendPayload): Promise<SmsOtpSendResult>;
|
|
698
|
+
/**
|
|
699
|
+
* Verify an SMS login code. On success the issued token set is applied
|
|
700
|
+
* internally and the result mirrors the other `loginWith*` verify
|
|
701
|
+
* methods. The documented 409 `phone_not_registered` (the account was
|
|
702
|
+
* anonymized between send and verify, backend `sms_otp.rs`) resolves as
|
|
703
|
+
* `{ kind: 'conflict' }` — the same shape as `send` — instead of
|
|
704
|
+
* throwing. All other HTTP failures throw `HeraldError`.
|
|
705
|
+
*/
|
|
706
|
+
verify(payload: SmsOtpVerifyPayload): Promise<LoginResult | SmsOtpConflict>;
|
|
707
|
+
};
|
|
657
708
|
getStatus(): Promise<StatusResponse>;
|
|
658
709
|
/**
|
|
659
710
|
* Explicitly refresh the Bearer token family (startup restore, proactive
|
|
@@ -791,4 +842,4 @@ declare class HeraldError extends Error {
|
|
|
791
842
|
constructor(init: HeraldErrorInit);
|
|
792
843
|
}
|
|
793
844
|
|
|
794
|
-
export { type AssertionResultJSON, type BrowserTokenResponse, type ConsentAgreement, type EmailOtpConflict, type EmailOtpSendPayload, type EmailOtpSendResult, type EmailOtpSent, type EmailOtpVerifyPayload, type HeraldClient, type HeraldClientConfig, type HeraldCredentialClass, HeraldError, type HeraldErrorInit, type HeraldErrorKind, type HeraldSession, type LdapLoginPayload, type LoginConsentRequired, type LoginOauthRedirect, type LoginPayload, type LoginRequiresSecondFactor, type LoginResult, type LoginSuccess, type PasskeyLoginBeginPayload, type PasskeyLoginBeginResult, type PasskeyLoginFinishPayload, type PublicKeyCredentialRequestOptionsJSON, type RegisterPayload, type RequestPasswordResetPayload, type SecondFactor, type SessionEvent, type SetTokensPayload, type StatusResponse, type TokenBridge, type TokenStorage, type TriggerVerifyEmailPayload, type VerifyTotpPayload, createHeraldClient, localStorageStorage, memoryStorage, performPasskeyAssertion };
|
|
845
|
+
export { type AssertionResultJSON, type BrowserTokenResponse, type ConsentAgreement, type EmailOtpConflict, type EmailOtpSendPayload, type EmailOtpSendResult, type EmailOtpSent, type EmailOtpVerifyPayload, type HeraldClient, type HeraldClientConfig, type HeraldCredentialClass, HeraldError, type HeraldErrorInit, type HeraldErrorKind, type HeraldSession, type LdapLoginPayload, type LoginConsentRequired, type LoginOauthRedirect, type LoginPayload, type LoginRequiresSecondFactor, type LoginResult, type LoginSuccess, type PasskeyLoginBeginPayload, type PasskeyLoginBeginResult, type PasskeyLoginFinishPayload, type PublicKeyCredentialRequestOptionsJSON, type RegisterPayload, type RequestPasswordResetPayload, type SecondFactor, type SessionEvent, type SetTokensPayload, type SmsOtpConflict, type SmsOtpSendPayload, type SmsOtpSendResult, type SmsOtpSent, type SmsOtpVerifyPayload, type StatusResponse, type TokenBridge, type TokenStorage, type TriggerVerifyEmailPayload, type VerifyTotpPayload, createHeraldClient, localStorageStorage, memoryStorage, performPasskeyAssertion };
|
package/dist/index.global.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Herald=(()=>{var
|
|
1
|
+
"use strict";var Herald=(()=>{var W=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var We=(e,t)=>{for(var s in t)W(e,s,{get:t[s],enumerable:!0})},ze=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ke(t))!qe.call(e,o)&&o!==s&&W(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var Fe=e=>ze(W({},"__esModule",{value:!0}),e);var ar={};We(ar,{HeraldError:()=>T,createHeraldClient:()=>Ue,localStorageStorage:()=>q,memoryStorage:()=>Ie,performPasskeyAssertion:()=>Ge});var Y={bodySerializer:e=>JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)};var Z=({onRequest:e,onSseError:t,onSseEvent:s,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:n,sseMaxRetryAttempts:a,sseMaxRetryDelay:i,sseSleepFn:l,url:d,...p})=>{let E,k=l??(c=>new Promise(g=>setTimeout(g,c)));return{stream:async function*(){let c=n??3e3,g=0,b=p.signal??new AbortController().signal;for(;!b.aborted;){g++;let A=p.headers instanceof Headers?p.headers:new Headers(p.headers);E!==void 0&&A.set("Last-Event-ID",E);try{let C={redirect:"follow",...p,body:p.serializedBody,headers:A,signal:b},w=new Request(d,C);e&&(w=await e(d,C));let h=await(p.fetch??globalThis.fetch)(w);if(!h.ok)throw new Error(`SSE failed: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("No body in SSE response");let O=h.body.pipeThrough(new TextDecoderStream).getReader(),I="",_=()=>{try{O.cancel()}catch{}};b.addEventListener("abort",_);try{for(;;){let{done:He,value:Le}=await O.read();if(He)break;I+=Le,I=I.replace(/\r\n/g,`
|
|
2
2
|
`).replace(/\r/g,`
|
|
3
|
-
`);let X=
|
|
3
|
+
`);let X=I.split(`
|
|
4
4
|
|
|
5
|
-
`);
|
|
6
|
-
`),
|
|
7
|
-
`);try{D=JSON.parse(R),J=!0}catch{D=R}}J&&(o&&await o(D),r&&(D=await r(D))),s?.({data:D,event:$,id:m,retry:c}),L.length&&(yield D)}}}finally{b.removeEventListener("abort",_),E.releaseLock()}break}catch(C){if(t?.(C),a!==void 0&&g>=a)break;let w=Math.min(c*2**(g-1),l??3e4);await P(w)}}}()}};var We=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Fe=e=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Ve=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j=({allowReserved:e,explode:t,name:s,style:r,value:o})=>{if(!t){let l=(e?o:o.map(i=>encodeURIComponent(i))).join(Fe(r));switch(r){case"label":return`.${l}`;case"matrix":return`;${s}=${l}`;case"simple":return l;default:return`${s}=${l}`}}let n=We(r),a=o.map(l=>r==="label"||r==="simple"?e?l:encodeURIComponent(l):x({allowReserved:e,name:s,value:l})).join(n);return r==="label"||r==="matrix"?n+a:a},x=({allowReserved:e,name:t,value:s})=>{if(s==null)return"";if(typeof s=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?s:encodeURIComponent(s)}`},M=({allowReserved:e,explode:t,name:s,style:r,value:o,valueOnly:n})=>{if(o instanceof Date)return n?o.toISOString():`${s}=${o.toISOString()}`;if(r!=="deepObject"&&!t){let i=[];Object.entries(o).forEach(([p,m])=>{i=[...i,p,e?m:encodeURIComponent(m)]});let d=i.join(",");switch(r){case"form":return`${s}=${d}`;case"label":return`.${d}`;case"matrix":return`;${s}=${d}`;default:return d}}let a=Ve(r),l=Object.entries(o).map(([i,d])=>x({allowReserved:e,name:r==="deepObject"?`${s}[${i}]`:i,value:d})).join(a);return r==="label"||r==="matrix"?a+l:l};var Ne=/\{[^{}]+\}/g,_e=({path:e,url:t})=>{let s=t,r=t.match(Ne);if(r)for(let o of r){let n=!1,a=o.substring(1,o.length-1),l="simple";a.endsWith("*")&&(n=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),l="label"):a.startsWith(";")&&(a=a.substring(1),l="matrix");let i=e[a];if(i==null)continue;if(Array.isArray(i)){s=s.replace(o,j({explode:n,name:a,style:l,value:i}));continue}if(typeof i=="object"){s=s.replace(o,M({explode:n,name:a,style:l,value:i,valueOnly:!0}));continue}if(l==="matrix"){s=s.replace(o,`;${x({name:a,value:i})}`);continue}let d=encodeURIComponent(l==="label"?`.${i}`:i);s=s.replace(o,d)}return s},ee=({baseUrl:e,path:t,query:s,querySerializer:r,url:o})=>{let n=o.startsWith("/")?o:`/${o}`,a=(e??"")+n;t&&(a=_e({path:t,url:a}));let l=s?r(s):"";return l.startsWith("?")&&(l=l.substring(1)),l&&(a+=`?${l}`),a};function W(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return"serializedBody"in e?e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null:e.body!==""?e.body:null;if(t)return e.body}var re=async(e,t)=>{let s=typeof t=="function"?await t(e):t;if(s)return e.scheme==="bearer"?`Bearer ${s}`:e.scheme==="basic"?`Basic ${btoa(s)}`:s};var te=({parameters:e={},...t}={})=>r=>{let o=[];if(r&&typeof r=="object")for(let n in r){let a=r[n];if(a==null)continue;let l=e[n]||t;if(Array.isArray(a)){let i=j({allowReserved:l.allowReserved,explode:!0,name:n,style:"form",value:a,...l.array});i&&o.push(i)}else if(typeof a=="object"){let i=M({allowReserved:l.allowReserved,explode:!0,name:n,style:"deepObject",value:a,...l.object});i&&o.push(i)}else{let i=x({allowReserved:l.allowReserved,name:n,value:a});i&&o.push(i)}}return o.join("&")},se=e=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(s=>t.startsWith(s)))return"blob";if(t.startsWith("text/"))return"text"}},Xe=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)):!1,oe=async({security:e,...t})=>{for(let s of e){if(Xe(t,s.name))continue;let r=await re(s,t.auth);if(!r)continue;let o=s.name??"Authorization";switch(s.in){case"query":t.query||(t.query={}),t.query[o]=r;break;case"cookie":t.headers.append("Cookie",`${o}=${r}`);break;default:t.headers.set(o,r);break}}},F=e=>ee({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer=="function"?e.querySerializer:te(e.querySerializer),url:e.url}),V=(e,t)=>{let s={...e,...t};return s.baseUrl?.endsWith("/")&&(s.baseUrl=s.baseUrl.substring(0,s.baseUrl.length-1)),s.headers=B(e.headers,t.headers),s},$e=e=>{let t=[];return e.forEach((s,r)=>{t.push([r,s])}),t},B=(...e)=>{let t=new Headers;for(let s of e){if(!s)continue;let r=s instanceof Headers?$e(s):Object.entries(s);for(let[o,n]of r)if(n===null)t.delete(o);else if(Array.isArray(n))for(let a of n)t.append(o,a);else n!==void 0&&t.set(o,typeof n=="object"?JSON.stringify(n):n)}return t},A=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(t){let s=this.getInterceptorIndex(t);this.fns[s]&&(this.fns[s]=null)}exists(t){let s=this.getInterceptorIndex(t);return!!this.fns[s]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,s){let r=this.getInterceptorIndex(t);return this.fns[r]?(this.fns[r]=s,t):!1}use(t){return this.fns.push(t),this.fns.length-1}},ne=()=>({error:new A,request:new A,response:new A}),Je=te({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Qe={"Content-Type":"application/json"},I=(e={})=>({...Y,headers:Qe,parseAs:"auto",querySerializer:Je,...e});var v=(e={})=>{let t=V(I(),e),s=()=>({...t}),r=d=>(t=V(t,d),s()),o=ne(),n=async d=>{let p={...t,...d,fetch:d.fetch??t.fetch??globalThis.fetch,headers:B(t.headers,d.headers),serializedBody:void 0};p.security&&await oe({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let m=F(p);return{opts:p,url:m}},a=async d=>{let{opts:p,url:m}=await n(d),P={redirect:"follow",...p,body:W(p)},f=new Request(m,P);for(let u of o.request.fns)u&&(f=await u(f,p));let H=p.fetch,c;try{c=await H(f)}catch(u){let h=u;for(let E of o.error.fns)E&&(h=await E(u,void 0,f,p));if(h=h||{},p.throwOnError)throw h;return p.responseStyle==="data"?void 0:{error:h,request:f,response:void 0}}for(let u of o.response.fns)u&&(c=await u(c,f,p));let g={request:f,response:c};if(c.ok){let u=(p.parseAs==="auto"?se(c.headers.get("Content-Type")):p.parseAs)??"json";if(c.status===204||c.headers.get("Content-Length")==="0"){let E;switch(u){case"arrayBuffer":case"blob":case"text":E=await c[u]();break;case"formData":E=new FormData;break;case"stream":E=c.body;break;default:E={};break}return p.responseStyle==="data"?E:{data:E,...g}}let h;switch(u){case"arrayBuffer":case"blob":case"formData":case"text":h=await c[u]();break;case"json":{let E=await c.text();h=E?JSON.parse(E):{};break}case"stream":return p.responseStyle==="data"?c.body:{data:c.body,...g}}return u==="json"&&(p.responseValidator&&await p.responseValidator(h),p.responseTransformer&&(h=await p.responseTransformer(h))),p.responseStyle==="data"?h:{data:h,...g}}let b=await c.text(),S;try{S=JSON.parse(b)}catch{}let C=S??b,w=C;for(let u of o.error.fns)u&&(w=await u(C,c,f,p));if(w=w||{},p.throwOnError)throw w;return p.responseStyle==="data"?void 0:{error:w,...g}},l=d=>p=>a({...p,method:d}),i=d=>async p=>{let{opts:m,url:P}=await n(p);return Z({...m,body:m.body,headers:m.headers,method:d,onRequest:async(f,H)=>{let c=new Request(f,H);for(let g of o.request.fns)g&&(c=await g(c,m));return c},serializedBody:W(m),url:P})};return{buildUrl:F,connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),getConfig:s,head:l("HEAD"),interceptors:o,options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),request:a,setConfig:r,sse:{connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),head:i("HEAD"),options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),trace:i("TRACE")},trace:l("TRACE")}};var O=v(I());var ae=e=>(e.client??O).post({url:"/api/auth/browser-token/refresh",...e,headers:{"Content-Type":"application/json",...e.headers}});var ie=e=>(e?.client??O).post({security:[{scheme:"bearer",type:"http"}],url:"/api/auth/logout",...e}),le=e=>(e?.client??O).get({security:[{scheme:"bearer",type:"http"}],url:"/api/auth/status",...e});var pe=e=>(e.client??O).post({url:"/api/auth/{realmId}/login",...e,headers:{"Content-Type":"application/json",...e.headers}}),ce=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/email-otp/send",...e,headers:{"Content-Type":"application/json",...e.headers}}),de=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/email-otp/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),he=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/ldap",...e,headers:{"Content-Type":"application/json",...e.headers}}),ue=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/passkey/2fa/options",...e,headers:{"Content-Type":"application/json",...e.headers}}),me=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/passkey/2fa/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),Ee=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/passkey/options",...e,headers:{"Content-Type":"application/json",...e.headers}}),Oe=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/passkey/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),ge=e=>(e.client??O).post({url:"/api/auth/{realmId}/login/verify-totp",...e,headers:{"Content-Type":"application/json",...e.headers}});var ye=e=>(e.client??O).post({url:"/api/auth/{realmId}/register",...e,headers:{"Content-Type":"application/json",...e.headers}});var Te=e=>(e.client??O).post({url:"/api/auth/{realmId}/reset_password/request",...e,headers:{"Content-Type":"application/json",...e.headers}});var fe=e=>(e.client??O).post({url:"/api/auth/{realmId}/verify_email/trigger",...e,headers:{"Content-Type":"application/json",...e.headers}});var y=class extends Error{constructor(t){super(t.message??t.kind),this.name="HeraldError",this.kind=t.kind,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.details=t.details}};function Ye(e){switch(e){case 400:return"validation";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 429:return"rate-limited";default:return"api"}}function K(e,t){if(!t)return new y({kind:"network",message:"Network request failed. For cross-origin integrations, ensure the page origin is pre-registered on the Client App (allowed_origins).",details:e});let s=e??{};return new y({kind:Ye(t.status),status:t.status,message:s.message??s.error??`HTTP ${t.status}`,code:s.code,requestId:s.requestId??void 0,details:s.details})}var Re="X-Herald-Refresh-Retried",we="/api/auth/browser-token/refresh";function be(e,t){let s=t.storage.getRefreshToken();if(!s)return t.session.emit({type:"session-expired",reason:"refresh-failed"}),Promise.resolve(null);let r=e.__heraldRefresh;if(r)return r;let o=(async()=>{try{let{data:n,error:a}=await ae({client:e,body:{refreshToken:s}});return a||!n?(t.session.emit({type:"session-expired",reason:"family-revoked"}),null):(t.accessTokenHolder.set(n.accessToken),t.storage.setRefreshToken(n.refreshToken),n)}catch{return t.session.emit({type:"session-expired",reason:"refresh-failed"}),null}finally{e.__heraldRefresh=null}})();return e.__heraldRefresh=o,o}async function Ze(e,t){let s=await e.request(t);if(!s.response)return new Response(null,{status:401});let r=new Headers(s.response.headers),o=s.data!==void 0?s.data:s.error,n=o!=null?JSON.stringify(o):null;return new Response(n,{status:s.response.status,headers:r})}function Ce(e){let t=v({baseUrl:e.baseUrl});return t.interceptors.request.use((s,r)=>{if(r.url===we)return s;let o=e.accessTokenHolder.get();if(!o)return s;let n=new Headers(s.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${o}`),new Request(s,{headers:n})}),t.interceptors.response.use(async(s,r,o)=>{if(s.status!==401||o.url===we||r.headers.get(Re)||!(await be(t,e)!==null))return s;let a={...o},l=new Headers(a.headers??void 0);return l.set(Re,"1"),a.headers=l,Ze(t,a)}),{client:t,refreshTokens:()=>be(t,e)}}async function T(e){let{data:t,error:s,response:r}=await e;if(t===void 0)throw K(s,r);return t}function er(e,t){t.accessTokenHolder.set(e.accessToken),t.storage.setRefreshToken(e.refreshToken)}function rr(e){return{authenticated:!0,realmId:e.realmId,userId:null,clientAppId:null,clientId:e.clientId,credentialClass:"custom_user_ui",permissions:[],scopes:[]}}function tr(e,t){return{authenticated:e.authenticated,realmId:e.realmId??t.realmId,userId:e.userId??null,clientAppId:e.clientAppId??null,clientId:e.clientId??t.clientId,credentialClass:e.credentialClass??null,permissions:e.permissions??[],scopes:e.scopes??[]}}function De(e){return Array.isArray(e)?e.map(t=>{let s=t??{};return{agreementType:String(s.agreementType??s.agreement_type??""),versionId:String(s.versionId??s.version_id??""),...t&&typeof t=="object"?{raw:s}:{}}}):[]}function sr(e){return e.filter(t=>t==="totp"||t==="passkey")}function G(e,t){let s=e??null;if(s&&typeof s.accessToken=="string"){er(s,t);let r=rr(t);return t.session.emit({type:"authenticated",session:r}),{kind:"success",session:r}}if(s&&s.consentRequired===!0)return{kind:"consent-required",agreements:De(s.agreements)};if(s&&Array.isArray(s.secondFactors)&&s.secondFactors.length>0)return{kind:"requires-second-factor",tempToken:String(s.tempToken??""),expiresInSeconds:Number(s.expiresInSeconds??0),secondFactors:sr(s.secondFactors),userId:String(s.userId??""),realmId:String(s.realmId??t.realmId)};if(s&&typeof s.redirectTo=="string")return{kind:"oauth-redirect",redirectTo:s.redirectTo};throw new y({kind:"api",message:"Unrecognized login response shape."})}function xe(e){let{realmId:t,client:s}=e;return{async register(r){let o=await T(ye({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,password:r.password,...r.username?{username:r.username}:{},...r.nickname?{nickname:r.nickname}:{},...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}));return{message:o.message,verificationRequired:o.verificationRequired}},async triggerVerifyEmail(r){return{message:(await T(fe({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}))).message}},async requestPasswordReset(r){return{message:(await T(Te({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}))).message}},async login(r){let o=await T(pe({client:s,path:{realmId:t},body:{clientId:e.clientId,password:r.password,...r.username?{username:r.username}:{},...r.email?{email:r.email}:{},...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{},...r.oauthClientId?{oauthClientId:r.oauthClientId}:{},...r.redirectUri?{redirectUri:r.redirectUri}:{},...r.state?{state:r.state}:{}}}));return G(o,e)},async loginWithLdap(r){let o=await T(he({client:s,path:{realmId:t},body:{clientId:e.clientId,username:r.username,password:r.password,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{},...r.oauthClientId?{oauthClientId:r.oauthClientId}:{},...r.redirectUri?{redirectUri:r.redirectUri}:{},...r.state?{state:r.state}:{}}}));return G(o,e)},async verifyTotp(r){let o=await T(ge({client:s,path:{realmId:t},body:{tempToken:r.tempToken,...r.code?{code:r.code}:{},...r.backupCode?{backupCode:r.backupCode}:{},...r.agreements?{agreements:r.agreements}:{}}}));return G(o,e)},passkey:{async loginBegin(r){let o=r.tempToken!==void 0?await T(ue({client:s,path:{realmId:t},body:{tempToken:r.tempToken}})):await T(Ee({client:s,path:{realmId:t},body:{clientId:e.clientId,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.oauth?{oauth:r.oauth}:{}}}));return{authToken:o.authToken,options:o.options}},async loginFinish(r){let o=await T(r.tempToken!==void 0?me({client:s,path:{realmId:t},body:{tempToken:r.tempToken,authToken:r.authToken,assertion:r.assertion,...r.agreements?{agreements:r.agreements}:{}}}):Oe({client:s,path:{realmId:t},body:{authToken:r.authToken,assertion:r.assertion,...r.agreements?{agreements:r.agreements}:{}}}));return G(o,e)}},loginWithEmailOtp:{async send(r){let{data:o,error:n,response:a}=await ce({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{}}});if(o)return{kind:"sent",message:o.message,expiresInSeconds:o.expiresInSeconds};let l=n??{},i=l.code;if(a?.status===409&&(i==="consent_required"||i==="email_not_registered"))return{kind:"conflict",code:String(i),message:String(l.message??""),consentRequired:l.consentRequired===!0,agreements:De(l.agreements)};throw K(n,a)},async verify(r){let o=await T(de({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,code:r.code,...r.agreements?{agreements:r.agreements}:{}}}));return G(o,e)}},async getStatus(){let r=await T(le({client:s}));return e.session.emit({type:"authenticated",session:tr(r,e)}),r},async refresh(){let r=await e.refreshTokens();if(!r)throw new y({kind:"session-expired",message:"Session refresh failed; sign in again."});return r},async logout(){let r=await T(ie({client:s}));return e.accessTokenHolder.clear(),e.storage.setRefreshToken(null),e.session.emit({type:"logged-out"}),{message:r?.message??"Logged out"}}}}function Pe(){let e=null;return{get:()=>e,set:t=>{e=t},clear:()=>{e=null}}}var N={authenticated:!1,realmId:null,userId:null,clientAppId:null,clientId:null,credentialClass:null,permissions:[],scopes:[]};function Se(e){let t={...N},s=new Set;return{getSession:()=>t,setSession:r=>{t=r??{...N}},subscribe:r=>(s.add(r),()=>{s.delete(r)}),emit:r=>{r.type==="authenticated"?t=r.session:(r.type==="session-expired"||r.type==="logged-out")&&(t={...N});for(let o of s)o(r);e?.(r)}}}function ke(){let e=null;return{getRefreshToken:()=>e,setRefreshToken:t=>{e=t}}}function q(e){if(typeof localStorage>"u"||localStorage===null)throw new y({kind:"ssr-no-storage",message:"localStorage is unavailable in this environment. Inject a TokenStorage adapter via `storage`, or use memoryStorage()."});return{getRefreshToken:()=>localStorage.getItem(e),setRefreshToken:t=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)}}}function Ae(e){let t=typeof localStorage<"u"&&localStorage!==null,s=e.storage;if(!s){if(!t)throw new y({kind:"ssr-no-storage",message:"No TokenStorage adapter was provided and localStorage is unavailable (SSR/Node). Inject a `storage` adapter or use memoryStorage()."});s=q(e.storageKey??"herald.refreshToken")}let r=Pe(),o=Se(e.onSessionChange),n=Ce({baseUrl:e.baseUrl,accessTokenHolder:r,storage:s,session:o}),a={realmId:e.realmId,clientId:e.clientId,client:n.client,accessTokenHolder:r,storage:s,session:o,refreshTokens:n.refreshTokens};return{...xe(a),storage:s,session:{getSession:()=>o.getSession(),subscribe:i=>o.subscribe(i)},tokens:{getAccessToken:()=>r.get(),setTokens:i=>{r.set(i.accessToken),s.setRefreshToken(i.refreshToken),i.clientId!==void 0&&(a.clientId=i.clientId)},clear:()=>{r.clear(),s.setRefreshToken(null)},bindClientId:i=>{a.clientId=i}}}}function Ie(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=t+"===".slice((t.length+3)%4),r=atob(s),o=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)o[n]=r.charCodeAt(n);return o.buffer}function U(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),s="";for(let r=0;r<t.length;r+=1)s+=String.fromCharCode(t[r]??0);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/[=]/g,"")}async function ve(e){if(typeof navigator>"u"||!navigator.credentials?.get)throw new Error("WebAuthn (navigator.credentials.get) is not available in this environment.");let t={challenge:Ie(e.challenge),...e.rpId?{rpId:e.rpId}:{},...e.timeout!==void 0?{timeout:e.timeout}:{},...e.userVerification?{userVerification:e.userVerification}:{},...e.allowCredentials?{allowCredentials:e.allowCredentials.map(n=>({type:"public-key",id:Ie(n.id),...n.transports?{transports:n.transports}:{}}))}:{}},s=await navigator.credentials.get({publicKey:t});if(!s)throw new Error("Passkey assertion returned no credential.");let r=s.response,o={id:s.id,rawId:U(s.rawId),type:"public-key",response:{authenticatorData:U(r.authenticatorData),clientDataJSON:U(r.clientDataJSON),signature:U(r.signature),...r.userHandle?{userHandle:U(r.userHandle)}:{}}};return typeof s.getClientExtensionResults=="function"&&(o.clientExtensionResults=s.getClientExtensionResults()),o}return ze(or);})();
|
|
5
|
+
`);I=X.pop()??"";for(let je of X){let Be=je.split(`
|
|
6
|
+
`),j=[],$;for(let R of Be)if(R.startsWith("data:"))j.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))$=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))E=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let Q=Number.parseInt(R.replace(/^retry:\s*/,""),10);Number.isNaN(Q)||(c=Q)}let D,J=!1;if(j.length){let R=j.join(`
|
|
7
|
+
`);try{D=JSON.parse(R),J=!0}catch{D=R}}J&&(o&&await o(D),r&&(D=await r(D))),s?.({data:D,event:$,id:E,retry:c}),j.length&&(yield D)}}}finally{b.removeEventListener("abort",_),O.releaseLock()}break}catch(C){if(t?.(C),a!==void 0&&g>=a)break;let w=Math.min(c*2**(g-1),i??3e4);await k(w)}}}()}};var Ve=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ne=e=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},_e=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},B=({allowReserved:e,explode:t,name:s,style:r,value:o})=>{if(!t){let i=(e?o:o.map(l=>encodeURIComponent(l))).join(Ne(r));switch(r){case"label":return`.${i}`;case"matrix":return`;${s}=${i}`;case"simple":return i;default:return`${s}=${i}`}}let n=Ve(r),a=o.map(i=>r==="label"||r==="simple"?e?i:encodeURIComponent(i):x({allowReserved:e,name:s,value:i})).join(n);return r==="label"||r==="matrix"?n+a:a},x=({allowReserved:e,name:t,value:s})=>{if(s==null)return"";if(typeof s=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?s:encodeURIComponent(s)}`},M=({allowReserved:e,explode:t,name:s,style:r,value:o,valueOnly:n})=>{if(o instanceof Date)return n?o.toISOString():`${s}=${o.toISOString()}`;if(r!=="deepObject"&&!t){let l=[];Object.entries(o).forEach(([p,E])=>{l=[...l,p,e?E:encodeURIComponent(E)]});let d=l.join(",");switch(r){case"form":return`${s}=${d}`;case"label":return`.${d}`;case"matrix":return`;${s}=${d}`;default:return d}}let a=_e(r),i=Object.entries(o).map(([l,d])=>x({allowReserved:e,name:r==="deepObject"?`${s}[${l}]`:l,value:d})).join(a);return r==="label"||r==="matrix"?a+i:i};var Xe=/\{[^{}]+\}/g,$e=({path:e,url:t})=>{let s=t,r=t.match(Xe);if(r)for(let o of r){let n=!1,a=o.substring(1,o.length-1),i="simple";a.endsWith("*")&&(n=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),i="label"):a.startsWith(";")&&(a=a.substring(1),i="matrix");let l=e[a];if(l==null)continue;if(Array.isArray(l)){s=s.replace(o,B({explode:n,name:a,style:i,value:l}));continue}if(typeof l=="object"){s=s.replace(o,M({explode:n,name:a,style:i,value:l,valueOnly:!0}));continue}if(i==="matrix"){s=s.replace(o,`;${x({name:a,value:l})}`);continue}let d=encodeURIComponent(i==="label"?`.${l}`:l);s=s.replace(o,d)}return s},ee=({baseUrl:e,path:t,query:s,querySerializer:r,url:o})=>{let n=o.startsWith("/")?o:`/${o}`,a=(e??"")+n;t&&(a=$e({path:t,url:a}));let i=s?r(s):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(a+=`?${i}`),a};function z(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return"serializedBody"in e?e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null:e.body!==""?e.body:null;if(t)return e.body}var re=async(e,t)=>{let s=typeof t=="function"?await t(e):t;if(s)return e.scheme==="bearer"?`Bearer ${s}`:e.scheme==="basic"?`Basic ${btoa(s)}`:s};var te=({parameters:e={},...t}={})=>r=>{let o=[];if(r&&typeof r=="object")for(let n in r){let a=r[n];if(a==null)continue;let i=e[n]||t;if(Array.isArray(a)){let l=B({allowReserved:i.allowReserved,explode:!0,name:n,style:"form",value:a,...i.array});l&&o.push(l)}else if(typeof a=="object"){let l=M({allowReserved:i.allowReserved,explode:!0,name:n,style:"deepObject",value:a,...i.object});l&&o.push(l)}else{let l=x({allowReserved:i.allowReserved,name:n,value:a});l&&o.push(l)}}return o.join("&")},se=e=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(s=>t.startsWith(s)))return"blob";if(t.startsWith("text/"))return"text"}},Je=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)):!1,oe=async({security:e,...t})=>{for(let s of e){if(Je(t,s.name))continue;let r=await re(s,t.auth);if(!r)continue;let o=s.name??"Authorization";switch(s.in){case"query":t.query||(t.query={}),t.query[o]=r;break;case"cookie":t.headers.append("Cookie",`${o}=${r}`);break;default:t.headers.set(o,r);break}}},F=e=>ee({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer=="function"?e.querySerializer:te(e.querySerializer),url:e.url}),V=(e,t)=>{let s={...e,...t};return s.baseUrl?.endsWith("/")&&(s.baseUrl=s.baseUrl.substring(0,s.baseUrl.length-1)),s.headers=K(e.headers,t.headers),s},Qe=e=>{let t=[];return e.forEach((s,r)=>{t.push([r,s])}),t},K=(...e)=>{let t=new Headers;for(let s of e){if(!s)continue;let r=s instanceof Headers?Qe(s):Object.entries(s);for(let[o,n]of r)if(n===null)t.delete(o);else if(Array.isArray(n))for(let a of n)t.append(o,a);else n!==void 0&&t.set(o,typeof n=="object"?JSON.stringify(n):n)}return t},U=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(t){let s=this.getInterceptorIndex(t);this.fns[s]&&(this.fns[s]=null)}exists(t){let s=this.getInterceptorIndex(t);return!!this.fns[s]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,s){let r=this.getInterceptorIndex(t);return this.fns[r]?(this.fns[r]=s,t):!1}use(t){return this.fns.push(t),this.fns.length-1}},ne=()=>({error:new U,request:new U,response:new U}),Ye=te({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Ze={"Content-Type":"application/json"},v=(e={})=>({...Y,headers:Ze,parseAs:"auto",querySerializer:Ye,...e});var G=(e={})=>{let t=V(v(),e),s=()=>({...t}),r=d=>(t=V(t,d),s()),o=ne(),n=async d=>{let p={...t,...d,fetch:d.fetch??t.fetch??globalThis.fetch,headers:K(t.headers,d.headers),serializedBody:void 0};p.security&&await oe({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let E=F(p);return{opts:p,url:E}},a=async d=>{let{opts:p,url:E}=await n(d),k={redirect:"follow",...p,body:z(p)},y=new Request(E,k);for(let u of o.request.fns)u&&(y=await u(y,p));let L=p.fetch,c;try{c=await L(y)}catch(u){let h=u;for(let O of o.error.fns)O&&(h=await O(u,void 0,y,p));if(h=h||{},p.throwOnError)throw h;return p.responseStyle==="data"?void 0:{error:h,request:y,response:void 0}}for(let u of o.response.fns)u&&(c=await u(c,y,p));let g={request:y,response:c};if(c.ok){let u=(p.parseAs==="auto"?se(c.headers.get("Content-Type")):p.parseAs)??"json";if(c.status===204||c.headers.get("Content-Length")==="0"){let O;switch(u){case"arrayBuffer":case"blob":case"text":O=await c[u]();break;case"formData":O=new FormData;break;case"stream":O=c.body;break;default:O={};break}return p.responseStyle==="data"?O:{data:O,...g}}let h;switch(u){case"arrayBuffer":case"blob":case"formData":case"text":h=await c[u]();break;case"json":{let O=await c.text();h=O?JSON.parse(O):{};break}case"stream":return p.responseStyle==="data"?c.body:{data:c.body,...g}}return u==="json"&&(p.responseValidator&&await p.responseValidator(h),p.responseTransformer&&(h=await p.responseTransformer(h))),p.responseStyle==="data"?h:{data:h,...g}}let b=await c.text(),A;try{A=JSON.parse(b)}catch{}let C=A??b,w=C;for(let u of o.error.fns)u&&(w=await u(C,c,y,p));if(w=w||{},p.throwOnError)throw w;return p.responseStyle==="data"?void 0:{error:w,...g}},i=d=>p=>a({...p,method:d}),l=d=>async p=>{let{opts:E,url:k}=await n(p);return Z({...E,body:E.body,headers:E.headers,method:d,onRequest:async(y,L)=>{let c=new Request(y,L);for(let g of o.request.fns)g&&(c=await g(c,E));return c},serializedBody:z(E),url:k})};return{buildUrl:F,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:s,head:i("HEAD"),interceptors:o,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:a,setConfig:r,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:i("TRACE")}};var m=G(v());var ae=e=>(e.client??m).post({url:"/api/auth/browser-token/refresh",...e,headers:{"Content-Type":"application/json",...e.headers}});var ie=e=>(e?.client??m).post({security:[{scheme:"bearer",type:"http"}],url:"/api/auth/logout",...e}),le=e=>(e?.client??m).get({security:[{scheme:"bearer",type:"http"}],url:"/api/auth/status",...e});var pe=e=>(e.client??m).post({url:"/api/auth/{realmId}/login",...e,headers:{"Content-Type":"application/json",...e.headers}}),ce=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/email-otp/send",...e,headers:{"Content-Type":"application/json",...e.headers}}),de=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/email-otp/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),he=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/ldap",...e,headers:{"Content-Type":"application/json",...e.headers}}),ue=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/passkey/2fa/options",...e,headers:{"Content-Type":"application/json",...e.headers}}),me=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/passkey/2fa/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),Ee=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/passkey/options",...e,headers:{"Content-Type":"application/json",...e.headers}}),Oe=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/passkey/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),ge=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/sms-otp/send",...e,headers:{"Content-Type":"application/json",...e.headers}}),Te=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/sms-otp/verify",...e,headers:{"Content-Type":"application/json",...e.headers}}),fe=e=>(e.client??m).post({url:"/api/auth/{realmId}/login/verify-totp",...e,headers:{"Content-Type":"application/json",...e.headers}});var ye=e=>(e.client??m).post({url:"/api/auth/{realmId}/register",...e,headers:{"Content-Type":"application/json",...e.headers}});var Re=e=>(e.client??m).post({url:"/api/auth/{realmId}/reset_password/request",...e,headers:{"Content-Type":"application/json",...e.headers}});var we=e=>(e.client??m).post({url:"/api/auth/{realmId}/verify_email/trigger",...e,headers:{"Content-Type":"application/json",...e.headers}});var T=class extends Error{constructor(t){super(t.message??t.kind),this.name="HeraldError",this.kind=t.kind,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.details=t.details}};function er(e){switch(e){case 400:return"validation";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 429:return"rate-limited";default:return"api"}}function P(e,t){if(!t)return new T({kind:"network",message:"Network request failed. For cross-origin integrations, ensure the page origin is pre-registered on the Client App (allowed_origins).",details:e});let s=e??{};return new T({kind:er(t.status),status:t.status,message:s.message??s.error??`HTTP ${t.status}`,code:s.code,requestId:s.requestId??void 0,details:s.details})}var be="X-Herald-Refresh-Retried",Ce="/api/auth/browser-token/refresh";function De(e,t){let s=t.storage.getRefreshToken();if(!s)return t.session.emit({type:"session-expired",reason:"refresh-failed"}),Promise.resolve(null);let r=e.__heraldRefresh;if(r)return r;let o=(async()=>{try{let{data:n,error:a}=await ae({client:e,body:{refreshToken:s}});return a||!n?(t.session.emit({type:"session-expired",reason:"family-revoked"}),null):(t.accessTokenHolder.set(n.accessToken),t.storage.setRefreshToken(n.refreshToken),n)}catch{return t.session.emit({type:"session-expired",reason:"refresh-failed"}),null}finally{e.__heraldRefresh=null}})();return e.__heraldRefresh=o,o}async function rr(e,t){let s=await e.request(t);if(!s.response)return new Response(null,{status:401});let r=new Headers(s.response.headers),o=s.data!==void 0?s.data:s.error,n=o!=null?JSON.stringify(o):null;return new Response(n,{status:s.response.status,headers:r})}function xe(e){let t=G({baseUrl:e.baseUrl});return t.interceptors.request.use((s,r)=>{if(r.url===Ce)return s;let o=e.accessTokenHolder.get();if(!o)return s;let n=new Headers(s.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${o}`),new Request(s,{headers:n})}),t.interceptors.response.use(async(s,r,o)=>{if(s.status!==401||o.url===Ce||r.headers.get(be)||!(await De(t,e)!==null))return s;let a={...o},i=new Headers(a.headers??void 0);return i.set(be,"1"),a.headers=i,rr(t,a)}),{client:t,refreshTokens:()=>De(t,e)}}async function f(e){let{data:t,error:s,response:r}=await e;if(t===void 0)throw P(s,r);return t}function tr(e,t){t.accessTokenHolder.set(e.accessToken),t.storage.setRefreshToken(e.refreshToken)}function sr(e){return{authenticated:!0,realmId:e.realmId,userId:null,clientAppId:null,clientId:e.clientId,credentialClass:"custom_user_ui",permissions:[],scopes:[]}}function or(e,t){return{authenticated:e.authenticated,realmId:e.realmId??t.realmId,userId:e.userId??null,clientAppId:e.clientAppId??null,clientId:e.clientId??t.clientId,credentialClass:e.credentialClass??null,permissions:e.permissions??[],scopes:e.scopes??[]}}function Pe(e){return Array.isArray(e)?e.map(t=>{let s=t??{};return{agreementType:String(s.agreementType??s.agreement_type??""),versionId:String(s.versionId??s.version_id??""),...t&&typeof t=="object"?{raw:s}:{}}}):[]}function nr(e){return e.filter(t=>t==="totp"||t==="passkey")}function S(e,t){let s=e??null;if(s&&typeof s.accessToken=="string"){tr(s,t);let r=sr(t);return t.session.emit({type:"authenticated",session:r}),{kind:"success",session:r}}if(s&&s.consentRequired===!0)return{kind:"consent-required",agreements:Pe(s.agreements)};if(s&&Array.isArray(s.secondFactors)&&s.secondFactors.length>0)return{kind:"requires-second-factor",tempToken:String(s.tempToken??""),expiresInSeconds:Number(s.expiresInSeconds??0),secondFactors:nr(s.secondFactors),userId:String(s.userId??""),realmId:String(s.realmId??t.realmId)};if(s&&typeof s.redirectTo=="string")return{kind:"oauth-redirect",redirectTo:s.redirectTo};throw new T({kind:"api",message:"Unrecognized login response shape."})}function Se(e){let{realmId:t,client:s}=e;return{async register(r){let o=await f(ye({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,password:r.password,...r.username?{username:r.username}:{},...r.nickname?{nickname:r.nickname}:{},...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}));return{message:o.message,verificationRequired:o.verificationRequired}},async triggerVerifyEmail(r){return{message:(await f(we({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}))).message}},async requestPasswordReset(r){return{message:(await f(Re({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}}))).message}},async login(r){let o=await f(pe({client:s,path:{realmId:t},body:{clientId:e.clientId,password:r.password,...r.username?{username:r.username}:{},...r.email?{email:r.email}:{},...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{},...r.oauthClientId?{oauthClientId:r.oauthClientId}:{},...r.redirectUri?{redirectUri:r.redirectUri}:{},...r.state?{state:r.state}:{}}}));return S(o,e)},async loginWithLdap(r){let o=await f(he({client:s,path:{realmId:t},body:{clientId:e.clientId,username:r.username,password:r.password,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{},...r.oauthClientId?{oauthClientId:r.oauthClientId}:{},...r.redirectUri?{redirectUri:r.redirectUri}:{},...r.state?{state:r.state}:{}}}));return S(o,e)},async verifyTotp(r){let o=await f(fe({client:s,path:{realmId:t},body:{tempToken:r.tempToken,...r.code?{code:r.code}:{},...r.backupCode?{backupCode:r.backupCode}:{},...r.agreements?{agreements:r.agreements}:{}}}));return S(o,e)},passkey:{async loginBegin(r){let o=r.tempToken!==void 0?await f(ue({client:s,path:{realmId:t},body:{tempToken:r.tempToken}})):await f(Ee({client:s,path:{realmId:t},body:{clientId:e.clientId,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.oauth?{oauth:r.oauth}:{}}}));return{authToken:o.authToken,options:o.options}},async loginFinish(r){let o=await f(r.tempToken!==void 0?me({client:s,path:{realmId:t},body:{tempToken:r.tempToken,authToken:r.authToken,assertion:r.assertion,...r.agreements?{agreements:r.agreements}:{}}}):Oe({client:s,path:{realmId:t},body:{authToken:r.authToken,assertion:r.assertion,...r.agreements?{agreements:r.agreements}:{}}}));return S(o,e)}},loginWithEmailOtp:{async send(r){let{data:o,error:n,response:a}=await ce({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{},...r.agreements?{agreements:r.agreements}:{}}});if(o)return{kind:"sent",message:o.message,expiresInSeconds:o.expiresInSeconds};let i=n??{},l=i.code;if(a?.status===409&&(l==="consent_required"||l==="email_not_registered"))return{kind:"conflict",code:String(l),message:String(i.message??""),consentRequired:i.consentRequired===!0,agreements:Pe(i.agreements)};throw P(n,a)},async verify(r){let o=await f(de({client:s,path:{realmId:t},body:{clientId:e.clientId,email:r.email,code:r.code,...r.agreements?{agreements:r.agreements}:{}}}));return S(o,e)}},loginWithSmsOtp:{async send(r){let{data:o,error:n,response:a}=await ge({client:s,path:{realmId:t},body:{clientId:e.clientId,phone:r.phone,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}});if(o)return{kind:"sent",message:o.message,expiresInSeconds:o.expiresInSeconds,maskedPhone:o.maskedPhone};let i=n??{};if(a?.status===409&&i.code==="phone_not_registered")return{kind:"conflict",code:String(i.code),message:String(i.message??"")};throw P(n,a)},async verify(r){let{data:o,error:n,response:a}=await Te({client:s,path:{realmId:t},body:{clientId:e.clientId,phone:r.phone,code:r.code,...r.turnstileToken?{turnstileToken:r.turnstileToken}:{}}});if(o)return S(o,e);let i=n??{};if(a?.status===409&&i.code==="phone_not_registered")return{kind:"conflict",code:String(i.code),message:String(i.message??"")};throw P(n,a)}},async getStatus(){let r=await f(le({client:s}));return e.session.emit({type:"authenticated",session:or(r,e)}),r},async refresh(){let r=await e.refreshTokens();if(!r)throw new T({kind:"session-expired",message:"Session refresh failed; sign in again."});return r},async logout(){let r=await f(ie({client:s}));return e.accessTokenHolder.clear(),e.storage.setRefreshToken(null),e.session.emit({type:"logged-out"}),{message:r?.message??"Logged out"}}}}function ke(){let e=null;return{get:()=>e,set:t=>{e=t},clear:()=>{e=null}}}var N={authenticated:!1,realmId:null,userId:null,clientAppId:null,clientId:null,credentialClass:null,permissions:[],scopes:[]};function Ae(e){let t={...N},s=new Set;return{getSession:()=>t,setSession:r=>{t=r??{...N}},subscribe:r=>(s.add(r),()=>{s.delete(r)}),emit:r=>{r.type==="authenticated"?t=r.session:(r.type==="session-expired"||r.type==="logged-out")&&(t={...N});for(let o of s)o(r);e?.(r)}}}function Ie(){let e=null;return{getRefreshToken:()=>e,setRefreshToken:t=>{e=t}}}function q(e){if(typeof localStorage>"u"||localStorage===null)throw new T({kind:"ssr-no-storage",message:"localStorage is unavailable in this environment. Inject a TokenStorage adapter via `storage`, or use memoryStorage()."});return{getRefreshToken:()=>localStorage.getItem(e),setRefreshToken:t=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)}}}function Ue(e){let t=typeof localStorage<"u"&&localStorage!==null,s=e.storage;if(!s){if(!t)throw new T({kind:"ssr-no-storage",message:"No TokenStorage adapter was provided and localStorage is unavailable (SSR/Node). Inject a `storage` adapter or use memoryStorage()."});s=q(e.storageKey??"herald.refreshToken")}let r=ke(),o=Ae(e.onSessionChange),n=xe({baseUrl:e.baseUrl,accessTokenHolder:r,storage:s,session:o}),a={realmId:e.realmId,clientId:e.clientId,client:n.client,accessTokenHolder:r,storage:s,session:o,refreshTokens:n.refreshTokens};return{...Se(a),storage:s,session:{getSession:()=>o.getSession(),subscribe:l=>o.subscribe(l)},tokens:{getAccessToken:()=>r.get(),setTokens:l=>{r.set(l.accessToken),s.setRefreshToken(l.refreshToken),l.clientId!==void 0&&(a.clientId=l.clientId)},clear:()=>{r.clear(),s.setRefreshToken(null)},bindClientId:l=>{a.clientId=l}}}}function ve(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=t+"===".slice((t.length+3)%4),r=atob(s),o=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)o[n]=r.charCodeAt(n);return o.buffer}function H(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),s="";for(let r=0;r<t.length;r+=1)s+=String.fromCharCode(t[r]??0);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/[=]/g,"")}async function Ge(e){if(typeof navigator>"u"||!navigator.credentials?.get)throw new Error("WebAuthn (navigator.credentials.get) is not available in this environment.");let t={challenge:ve(e.challenge),...e.rpId?{rpId:e.rpId}:{},...e.timeout!==void 0?{timeout:e.timeout}:{},...e.userVerification?{userVerification:e.userVerification}:{},...e.allowCredentials?{allowCredentials:e.allowCredentials.map(n=>({type:"public-key",id:ve(n.id),...n.transports?{transports:n.transports}:{}}))}:{}},s=await navigator.credentials.get({publicKey:t});if(!s)throw new Error("Passkey assertion returned no credential.");let r=s.response,o={id:s.id,rawId:H(s.rawId),type:"public-key",response:{authenticatorData:H(r.authenticatorData),clientDataJSON:H(r.clientDataJSON),signature:H(r.signature),...r.userHandle?{userHandle:H(r.userHandle)}:{}}};return typeof s.getClientExtensionResults=="function"&&(o.clientExtensionResults=s.getClientExtensionResults()),o}return Fe(ar);})();
|
|
8
8
|
//# sourceMappingURL=index.global.js.map
|