@junobuild/auth 0.0.3 → 1.0.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 (39) hide show
  1. package/dist/browser/_context.js +1 -1
  2. package/dist/browser/_openid.js +1 -1
  3. package/dist/browser/_session.js +1 -1
  4. package/dist/browser/authenticate.js +1 -1
  5. package/dist/browser/chunk-AO3TH3FT.js +2 -0
  6. package/dist/browser/chunk-AO3TH3FT.js.map +7 -0
  7. package/dist/browser/chunk-HE7SWFN4.js +2 -0
  8. package/dist/browser/chunk-HE7SWFN4.js.map +7 -0
  9. package/dist/browser/chunk-JYGIWWOR.js +2 -0
  10. package/dist/browser/chunk-JYGIWWOR.js.map +7 -0
  11. package/dist/browser/chunk-PIJCHIUI.js +2 -0
  12. package/dist/browser/chunk-PIJCHIUI.js.map +7 -0
  13. package/dist/browser/chunk-ZSWBJ7CY.js +2 -0
  14. package/dist/browser/chunk-ZSWBJ7CY.js.map +7 -0
  15. package/dist/browser/index.js +1 -1
  16. package/dist/browser/request.js +1 -1
  17. package/dist/node/index.mjs +1 -1
  18. package/dist/node/index.mjs.map +3 -3
  19. package/dist/types/_session.d.ts +2 -3
  20. package/dist/types/authenticate.d.ts +2 -2
  21. package/dist/types/request.d.ts +7 -6
  22. package/dist/types/types/actor.d.ts +6 -11
  23. package/dist/types/types/authenticate.d.ts +19 -5
  24. package/dist/types/types/context.d.ts +1 -1
  25. package/dist/types/types/request.d.ts +8 -3
  26. package/dist/types/types/session.d.ts +1 -1
  27. package/dist/types/utils/auth.utils.d.ts +1 -1
  28. package/dist/types/utils/session.utils.d.ts +1 -1
  29. package/package.json +4 -7
  30. package/dist/browser/chunk-36KNLPQZ.js +0 -2
  31. package/dist/browser/chunk-36KNLPQZ.js.map +0 -7
  32. package/dist/browser/chunk-E4CYLKZY.js +0 -2
  33. package/dist/browser/chunk-E4CYLKZY.js.map +0 -7
  34. package/dist/browser/chunk-JOJCKPWQ.js +0 -2
  35. package/dist/browser/chunk-JOJCKPWQ.js.map +0 -7
  36. package/dist/browser/chunk-JOOQTYYG.js +0 -2
  37. package/dist/browser/chunk-JOOQTYYG.js.map +0 -7
  38. package/dist/browser/chunk-JTJJD55H.js +0 -2
  39. package/dist/browser/chunk-JTJJD55H.js.map +0 -7
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-JTJJD55H.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as initContext,b as loadContext};
1
+ import{a,b}from"./chunk-HE7SWFN4.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as initContext,b as loadContext};
2
2
  //# sourceMappingURL=_context.js.map
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-JOOQTYYG.js";import"./chunk-2BORB4XM.js";export{a as requestJwtWithRedirect,b as requestWithCredentials};
1
+ import{a,b}from"./chunk-AO3TH3FT.js";import"./chunk-2BORB4XM.js";export{a as requestJwtWithRedirect,b as requestWithCredentials};
2
2
  //# sourceMappingURL=_openid.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-36KNLPQZ.js";import"./chunk-2BORB4XM.js";export{a as authenticate};
1
+ import{a}from"./chunk-PIJCHIUI.js";import"./chunk-2BORB4XM.js";export{a as authenticateSession};
2
2
  //# sourceMappingURL=_session.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-E4CYLKZY.js";import"./chunk-36KNLPQZ.js";import"./chunk-JTJJD55H.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as authenticate};
1
+ import{a}from"./chunk-JYGIWWOR.js";import"./chunk-PIJCHIUI.js";import"./chunk-HE7SWFN4.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as authenticate};
2
2
  //# sourceMappingURL=authenticate.js.map
@@ -0,0 +1,2 @@
1
+ import{a as d,c as h,d as l}from"./chunk-2BORB4XM.js";import{isNullish as p,notEmptyString as u}from"@dfinity/utils";var C=({authUrl:r,clientId:n,nonce:s,loginHint:i,authScopes:o,state:t,redirectUrl:a})=>{let e=(()=>{try{return new URL(r)}catch{throw new d("Cannot parse authURL",{cause:r})}})();e.searchParams.set("client_id",n);let{location:{origin:m}}=window;e.searchParams.set("redirect_uri",a??m),e.searchParams.set("response_type","code id_token"),e.searchParams.set("scope",o.join(" ")),e.searchParams.set("state",t),e.searchParams.set("nonce",s),u(i)?e.searchParams.set("login_hint",i):e.searchParams.set("prompt","select_account"),window.location.href=e.toString()},P=async({configUrl:r,clientId:n,nonce:s,loginHint:i,domainHint:o})=>{let t=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:r,clientId:n,nonce:s,loginHint:i,domainHint:o}],mode:"active"},mediation:"required"});if(p(t))throw new h;let{type:a}=t;if(a!=="identity"||!("token"in t)||typeof t.token!="string")throw new l("Invalid credential received from FedCM API",{cause:t});let{token:c}=t;return{jwt:c}};export{C as a,P as b};
2
+ //# sourceMappingURL=chunk-AO3TH3FT.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/_openid.ts"],
4
+ "sourcesContent": ["import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestJwtWithCredentials, RequestJwtWithRedirect} from './types/openid';\n\n/**\n * Initiates an OpenID Connect authorization request by redirecting the browser.\n *\n * References:\n * - OAuth 2.0 (Google): https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow\n * - OpenID Connect: https://developers.google.com/identity/openid-connect/openid-connect\n */\nexport const requestJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestJwtWithRedirect) => {\n const parseAuthUrl = (): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(authUrl);\n } catch (_error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: authUrl});\n }\n };\n\n const requestUrl = parseAuthUrl();\n\n requestUrl.searchParams.set('client_id', clientId);\n\n const {\n location: {origin: currentUrl}\n } = window;\n\n requestUrl.searchParams.set('redirect_uri', redirectUrl ?? currentUrl);\n\n // We do not request \"token\" because we use the ID token (JWT).\n // \"code\" is required according to II's codebase as Apple ID throws an error otherwise.\n requestUrl.searchParams.set('response_type', 'code id_token');\n\n requestUrl.searchParams.set('scope', authScopes.join(' '));\n\n // Used for security reasons. When the provider redirects to the application,\n // the state will be compared with the session storage value.\n requestUrl.searchParams.set('state', state);\n\n // Used to validate the JSON Web Token (JWT) in the backend \u2014 i.e. we pass the nonce\n // to the provider and make the request to the backend with its salt.\n requestUrl.searchParams.set('nonce', nonce);\n\n if (notEmptyString(loginHint)) {\n requestUrl.searchParams.set('login_hint', loginHint);\n } else {\n requestUrl.searchParams.set('prompt', 'select_account');\n }\n\n window.location.href = requestUrl.toString();\n};\n\n/**\n * References:\n * - identity spec: https://www.w3.org/TR/fedcm/#browser-api-credential-request-options\n * - https://privacysandbox.google.com/cookies/fedcm/implement/identity-provider\n * - https://privacysandbox.google.com/cookies/fedcm/why\n */\nexport const requestWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestJwtWithCredentials): Promise<{jwt: string}> => {\n const identityCredential = await navigator.credentials.get({\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n identity: {\n context: 'use',\n providers: [\n {\n configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n }\n ],\n mode: 'active'\n },\n // https://privacysandbox.google.com/cookies/fedcm/implement/relying-party#auto-reauthn\n mediation: 'required'\n });\n\n if (isNullish(identityCredential)) {\n throw new FedCMIdentityCredentialUndefinedError();\n }\n\n const {type} = identityCredential;\n\n if (\n type !== 'identity' ||\n !('token' in identityCredential) ||\n typeof identityCredential.token !== 'string'\n ) {\n // This should be unreachable in FedCM spec-compliant browsers.\n throw new FedCMIdentityCredentialInvalidError('Invalid credential received from FedCM API', {\n cause: identityCredential\n });\n }\n\n const {token: jwt} = identityCredential;\n return {jwt};\n};\n"],
5
+ "mappings": "sDAAA,OAAQ,aAAAA,EAAW,kBAAAC,MAAqB,iBAejC,IAAMC,EAAyB,CAAC,CACrC,QAAAC,EACA,SAAAC,EACA,MAAAC,EACA,UAAAC,EACA,WAAAC,EACA,MAAAC,EACA,YAAAC,CACF,IAA8B,CAU5B,IAAMC,GATe,IAAW,CAC9B,GAAI,CAEF,OAAO,IAAI,IAAIP,CAAO,CACxB,MAA0B,CACxB,MAAM,IAAIQ,EAAgB,uBAAwB,CAAC,MAAOR,CAAO,CAAC,CACpE,CACF,GAEgC,EAEhCO,EAAW,aAAa,IAAI,YAAaN,CAAQ,EAEjD,GAAM,CACJ,SAAU,CAAC,OAAQQ,CAAU,CAC/B,EAAI,OAEJF,EAAW,aAAa,IAAI,eAAgBD,GAAeG,CAAU,EAIrEF,EAAW,aAAa,IAAI,gBAAiB,eAAe,EAE5DA,EAAW,aAAa,IAAI,QAASH,EAAW,KAAK,GAAG,CAAC,EAIzDG,EAAW,aAAa,IAAI,QAASF,CAAK,EAI1CE,EAAW,aAAa,IAAI,QAASL,CAAK,EAEtCQ,EAAeP,CAAS,EAC1BI,EAAW,aAAa,IAAI,aAAcJ,CAAS,EAEnDI,EAAW,aAAa,IAAI,SAAU,gBAAgB,EAGxD,OAAO,SAAS,KAAOA,EAAW,SAAS,CAC7C,EAQaI,EAAyB,MAAO,CAC3C,UAAWC,EACX,SAAAX,EACA,MAAAC,EACA,UAAAC,EACA,WAAAU,CACF,IAAyD,CACvD,IAAMC,EAAqB,MAAM,UAAU,YAAY,IAAI,CAGzD,SAAU,CACR,QAAS,MACT,UAAW,CACT,CACE,UAAAF,EACA,SAAAX,EACA,MAAAC,EACA,UAAAC,EACA,WAAAU,CACF,CACF,EACA,KAAM,QACR,EAEA,UAAW,UACb,CAAC,EAED,GAAIE,EAAUD,CAAkB,EAC9B,MAAM,IAAIE,EAGZ,GAAM,CAAC,KAAAC,CAAI,EAAIH,EAEf,GACEG,IAAS,YACT,EAAE,UAAWH,IACb,OAAOA,EAAmB,OAAU,SAGpC,MAAM,IAAII,EAAoC,6CAA8C,CAC1F,MAAOJ,CACT,CAAC,EAGH,GAAM,CAAC,MAAOK,CAAG,EAAIL,EACrB,MAAO,CAAC,IAAAK,CAAG,CACb",
6
+ "names": ["isNullish", "notEmptyString", "requestJwtWithRedirect", "authUrl", "clientId", "nonce", "loginHint", "authScopes", "state", "redirectUrl", "requestUrl", "InvalidUrlError", "currentUrl", "notEmptyString", "requestWithCredentials", "configURL", "domainHint", "identityCredential", "isNullish", "FedCMIdentityCredentialUndefinedError", "type", "FedCMIdentityCredentialInvalidError", "jwt"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-VYICNPPG.js";import{b as i}from"./chunk-2BORB4XM.js";import{isNullish as E}from"@dfinity/utils";import{Ed25519KeyIdentity as N}from"@icp-sdk/core/identity";import{arrayBufferToUint8Array as S}from"@dfinity/utils";import{uint8ArrayToBase64 as g}from"@dfinity/utils";var r=t=>g(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var x=()=>window.crypto.getRandomValues(new Uint8Array(32)),_=async({salt:t,caller:e})=>{let o=e.getPrincipal().toUint8Array(),n=new Uint8Array(t.length+o.byteLength);n.set(t),n.set(o,t.length);let s=await window.crypto.subtle.digest("SHA-256",n);return r(S(s))},c=async({caller:t})=>{let e=x();return{nonce:await _({salt:e,caller:t}),salt:e}};import{base64ToUint8Array as A,uint8ArrayToBase64 as C}from"@dfinity/utils";import{Ed25519KeyIdentity as u}from"@icp-sdk/core/identity";var p="__caller__",y="__salt__",m="__state__",d=({caller:t,state:e,salt:o})=>{let n={[p]:t.toJSON(),[y]:C(o),[m]:e};return JSON.stringify(n)},l=t=>{let{[p]:e,[y]:o,[m]:n}=JSON.parse(t);return{caller:u.fromParsedJson(e),salt:A(o),state:n}};var f=()=>r(window.crypto.getRandomValues(new Uint8Array(12)));var D=async()=>{let t=N.generate(),{nonce:e,salt:o}=await c({caller:t}),n=f(),s=d({caller:t,salt:o,state:n});return sessionStorage.setItem(a,s),{nonce:e,state:n}},H=()=>{let t=sessionStorage.getItem(a);if(E(t))throw new i;return l(t)};export{D as a,H as b};
2
+ //# sourceMappingURL=chunk-HE7SWFN4.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/_context.ts", "../../src/utils/auth.utils.ts", "../../src/utils/url.utils.ts", "../../src/utils/session-storage.utils.ts", "../../src/utils/state.utils.ts"],
4
+ "sourcesContent": ["import {isNullish} from '@dfinity/utils';\nimport {Ed25519KeyIdentity} from '@icp-sdk/core/identity';\nimport {CONTEXT_KEY} from './_constants';\nimport {ContextUndefinedError} from './errors';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Nonce} from './types/nonce';\nimport {generateNonce} from './utils/auth.utils';\nimport {parseContext, stringifyContext} from './utils/session-storage.utils';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const initContext = async (): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n const state = generateRandomState();\n\n const storedData = stringifyContext({\n caller,\n salt,\n state\n });\n\n sessionStorage.setItem(CONTEXT_KEY, storedData);\n\n return {\n nonce,\n state\n };\n};\n\nexport const loadContext = (): OpenIdAuthContext => {\n const storedContext = sessionStorage.getItem(CONTEXT_KEY);\n\n if (isNullish(storedContext)) {\n throw new ContextUndefinedError();\n }\n\n return parseContext(storedContext);\n};\n", "import {arrayBufferToUint8Array} from '@dfinity/utils';\nimport type {Ed25519KeyIdentity} from '@icp-sdk/core/identity';\nimport type {Nonce, Salt} from '../types/nonce';\nimport {toBase64URL} from './url.utils';\n\nconst generateSalt = (): Salt => window.crypto.getRandomValues(new Uint8Array(32));\n\nconst buildNonce = async ({salt, caller}: {salt: Salt; caller: Ed25519KeyIdentity}) => {\n const principal = caller.getPrincipal().toUint8Array();\n\n const bytes = new Uint8Array(salt.length + principal.byteLength);\n bytes.set(salt);\n bytes.set(principal, salt.length);\n\n const hash = await window.crypto.subtle.digest('SHA-256', bytes);\n\n return toBase64URL(arrayBufferToUint8Array(hash));\n};\n\nexport const generateNonce = async ({\n caller\n}: {\n caller: Ed25519KeyIdentity;\n}): Promise<{nonce: Nonce; salt: Salt}> => {\n const salt = generateSalt();\n const nonce = await buildNonce({salt, caller});\n\n return {nonce, salt};\n};\n", "import {uint8ArrayToBase64} from '@dfinity/utils';\n\n// In the future: uint8Array.toBase64({ alphabet: \"base64url\" })\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64\nexport const toBase64URL = (uint8Array: Uint8Array): string =>\n uint8ArrayToBase64(uint8Array).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n", "import {base64ToUint8Array, uint8ArrayToBase64} from '@dfinity/utils';\nimport {Ed25519KeyIdentity, type JsonnableEd25519KeyIdentity} from '@icp-sdk/core/identity';\nimport type {OpenIdAuthContext} from '../types/context';\n\nconst JSON_KEY_CALLER = '__caller__';\nconst JSON_KEY_SALT = '__salt__';\nconst JSON_KEY_STATE = '__state__';\n\ninterface StoredContext {\n [JSON_KEY_CALLER]: JsonnableEd25519KeyIdentity;\n [JSON_KEY_SALT]: string;\n [JSON_KEY_STATE]: string;\n}\n\nexport const stringifyContext = ({caller, state, salt}: OpenIdAuthContext): string => {\n const data: StoredContext = {\n [JSON_KEY_CALLER]: caller.toJSON(),\n [JSON_KEY_SALT]: uint8ArrayToBase64(salt),\n [JSON_KEY_STATE]: state\n };\n\n return JSON.stringify(data);\n};\n\nexport const parseContext = (jsonData: string): OpenIdAuthContext => {\n const {\n [JSON_KEY_CALLER]: jsonCaller,\n [JSON_KEY_SALT]: jsonSalt,\n [JSON_KEY_STATE]: state\n }: StoredContext = JSON.parse(jsonData);\n\n return {\n caller: Ed25519KeyIdentity.fromParsedJson(jsonCaller),\n salt: base64ToUint8Array(jsonSalt),\n state\n };\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n"],
5
+ "mappings": "2EAAA,OAAQ,aAAAA,MAAgB,iBACxB,OAAQ,sBAAAC,MAAyB,yBCDjC,OAAQ,2BAAAC,MAA8B,iBCAtC,OAAQ,sBAAAC,MAAyB,iBAI1B,IAAMC,EAAeC,GAC1BF,EAAmBE,CAAU,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,EAAE,EDA1F,IAAMC,EAAe,IAAY,OAAO,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,EAE3EC,EAAa,MAAO,CAAC,KAAAC,EAAM,OAAAC,CAAM,IAAgD,CACrF,IAAMC,EAAYD,EAAO,aAAa,EAAE,aAAa,EAE/CE,EAAQ,IAAI,WAAWH,EAAK,OAASE,EAAU,UAAU,EAC/DC,EAAM,IAAIH,CAAI,EACdG,EAAM,IAAID,EAAWF,EAAK,MAAM,EAEhC,IAAMI,EAAO,MAAM,OAAO,OAAO,OAAO,OAAO,UAAWD,CAAK,EAE/D,OAAOE,EAAYC,EAAwBF,CAAI,CAAC,CAClD,EAEaG,EAAgB,MAAO,CAClC,OAAAN,CACF,IAE2C,CACzC,IAAMD,EAAOF,EAAa,EAG1B,MAAO,CAAC,MAFM,MAAMC,EAAW,CAAC,KAAAC,EAAM,OAAAC,CAAM,CAAC,EAE9B,KAAAD,CAAI,CACrB,EE5BA,OAAQ,sBAAAQ,EAAoB,sBAAAC,MAAyB,iBACrD,OAAQ,sBAAAC,MAA2D,yBAGnE,IAAMC,EAAkB,aAClBC,EAAgB,WAChBC,EAAiB,YAQVC,EAAmB,CAAC,CAAC,OAAAC,EAAQ,MAAAC,EAAO,KAAAC,CAAI,IAAiC,CACpF,IAAMC,EAAsB,CAC1B,CAACP,CAAe,EAAGI,EAAO,OAAO,EACjC,CAACH,CAAa,EAAGH,EAAmBQ,CAAI,EACxC,CAACJ,CAAc,EAAGG,CACpB,EAEA,OAAO,KAAK,UAAUE,CAAI,CAC5B,EAEaC,EAAgBC,GAAwC,CACnE,GAAM,CACJ,CAACT,CAAe,EAAGU,EACnB,CAACT,CAAa,EAAGU,EACjB,CAACT,CAAc,EAAGG,CACpB,EAAmB,KAAK,MAAMI,CAAQ,EAEtC,MAAO,CACL,OAAQV,EAAmB,eAAeW,CAAU,EACpD,KAAMb,EAAmBc,CAAQ,EACjC,MAAAN,CACF,CACF,EClCO,IAAMO,EAAsB,IACjCC,EAAY,OAAO,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,CAAC,EJOxD,IAAMC,EAAc,SAAwE,CACjG,IAAMC,EAASC,EAAmB,SAAS,EACrC,CAAC,MAAAC,EAAO,KAAAC,CAAI,EAAI,MAAMC,EAAc,CAAC,OAAAJ,CAAM,CAAC,EAC5CK,EAAQC,EAAoB,EAE5BC,EAAaC,EAAiB,CAClC,OAAAR,EACA,KAAAG,EACA,MAAAE,CACF,CAAC,EAED,sBAAe,QAAQI,EAAaF,CAAU,EAEvC,CACL,MAAAL,EACA,MAAAG,CACF,CACF,EAEaK,EAAc,IAAyB,CAClD,IAAMC,EAAgB,eAAe,QAAQF,CAAW,EAExD,GAAIG,EAAUD,CAAa,EACzB,MAAM,IAAIE,EAGZ,OAAOC,EAAaH,CAAa,CACnC",
6
+ "names": ["isNullish", "Ed25519KeyIdentity", "arrayBufferToUint8Array", "uint8ArrayToBase64", "toBase64URL", "uint8Array", "generateSalt", "buildNonce", "salt", "caller", "principal", "bytes", "hash", "toBase64URL", "arrayBufferToUint8Array", "generateNonce", "base64ToUint8Array", "uint8ArrayToBase64", "Ed25519KeyIdentity", "JSON_KEY_CALLER", "JSON_KEY_SALT", "JSON_KEY_STATE", "stringifyContext", "caller", "state", "salt", "data", "parseContext", "jsonData", "jsonCaller", "jsonSalt", "generateRandomState", "toBase64URL", "initContext", "caller", "Ed25519KeyIdentity", "nonce", "salt", "generateNonce", "state", "generateRandomState", "storedData", "stringifyContext", "CONTEXT_KEY", "loadContext", "storedContext", "isNullish", "ContextUndefinedError", "parseContext"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as i}from"./chunk-PIJCHIUI.js";import{b as m}from"./chunk-HE7SWFN4.js";import{f as h,g as u,h as d}from"./chunk-2BORB4XM.js";import{isEmptyString as o}from"@dfinity/utils";var P=async t=>{let e=m();if("credentials"in t){let{credentials:{jwt:n},auth:a}=t;return await i({jwt:n,context:e,auth:a})}return await w({...t,context:e})},w=async({auth:t,context:e})=>{let{location:{hash:n}}=window;if(o(n)||!n.startsWith("#"))throw new h("No hash found in the current location URL");let a=new URLSearchParams(n.slice(1)),r=a.get("state"),s=a.get("id_token"),{state:c}=e;if(o(c)||r!==c)throw new u("The provided state is invalid",{cause:r});if(o(s))throw new d;return await i({jwt:s,auth:t,context:e})};export{P as a};
2
+ //# sourceMappingURL=chunk-JYGIWWOR.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/authenticate.ts"],
4
+ "sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {loadContext} from './_context';\nimport {authenticateSession} from './_session';\nimport {\n AuthenticationInvalidStateError,\n AuthenticationUndefinedJwtError,\n AuthenticationUrlHashError\n} from './errors';\nimport type {\n AuthenticatedSession,\n AuthenticationParams,\n AuthParameters\n} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\n\nexport const authenticate = async <T extends AuthParameters>(\n params: AuthenticationParams<T>\n): Promise<AuthenticatedSession<T>> => {\n const context = loadContext();\n\n if ('credentials' in params) {\n const {\n credentials: {jwt},\n auth\n } = params;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateWithRedirect<T>({...params, context});\n};\n\nconst authenticateWithRedirect = async <T extends AuthParameters>({\n auth,\n context\n}: {\n auth: AuthParameters;\n context: OpenIdAuthContext;\n}): Promise<AuthenticatedSession<T>> => {\n const {\n location: {hash}\n } = window;\n\n if (isEmptyString(hash) || !hash.startsWith('#')) {\n throw new AuthenticationUrlHashError('No hash found in the current location URL');\n }\n\n const params = new URLSearchParams(hash.slice(1));\n const state = params.get('state');\n const idToken = params.get('id_token');\n\n const {state: savedState} = context;\n\n if (isEmptyString(savedState) || state !== savedState) {\n throw new AuthenticationInvalidStateError('The provided state is invalid', {cause: state});\n }\n\n // id_token === jwt\n if (isEmptyString(idToken)) {\n throw new AuthenticationUndefinedJwtError();\n }\n\n return await authenticateSession({\n jwt: idToken,\n auth,\n context\n });\n};\n"],
5
+ "mappings": "sIAAA,OAAQ,iBAAAA,MAAoB,iBAerB,IAAMC,EAAe,MAC1BC,GACqC,CACrC,IAAMC,EAAUC,EAAY,EAE5B,GAAI,gBAAiBF,EAAQ,CAC3B,GAAM,CACJ,YAAa,CAAC,IAAAG,CAAG,EACjB,KAAAC,CACF,EAAIJ,EAEJ,OAAO,MAAMK,EAAoB,CAC/B,IAAAF,EACA,QAAAF,EACA,KAAAG,CACF,CAAC,CACH,CAEA,OAAO,MAAME,EAA4B,CAAC,GAAGN,EAAQ,QAAAC,CAAO,CAAC,CAC/D,EAEMK,EAA2B,MAAiC,CAChE,KAAAF,EACA,QAAAH,CACF,IAGwC,CACtC,GAAM,CACJ,SAAU,CAAC,KAAAM,CAAI,CACjB,EAAI,OAEJ,GAAIC,EAAcD,CAAI,GAAK,CAACA,EAAK,WAAW,GAAG,EAC7C,MAAM,IAAIE,EAA2B,2CAA2C,EAGlF,IAAMT,EAAS,IAAI,gBAAgBO,EAAK,MAAM,CAAC,CAAC,EAC1CG,EAAQV,EAAO,IAAI,OAAO,EAC1BW,EAAUX,EAAO,IAAI,UAAU,EAE/B,CAAC,MAAOY,CAAU,EAAIX,EAE5B,GAAIO,EAAcI,CAAU,GAAKF,IAAUE,EACzC,MAAM,IAAIC,EAAgC,gCAAiC,CAAC,MAAOH,CAAK,CAAC,EAI3F,GAAIF,EAAcG,CAAO,EACvB,MAAM,IAAIG,EAGZ,OAAO,MAAMT,EAAoB,CAC/B,IAAKM,EACL,KAAAP,EACA,QAAAH,CACF,CAAC,CACH",
6
+ "names": ["isEmptyString", "authenticate", "params", "context", "loadContext", "jwt", "auth", "authenticateSession", "authenticateWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{e as m,i as A,j as y}from"./chunk-2BORB4XM.js";import{fromNullable as G}from"@dfinity/utils";import{Delegation as E,ECDSAKeyIdentity as k}from"@icp-sdk/core/identity";import{getConsoleActor as P,getSatelliteActor as S}from"@junobuild/ic-client/actor";var l=({auth:t,identity:e})=>"satellite"in t?S({...t.satellite,identity:e}):P({...t.console,identity:e});var p=async({actorParams:t,args:e})=>{let{authenticate:n}=await l(t);return await n(e)},d=async({actorParams:t,args:e})=>{let{get_delegation:n}=await l(t);return await n(e)};import{DelegationChain as C,DelegationIdentity as I}from"@icp-sdk/core/identity";var h=({delegations:t,sessionKey:e})=>{let[n,i]=t,o=C.fromDelegations(i,Uint8Array.from(n));return{identity:I.fromDelegation(e,o),delegationChain:o,sessionKey:e}};var F=async({jwt:t,context:e,auth:n})=>{let i=await k.generate({extractable:!1}),o=new Uint8Array(i.getPublicKey().toDer()),{delegations:a,data:g}=await K({jwt:t,publicKey:o,context:e,auth:n});return{identity:h({sessionKey:i,delegations:a}),data:g}},K=async({jwt:t,publicKey:e,context:{caller:n,salt:i},auth:o})=>{let a=await p({args:{OpenId:{jwt:t,session_key:e,salt:i}},actorParams:{auth:o,identity:n}});if("Err"in a)throw new m("Authentication failed",{cause:a});let{delegation:{user_key:g,expiration:r},...u}=a.Ok,s=await b({jwt:t,context:{caller:n,salt:i},auth:o,publicKey:e,expiration:r}),{delegation:c,signature:D}=s,{pubkey:f,expiration:x,targets:w}=c;return{delegations:[g,[{delegation:new E(Uint8Array.from(f),x,G(w)),signature:Uint8Array.from(D)}]],data:u}},b=async({jwt:t,publicKey:e,context:{salt:n,caller:i},auth:o,expiration:a,maxRetries:g=5})=>{for(let r=0;r<g;r++){await new Promise(c=>{setInterval(c,1e3*r)});let s=await d({args:{OpenId:{jwt:t,session_key:e,salt:n,expiration:a}},actorParams:{auth:o,identity:i}});if("Err"in s){let{Err:c}=s;if("NoSuchDelegation"in c||"GetCachedJwks"in c)continue;throw new A("Getting delegation failed",{cause:s})}return s.Ok}throw new y};export{F as a};
2
+ //# sourceMappingURL=chunk-PIJCHIUI.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/_session.ts", "../../src/api/_actor.api.ts", "../../src/api/auth.api.ts", "../../src/utils/session.utils.ts"],
4
+ "sourcesContent": ["import {fromNullable} from '@dfinity/utils';\nimport type {Signature} from '@icp-sdk/core/agent';\nimport {Delegation, ECDSAKeyIdentity} from '@icp-sdk/core/identity';\nimport {authenticate as authenticateApi, getDelegation as getDelegationApi} from './api/auth.api';\nimport {AuthenticationError, GetDelegationError, GetDelegationRetryError} from './errors';\nimport type {AuthenticationData, GetDelegationArgs, SignedDelegation} from './types/actor';\nimport type {AuthenticatedSession, AuthParameters} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Delegations} from './types/session';\nimport {generateIdentity} from './utils/session.utils';\n\ninterface AuthContext {\n context: Omit<OpenIdAuthContext, 'state'>;\n auth: AuthParameters;\n}\ntype AuthenticationArgs = {jwt: string} & AuthContext;\n\nexport const authenticateSession = async <T extends AuthParameters>({\n jwt,\n context,\n auth\n}: AuthenticationArgs): Promise<AuthenticatedSession<T>> => {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const publicKey = new Uint8Array(sessionKey.getPublicKey().toDer());\n\n const {delegations, data} = await authenticate<T>({\n jwt,\n publicKey,\n context,\n auth\n });\n\n const identity = generateIdentity({\n sessionKey,\n delegations\n });\n\n return {identity, data};\n};\n\nconst authenticate = async <T extends AuthParameters>({\n jwt,\n publicKey,\n context: {caller, salt},\n auth\n}: {\n publicKey: Uint8Array;\n} & AuthenticationArgs): Promise<{delegations: Delegations; data: AuthenticationData<T>}> => {\n const result = await authenticateApi({\n args: {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt\n }\n },\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n throw new AuthenticationError('Authentication failed', {cause: result});\n }\n\n const {\n delegation: {user_key: userKey, expiration},\n ...rest\n } = result.Ok;\n\n const signedDelegation = await retryGetDelegation({\n jwt,\n context: {caller, salt},\n auth,\n publicKey,\n expiration\n });\n\n const {delegation, signature} = signedDelegation;\n const {pubkey, expiration: signedExpiration, targets} = delegation;\n\n const delegations: Delegations = [\n userKey,\n [\n {\n delegation: new Delegation(\n Uint8Array.from(pubkey),\n signedExpiration,\n fromNullable(targets)\n ),\n signature: Uint8Array.from(signature) as unknown as Signature\n }\n ]\n ];\n\n return {delegations, data: rest as AuthenticationData<T>};\n};\n\nconst retryGetDelegation = async ({\n jwt,\n publicKey,\n context: {salt, caller},\n auth,\n expiration,\n maxRetries = 5\n}: {\n publicKey: Uint8Array;\n expiration: bigint;\n maxRetries?: number;\n} & AuthenticationArgs): Promise<SignedDelegation> => {\n for (let i = 0; i < maxRetries; i++) {\n // Linear backoff\n await new Promise((resolve) => {\n setInterval(resolve, 1000 * i);\n });\n\n const args: GetDelegationArgs = {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt,\n expiration\n }\n };\n\n const result = await getDelegationApi({\n args,\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n const {Err} = result;\n\n if ('NoSuchDelegation' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if ('GetCachedJwks' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n throw new GetDelegationError('Getting delegation failed', {cause: result});\n }\n\n return result.Ok;\n }\n\n throw new GetDelegationRetryError();\n};\n", "import {\n type ConsoleActor,\n type SatelliteActor,\n getConsoleActor,\n getSatelliteActor\n} from '@junobuild/ic-client/actor';\nimport type {ActorParameters} from '../types/actor';\n\nexport const getAuthActor = ({\n auth,\n identity\n}: ActorParameters): Promise<ConsoleActor | SatelliteActor> =>\n 'satellite' in auth\n ? getSatelliteActor({...auth.satellite, identity})\n : getConsoleActor({...auth.console, identity});\n", "import type {\n ActorParameters,\n AuthenticationArgs,\n AuthenticationResult,\n GetDelegationArgs,\n GetDelegationResult\n} from '../types/actor';\nimport {getAuthActor} from './_actor.api';\n\nexport const authenticate = async ({\n actorParams,\n args\n}: {\n args: AuthenticationArgs;\n actorParams: ActorParameters;\n}): Promise<AuthenticationResult> => {\n const {authenticate} = await getAuthActor(actorParams);\n return await authenticate(args);\n};\n\nexport const getDelegation = async ({\n actorParams,\n args\n}: {\n args: GetDelegationArgs;\n actorParams: ActorParameters;\n}): Promise<GetDelegationResult> => {\n const {get_delegation} = await getAuthActor(actorParams);\n return await get_delegation(args);\n};\n", "import {DelegationChain, DelegationIdentity, type ECDSAKeyIdentity} from '@icp-sdk/core/identity';\nimport type {AuthenticatedIdentity} from '../types/authenticate';\nimport type {Delegations} from '../types/session';\n\nexport const generateIdentity = ({\n delegations,\n sessionKey\n}: {\n delegations: Delegations;\n sessionKey: ECDSAKeyIdentity;\n}): AuthenticatedIdentity => {\n const [userKey, signedDelegations] = delegations;\n\n const delegationChain = DelegationChain.fromDelegations(\n signedDelegations,\n Uint8Array.from(userKey)\n );\n\n const identity = DelegationIdentity.fromDelegation(sessionKey, delegationChain);\n\n return {identity, delegationChain, sessionKey};\n};\n"],
5
+ "mappings": "sDAAA,OAAQ,gBAAAA,MAAmB,iBAE3B,OAAQ,cAAAC,EAAY,oBAAAC,MAAuB,yBCF3C,OAGE,mBAAAC,EACA,qBAAAC,MACK,6BAGA,IAAMC,EAAe,CAAC,CAC3B,KAAAC,EACA,SAAAC,CACF,IACE,cAAeD,EACXF,EAAkB,C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CACF,CAAC,EAED,GAAI,QAASE,EAAQ,CACnB,GAAM,CAAC,IAAAkB,CAAG,EAAIlB,EAOd,GALI,qBAAsBkB,GAKtB,kBAAmBA,EAErB,SAGF,MAAM,IAAIC,EAAmB,4BAA6B,CAAC,MAAOnB,CAAM,CAAC,CAC3E,CAEA,OAAOA,EAAO,EAChB,CAEA,MAAM,IAAIoB,CACZ",
6
+ "names": ["fromNullable", "Delegation", "ECDSAKeyIdentity", "getConsoleActor", "getSatelliteActor", "getAuthActor", "auth", "identity", "authenticate", "actorParams", "args", "getAuthActor", "getDelegation", "get_delegation", "DelegationChain", "DelegationIdentity", "generateIdentity", "delegations", "sessionKey", "userKey", "signedDelegations", "delegationChain", "authenticateSession", "jwt", "context", "auth", "sessionKey", "ECDSAKeyIdentity", "publicKey", "delegations", "data", "authenticate", "generateIdentity", "caller", "salt", "result", "AuthenticationError", "userKey", "expiration", "rest", "signedDelegation", "retryGetDelegation", "delegation", "signature", "pubkey", "signedExpiration", "targets", "Delegation", "fromNullable", "maxRetries", "i", "resolve", "getDelegation", "Err", "GetDelegationError", "GetDelegationRetryError"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as i,b as o}from"./chunk-AO3TH3FT.js";import{a as s}from"./chunk-HE7SWFN4.js";import{b as e}from"./chunk-VYICNPPG.js";async function d({google:t}){let r=await s();if("credentials"in t){let{credentials:c}=t,{configUrl:m}=e;return await o({...c,...r,configUrl:m})}let{redirect:a}=t,{authUrl:n,authScopes:u}=e;i({...a,...r,authUrl:n,authScopes:u})}export{d as a};
2
+ //# sourceMappingURL=chunk-ZSWBJ7CY.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/request.ts"],
4
+ "sourcesContent": ["import {GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {requestJwtWithRedirect, requestWithCredentials} from './_openid';\nimport type {\n RequestJwtCredentialsParams,\n RequestJwtCredentialsResult,\n RequestJwtParams,\n RequestJwtRedirectParams\n} from './types/request';\n\nexport function requestJwt(args: {\n google: RequestJwtCredentialsParams;\n}): Promise<RequestJwtCredentialsResult>;\n\nexport function requestJwt(args: {google: RequestJwtRedirectParams}): Promise<void>;\n\nexport async function requestJwt({\n google\n}: {\n google: RequestJwtParams;\n}): Promise<RequestJwtCredentialsResult | void> {\n const context = await initContext();\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestJwtWithRedirect({\n ...redirect,\n ...context,\n authUrl,\n authScopes\n });\n}\n"],
5
+ "mappings": "+HAgBA,eAAsBA,EAAW,CAC/B,OAAAC,CACF,EAEgD,CAC9C,IAAMC,EAAU,MAAMC,EAAY,EAElC,GAAI,gBAAiBF,EAAQ,CAC3B,GAAM,CAAC,YAAAG,CAAW,EAAIH,EAChB,CAAC,UAAAI,CAAS,EAAIC,EAEpB,OAAO,MAAMC,EAAuB,CAClC,GAAGH,EACH,GAAGF,EACH,UAAAG,CACF,CAAC,CACH,CAEA,GAAM,CAAC,SAAAG,CAAQ,EAAIP,EACb,CAAC,QAAAQ,EAAS,WAAAC,CAAU,EAAIJ,EAE9BK,EAAuB,CACrB,GAAGH,EACH,GAAGN,EACH,QAAAO,EACA,WAAAC,CACF,CAAC,CACH",
6
+ "names": ["requestJwt", "google", "context", "initContext", "credentials", "configUrl", "GOOGLE_PROVIDER", "requestWithCredentials", "redirect", "authUrl", "authScopes", "requestJwtWithRedirect"]
7
+ }
@@ -1,2 +1,2 @@
1
- import{a as x}from"./chunk-E4CYLKZY.js";import"./chunk-36KNLPQZ.js";import{a as y}from"./chunk-JOJCKPWQ.js";import"./chunk-JOOQTYYG.js";import"./chunk-JTJJD55H.js";import"./chunk-VYICNPPG.js";import{a as t,b as o,c as s,d as p,e as n,f as i,g as a,h as m,i as f,j as u}from"./chunk-2BORB4XM.js";var d=()=>{let{userAgent:e}=navigator;return/SamsungBrowser/i.test(e)?!1:"IdentityCredential"in window};export{n as AuthenticationError,a as AuthenticationInvalidStateError,m as AuthenticationUndefinedJwtError,i as AuthenticationUrlHashError,o as ContextUndefinedError,p as FedCMIdentityCredentialInvalidError,s as FedCMIdentityCredentialUndefinedError,f as GetDelegationError,u as GetDelegationRetryError,t as InvalidUrlError,x as authenticate,d as isFedCMSupported,y as requestJwt};
1
+ import{a as x}from"./chunk-JYGIWWOR.js";import"./chunk-PIJCHIUI.js";import{a as y}from"./chunk-ZSWBJ7CY.js";import"./chunk-AO3TH3FT.js";import"./chunk-HE7SWFN4.js";import"./chunk-VYICNPPG.js";import{a as t,b as o,c as s,d as p,e as n,f as i,g as a,h as m,i as f,j as u}from"./chunk-2BORB4XM.js";var d=()=>{let{userAgent:e}=navigator;return/SamsungBrowser/i.test(e)?!1:"IdentityCredential"in window};export{n as AuthenticationError,a as AuthenticationInvalidStateError,m as AuthenticationUndefinedJwtError,i as AuthenticationUrlHashError,o as ContextUndefinedError,p as FedCMIdentityCredentialInvalidError,s as FedCMIdentityCredentialUndefinedError,f as GetDelegationError,u as GetDelegationRetryError,t as InvalidUrlError,x as authenticate,d as isFedCMSupported,y as requestJwt};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-JOJCKPWQ.js";import"./chunk-JOOQTYYG.js";import"./chunk-JTJJD55H.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as requestJwt};
1
+ import{a}from"./chunk-ZSWBJ7CY.js";import"./chunk-AO3TH3FT.js";import"./chunk-HE7SWFN4.js";import"./chunk-VYICNPPG.js";import"./chunk-2BORB4XM.js";export{a as requestJwt};
2
2
  //# sourceMappingURL=request.js.map
@@ -1,4 +1,4 @@
1
1
  import { createRequire as topLevelCreateRequire } from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
- import{isEmptyString as _}from"@dfinity/utils";import{Ed25519KeyIdentity as H}from"@dfinity/identity";import{isNullish as Q}from"@dfinity/utils";var P="juno:auth:openid",C={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"};var d=class extends Error{},l=class extends Error{},u=class extends Error{},y=class extends Error{},g=class extends Error{},h=class extends Error{},f=class extends Error{},A=class extends Error{},x=class extends Error{},w=class extends Error{};import{arrayBufferToUint8Array as V}from"@dfinity/utils";import{uint8ArrayToBase64 as Y}from"@dfinity/utils";var S=t=>Y(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var F=()=>window.crypto.getRandomValues(new Uint8Array(32)),M=async({salt:t,caller:e})=>{let r=e.getPrincipal().toUint8Array(),o=new Uint8Array(t.length+r.byteLength);o.set(t),o.set(r,t.length);let n=await window.crypto.subtle.digest("SHA-256",o);return S(V(n))},O=async({caller:t})=>{let e=F();return{nonce:await M({salt:e,caller:t}),salt:e}};import{Ed25519KeyIdentity as X}from"@dfinity/identity";import{base64ToUint8Array as $,uint8ArrayToBase64 as z}from"@dfinity/utils";var R="__caller__",U="__salt__",D="__state__",K=({caller:t,state:e,salt:r})=>{let o={[R]:t.toJSON(),[U]:z(r),[D]:e};return JSON.stringify(o)},N=t=>{let{[R]:e,[U]:r,[D]:o}=JSON.parse(t);return{caller:X.fromParsedJson(e),salt:$(r),state:o}};var J=()=>S(window.crypto.getRandomValues(new Uint8Array(12)));var b=async()=>{let t=H.generate(),{nonce:e,salt:r}=await O({caller:t}),o=J(),n=K({caller:t,salt:r,state:o});return sessionStorage.setItem(P,n),{nonce:e,state:o}},L=()=>{let t=sessionStorage.getItem(P);if(Q(t))throw new l;return N(t)};import{Delegation as ot,ECDSAKeyIdentity as nt}from"@dfinity/identity";import{fromNullable as it}from"@dfinity/utils";import{getConsoleActor as Z,getSatelliteActor as tt}from"@junobuild/ic-client/actor";var E=({auth:t,identity:e})=>"satellite"in t?tt({...t.satellite,identity:e}):Z({...t.console,identity:e});var k=async({actorParams:t,args:e})=>{let{authenticate:r}=await E(t);return await r(e)},T=async({actorParams:t,args:e})=>{let{get_delegation:r}=await E(t);return await r(e)};import{DelegationChain as et,DelegationIdentity as rt}from"@dfinity/identity";var q=({delegations:t,sessionKey:e})=>{let[r,o]=t,n=et.fromDelegations(o,Uint8Array.from(r));return{identity:rt.fromDelegation(e,n),delegationChain:n}};var I=async({jwt:t,context:e,auth:r})=>{let o=await nt.generate({extractable:!1}),n=new Uint8Array(o.getPublicKey().toDer()),i=await st({jwt:t,publicKey:n,context:e,auth:r});return q({sessionKey:o,delegations:i})},st=async({jwt:t,publicKey:e,context:{caller:r,salt:o},auth:n})=>{let i=await k({args:{OpenId:{jwt:t,session_key:e,salt:o}},actorParams:{auth:n,identity:r}});if("Err"in i)throw new g("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:c}}=i.Ok,a=await at({jwt:t,context:{caller:r,salt:o},auth:n,publicKey:e,expiration:c}),{delegation:p,signature:m}=a,{pubkey:j,expiration:W,targets:B}=p;return[s,[{delegation:new ot(Uint8Array.from(j),W,it(B)),signature:Uint8Array.from(m)}]]},at=async({jwt:t,publicKey:e,context:{salt:r,caller:o},auth:n,expiration:i,maxRetries:s=5})=>{for(let c=0;c<s;c++){await new Promise(m=>{setInterval(m,1e3*c)});let p=await T({args:{OpenId:{jwt:t,session_key:e,salt:r,expiration:i}},actorParams:{auth:n,identity:o}});if("Err"in p){let{Err:m}=p;if("NoSuchDelegation"in m||"GetCachedJwks"in m)continue;throw new x("Getting delegation failed",{cause:p})}return p.Ok}throw new w};var Mt=async t=>{let e=L();if("credentials"in t){let{credentials:{jwt:r},auth:o}=t;return await I({jwt:r,context:e,auth:o})}return await ct({...t,context:e})},ct=async({auth:t,context:e})=>{let{location:{hash:r}}=window;if(_(r)||!r.startsWith("#"))throw new h("No hash found in the current location URL");let o=new URLSearchParams(r.slice(1)),n=o.get("state"),i=o.get("id_token"),{state:s}=e;if(_(s)||n!==s)throw new f("The provided state is invalid",{cause:n});if(_(i))throw new A;return await I({jwt:i,auth:t,context:e})};import{isNullish as pt,notEmptyString as mt}from"@dfinity/utils";var v=({authUrl:t,clientId:e,nonce:r,loginHint:o,authScopes:n,state:i,redirectUrl:s})=>{let a=(()=>{try{return new URL(t)}catch(m){throw new d("Cannot parse authURL",{cause:m})}})();a.searchParams.set("client_id",e);let{location:{origin:p}}=window;a.searchParams.set("redirect_uri",s??p),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("state",i),a.searchParams.set("nonce",r),mt(o)?a.searchParams.set("login_hint",o):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},G=async({configUrl:t,clientId:e,nonce:r,loginHint:o,domainHint:n})=>{let i=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:t,clientId:e,nonce:r,loginHint:o,domainHint:n}],mode:"active"},mediation:"required"});if(pt(i))throw new u;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new y("Invalid credential received from FedCM API",{cause:i});let{token:c}=i;return{jwt:c}};var ee=async({google:t})=>{let e=await b();if("credentials"in t){let{credentials:i}=t,{configUrl:s}=C;return await G({...i,...e,configUrl:s})}let{redirect:r}=t,{authUrl:o,authScopes:n}=C;throw v({...r,...e,authUrl:o,authScopes:n}),new Error("Unreachable")};var oe=()=>{let{userAgent:t}=navigator;return/SamsungBrowser/i.test(t)?!1:"IdentityCredential"in window};export{g as AuthenticationError,f as AuthenticationInvalidStateError,A as AuthenticationUndefinedJwtError,h as AuthenticationUrlHashError,l as ContextUndefinedError,y as FedCMIdentityCredentialInvalidError,u as FedCMIdentityCredentialUndefinedError,x as GetDelegationError,w as GetDelegationRetryError,d as InvalidUrlError,Mt as authenticate,oe as isFedCMSupported,ee as requestJwt};
3
+ import{isEmptyString as _}from"@dfinity/utils";import{isNullish as Q}from"@dfinity/utils";import{Ed25519KeyIdentity as Z}from"@icp-sdk/core/identity";var S="juno:auth:openid",C={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"};var d=class extends Error{},u=class extends Error{},l=class extends Error{},y=class extends Error{},g=class extends Error{},h=class extends Error{},f=class extends Error{},A=class extends Error{},x=class extends Error{},w=class extends Error{};import{arrayBufferToUint8Array as F}from"@dfinity/utils";import{uint8ArrayToBase64 as V}from"@dfinity/utils";var P=t=>V(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var M=()=>window.crypto.getRandomValues(new Uint8Array(32)),X=async({salt:t,caller:e})=>{let r=e.getPrincipal().toUint8Array(),o=new Uint8Array(t.length+r.byteLength);o.set(t),o.set(r,t.length);let n=await window.crypto.subtle.digest("SHA-256",o);return P(F(n))},I=async({caller:t})=>{let e=M();return{nonce:await X({salt:e,caller:t}),salt:e}};import{base64ToUint8Array as $,uint8ArrayToBase64 as z}from"@dfinity/utils";import{Ed25519KeyIdentity as H}from"@icp-sdk/core/identity";var D="__caller__",O="__salt__",J="__state__",U=({caller:t,state:e,salt:r})=>{let o={[D]:t.toJSON(),[O]:z(r),[J]:e};return JSON.stringify(o)},T=t=>{let{[D]:e,[O]:r,[J]:o}=JSON.parse(t);return{caller:H.fromParsedJson(e),salt:$(r),state:o}};var q=()=>P(window.crypto.getRandomValues(new Uint8Array(12)));var K=async()=>{let t=Z.generate(),{nonce:e,salt:r}=await I({caller:t}),o=q(),n=U({caller:t,salt:r,state:o});return sessionStorage.setItem(S,n),{nonce:e,state:o}},N=()=>{let t=sessionStorage.getItem(S);if(Q(t))throw new u;return T(t)};import{fromNullable as nt}from"@dfinity/utils";import{Delegation as st,ECDSAKeyIdentity as it}from"@icp-sdk/core/identity";import{getConsoleActor as tt,getSatelliteActor as et}from"@junobuild/ic-client/actor";var R=({auth:t,identity:e})=>"satellite"in t?et({...t.satellite,identity:e}):tt({...t.console,identity:e});var k=async({actorParams:t,args:e})=>{let{authenticate:r}=await R(t);return await r(e)},v=async({actorParams:t,args:e})=>{let{get_delegation:r}=await R(t);return await r(e)};import{DelegationChain as rt,DelegationIdentity as ot}from"@icp-sdk/core/identity";var L=({delegations:t,sessionKey:e})=>{let[r,o]=t,n=rt.fromDelegations(o,Uint8Array.from(r));return{identity:ot.fromDelegation(e,n),delegationChain:n,sessionKey:e}};var E=async({jwt:t,context:e,auth:r})=>{let o=await it.generate({extractable:!1}),n=new Uint8Array(o.getPublicKey().toDer()),{delegations:s,data:i}=await at({jwt:t,publicKey:n,context:e,auth:r});return{identity:L({sessionKey:o,delegations:s}),data:i}},at=async({jwt:t,publicKey:e,context:{caller:r,salt:o},auth:n})=>{let s=await k({args:{OpenId:{jwt:t,session_key:e,salt:o}},actorParams:{auth:n,identity:r}});if("Err"in s)throw new g("Authentication failed",{cause:s});let{delegation:{user_key:i,expiration:c},...a}=s.Ok,p=await ct({jwt:t,context:{caller:r,salt:o},auth:n,publicKey:e,expiration:c}),{delegation:m,signature:W}=p,{pubkey:j,expiration:B,targets:Y}=m;return{delegations:[i,[{delegation:new st(Uint8Array.from(j),B,nt(Y)),signature:Uint8Array.from(W)}]],data:a}},ct=async({jwt:t,publicKey:e,context:{salt:r,caller:o},auth:n,expiration:s,maxRetries:i=5})=>{for(let c=0;c<i;c++){await new Promise(m=>{setInterval(m,1e3*c)});let p=await v({args:{OpenId:{jwt:t,session_key:e,salt:r,expiration:s}},actorParams:{auth:n,identity:o}});if("Err"in p){let{Err:m}=p;if("NoSuchDelegation"in m||"GetCachedJwks"in m)continue;throw new x("Getting delegation failed",{cause:p})}return p.Ok}throw new w};var $t=async t=>{let e=N();if("credentials"in t){let{credentials:{jwt:r},auth:o}=t;return await E({jwt:r,context:e,auth:o})}return await pt({...t,context:e})},pt=async({auth:t,context:e})=>{let{location:{hash:r}}=window;if(_(r)||!r.startsWith("#"))throw new h("No hash found in the current location URL");let o=new URLSearchParams(r.slice(1)),n=o.get("state"),s=o.get("id_token"),{state:i}=e;if(_(i)||n!==i)throw new f("The provided state is invalid",{cause:n});if(_(s))throw new A;return await E({jwt:s,auth:t,context:e})};import{isNullish as mt,notEmptyString as dt}from"@dfinity/utils";var b=({authUrl:t,clientId:e,nonce:r,loginHint:o,authScopes:n,state:s,redirectUrl:i})=>{let a=(()=>{try{return new URL(t)}catch{throw new d("Cannot parse authURL",{cause:t})}})();a.searchParams.set("client_id",e);let{location:{origin:p}}=window;a.searchParams.set("redirect_uri",i??p),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("state",s),a.searchParams.set("nonce",r),dt(o)?a.searchParams.set("login_hint",o):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},G=async({configUrl:t,clientId:e,nonce:r,loginHint:o,domainHint:n})=>{let s=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:t,clientId:e,nonce:r,loginHint:o,domainHint:n}],mode:"active"},mediation:"required"});if(mt(s))throw new l;let{type:i}=s;if(i!=="identity"||!("token"in s)||typeof s.token!="string")throw new y("Invalid credential received from FedCM API",{cause:s});let{token:c}=s;return{jwt:c}};async function oe({google:t}){let e=await K();if("credentials"in t){let{credentials:s}=t,{configUrl:i}=C;return await G({...s,...e,configUrl:i})}let{redirect:r}=t,{authUrl:o,authScopes:n}=C;b({...r,...e,authUrl:o,authScopes:n})}var se=()=>{let{userAgent:t}=navigator;return/SamsungBrowser/i.test(t)?!1:"IdentityCredential"in window};export{g as AuthenticationError,f as AuthenticationInvalidStateError,A as AuthenticationUndefinedJwtError,h as AuthenticationUrlHashError,u as ContextUndefinedError,y as FedCMIdentityCredentialInvalidError,l as FedCMIdentityCredentialUndefinedError,x as GetDelegationError,w as GetDelegationRetryError,d as InvalidUrlError,$t as authenticate,se as isFedCMSupported,oe as requestJwt};
4
4
  //# sourceMappingURL=index.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/authenticate.ts", "../../src/_context.ts", "../../src/_constants.ts", "../../src/errors.ts", "../../src/utils/auth.utils.ts", "../../src/utils/url.utils.ts", "../../src/utils/session-storage.utils.ts", "../../src/utils/state.utils.ts", "../../src/_session.ts", "../../src/api/_actor.api.ts", "../../src/api/auth.api.ts", "../../src/utils/session.utils.ts", "../../src/_openid.ts", "../../src/request.ts", "../../src/utils/openid.utils.ts"],
4
- "sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {loadContext} from './_context';\nimport {authenticate as authenticateSession} from './_session';\nimport {\n AuthenticationInvalidStateError,\n AuthenticationUndefinedJwtError,\n AuthenticationUrlHashError\n} from './errors';\nimport type {AuthParameters} from './types/actor';\nimport type {AuthenticatedIdentity, AuthenticationParams} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\n\nexport const authenticate = async (\n params: AuthenticationParams\n): Promise<AuthenticatedIdentity> => {\n const context = loadContext();\n\n if ('credentials' in params) {\n const {\n credentials: {jwt},\n auth\n } = params;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateWithRedirect({...params, context});\n};\n\nconst authenticateWithRedirect = async ({\n auth,\n context\n}: {\n auth: AuthParameters;\n context: OpenIdAuthContext;\n}): Promise<AuthenticatedIdentity> => {\n const {\n location: {hash}\n } = window;\n\n if (isEmptyString(hash) || !hash.startsWith('#')) {\n throw new AuthenticationUrlHashError('No hash found in the current location URL');\n }\n\n const params = new URLSearchParams(hash.slice(1));\n const state = params.get('state');\n const idToken = params.get('id_token');\n\n const {state: savedState} = context;\n\n if (isEmptyString(savedState) || state !== savedState) {\n throw new AuthenticationInvalidStateError('The provided state is invalid', {cause: state});\n }\n\n // id_token === jwt\n if (isEmptyString(idToken)) {\n throw new AuthenticationUndefinedJwtError();\n }\n\n return await authenticateSession({\n jwt: idToken,\n auth,\n context\n });\n};\n", "import {Ed25519KeyIdentity} from '@dfinity/identity';\nimport {isNullish} from '@dfinity/utils';\nimport {CONTEXT_KEY} from './_constants';\nimport {ContextUndefinedError} from './errors';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Nonce} from './types/nonce';\nimport {generateNonce} from './utils/auth.utils';\nimport {parseContext, stringifyContext} from './utils/session-storage.utils';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const initContext = async (): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n const state = generateRandomState();\n\n const storedData = stringifyContext({\n caller,\n salt,\n state\n });\n\n sessionStorage.setItem(CONTEXT_KEY, storedData);\n\n return {\n nonce,\n state\n };\n};\n\nexport const loadContext = (): OpenIdAuthContext => {\n const storedContext = sessionStorage.getItem(CONTEXT_KEY);\n\n if (isNullish(storedContext)) {\n throw new ContextUndefinedError();\n }\n\n return parseContext(storedContext);\n};\n", "import type {OpenIdProvider} from './types/provider';\n\nexport const CONTEXT_KEY = 'juno:auth:openid';\n\n// Create client_id: https://developers.google.com/identity/openid-connect/openid-connect#authenticationuriparameters\nexport const GOOGLE_PROVIDER: Omit<OpenIdProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n authScopes: ['openid', 'profile', 'email'],\n configUrl: 'https://accounts.google.com/gsi/fedcm.json'\n};\n", "export class InvalidUrlError extends Error {}\nexport class ContextUndefinedError extends Error {}\n\nexport class FedCMIdentityCredentialUndefinedError extends Error {}\nexport class FedCMIdentityCredentialInvalidError extends Error {}\n\nexport class AuthenticationError extends Error {}\nexport class AuthenticationUrlHashError extends Error {}\nexport class AuthenticationInvalidStateError extends Error {}\nexport class AuthenticationUndefinedJwtError extends Error {}\n\nexport class GetDelegationError extends Error {}\nexport class GetDelegationRetryError extends Error {}\n", "import type {Ed25519KeyIdentity} from '@dfinity/identity';\nimport {arrayBufferToUint8Array} from '@dfinity/utils';\nimport type {Nonce, Salt} from '../types/nonce';\nimport {toBase64URL} from './url.utils';\n\nconst generateSalt = (): Salt => window.crypto.getRandomValues(new Uint8Array(32));\n\nconst buildNonce = async ({salt, caller}: {salt: Salt; caller: Ed25519KeyIdentity}) => {\n const principal = caller.getPrincipal().toUint8Array();\n\n const bytes = new Uint8Array(salt.length + principal.byteLength);\n bytes.set(salt);\n bytes.set(principal, salt.length);\n\n const hash = await window.crypto.subtle.digest('SHA-256', bytes);\n\n return toBase64URL(arrayBufferToUint8Array(hash));\n};\n\nexport const generateNonce = async ({\n caller\n}: {\n caller: Ed25519KeyIdentity;\n}): Promise<{nonce: Nonce; salt: Salt}> => {\n const salt = generateSalt();\n const nonce = await buildNonce({salt, caller});\n\n return {nonce, salt};\n};\n", "import {uint8ArrayToBase64} from '@dfinity/utils';\n\n// In the future: uint8Array.toBase64({ alphabet: \"base64url\" })\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64\nexport const toBase64URL = (uint8Array: Uint8Array): string =>\n uint8ArrayToBase64(uint8Array).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n", "import {Ed25519KeyIdentity, type JsonnableEd25519KeyIdentity} from '@dfinity/identity';\nimport {base64ToUint8Array, uint8ArrayToBase64} from '@dfinity/utils';\nimport type {OpenIdAuthContext} from '../types/context';\n\nconst JSON_KEY_CALLER = '__caller__';\nconst JSON_KEY_SALT = '__salt__';\nconst JSON_KEY_STATE = '__state__';\n\ninterface StoredContext {\n [JSON_KEY_CALLER]: JsonnableEd25519KeyIdentity;\n [JSON_KEY_SALT]: string;\n [JSON_KEY_STATE]: string;\n}\n\nexport const stringifyContext = ({caller, state, salt}: OpenIdAuthContext): string => {\n const data: StoredContext = {\n [JSON_KEY_CALLER]: caller.toJSON(),\n [JSON_KEY_SALT]: uint8ArrayToBase64(salt),\n [JSON_KEY_STATE]: state\n };\n\n return JSON.stringify(data);\n};\n\nexport const parseContext = (jsonData: string): OpenIdAuthContext => {\n const {\n [JSON_KEY_CALLER]: jsonCaller,\n [JSON_KEY_SALT]: jsonSalt,\n [JSON_KEY_STATE]: state\n }: StoredContext = JSON.parse(jsonData);\n\n return {\n caller: Ed25519KeyIdentity.fromParsedJson(jsonCaller),\n salt: base64ToUint8Array(jsonSalt),\n state\n };\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n", "import type {Signature} from '@dfinity/agent';\nimport {Delegation, ECDSAKeyIdentity} from '@dfinity/identity';\nimport {fromNullable} from '@dfinity/utils';\nimport {authenticate as authenticateApi, getDelegation as getDelegationApi} from './api/auth.api';\nimport {AuthenticationError, GetDelegationError, GetDelegationRetryError} from './errors';\nimport type {AuthParameters, GetDelegationArgs, SignedDelegation} from './types/actor';\nimport type {AuthenticatedIdentity} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Delegations} from './types/session';\nimport {generateIdentity} from './utils/session.utils';\n\ninterface AuthContext {\n context: Omit<OpenIdAuthContext, 'state'>;\n auth: AuthParameters;\n}\ntype AuthenticationArgs = {jwt: string} & AuthContext;\n\nexport const authenticate = async ({\n jwt,\n context,\n auth\n}: AuthenticationArgs): Promise<AuthenticatedIdentity> => {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const publicKey = new Uint8Array(sessionKey.getPublicKey().toDer());\n\n const delegations = await authenticateSession({jwt, publicKey, context, auth});\n\n return generateIdentity({\n sessionKey,\n delegations\n });\n};\n\nconst authenticateSession = async ({\n jwt,\n publicKey,\n context: {caller, salt},\n auth\n}: {\n publicKey: Uint8Array;\n} & AuthenticationArgs): Promise<Delegations> => {\n const result = await authenticateApi({\n args: {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt\n }\n },\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n throw new AuthenticationError('Authentication failed', {cause: result});\n }\n\n const {\n delegation: {user_key: userKey, expiration}\n } = result.Ok;\n\n const signedDelegation = await retryGetDelegation({\n jwt,\n context: {caller, salt},\n auth,\n publicKey,\n expiration\n });\n\n const {delegation, signature} = signedDelegation;\n const {pubkey, expiration: signedExpiration, targets} = delegation;\n\n return [\n userKey,\n [\n {\n delegation: new Delegation(\n Uint8Array.from(pubkey),\n signedExpiration,\n fromNullable(targets)\n ),\n signature: Uint8Array.from(signature) as unknown as Signature\n }\n ]\n ];\n};\n\nconst retryGetDelegation = async ({\n jwt,\n publicKey,\n context: {salt, caller},\n auth,\n expiration,\n maxRetries = 5\n}: {\n publicKey: Uint8Array;\n expiration: bigint;\n maxRetries?: number;\n} & AuthenticationArgs): Promise<SignedDelegation> => {\n for (let i = 0; i < maxRetries; i++) {\n // Linear backoff\n await new Promise((resolve) => {\n setInterval(resolve, 1000 * i);\n });\n\n const args: GetDelegationArgs = {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt,\n expiration\n }\n };\n\n const result = await getDelegationApi({\n args,\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n const {Err} = result;\n\n if ('NoSuchDelegation' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if ('GetCachedJwks' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n throw new GetDelegationError('Getting delegation failed', {cause: result});\n }\n\n return result.Ok;\n }\n\n throw new GetDelegationRetryError();\n};\n", "import {\n type ConsoleActor,\n type SatelliteActor,\n getConsoleActor,\n getSatelliteActor\n} from '@junobuild/ic-client/actor';\nimport type {ActorParameters} from '../types/actor';\n\nexport const getAuthActor = ({\n auth,\n identity\n}: ActorParameters): Promise<ConsoleActor | SatelliteActor> =>\n 'satellite' in auth\n ? getSatelliteActor({...auth.satellite, identity})\n : getConsoleActor({...auth.console, identity});\n", "import type {\n ActorParameters,\n AuthenticationArgs,\n AuthenticationResult,\n GetDelegationArgs,\n GetDelegationResult\n} from '../types/actor';\nimport {getAuthActor} from './_actor.api';\n\nexport const authenticate = async ({\n actorParams,\n args\n}: {\n args: AuthenticationArgs;\n actorParams: ActorParameters;\n}): Promise<AuthenticationResult> => {\n const {authenticate} = await getAuthActor(actorParams);\n return await authenticate(args);\n};\n\nexport const getDelegation = async ({\n actorParams,\n args\n}: {\n args: GetDelegationArgs;\n actorParams: ActorParameters;\n}): Promise<GetDelegationResult> => {\n const {get_delegation} = await getAuthActor(actorParams);\n return await get_delegation(args);\n};\n", "import {DelegationChain, DelegationIdentity, type ECDSAKeyIdentity} from '@dfinity/identity';\nimport type {AuthenticatedIdentity} from '../types/authenticate';\nimport type {Delegations} from '../types/session';\n\nexport const generateIdentity = ({\n delegations,\n sessionKey\n}: {\n delegations: Delegations;\n sessionKey: ECDSAKeyIdentity;\n}): AuthenticatedIdentity => {\n const [userKey, signedDelegations] = delegations;\n\n const delegationChain = DelegationChain.fromDelegations(\n signedDelegations,\n Uint8Array.from(userKey)\n );\n\n const identity = DelegationIdentity.fromDelegation(sessionKey, delegationChain);\n\n return {identity, delegationChain};\n};\n", "import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestJwtWithCredentials, RequestJwtWithRedirect} from './types/openid';\n\n/**\n * Initiates an OpenID Connect authorization request by redirecting the browser.\n *\n * References:\n * - OAuth 2.0 (Google): https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow\n * - OpenID Connect: https://developers.google.com/identity/openid-connect/openid-connect\n */\nexport const requestJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestJwtWithRedirect) => {\n const parseAuthUrl = (): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(authUrl);\n } catch (error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: error});\n }\n };\n\n const requestUrl = parseAuthUrl();\n\n requestUrl.searchParams.set('client_id', clientId);\n\n const {\n location: {origin: currentUrl}\n } = window;\n\n requestUrl.searchParams.set('redirect_uri', redirectUrl ?? currentUrl);\n\n // We do not request \"token\" because we use the ID token (JWT).\n // \"code\" is required according to II's codebase as Apple ID throws an error otherwise.\n requestUrl.searchParams.set('response_type', 'code id_token');\n\n requestUrl.searchParams.set('scope', authScopes.join(' '));\n\n // Used for security reasons. When the provider redirects to the application,\n // the state will be compared with the session storage value.\n requestUrl.searchParams.set('state', state);\n\n // Used to validate the JSON Web Token (JWT) in the backend \u2014 i.e. we pass the nonce\n // to the provider and make the request to the backend with its salt.\n requestUrl.searchParams.set('nonce', nonce);\n\n if (notEmptyString(loginHint)) {\n requestUrl.searchParams.set('login_hint', loginHint);\n } else {\n requestUrl.searchParams.set('prompt', 'select_account');\n }\n\n window.location.href = requestUrl.toString();\n};\n\n/**\n * References:\n * - identity spec: https://www.w3.org/TR/fedcm/#browser-api-credential-request-options\n * - https://privacysandbox.google.com/cookies/fedcm/implement/identity-provider\n * - https://privacysandbox.google.com/cookies/fedcm/why\n */\nexport const requestWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestJwtWithCredentials): Promise<{jwt: string}> => {\n const identityCredential = await navigator.credentials.get({\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n identity: {\n context: 'use',\n providers: [\n {\n configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n }\n ],\n mode: 'active'\n },\n // https://privacysandbox.google.com/cookies/fedcm/implement/relying-party#auto-reauthn\n mediation: 'required'\n });\n\n if (isNullish(identityCredential)) {\n throw new FedCMIdentityCredentialUndefinedError();\n }\n\n const {type} = identityCredential;\n\n if (\n type !== 'identity' ||\n !('token' in identityCredential) ||\n typeof identityCredential.token !== 'string'\n ) {\n // This should be unreachable in FedCM spec-compliant browsers.\n throw new FedCMIdentityCredentialInvalidError('Invalid credential received from FedCM API', {\n cause: identityCredential\n });\n }\n\n const {token: jwt} = identityCredential;\n return {jwt};\n};\n", "import {GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {requestJwtWithRedirect, requestWithCredentials} from './_openid';\nimport type {RequestJwtParams} from './types/request';\n\nexport const requestJwt = async ({google}: {google: RequestJwtParams}): Promise<{jwt: string}> => {\n const context = await initContext();\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestJwtWithRedirect({\n ...redirect,\n ...context,\n authUrl,\n authScopes\n });\n\n throw new Error('Unreachable');\n};\n", "/**\n * Detects whether the browser supports FedCM (Federated Credential Management).\n *\n * @returns {boolean} `true` if FedCM is supported, otherwise `false`.\n *\n * References:\n * - MDN IdentityCredential: https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential\n */\nexport const isFedCMSupported = (): boolean => {\n const {userAgent} = navigator;\n\n // Samsung browser implements \"IdentityCredential\" but does not support \"configURL\"\n // https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential\n const isSamsungBrowser = /SamsungBrowser/i.test(userAgent);\n if (isSamsungBrowser) {\n return false;\n }\n\n return 'IdentityCredential' in window;\n};\n"],
5
- "mappings": ";;AAAA,OAAQ,iBAAAA,MAAoB,iBCA5B,OAAQ,sBAAAC,MAAyB,oBACjC,OAAQ,aAAAC,MAAgB,iBCCjB,IAAMC,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb,ECTO,IAAMC,EAAN,cAA8B,KAAM,CAAC,EAC/BC,EAAN,cAAoC,KAAM,CAAC,EAErCC,EAAN,cAAoD,KAAM,CAAC,EACrDC,EAAN,cAAkD,KAAM,CAAC,EAEnDC,EAAN,cAAkC,KAAM,CAAC,EACnCC,EAAN,cAAyC,KAAM,CAAC,EAC1CC,EAAN,cAA8C,KAAM,CAAC,EAC/CC,EAAN,cAA8C,KAAM,CAAC,EAE/CC,EAAN,cAAiC,KAAM,CAAC,EAClCC,EAAN,cAAsC,KAAM,CAAC,ECXpD,OAAQ,2BAAAC,M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C,EAEK,IAAI,MAAM,aAAa,CAC/B,ECtBO,IAAME,GAAmB,IAAe,CAC7C,GAAM,CAAC,UAAAC,CAAS,EAAI,UAKpB,MADyB,kBAAkB,KAAKA,CAAS,EAEhD,GAGF,uBAAwB,MACjC",
6
- "names": ["isEmptyString", "Ed25519KeyIdentity", "isNullish", "CONTEXT_KEY", "GOOGLE_PROVIDER", "InvalidUrlError", "ContextUndefinedError", "FedCMIdentityCredentialUndefinedError", "FedCMIdentityCredentialInvalidError", "AuthenticationError", "AuthenticationUrlHashError", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "GetDelegationError", "GetDelegationRetryError", "arrayBufferToUint8Array", "uint8ArrayToBase64", "toBase64URL", "uint8Array", "generateSalt", "buildNonce", "salt", "caller", "principal", "bytes", "hash", "toBase64URL", "arrayBufferToUint8Array", "generateNonce", "Ed25519KeyIdentity", "base64ToUint8Array", "uint8ArrayToBase64", "JSON_KEY_CALLER", "JSON_KEY_SALT", "JSON_KEY_STATE", "stringifyContext", "caller", "state", "salt", "data", "parseContext", "jsonData", "jsonCaller", "jsonSalt", "generateRandomState", "toBase64URL", "initContext", "caller", "Ed25519KeyIdentity", "nonce", "salt", "generateNonce", "state", "generateRandomState", "storedData", "stringifyContext", "CONTEXT_KEY", "loadContext", "storedContext", "isNullish", "ContextUndefinedError", "parseContext", "Delegation", "ECDSAKeyIdentity", "fromNullable", "getConsoleActor", "getSatelliteActor", "getAuthActor", "auth", "identity", "authenticate", "actorParams", "args", "getAuthActor", "getDelegation", "get_delegation", "DelegationChain", "DelegationIdentity", "generateIdentity", "delegations", "sessionKey", "userKey", "signedDelegations", "delegationChain", "authenticate", "jwt", "context", "auth", "sessionKey", "ECDSAKeyIdentity", "publicKey", "delegations", "authenticateSession", "generateIdentity", "caller", "salt", "result", "AuthenticationError", "userKey", "expiration", "signedDelegation", "retryGetDelegation", "delegation", "signature", "pubkey", "signedExpiration", "targets", "Delegation", "fromNullable", "maxRetries", "i", "resolve", "getDelegation", "Err", "GetDelegationError", "GetDelegationRetryError", "authenticate", "params", "context", "loadContext", "jwt", "auth", "authenticateWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "isNullish", "notEmptyString", "requestJwtWithRedirect", "authUrl", "clientId", "nonce", "loginHint", "authScopes", "state", "redirectUrl", "requestUrl", "error", "InvalidUrlError", "currentUrl", "notEmptyString", "requestWithCredentials", "configURL", "domainHint", "identityCredential", "isNullish", "FedCMIdentityCredentialUndefinedError", "type", "FedCMIdentityCredentialInvalidError", "jwt", "requestJwt", "google", "context", "initContext", "credentials", "configUrl", "GOOGLE_PROVIDER", "requestWithCredentials", "redirect", "authUrl", "authScopes", "requestJwtWithRedirect", "isFedCMSupported", "userAgent"]
4
+ "sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {loadContext} from './_context';\nimport {authenticateSession} from './_session';\nimport {\n AuthenticationInvalidStateError,\n AuthenticationUndefinedJwtError,\n AuthenticationUrlHashError\n} from './errors';\nimport type {\n AuthenticatedSession,\n AuthenticationParams,\n AuthParameters\n} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\n\nexport const authenticate = async <T extends AuthParameters>(\n params: AuthenticationParams<T>\n): Promise<AuthenticatedSession<T>> => {\n const context = loadContext();\n\n if ('credentials' in params) {\n const {\n credentials: {jwt},\n auth\n } = params;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateWithRedirect<T>({...params, context});\n};\n\nconst authenticateWithRedirect = async <T extends AuthParameters>({\n auth,\n context\n}: {\n auth: AuthParameters;\n context: OpenIdAuthContext;\n}): Promise<AuthenticatedSession<T>> => {\n const {\n location: {hash}\n } = window;\n\n if (isEmptyString(hash) || !hash.startsWith('#')) {\n throw new AuthenticationUrlHashError('No hash found in the current location URL');\n }\n\n const params = new URLSearchParams(hash.slice(1));\n const state = params.get('state');\n const idToken = params.get('id_token');\n\n const {state: savedState} = context;\n\n if (isEmptyString(savedState) || state !== savedState) {\n throw new AuthenticationInvalidStateError('The provided state is invalid', {cause: state});\n }\n\n // id_token === jwt\n if (isEmptyString(idToken)) {\n throw new AuthenticationUndefinedJwtError();\n }\n\n return await authenticateSession({\n jwt: idToken,\n auth,\n context\n });\n};\n", "import {isNullish} from '@dfinity/utils';\nimport {Ed25519KeyIdentity} from '@icp-sdk/core/identity';\nimport {CONTEXT_KEY} from './_constants';\nimport {ContextUndefinedError} from './errors';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Nonce} from './types/nonce';\nimport {generateNonce} from './utils/auth.utils';\nimport {parseContext, stringifyContext} from './utils/session-storage.utils';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const initContext = async (): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n const state = generateRandomState();\n\n const storedData = stringifyContext({\n caller,\n salt,\n state\n });\n\n sessionStorage.setItem(CONTEXT_KEY, storedData);\n\n return {\n nonce,\n state\n };\n};\n\nexport const loadContext = (): OpenIdAuthContext => {\n const storedContext = sessionStorage.getItem(CONTEXT_KEY);\n\n if (isNullish(storedContext)) {\n throw new ContextUndefinedError();\n }\n\n return parseContext(storedContext);\n};\n", "import type {OpenIdProvider} from './types/provider';\n\nexport const CONTEXT_KEY = 'juno:auth:openid';\n\n// Create client_id: https://developers.google.com/identity/openid-connect/openid-connect#authenticationuriparameters\nexport const GOOGLE_PROVIDER: Omit<OpenIdProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n authScopes: ['openid', 'profile', 'email'],\n configUrl: 'https://accounts.google.com/gsi/fedcm.json'\n};\n", "export class InvalidUrlError extends Error {}\nexport class ContextUndefinedError extends Error {}\n\nexport class FedCMIdentityCredentialUndefinedError extends Error {}\nexport class FedCMIdentityCredentialInvalidError extends Error {}\n\nexport class AuthenticationError extends Error {}\nexport class AuthenticationUrlHashError extends Error {}\nexport class AuthenticationInvalidStateError extends Error {}\nexport class AuthenticationUndefinedJwtError extends Error {}\n\nexport class GetDelegationError extends Error {}\nexport class GetDelegationRetryError extends Error {}\n", "import {arrayBufferToUint8Array} from '@dfinity/utils';\nimport type {Ed25519KeyIdentity} from '@icp-sdk/core/identity';\nimport type {Nonce, Salt} from '../types/nonce';\nimport {toBase64URL} from './url.utils';\n\nconst generateSalt = (): Salt => window.crypto.getRandomValues(new Uint8Array(32));\n\nconst buildNonce = async ({salt, caller}: {salt: Salt; caller: Ed25519KeyIdentity}) => {\n const principal = caller.getPrincipal().toUint8Array();\n\n const bytes = new Uint8Array(salt.length + principal.byteLength);\n bytes.set(salt);\n bytes.set(principal, salt.length);\n\n const hash = await window.crypto.subtle.digest('SHA-256', bytes);\n\n return toBase64URL(arrayBufferToUint8Array(hash));\n};\n\nexport const generateNonce = async ({\n caller\n}: {\n caller: Ed25519KeyIdentity;\n}): Promise<{nonce: Nonce; salt: Salt}> => {\n const salt = generateSalt();\n const nonce = await buildNonce({salt, caller});\n\n return {nonce, salt};\n};\n", "import {uint8ArrayToBase64} from '@dfinity/utils';\n\n// In the future: uint8Array.toBase64({ alphabet: \"base64url\" })\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64\nexport const toBase64URL = (uint8Array: Uint8Array): string =>\n uint8ArrayToBase64(uint8Array).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n", "import {base64ToUint8Array, uint8ArrayToBase64} from '@dfinity/utils';\nimport {Ed25519KeyIdentity, type JsonnableEd25519KeyIdentity} from '@icp-sdk/core/identity';\nimport type {OpenIdAuthContext} from '../types/context';\n\nconst JSON_KEY_CALLER = '__caller__';\nconst JSON_KEY_SALT = '__salt__';\nconst JSON_KEY_STATE = '__state__';\n\ninterface StoredContext {\n [JSON_KEY_CALLER]: JsonnableEd25519KeyIdentity;\n [JSON_KEY_SALT]: string;\n [JSON_KEY_STATE]: string;\n}\n\nexport const stringifyContext = ({caller, state, salt}: OpenIdAuthContext): string => {\n const data: StoredContext = {\n [JSON_KEY_CALLER]: caller.toJSON(),\n [JSON_KEY_SALT]: uint8ArrayToBase64(salt),\n [JSON_KEY_STATE]: state\n };\n\n return JSON.stringify(data);\n};\n\nexport const parseContext = (jsonData: string): OpenIdAuthContext => {\n const {\n [JSON_KEY_CALLER]: jsonCaller,\n [JSON_KEY_SALT]: jsonSalt,\n [JSON_KEY_STATE]: state\n }: StoredContext = JSON.parse(jsonData);\n\n return {\n caller: Ed25519KeyIdentity.fromParsedJson(jsonCaller),\n salt: base64ToUint8Array(jsonSalt),\n state\n };\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n", "import {fromNullable} from '@dfinity/utils';\nimport type {Signature} from '@icp-sdk/core/agent';\nimport {Delegation, ECDSAKeyIdentity} from '@icp-sdk/core/identity';\nimport {authenticate as authenticateApi, getDelegation as getDelegationApi} from './api/auth.api';\nimport {AuthenticationError, GetDelegationError, GetDelegationRetryError} from './errors';\nimport type {AuthenticationData, GetDelegationArgs, SignedDelegation} from './types/actor';\nimport type {AuthenticatedSession, AuthParameters} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Delegations} from './types/session';\nimport {generateIdentity} from './utils/session.utils';\n\ninterface AuthContext {\n context: Omit<OpenIdAuthContext, 'state'>;\n auth: AuthParameters;\n}\ntype AuthenticationArgs = {jwt: string} & AuthContext;\n\nexport const authenticateSession = async <T extends AuthParameters>({\n jwt,\n context,\n auth\n}: AuthenticationArgs): Promise<AuthenticatedSession<T>> => {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const publicKey = new Uint8Array(sessionKey.getPublicKey().toDer());\n\n const {delegations, data} = await authenticate<T>({\n jwt,\n publicKey,\n context,\n auth\n });\n\n const identity = generateIdentity({\n sessionKey,\n delegations\n });\n\n return {identity, data};\n};\n\nconst authenticate = async <T extends AuthParameters>({\n jwt,\n publicKey,\n context: {caller, salt},\n auth\n}: {\n publicKey: Uint8Array;\n} & AuthenticationArgs): Promise<{delegations: Delegations; data: AuthenticationData<T>}> => {\n const result = await authenticateApi({\n args: {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt\n }\n },\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n throw new AuthenticationError('Authentication failed', {cause: result});\n }\n\n const {\n delegation: {user_key: userKey, expiration},\n ...rest\n } = result.Ok;\n\n const signedDelegation = await retryGetDelegation({\n jwt,\n context: {caller, salt},\n auth,\n publicKey,\n expiration\n });\n\n const {delegation, signature} = signedDelegation;\n const {pubkey, expiration: signedExpiration, targets} = delegation;\n\n const delegations: Delegations = [\n userKey,\n [\n {\n delegation: new Delegation(\n Uint8Array.from(pubkey),\n signedExpiration,\n fromNullable(targets)\n ),\n signature: Uint8Array.from(signature) as unknown as Signature\n }\n ]\n ];\n\n return {delegations, data: rest as AuthenticationData<T>};\n};\n\nconst retryGetDelegation = async ({\n jwt,\n publicKey,\n context: {salt, caller},\n auth,\n expiration,\n maxRetries = 5\n}: {\n publicKey: Uint8Array;\n expiration: bigint;\n maxRetries?: number;\n} & AuthenticationArgs): Promise<SignedDelegation> => {\n for (let i = 0; i < maxRetries; i++) {\n // Linear backoff\n await new Promise((resolve) => {\n setInterval(resolve, 1000 * i);\n });\n\n const args: GetDelegationArgs = {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt,\n expiration\n }\n };\n\n const result = await getDelegationApi({\n args,\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n const {Err} = result;\n\n if ('NoSuchDelegation' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if ('GetCachedJwks' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n throw new GetDelegationError('Getting delegation failed', {cause: result});\n }\n\n return result.Ok;\n }\n\n throw new GetDelegationRetryError();\n};\n", "import {\n type ConsoleActor,\n type SatelliteActor,\n getConsoleActor,\n getSatelliteActor\n} from '@junobuild/ic-client/actor';\nimport type {ActorParameters} from '../types/actor';\n\nexport const getAuthActor = ({\n auth,\n identity\n}: ActorParameters): Promise<ConsoleActor | SatelliteActor> =>\n 'satellite' in auth\n ? getSatelliteActor({...auth.satellite, identity})\n : getConsoleActor({...auth.console, identity});\n", "import type {\n ActorParameters,\n AuthenticationArgs,\n AuthenticationResult,\n GetDelegationArgs,\n GetDelegationResult\n} from '../types/actor';\nimport {getAuthActor} from './_actor.api';\n\nexport const authenticate = async ({\n actorParams,\n args\n}: {\n args: AuthenticationArgs;\n actorParams: ActorParameters;\n}): Promise<AuthenticationResult> => {\n const {authenticate} = await getAuthActor(actorParams);\n return await authenticate(args);\n};\n\nexport const getDelegation = async ({\n actorParams,\n args\n}: {\n args: GetDelegationArgs;\n actorParams: ActorParameters;\n}): Promise<GetDelegationResult> => {\n const {get_delegation} = await getAuthActor(actorParams);\n return await get_delegation(args);\n};\n", "import {DelegationChain, DelegationIdentity, type ECDSAKeyIdentity} from '@icp-sdk/core/identity';\nimport type {AuthenticatedIdentity} from '../types/authenticate';\nimport type {Delegations} from '../types/session';\n\nexport const generateIdentity = ({\n delegations,\n sessionKey\n}: {\n delegations: Delegations;\n sessionKey: ECDSAKeyIdentity;\n}): AuthenticatedIdentity => {\n const [userKey, signedDelegations] = delegations;\n\n const delegationChain = DelegationChain.fromDelegations(\n signedDelegations,\n Uint8Array.from(userKey)\n );\n\n const identity = DelegationIdentity.fromDelegation(sessionKey, delegationChain);\n\n return {identity, delegationChain, sessionKey};\n};\n", "import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestJwtWithCredentials, RequestJwtWithRedirect} from './types/openid';\n\n/**\n * Initiates an OpenID Connect authorization request by redirecting the browser.\n *\n * References:\n * - OAuth 2.0 (Google): https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow\n * - OpenID Connect: https://developers.google.com/identity/openid-connect/openid-connect\n */\nexport const requestJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestJwtWithRedirect) => {\n const parseAuthUrl = (): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(authUrl);\n } catch (_error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: authUrl});\n }\n };\n\n const requestUrl = parseAuthUrl();\n\n requestUrl.searchParams.set('client_id', clientId);\n\n const {\n location: {origin: currentUrl}\n } = window;\n\n requestUrl.searchParams.set('redirect_uri', redirectUrl ?? currentUrl);\n\n // We do not request \"token\" because we use the ID token (JWT).\n // \"code\" is required according to II's codebase as Apple ID throws an error otherwise.\n requestUrl.searchParams.set('response_type', 'code id_token');\n\n requestUrl.searchParams.set('scope', authScopes.join(' '));\n\n // Used for security reasons. When the provider redirects to the application,\n // the state will be compared with the session storage value.\n requestUrl.searchParams.set('state', state);\n\n // Used to validate the JSON Web Token (JWT) in the backend \u2014 i.e. we pass the nonce\n // to the provider and make the request to the backend with its salt.\n requestUrl.searchParams.set('nonce', nonce);\n\n if (notEmptyString(loginHint)) {\n requestUrl.searchParams.set('login_hint', loginHint);\n } else {\n requestUrl.searchParams.set('prompt', 'select_account');\n }\n\n window.location.href = requestUrl.toString();\n};\n\n/**\n * References:\n * - identity spec: https://www.w3.org/TR/fedcm/#browser-api-credential-request-options\n * - https://privacysandbox.google.com/cookies/fedcm/implement/identity-provider\n * - https://privacysandbox.google.com/cookies/fedcm/why\n */\nexport const requestWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestJwtWithCredentials): Promise<{jwt: string}> => {\n const identityCredential = await navigator.credentials.get({\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n identity: {\n context: 'use',\n providers: [\n {\n configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n }\n ],\n mode: 'active'\n },\n // https://privacysandbox.google.com/cookies/fedcm/implement/relying-party#auto-reauthn\n mediation: 'required'\n });\n\n if (isNullish(identityCredential)) {\n throw new FedCMIdentityCredentialUndefinedError();\n }\n\n const {type} = identityCredential;\n\n if (\n type !== 'identity' ||\n !('token' in identityCredential) ||\n typeof identityCredential.token !== 'string'\n ) {\n // This should be unreachable in FedCM spec-compliant browsers.\n throw new FedCMIdentityCredentialInvalidError('Invalid credential received from FedCM API', {\n cause: identityCredential\n });\n }\n\n const {token: jwt} = identityCredential;\n return {jwt};\n};\n", "import {GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {requestJwtWithRedirect, requestWithCredentials} from './_openid';\nimport type {\n RequestJwtCredentialsParams,\n RequestJwtCredentialsResult,\n RequestJwtParams,\n RequestJwtRedirectParams\n} from './types/request';\n\nexport function requestJwt(args: {\n google: RequestJwtCredentialsParams;\n}): Promise<RequestJwtCredentialsResult>;\n\nexport function requestJwt(args: {google: RequestJwtRedirectParams}): Promise<void>;\n\nexport async function requestJwt({\n google\n}: {\n google: RequestJwtParams;\n}): Promise<RequestJwtCredentialsResult | void> {\n const context = await initContext();\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestJwtWithRedirect({\n ...redirect,\n ...context,\n authUrl,\n authScopes\n });\n}\n", "/**\n * Detects whether the browser supports FedCM (Federated Credential Management).\n *\n * @returns {boolean} `true` if FedCM is supported, otherwise `false`.\n *\n * References:\n * - MDN IdentityCredential: https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential\n */\nexport const isFedCMSupported = (): boolean => {\n const {userAgent} = navigator;\n\n // Samsung browser implements \"IdentityCredential\" but does not support \"configURL\"\n // https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential\n const isSamsungBrowser = /SamsungBrowser/i.test(userAgent);\n if (isSamsungBrowser) {\n return false;\n }\n\n return 'IdentityCredential' in window;\n};\n"],
5
+ "mappings": ";;AAAA,OAAQ,iBAAAA,MAAoB,iBCA5B,OAAQ,aAAAC,MAAgB,iBACxB,OAAQ,sBAAAC,MAAyB,yBCC1B,IAAMC,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb,ECTO,IAAMC,EAAN,cAA8B,KAAM,CAAC,EAC/BC,EAAN,cAAoC,KAAM,CAAC,EAErCC,EAAN,cAAoD,KAAM,CAAC,EACrDC,EAAN,cAAkD,KAAM,CAAC,EAEnDC,EAAN,cAAkC,KAAM,CAAC,EACnCC,EAAN,cAAyC,KAAM,CAAC,EAC1CC,EAAN,cAA8C,KAAM,CAAC,EAC/CC,EAAN,cAA8C,KAAM,CAAC,EAE/CC,EAAN,cAAiC,KAAM,CAAC,EAClCC,EAAN,cAAsC,KAAM,CAAC,ECZpD,OAAQ,2BAAAC,MAA8B,iBCAtC,OAAQ,sBAAAC,MAAyB,iBAI1B,IAAMC,EAAeC,GAC1BF,EAAmBE,CAAU,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,EAAE,EDA1F,IAAMC,EAAe,IAAY,OAAO,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,EAE3EC,EAAa,MAAO,CAAC,KAAAC,EAAM,OAAAC,CAAM,IAAgD,CACrF,IAAMC,EAAYD,EAAO,aAAa,EAAE,aAAa,EAE/CE,EAAQ,IAAI,WAAWH,EAAK,OAASE,EAAU,UAAU,EAC/DC,EAAM,IAAIH,CAAI,EACdG,EAAM,IAAID,EAAWF,EAAK,MAAM,EAEhC,IAAMI,EAAO,MAAM,OAAO,OAAO,OAAO,OAAO,UAAWD,CAAK,EAE/D,OAAOE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CACT,CACE,UAAAF,EACA,SAAAX,EACA,MAAAC,EACA,UAAAC,EACA,WAAAU,CACF,CACF,EACA,KAAM,QACR,EAEA,UAAW,UACb,CAAC,EAED,GAAIE,GAAUD,CAAkB,EAC9B,MAAM,IAAIE,EAGZ,GAAM,CAAC,KAAAC,CAAI,EAAIH,EAEf,GACEG,IAAS,YACT,EAAE,UAAWH,IACb,OAAOA,EAAmB,OAAU,SAGpC,MAAM,IAAII,EAAoC,6CAA8C,CAC1F,MAAOJ,CACT,CAAC,EAGH,GAAM,CAAC,MAAOK,CAAG,EAAIL,EACrB,MAAO,CAAC,IAAAK,CAAG,CACb,ECtGA,eAAsBC,GAAW,CAC/B,OAAAC,CACF,EAEgD,CAC9C,IAAMC,EAAU,MAAMC,EAAY,EAElC,GAAI,gBAAiBF,EAAQ,CAC3B,GAAM,CAAC,YAAAG,CAAW,EAAIH,EAChB,CAAC,UAAAI,CAAS,EAAIC,EAEpB,OAAO,MAAMC,EAAuB,CAClC,GAAGH,EACH,GAAGF,EACH,UAAAG,CACF,CAAC,CACH,CAEA,GAAM,CAAC,SAAAG,CAAQ,EAAIP,EACb,CAAC,QAAAQ,EAAS,WAAAC,CAAU,EAAIJ,EAE9BK,EAAuB,CACrB,GAAGH,EACH,GAAGN,EACH,QAAAO,EACA,WAAAC,CACF,CAAC,CACH,CCnCO,IAAME,GAAmB,IAAe,CAC7C,GAAM,CAAC,UAAAC,CAAS,EAAI,UAKpB,MADyB,kBAAkB,KAAKA,CAAS,EAEhD,GAGF,uBAAwB,MACjC",
6
+ "names": ["isEmptyString", "isNullish", "Ed25519KeyIdentity", "CONTEXT_KEY", "GOOGLE_PROVIDER", "InvalidUrlError", "ContextUndefinedError", "FedCMIdentityCredentialUndefinedError", "FedCMIdentityCredentialInvalidError", "AuthenticationError", "AuthenticationUrlHashError", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "GetDelegationError", "GetDelegationRetryError", "arrayBufferToUint8Array", "uint8ArrayToBase64", "toBase64URL", "uint8Array", "generateSalt", "buildNonce", "salt", "caller", "principal", "bytes", "hash", "toBase64URL", "arrayBufferToUint8Array", "generateNonce", "base64ToUint8Array", "uint8ArrayToBase64", "Ed25519KeyIdentity", "JSON_KEY_CALLER", "JSON_KEY_SALT", "JSON_KEY_STATE", "stringifyContext", "caller", "state", "salt", "data", "parseContext", "jsonData", "jsonCaller", "jsonSalt", "generateRandomState", "toBase64URL", "initContext", "caller", "Ed25519KeyIdentity", "nonce", "salt", "generateNonce", "state", "generateRandomState", "storedData", "stringifyContext", "CONTEXT_KEY", "loadContext", "storedContext", "isNullish", "ContextUndefinedError", "parseContext", "fromNullable", "Delegation", "ECDSAKeyIdentity", "getConsoleActor", "getSatelliteActor", "getAuthActor", "auth", "identity", "authenticate", "actorParams", "args", "getAuthActor", "getDelegation", "get_delegation", "DelegationChain", "DelegationIdentity", "generateIdentity", "delegations", "sessionKey", "userKey", "signedDelegations", "delegationChain", "authenticateSession", "jwt", "context", "auth", "sessionKey", "ECDSAKeyIdentity", "publicKey", "delegations", "data", "authenticate", "generateIdentity", "caller", "salt", "result", "AuthenticationError", "userKey", "expiration", "rest", "signedDelegation", "retryGetDelegation", "delegation", "signature", "pubkey", "signedExpiration", "targets", "Delegation", "fromNullable", "maxRetries", "i", "resolve", "getDelegation", "Err", "GetDelegationError", "GetDelegationRetryError", "authenticate", "params", "context", "loadContext", "jwt", "auth", "authenticateSession", "authenticateWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "isNullish", "notEmptyString", "requestJwtWithRedirect", "authUrl", "clientId", "nonce", "loginHint", "authScopes", "state", "redirectUrl", "requestUrl", "InvalidUrlError", "currentUrl", "notEmptyString", "requestWithCredentials", "configURL", "domainHint", "identityCredential", "isNullish", "FedCMIdentityCredentialUndefinedError", "type", "FedCMIdentityCredentialInvalidError", "jwt", "requestJwt", "google", "context", "initContext", "credentials", "configUrl", "GOOGLE_PROVIDER", "requestWithCredentials", "redirect", "authUrl", "authScopes", "requestJwtWithRedirect", "isFedCMSupported", "userAgent"]
7
7
  }
@@ -1,5 +1,4 @@
1
- import type { AuthParameters } from './types/actor';
2
- import type { AuthenticatedIdentity } from './types/authenticate';
1
+ import type { AuthenticatedSession, AuthParameters } from './types/authenticate';
3
2
  import type { OpenIdAuthContext } from './types/context';
4
3
  interface AuthContext {
5
4
  context: Omit<OpenIdAuthContext, 'state'>;
@@ -8,5 +7,5 @@ interface AuthContext {
8
7
  type AuthenticationArgs = {
9
8
  jwt: string;
10
9
  } & AuthContext;
11
- export declare const authenticate: ({ jwt, context, auth }: AuthenticationArgs) => Promise<AuthenticatedIdentity>;
10
+ export declare const authenticateSession: <T extends AuthParameters>({ jwt, context, auth }: AuthenticationArgs) => Promise<AuthenticatedSession<T>>;
12
11
  export {};
@@ -1,2 +1,2 @@
1
- import type { AuthenticatedIdentity, AuthenticationParams } from './types/authenticate';
2
- export declare const authenticate: (params: AuthenticationParams) => Promise<AuthenticatedIdentity>;
1
+ import type { AuthenticatedSession, AuthenticationParams, AuthParameters } from './types/authenticate';
2
+ export declare const authenticate: <T extends AuthParameters>(params: AuthenticationParams<T>) => Promise<AuthenticatedSession<T>>;
@@ -1,6 +1,7 @@
1
- import type { RequestJwtParams } from './types/request';
2
- export declare const requestJwt: ({ google }: {
3
- google: RequestJwtParams;
4
- }) => Promise<{
5
- jwt: string;
6
- }>;
1
+ import type { RequestJwtCredentialsParams, RequestJwtCredentialsResult, RequestJwtRedirectParams } from './types/request';
2
+ export declare function requestJwt(args: {
3
+ google: RequestJwtCredentialsParams;
4
+ }): Promise<RequestJwtCredentialsResult>;
5
+ export declare function requestJwt(args: {
6
+ google: RequestJwtRedirectParams;
7
+ }): Promise<void>;
@@ -1,14 +1,6 @@
1
- import type { Identity } from '@dfinity/agent';
2
- import type { ConsoleDid, ConsoleParameters, SatelliteDid, SatelliteParameters } from '@junobuild/ic-client/actor';
3
- /**
4
- * Represents initialization parameters for either a Console or Satellite actor.
5
- * Use discriminated unions to pass the correct parameters depending on the authentication to target.
6
- */
7
- export type AuthParameters = {
8
- console: Omit<ConsoleParameters, 'consoleId' | 'identity'> & Required<Pick<ConsoleParameters, 'consoleId'>>;
9
- } | {
10
- satellite: Omit<SatelliteParameters, 'satelliteId' | 'identity'> & Required<Pick<SatelliteParameters, 'satelliteId'>>;
11
- };
1
+ import type { Identity } from '@icp-sdk/core/agent';
2
+ import type { ConsoleDid, SatelliteDid } from '@junobuild/ic-client/actor';
3
+ import type { AuthParameters } from './authenticate';
12
4
  export interface ActorParameters {
13
5
  auth: AuthParameters;
14
6
  identity: Identity;
@@ -18,3 +10,6 @@ export type GetDelegationArgs = SatelliteDid.GetDelegationArgs | ConsoleDid.GetD
18
10
  export type AuthenticationResult = SatelliteDid.AuthenticateResultResponse | ConsoleDid.Result;
19
11
  export type GetDelegationResult = SatelliteDid.GetDelegationResultResponse | ConsoleDid.Result_1;
20
12
  export type SignedDelegation = SatelliteDid.SignedDelegation | ConsoleDid.SignedDelegation;
13
+ export type AuthenticationData<T extends AuthParameters> = T extends {
14
+ satellite: unknown;
15
+ } ? Pick<SatelliteDid.Authentication, 'doc'> : Pick<ConsoleDid.Authentication, 'mission_control'>;
@@ -1,16 +1,30 @@
1
- import type { DelegationChain, DelegationIdentity } from '@dfinity/identity';
2
- import type { AuthParameters } from './actor';
1
+ import type { DelegationChain, DelegationIdentity, ECDSAKeyIdentity } from '@icp-sdk/core/identity';
2
+ import type { ConsoleParameters, SatelliteParameters } from '@junobuild/ic-client/actor';
3
+ import type { AuthenticationData } from './actor';
3
4
  export interface AuthenticationCredentials {
4
5
  jwt: string;
5
6
  }
6
- export type AuthenticationParams = {
7
+ export type AuthenticationParams<T extends AuthParameters = AuthParameters> = {
7
8
  redirect: null;
8
- auth: AuthParameters;
9
+ auth: T;
9
10
  } | {
10
11
  credentials: AuthenticationCredentials;
11
- auth: AuthParameters;
12
+ auth: T;
12
13
  };
13
14
  export interface AuthenticatedIdentity {
14
15
  identity: DelegationIdentity;
15
16
  delegationChain: DelegationChain;
17
+ sessionKey: ECDSAKeyIdentity;
18
+ }
19
+ /**
20
+ * Represents initialization parameters for either a Console or Satellite actor.
21
+ */
22
+ export type AuthParameters = {
23
+ console: Omit<ConsoleParameters, 'consoleId' | 'identity'> & Required<Pick<ConsoleParameters, 'consoleId'>>;
24
+ } | {
25
+ satellite: Omit<SatelliteParameters, 'satelliteId' | 'identity'> & Required<Pick<SatelliteParameters, 'satelliteId'>>;
26
+ };
27
+ export interface AuthenticatedSession<T extends AuthParameters> {
28
+ identity: AuthenticatedIdentity;
29
+ data: AuthenticationData<T>;
16
30
  }
@@ -1,4 +1,4 @@
1
- import type { Ed25519KeyIdentity } from '@dfinity/identity';
1
+ import type { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
2
2
  import type { Salt } from './nonce';
3
3
  export interface OpenIdAuthContext {
4
4
  caller: Ed25519KeyIdentity;
@@ -9,8 +9,13 @@ export type RequestJwtCredentials = RequestJwt & {
9
9
  loginHint?: string;
10
10
  domainHint?: string | 'any';
11
11
  };
12
- export type RequestJwtParams = {
12
+ export interface RequestJwtRedirectParams {
13
13
  redirect: RequestJwtRedirect;
14
- } | {
14
+ }
15
+ export interface RequestJwtCredentialsParams {
15
16
  credentials: RequestJwtCredentials;
16
- };
17
+ }
18
+ export interface RequestJwtCredentialsResult {
19
+ jwt: string;
20
+ }
21
+ export type RequestJwtParams = RequestJwtRedirectParams | RequestJwtCredentialsParams;
@@ -1,3 +1,3 @@
1
- import type { SignedDelegation } from '@dfinity/identity';
1
+ import type { SignedDelegation } from '@icp-sdk/core/identity';
2
2
  export type UserKey = Uint8Array | number[];
3
3
  export type Delegations = [UserKey, SignedDelegation[]];
@@ -1,4 +1,4 @@
1
- import type { Ed25519KeyIdentity } from '@dfinity/identity';
1
+ import type { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
2
2
  import type { Nonce, Salt } from '../types/nonce';
3
3
  export declare const generateNonce: ({ caller }: {
4
4
  caller: Ed25519KeyIdentity;
@@ -1,4 +1,4 @@
1
- import { type ECDSAKeyIdentity } from '@dfinity/identity';
1
+ import { type ECDSAKeyIdentity } from '@icp-sdk/core/identity';
2
2
  import type { AuthenticatedIdentity } from '../types/authenticate';
3
3
  import type { Delegations } from '../types/session';
4
4
  export declare const generateIdentity: ({ delegations, sessionKey }: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@junobuild/auth",
3
- "version": "0.0.3",
3
+ "version": "1.0.0",
4
4
  "description": "A SDK for working with Juno authentication modules",
5
5
  "author": "David Dal Busco (https://daviddalbusco.com)",
6
6
  "license": "MIT",
@@ -47,11 +47,8 @@
47
47
  ],
48
48
  "homepage": "https://juno.build",
49
49
  "peerDependencies": {
50
- "@dfinity/agent": "^3.2.6",
51
- "@dfinity/candid": "^3.2.6",
52
- "@dfinity/identity": "^3.2.6",
53
- "@dfinity/principal": "^3.2.6",
54
- "@dfinity/utils": "^3.1",
55
- "@junobuild/ic-client": "^3"
50
+ "@dfinity/utils": "^4",
51
+ "@icp-sdk/core": "^4.2",
52
+ "@junobuild/ic-client": "^4"
56
53
  }
57
54
  }
@@ -1,2 +0,0 @@
1
- import{e as m,i as u,j as p}from"./chunk-2BORB4XM.js";import{Delegation as S,ECDSAKeyIdentity as G}from"@dfinity/identity";import{fromNullable as E}from"@dfinity/utils";import{getConsoleActor as x,getSatelliteActor as P}from"@junobuild/ic-client/actor";var l=({auth:t,identity:e})=>"satellite"in t?P({...t.satellite,identity:e}):x({...t.console,identity:e});var A=async({actorParams:t,args:e})=>{let{authenticate:n}=await l(t);return await n(e)},d=async({actorParams:t,args:e})=>{let{get_delegation:n}=await l(t);return await n(e)};import{DelegationChain as I,DelegationIdentity as C}from"@dfinity/identity";var h=({delegations:t,sessionKey:e})=>{let[n,i]=t,o=I.fromDelegations(i,Uint8Array.from(n));return{identity:C.fromDelegation(e,o),delegationChain:o}};var B=async({jwt:t,context:e,auth:n})=>{let i=await G.generate({extractable:!1}),o=new Uint8Array(i.getPublicKey().toDer()),r=await K({jwt:t,publicKey:o,context:e,auth:n});return h({sessionKey:i,delegations:r})},K=async({jwt:t,publicKey:e,context:{caller:n,salt:i},auth:o})=>{let r=await A({args:{OpenId:{jwt:t,session_key:e,salt:i}},actorParams:{auth:o,identity:n}});if("Err"in r)throw new m("Authentication failed",{cause:r});let{delegation:{user_key:g,expiration:c}}=r.Ok,y=await b({jwt:t,context:{caller:n,salt:i},auth:o,publicKey:e,expiration:c}),{delegation:a,signature:s}=y,{pubkey:f,expiration:D,targets:w}=a;return[g,[{delegation:new S(Uint8Array.from(f),D,E(w)),signature:Uint8Array.from(s)}]]},b=async({jwt:t,publicKey:e,context:{salt:n,caller:i},auth:o,expiration:r,maxRetries:g=5})=>{for(let c=0;c<g;c++){await new Promise(s=>{setInterval(s,1e3*c)});let a=await d({args:{OpenId:{jwt:t,session_key:e,salt:n,expiration:r}},actorParams:{auth:o,identity:i}});if("Err"in a){let{Err:s}=a;if("NoSuchDelegation"in s||"GetCachedJwks"in s)continue;throw new u("Getting delegation failed",{cause:a})}return a.Ok}throw new p};export{B as a};
2
- //# sourceMappingURL=chunk-36KNLPQZ.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/_session.ts", "../../src/api/_actor.api.ts", "../../src/api/auth.api.ts", "../../src/utils/session.utils.ts"],
4
- "sourcesContent": ["import type {Signature} from '@dfinity/agent';\nimport {Delegation, ECDSAKeyIdentity} from '@dfinity/identity';\nimport {fromNullable} from '@dfinity/utils';\nimport {authenticate as authenticateApi, getDelegation as getDelegationApi} from './api/auth.api';\nimport {AuthenticationError, GetDelegationError, GetDelegationRetryError} from './errors';\nimport type {AuthParameters, GetDelegationArgs, SignedDelegation} from './types/actor';\nimport type {AuthenticatedIdentity} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Delegations} from './types/session';\nimport {generateIdentity} from './utils/session.utils';\n\ninterface AuthContext {\n context: Omit<OpenIdAuthContext, 'state'>;\n auth: AuthParameters;\n}\ntype AuthenticationArgs = {jwt: string} & AuthContext;\n\nexport const authenticate = async ({\n jwt,\n context,\n auth\n}: AuthenticationArgs): Promise<AuthenticatedIdentity> => {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const publicKey = new Uint8Array(sessionKey.getPublicKey().toDer());\n\n const delegations = await authenticateSession({jwt, publicKey, context, auth});\n\n return generateIdentity({\n sessionKey,\n delegations\n });\n};\n\nconst authenticateSession = async ({\n jwt,\n publicKey,\n context: {caller, salt},\n auth\n}: {\n publicKey: Uint8Array;\n} & AuthenticationArgs): Promise<Delegations> => {\n const result = await authenticateApi({\n args: {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt\n }\n },\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n throw new AuthenticationError('Authentication failed', {cause: result});\n }\n\n const {\n delegation: {user_key: userKey, expiration}\n } = result.Ok;\n\n const signedDelegation = await retryGetDelegation({\n jwt,\n context: {caller, salt},\n auth,\n publicKey,\n expiration\n });\n\n const {delegation, signature} = signedDelegation;\n const {pubkey, expiration: signedExpiration, targets} = delegation;\n\n return [\n userKey,\n [\n {\n delegation: new Delegation(\n Uint8Array.from(pubkey),\n signedExpiration,\n fromNullable(targets)\n ),\n signature: Uint8Array.from(signature) as unknown as Signature\n }\n ]\n ];\n};\n\nconst retryGetDelegation = async ({\n jwt,\n publicKey,\n context: {salt, caller},\n auth,\n expiration,\n maxRetries = 5\n}: {\n publicKey: Uint8Array;\n expiration: bigint;\n maxRetries?: number;\n} & AuthenticationArgs): Promise<SignedDelegation> => {\n for (let i = 0; i < maxRetries; i++) {\n // Linear backoff\n await new Promise((resolve) => {\n setInterval(resolve, 1000 * i);\n });\n\n const args: GetDelegationArgs = {\n OpenId: {\n jwt,\n session_key: publicKey,\n salt,\n expiration\n }\n };\n\n const result = await getDelegationApi({\n args,\n actorParams: {\n auth,\n identity: caller\n }\n });\n\n if ('Err' in result) {\n const {Err} = result;\n\n if ('NoSuchDelegation' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if ('GetCachedJwks' in Err) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n throw new GetDelegationError('Getting delegation failed', {cause: result});\n }\n\n return result.Ok;\n }\n\n throw new GetDelegationRetryError();\n};\n", "import {\n type ConsoleActor,\n type SatelliteActor,\n getConsoleActor,\n getSatelliteActor\n} from '@junobuild/ic-client/actor';\nimport type {ActorParameters} from '../types/actor';\n\nexport const getAuthActor = ({\n auth,\n identity\n}: ActorParameters): Promise<ConsoleActor | SatelliteActor> =>\n 'satellite' in auth\n ? getSatelliteActor({...auth.satellite, identity})\n : getConsoleActor({...auth.console, identity});\n", "import type {\n ActorParameters,\n AuthenticationArgs,\n AuthenticationResult,\n GetDelegationArgs,\n GetDelegationResult\n} from '../types/actor';\nimport {getAuthActor} from './_actor.api';\n\nexport const authenticate = async ({\n actorParams,\n args\n}: {\n args: AuthenticationArgs;\n actorParams: ActorParameters;\n}): Promise<AuthenticationResult> => {\n const {authenticate} = await getAuthActor(actorParams);\n return await authenticate(args);\n};\n\nexport const getDelegation = async ({\n actorParams,\n args\n}: {\n args: GetDelegationArgs;\n actorParams: ActorParameters;\n}): Promise<GetDelegationResult> => {\n const {get_delegation} = await getAuthActor(actorParams);\n return await get_delegation(args);\n};\n", "import {DelegationChain, DelegationIdentity, type ECDSAKeyIdentity} from '@dfinity/identity';\nimport type {AuthenticatedIdentity} from '../types/authenticate';\nimport type {Delegations} from '../types/session';\n\nexport const generateIdentity = ({\n delegations,\n sessionKey\n}: {\n delegations: Delegations;\n sessionKey: ECDSAKeyIdentity;\n}): AuthenticatedIdentity => {\n const [userKey, signedDelegations] = delegations;\n\n const delegationChain = DelegationChain.fromDelegations(\n signedDelegations,\n Uint8Array.from(userKey)\n );\n\n const identity = DelegationIdentity.fromDelegation(sessionKey, delegationChain);\n\n return {identity, delegationChain};\n};\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AaK,EACb,KAAAK,EACA,WAAAI,CACF,CACF,EAIE,YAAa,CACX,KAAAZ,EACA,SAAUO,CACZ,CACF,CAAC,EAED,GAAI,QAASE,EAAQ,CACnB,GAAM,CAAC,IAAAiB,CAAG,EAAIjB,EAOd,GALI,qBAAsBiB,GAKtB,kBAAmBA,EAErB,SAGF,MAAM,IAAIC,EAAmB,4BAA6B,CAAC,MAAOlB,CAAM,CAAC,CAC3E,CAEA,OAAOA,EAAO,EAChB,CAEA,MAAM,IAAImB,CACZ",
6
- "names": ["Delegation", "ECDSAKeyIdentity", "fromNullable", "getConsoleActor", "getSatelliteActor", "getAuthActor", "auth", "identity", "authenticate", "actorParams", "args", "getAuthActor", "getDelegation", "get_delegation", "DelegationChain", "DelegationIdentity", "generateIdentity", "delegations", "sessionKey", "userKey", "signedDelegations", "delegationChain", "authenticate", "jwt", "context", "auth", "sessionKey", "ECDSAKeyIdentity", "publicKey", "delegations", "authenticateSession", "generateIdentity", "caller", "salt", "result", "AuthenticationError", "userKey", "expiration", "signedDelegation", "retryGetDelegation", "delegation", "signature", "pubkey", "signedExpiration", "targets", "Delegation", "fromNullable", "maxRetries", "i", "resolve", "getDelegation", "Err", "GetDelegationError", "GetDelegationRetryError"]
7
- }
@@ -1,2 +0,0 @@
1
- import{a}from"./chunk-36KNLPQZ.js";import{b as m}from"./chunk-JTJJD55H.js";import{f as h,g as u,h as d}from"./chunk-2BORB4XM.js";import{isEmptyString as o}from"@dfinity/utils";var l=async t=>{let e=m();if("credentials"in t){let{credentials:{jwt:n},auth:i}=t;return await a({jwt:n,context:e,auth:i})}return await p({...t,context:e})},p=async({auth:t,context:e})=>{let{location:{hash:n}}=window;if(o(n)||!n.startsWith("#"))throw new h("No hash found in the current location URL");let i=new URLSearchParams(n.slice(1)),r=i.get("state"),s=i.get("id_token"),{state:c}=e;if(o(c)||r!==c)throw new u("The provided state is invalid",{cause:r});if(o(s))throw new d;return await a({jwt:s,auth:t,context:e})};export{l as a};
2
- //# sourceMappingURL=chunk-E4CYLKZY.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/authenticate.ts"],
4
- "sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {loadContext} from './_context';\nimport {authenticate as authenticateSession} from './_session';\nimport {\n AuthenticationInvalidStateError,\n AuthenticationUndefinedJwtError,\n AuthenticationUrlHashError\n} from './errors';\nimport type {AuthParameters} from './types/actor';\nimport type {AuthenticatedIdentity, AuthenticationParams} from './types/authenticate';\nimport type {OpenIdAuthContext} from './types/context';\n\nexport const authenticate = async (\n params: AuthenticationParams\n): Promise<AuthenticatedIdentity> => {\n const context = loadContext();\n\n if ('credentials' in params) {\n const {\n credentials: {jwt},\n auth\n } = params;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateWithRedirect({...params, context});\n};\n\nconst authenticateWithRedirect = async ({\n auth,\n context\n}: {\n auth: AuthParameters;\n context: OpenIdAuthContext;\n}): Promise<AuthenticatedIdentity> => {\n const {\n location: {hash}\n } = window;\n\n if (isEmptyString(hash) || !hash.startsWith('#')) {\n throw new AuthenticationUrlHashError('No hash found in the current location URL');\n }\n\n const params = new URLSearchParams(hash.slice(1));\n const state = params.get('state');\n const idToken = params.get('id_token');\n\n const {state: savedState} = context;\n\n if (isEmptyString(savedState) || state !== savedState) {\n throw new AuthenticationInvalidStateError('The provided state is invalid', {cause: state});\n }\n\n // id_token === jwt\n if (isEmptyString(idToken)) {\n throw new AuthenticationUndefinedJwtError();\n }\n\n return await authenticateSession({\n jwt: idToken,\n auth,\n context\n });\n};\n"],
5
- "mappings": "iIAAA,OAAQ,iBAAAA,MAAoB,iBAYrB,IAAMC,EAAe,MAC1BC,GACmC,CACnC,IAAMC,EAAUC,EAAY,EAE5B,GAAI,gBAAiBF,EAAQ,CAC3B,GAAM,CACJ,YAAa,CAAC,IAAAG,CAAG,EACjB,KAAAC,CACF,EAAIJ,EAEJ,OAAO,MAAMD,EAAoB,CAC/B,IAAAI,EACA,QAAAF,EACA,KAAAG,CACF,CAAC,CACH,CAEA,OAAO,MAAMC,EAAyB,CAAC,GAAGL,EAAQ,QAAAC,CAAO,CAAC,CAC5D,EAEMI,EAA2B,MAAO,CACtC,KAAAD,EACA,QAAAH,CACF,IAGsC,CACpC,GAAM,CACJ,SAAU,CAAC,KAAAK,CAAI,CACjB,EAAI,OAEJ,GAAIC,EAAcD,CAAI,GAAK,CAACA,EAAK,WAAW,GAAG,EAC7C,MAAM,IAAIE,EAA2B,2CAA2C,EAGlF,IAAMR,EAAS,IAAI,gBAAgBM,EAAK,MAAM,CAAC,CAAC,EAC1CG,EAAQT,EAAO,IAAI,OAAO,EAC1BU,EAAUV,EAAO,IAAI,UAAU,EAE/B,CAAC,MAAOW,CAAU,EAAIV,EAE5B,GAAIM,EAAcI,CAAU,GAAKF,IAAUE,EACzC,MAAM,IAAIC,EAAgC,gCAAiC,CAAC,MAAOH,CAAK,CAAC,EAI3F,GAAIF,EAAcG,CAAO,EACvB,MAAM,IAAIG,EAGZ,OAAO,MAAMd,EAAoB,CAC/B,IAAKW,EACL,KAAAN,EACA,QAAAH,CACF,CAAC,CACH",
6
- "names": ["isEmptyString", "authenticate", "params", "context", "loadContext", "jwt", "auth", "authenticateWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError"]
7
- }
@@ -1,2 +0,0 @@
1
- import{a as i,b as o}from"./chunk-JOOQTYYG.js";import{a as s}from"./chunk-JTJJD55H.js";import{b as e}from"./chunk-VYICNPPG.js";var h=async({google:t})=>{let r=await s();if("credentials"in t){let{credentials:m}=t,{configUrl:u}=e;return await o({...m,...r,configUrl:u})}let{redirect:n}=t,{authUrl:a,authScopes:c}=e;throw i({...n,...r,authUrl:a,authScopes:c}),new Error("Unreachable")};export{h as a};
2
- //# sourceMappingURL=chunk-JOJCKPWQ.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/request.ts"],
4
- "sourcesContent": ["import {GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {requestJwtWithRedirect, requestWithCredentials} from './_openid';\nimport type {RequestJwtParams} from './types/request';\n\nexport const requestJwt = async ({google}: {google: RequestJwtParams}): Promise<{jwt: string}> => {\n const context = await initContext();\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestJwtWithRedirect({\n ...redirect,\n ...context,\n authUrl,\n authScopes\n });\n\n throw new Error('Unreachable');\n};\n"],
5
- "mappings": "+HAKO,IAAMA,EAAa,MAAO,CAAC,OAAAC,CAAM,IAA0D,CAChG,IAAMC,EAAU,MAAMC,EAAY,EAElC,GAAI,gBAAiBF,EAAQ,CAC3B,GAAM,CAAC,YAAAG,CAAW,EAAIH,EAChB,CAAC,UAAAI,CAAS,EAAIC,EAEpB,OAAO,MAAMC,EAAuB,CAClC,GAAGH,EACH,GAAGF,EACH,UAAAG,CACF,CAAC,CACH,CAEA,GAAM,CAAC,SAAAG,CAAQ,EAAIP,EACb,CAAC,QAAAQ,EAAS,WAAAC,CAAU,EAAIJ,EAE9B,MAAAK,EAAuB,CACrB,GAAGH,EACH,GAAGN,EACH,QAAAO,EACA,WAAAC,CACF,CAAC,EAEK,IAAI,MAAM,aAAa,CAC/B",
6
- "names": ["requestJwt", "google", "context", "initContext", "credentials", "configUrl", "GOOGLE_PROVIDER", "requestWithCredentials", "redirect", "authUrl", "authScopes", "requestJwtWithRedirect"]
7
- }
@@ -1,2 +0,0 @@
1
- import{a as d,c as h,d as l}from"./chunk-2BORB4XM.js";import{isNullish as p,notEmptyString as w}from"@dfinity/utils";var C=({authUrl:i,clientId:n,nonce:s,loginHint:r,authScopes:o,state:t,redirectUrl:a})=>{let e=(()=>{try{return new URL(i)}catch(m){throw new d("Cannot parse authURL",{cause:m})}})();e.searchParams.set("client_id",n);let{location:{origin:u}}=window;e.searchParams.set("redirect_uri",a??u),e.searchParams.set("response_type","code id_token"),e.searchParams.set("scope",o.join(" ")),e.searchParams.set("state",t),e.searchParams.set("nonce",s),w(r)?e.searchParams.set("login_hint",r):e.searchParams.set("prompt","select_account"),window.location.href=e.toString()},P=async({configUrl:i,clientId:n,nonce:s,loginHint:r,domainHint:o})=>{let t=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:i,clientId:n,nonce:s,loginHint:r,domainHint:o}],mode:"active"},mediation:"required"});if(p(t))throw new h;let{type:a}=t;if(a!=="identity"||!("token"in t)||typeof t.token!="string")throw new l("Invalid credential received from FedCM API",{cause:t});let{token:c}=t;return{jwt:c}};export{C as a,P as b};
2
- //# sourceMappingURL=chunk-JOOQTYYG.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/_openid.ts"],
4
- "sourcesContent": ["import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestJwtWithCredentials, RequestJwtWithRedirect} from './types/openid';\n\n/**\n * Initiates an OpenID Connect authorization request by redirecting the browser.\n *\n * References:\n * - OAuth 2.0 (Google): https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow\n * - OpenID Connect: https://developers.google.com/identity/openid-connect/openid-connect\n */\nexport const requestJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestJwtWithRedirect) => {\n const parseAuthUrl = (): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(authUrl);\n } catch (error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: error});\n }\n };\n\n const requestUrl = parseAuthUrl();\n\n requestUrl.searchParams.set('client_id', clientId);\n\n const {\n location: {origin: currentUrl}\n } = window;\n\n requestUrl.searchParams.set('redirect_uri', redirectUrl ?? currentUrl);\n\n // We do not request \"token\" because we use the ID token (JWT).\n // \"code\" is required according to II's codebase as Apple ID throws an error otherwise.\n requestUrl.searchParams.set('response_type', 'code id_token');\n\n requestUrl.searchParams.set('scope', authScopes.join(' '));\n\n // Used for security reasons. When the provider redirects to the application,\n // the state will be compared with the session storage value.\n requestUrl.searchParams.set('state', state);\n\n // Used to validate the JSON Web Token (JWT) in the backend \u2014 i.e. we pass the nonce\n // to the provider and make the request to the backend with its salt.\n requestUrl.searchParams.set('nonce', nonce);\n\n if (notEmptyString(loginHint)) {\n requestUrl.searchParams.set('login_hint', loginHint);\n } else {\n requestUrl.searchParams.set('prompt', 'select_account');\n }\n\n window.location.href = requestUrl.toString();\n};\n\n/**\n * References:\n * - identity spec: https://www.w3.org/TR/fedcm/#browser-api-credential-request-options\n * - https://privacysandbox.google.com/cookies/fedcm/implement/identity-provider\n * - https://privacysandbox.google.com/cookies/fedcm/why\n */\nexport const requestWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestJwtWithCredentials): Promise<{jwt: string}> => {\n const identityCredential = await navigator.credentials.get({\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n identity: {\n context: 'use',\n providers: [\n {\n configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n }\n ],\n mode: 'active'\n },\n // https://privacysandbox.google.com/cookies/fedcm/implement/relying-party#auto-reauthn\n mediation: 'required'\n });\n\n if (isNullish(identityCredential)) {\n throw new FedCMIdentityCredentialUndefinedError();\n }\n\n const {type} = identityCredential;\n\n if (\n type !== 'identity' ||\n !('token' in identityCredential) ||\n typeof identityCredential.token !== 'string'\n ) {\n // This should be unreachable in FedCM spec-compliant browsers.\n throw new FedCMIdentityCredentialInvalidError('Invalid credential received from FedCM API', {\n cause: identityCredential\n });\n }\n\n const {token: jwt} = identityCredential;\n return {jwt};\n};\n"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IACb,OAAOA,EAAmB,OAAU,SAGpC,MAAM,IAAII,EAAoC,6CAA8C,CAC1F,MAAOJ,CACT,CAAC,EAGH,GAAM,CAAC,MAAOK,CAAG,EAAIL,EACrB,MAAO,CAAC,IAAAK,CAAG,CACb",
6
- "names": ["isNullish", "notEmptyString", "requestJwtWithRedirect", "authUrl", "clientId", "nonce", "loginHint", "authScopes", "state", "redirectUrl", "requestUrl", "error", "InvalidUrlError", "currentUrl", "notEmptyString", "requestWithCredentials", "configURL", "domainHint", "identityCredential", "isNullish", "FedCMIdentityCredentialUndefinedError", "type", "FedCMIdentityCredentialInvalidError", "jwt"]
7
- }
@@ -1,2 +0,0 @@
1
- import{a}from"./chunk-VYICNPPG.js";import{b as i}from"./chunk-2BORB4XM.js";import{Ed25519KeyIdentity as E}from"@dfinity/identity";import{isNullish as N}from"@dfinity/utils";import{arrayBufferToUint8Array as S}from"@dfinity/utils";import{uint8ArrayToBase64 as g}from"@dfinity/utils";var r=t=>g(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var x=()=>window.crypto.getRandomValues(new Uint8Array(32)),_=async({salt:t,caller:e})=>{let o=e.getPrincipal().toUint8Array(),n=new Uint8Array(t.length+o.byteLength);n.set(t),n.set(o,t.length);let s=await window.crypto.subtle.digest("SHA-256",n);return r(S(s))},c=async({caller:t})=>{let e=x();return{nonce:await _({salt:e,caller:t}),salt:e}};import{Ed25519KeyIdentity as A}from"@dfinity/identity";import{base64ToUint8Array as C,uint8ArrayToBase64 as u}from"@dfinity/utils";var p="__caller__",y="__salt__",m="__state__",d=({caller:t,state:e,salt:o})=>{let n={[p]:t.toJSON(),[y]:u(o),[m]:e};return JSON.stringify(n)},l=t=>{let{[p]:e,[y]:o,[m]:n}=JSON.parse(t);return{caller:A.fromParsedJson(e),salt:C(o),state:n}};var f=()=>r(window.crypto.getRandomValues(new Uint8Array(12)));var D=async()=>{let t=E.generate(),{nonce:e,salt:o}=await c({caller:t}),n=f(),s=d({caller:t,salt:o,state:n});return sessionStorage.setItem(a,s),{nonce:e,state:n}},H=()=>{let t=sessionStorage.getItem(a);if(N(t))throw new i;return l(t)};export{D as a,H as b};
2
- //# sourceMappingURL=chunk-JTJJD55H.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/_context.ts", "../../src/utils/auth.utils.ts", "../../src/utils/url.utils.ts", "../../src/utils/session-storage.utils.ts", "../../src/utils/state.utils.ts"],
4
- "sourcesContent": ["import {Ed25519KeyIdentity} from '@dfinity/identity';\nimport {isNullish} from '@dfinity/utils';\nimport {CONTEXT_KEY} from './_constants';\nimport {ContextUndefinedError} from './errors';\nimport type {OpenIdAuthContext} from './types/context';\nimport type {Nonce} from './types/nonce';\nimport {generateNonce} from './utils/auth.utils';\nimport {parseContext, stringifyContext} from './utils/session-storage.utils';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const initContext = async (): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n const state = generateRandomState();\n\n const storedData = stringifyContext({\n caller,\n salt,\n state\n });\n\n sessionStorage.setItem(CONTEXT_KEY, storedData);\n\n return {\n nonce,\n state\n };\n};\n\nexport const loadContext = (): OpenIdAuthContext => {\n const storedContext = sessionStorage.getItem(CONTEXT_KEY);\n\n if (isNullish(storedContext)) {\n throw new ContextUndefinedError();\n }\n\n return parseContext(storedContext);\n};\n", "import type {Ed25519KeyIdentity} from '@dfinity/identity';\nimport {arrayBufferToUint8Array} from '@dfinity/utils';\nimport type {Nonce, Salt} from '../types/nonce';\nimport {toBase64URL} from './url.utils';\n\nconst generateSalt = (): Salt => window.crypto.getRandomValues(new Uint8Array(32));\n\nconst buildNonce = async ({salt, caller}: {salt: Salt; caller: Ed25519KeyIdentity}) => {\n const principal = caller.getPrincipal().toUint8Array();\n\n const bytes = new Uint8Array(salt.length + principal.byteLength);\n bytes.set(salt);\n bytes.set(principal, salt.length);\n\n const hash = await window.crypto.subtle.digest('SHA-256', bytes);\n\n return toBase64URL(arrayBufferToUint8Array(hash));\n};\n\nexport const generateNonce = async ({\n caller\n}: {\n caller: Ed25519KeyIdentity;\n}): Promise<{nonce: Nonce; salt: Salt}> => {\n const salt = generateSalt();\n const nonce = await buildNonce({salt, caller});\n\n return {nonce, salt};\n};\n", "import {uint8ArrayToBase64} from '@dfinity/utils';\n\n// In the future: uint8Array.toBase64({ alphabet: \"base64url\" })\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64\nexport const toBase64URL = (uint8Array: Uint8Array): string =>\n uint8ArrayToBase64(uint8Array).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n", "import {Ed25519KeyIdentity, type JsonnableEd25519KeyIdentity} from '@dfinity/identity';\nimport {base64ToUint8Array, uint8ArrayToBase64} from '@dfinity/utils';\nimport type {OpenIdAuthContext} from '../types/context';\n\nconst JSON_KEY_CALLER = '__caller__';\nconst JSON_KEY_SALT = '__salt__';\nconst JSON_KEY_STATE = '__state__';\n\ninterface StoredContext {\n [JSON_KEY_CALLER]: JsonnableEd25519KeyIdentity;\n [JSON_KEY_SALT]: string;\n [JSON_KEY_STATE]: string;\n}\n\nexport const stringifyContext = ({caller, state, salt}: OpenIdAuthContext): string => {\n const data: StoredContext = {\n [JSON_KEY_CALLER]: caller.toJSON(),\n [JSON_KEY_SALT]: uint8ArrayToBase64(salt),\n [JSON_KEY_STATE]: state\n };\n\n return JSON.stringify(data);\n};\n\nexport const parseContext = (jsonData: string): OpenIdAuthContext => {\n const {\n [JSON_KEY_CALLER]: jsonCaller,\n [JSON_KEY_SALT]: jsonSalt,\n [JSON_KEY_STATE]: state\n }: StoredContext = JSON.parse(jsonData);\n\n return {\n caller: Ed25519KeyIdentity.fromParsedJson(jsonCaller),\n salt: base64ToUint8Array(jsonSalt),\n state\n };\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = ():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AAK,UAAUE,CAAI,CAC5B,EAEaC,EAAgBC,GAAwC,CACnE,GAAM,CACJ,CAACT,CAAe,EAAGU,EACnB,CAACT,CAAa,EAAGU,EACjB,CAACT,CAAc,EAAGG,CACpB,EAAmB,KAAK,MAAMI,CAAQ,EAEtC,MAAO,CACL,OAAQZ,EAAmB,eAAea,CAAU,EACpD,KAAMZ,EAAmBa,CAAQ,EACjC,MAAAN,CACF,CACF,EClCO,IAAMO,EAAsB,IACjCC,EAAY,OAAO,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,CAAC,EJOxD,IAAMC,EAAc,SAAwE,CACjG,IAAMC,EAASC,EAAmB,SAAS,EACrC,CAAC,MAAAC,EAAO,KAAAC,CAAI,EAAI,MAAMC,EAAc,CAAC,OAAAJ,CAAM,CAAC,EAC5CK,EAAQC,EAAoB,EAE5BC,EAAaC,EAAiB,CAClC,OAAAR,EACA,KAAAG,EACA,MAAAE,CACF,CAAC,EAED,sBAAe,QAAQI,EAAaF,CAAU,EAEvC,CACL,MAAAL,EACA,MAAAG,CACF,CACF,EAEaK,EAAc,IAAyB,CAClD,IAAMC,EAAgB,eAAe,QAAQF,CAAW,EAExD,GAAIG,EAAUD,CAAa,EACzB,MAAM,IAAIE,EAGZ,OAAOC,EAAaH,CAAa,CACnC",
6
- "names": ["Ed25519KeyIdentity", "isNullish", "arrayBufferToUint8Array", "uint8ArrayToBase64", "toBase64URL", "uint8Array", "generateSalt", "buildNonce", "salt", "caller", "principal", "bytes", "hash", "toBase64URL", "arrayBufferToUint8Array", "generateNonce", "Ed25519KeyIdentity", "base64ToUint8Array", "uint8ArrayToBase64", "JSON_KEY_CALLER", "JSON_KEY_SALT", "JSON_KEY_STATE", "stringifyContext", "caller", "state", "salt", "data", "parseContext", "jsonData", "jsonCaller", "jsonSalt", "generateRandomState", "toBase64URL", "initContext", "caller", "Ed25519KeyIdentity", "nonce", "salt", "generateNonce", "state", "generateRandomState", "storedData", "stringifyContext", "CONTEXT_KEY", "loadContext", "storedContext", "isNullish", "ContextUndefinedError", "parseContext"]
7
- }