@junobuild/auth 2.1.1-next-2026-01-16 → 2.1.1-next-2026-01-17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/_constants.js +1 -1
- package/dist/browser/_context.js +1 -1
- package/dist/browser/authenticate.js +1 -1
- package/dist/browser/{chunk-OW2LUQYD.js → chunk-AWCR2PAA.js} +2 -2
- package/dist/browser/chunk-FXVGSODN.js +2 -0
- package/dist/browser/{chunk-ZM3NK2BE.js.map → chunk-FXVGSODN.js.map} +2 -2
- package/dist/browser/{chunk-ACCTNTPN.js → chunk-TIYP5THJ.js} +2 -2
- package/dist/browser/chunk-X4UUWFNR.js +2 -0
- package/dist/browser/chunk-X4UUWFNR.js.map +7 -0
- package/dist/browser/index.js +1 -1
- package/dist/browser/request.js +1 -1
- package/dist/node/index.mjs +1 -1
- package/dist/node/index.mjs.map +4 -4
- package/dist/types/types/authenticate.github.d.ts +1 -1
- package/package.json +1 -1
- package/dist/browser/chunk-BATUXMHN.js +0 -2
- package/dist/browser/chunk-BATUXMHN.js.map +0 -7
- package/dist/browser/chunk-ZM3NK2BE.js +0 -2
- /package/dist/browser/{chunk-OW2LUQYD.js.map → chunk-AWCR2PAA.js.map} +0 -0
- /package/dist/browser/{chunk-ACCTNTPN.js.map → chunk-TIYP5THJ.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-FXVGSODN.js";export{a as CONTEXT_KEY,c as GITHUB_PROVIDER,b as GOOGLE_PROVIDER};
|
|
2
2
|
//# sourceMappingURL=_constants.js.map
|
package/dist/browser/_context.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-AWCR2PAA.js";import"./chunk-FXVGSODN.js";import"./chunk-RLSIVIYR.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}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-X4UUWFNR.js";import"./chunk-AWCR2PAA.js";import"./chunk-FXVGSODN.js";import"./chunk-RLSIVIYR.js";import"./chunk-PIJCHIUI.js";import"./chunk-2BORB4XM.js";export{a as authenticate};
|
|
2
2
|
//# sourceMappingURL=authenticate.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as s}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as s}from"./chunk-FXVGSODN.js";import{a as i}from"./chunk-RLSIVIYR.js";import{b as a}from"./chunk-2BORB4XM.js";import{isNullish as A}from"@dfinity/utils";import{Ed25519KeyIdentity as N}from"@icp-sdk/core/identity";import{arrayBufferToUint8Array as _}from"@dfinity/utils";var f=()=>window.crypto.getRandomValues(new Uint8Array(32)),x=async({salt:t,caller:e})=>{let n=e.getPrincipal().toUint8Array(),o=new Uint8Array(t.length+n.byteLength);o.set(t),o.set(n,t.length);let r=await window.crypto.subtle.digest("SHA-256",o);return i(_(r))},c=async({caller:t})=>{let e=f();return{nonce:await x({salt:e,caller:t}),salt:e}};import{base64ToUint8Array as g,uint8ArrayToBase64 as C}from"@dfinity/utils";import{Ed25519KeyIdentity as E}from"@icp-sdk/core/identity";var p="__caller__",y="__salt__",m="__state__",d=({caller:t,state:e,salt:n})=>{let o={[p]:t.toJSON(),[y]:C(n),[m]:e};return JSON.stringify(o)},l=t=>{let{[p]:e,[y]:n,[m]:o}=JSON.parse(t);return{caller:E.fromParsedJson(e),salt:g(n),state:o}};var P=async({generateState:t})=>{let e=N.generate(),{nonce:n,salt:o}=await c({caller:e}),r=await t({nonce:n}),S=d({caller:e,salt:o,state:r});return sessionStorage.setItem(s,S),{nonce:n,state:r}},R=()=>{let t=sessionStorage.getItem(s);if(A(t))throw new a;return l(t)};export{P as a,R as b};
|
|
2
|
+
//# sourceMappingURL=chunk-AWCR2PAA.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var t="juno:auth:openid",o={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},e={authUrl:"https://github.com/login/oauth/authorize",authScopes:["read:user","repo"],initUrl:"http://localhost:3000/v1/auth/init/github",finalizeUrl:"http://localhost:3000/v1/auth/finalize/github"};export{t as a,o as b,e as c};
|
|
2
|
+
//# sourceMappingURL=chunk-FXVGSODN.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/_constants.ts"],
|
|
4
|
-
"sourcesContent": ["import type {OpenIdProvider} from './types/provider';\nimport {OpenIdGitHubProvider} from './types/provider.github';\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\nexport const GITHUB_PROVIDER: Omit<OpenIdGitHubProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: '
|
|
5
|
-
"mappings": "AAGO,IAAMA,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb,EAEaC,EAA0E,CACrF,QAAS,
|
|
4
|
+
"sourcesContent": ["import type {OpenIdProvider} from './types/provider';\nimport {OpenIdGitHubProvider} from './types/provider.github';\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\nexport const GITHUB_PROVIDER: Omit<OpenIdGitHubProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: 'https://github.com/login/oauth/authorize',\n authScopes: ['read:user', 'repo'],\n initUrl: 'http://localhost:3000/v1/auth/init/github',\n finalizeUrl: 'http://localhost:3000/v1/auth/finalize/github'\n};\n"],
|
|
5
|
+
"mappings": "AAGO,IAAMA,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb,EAEaC,EAA0E,CACrF,QAAS,2CACT,WAAY,CAAC,YAAa,MAAM,EAChC,QAAS,4CACT,YAAa,+CACf",
|
|
6
6
|
"names": ["CONTEXT_KEY", "GOOGLE_PROVIDER", "GITHUB_PROVIDER"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as u}from"./chunk-WLTG7SQV.js";import{a as c}from"./chunk-Y4QA5UKR.js";import{a as l}from"./chunk-4OXP7K62.js";import{a as m,b as R}from"./chunk-WFK7CGLR.js";import{a as s}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as u}from"./chunk-WLTG7SQV.js";import{a as c}from"./chunk-Y4QA5UKR.js";import{a as l}from"./chunk-4OXP7K62.js";import{a as m,b as R}from"./chunk-WFK7CGLR.js";import{a as s}from"./chunk-AWCR2PAA.js";import{b as i,c as n}from"./chunk-FXVGSODN.js";async function S(t){if("github"in t){let{github:r}=t,{redirect:o}=r,{initUrl:q,...J}=o,{authUrl:p,authScopes:G,initUrl:f}=n,P=await s({generateState:u({initUrl:q??f})});l({...J,...P,authUrl:p,authScopes:G});return}let a=await s({generateState:c}),{google:e}=t;if("credentials"in e){let{credentials:r}=e,{configUrl:o}=i;return await R({...r,...a,configUrl:o})}let{redirect:g}=e,{authUrl:d,authScopes:w}=i;m({...g,...a,authUrl:d,authScopes:w})}export{S as a};
|
|
2
|
+
//# sourceMappingURL=chunk-TIYP5THJ.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as w}from"./chunk-AWCR2PAA.js";import{c as d}from"./chunk-FXVGSODN.js";import{a as s}from"./chunk-PIJCHIUI.js";import{f as m,g as l,h}from"./chunk-2BORB4XM.js";import{isEmptyString as c}from"@dfinity/utils";var y=async a=>{let n=w();if("github"in a){let{github:{redirect:{finalizeUrl:i},auth:e}}=a,{finalizeUrl:o}=d;return await P({finalizeUrl:i??o,auth:e,context:n})}let{google:t}=a;if("credentials"in t){let{credentials:{jwt:i},auth:e}=t;return await s({jwt:i,context:n,auth:e})}return await p({...t,context:n})},p=async({auth:a,context:n})=>{let{location:{hash:t}}=window;if(c(t)||!t.startsWith("#"))throw new m("No hash found in the current location URL");let i=new URLSearchParams(t.slice(1)),e=i.get("state"),o=i.get("id_token"),{state:r}=n;if(c(r)||e!==r)throw new l("The provided state is invalid",{cause:e});if(c(o))throw new h;return await s({jwt:o,auth:a,context:n})},P=async({auth:a,context:n,finalizeUrl:t})=>{let{location:{search:i}}=window,e=new URLSearchParams(i),o=e.get("code"),r=e.get("state"),{token:u}=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o,state:r})}).then(f=>f.json());if(c(u))throw new h;return await s({jwt:u,auth:a,context:n})};export{y as a};
|
|
2
|
+
//# sourceMappingURL=chunk-X4UUWFNR.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/authenticate.ts"],
|
|
4
|
+
"sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {GITHUB_PROVIDER} from './_constants';\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';\nimport {OpenIdGitHubProvider} from './types/provider.github';\n\nexport const authenticate = async <T extends AuthParameters>(\n params: AuthenticationParams<T>\n): Promise<AuthenticatedSession<T>> => {\n const context = loadContext();\n\n if ('github' in params) {\n const {\n github: {\n redirect: {finalizeUrl: userFinalizeUrl},\n auth\n }\n } = params;\n\n const {finalizeUrl} = GITHUB_PROVIDER;\n\n return await authenticateGitHubWithRedirect<T>({\n finalizeUrl: userFinalizeUrl ?? finalizeUrl,\n auth,\n context\n });\n }\n\n const {google} = params;\n\n if ('credentials' in google) {\n const {\n credentials: {jwt},\n auth\n } = google;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateGoogleWithRedirect<T>({...google, context});\n};\n\nconst authenticateGoogleWithRedirect = 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\nconst authenticateGitHubWithRedirect = async <T extends AuthParameters>({\n auth,\n context,\n finalizeUrl\n}: {\n auth: AuthParameters;\n context: Omit<OpenIdAuthContext, 'state'>;\n} & Pick<OpenIdGitHubProvider, 'finalizeUrl'>): Promise<AuthenticatedSession<T>> => {\n const {\n location: {search}\n } = window;\n\n const urlParams = new URLSearchParams(search);\n const code = urlParams.get('code');\n const state = urlParams.get('state');\n\n // TODO: handle error\n const {token: idToken} = await fetch(finalizeUrl, {\n method: 'POST',\n credentials: 'include',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({code, state})\n }).then((r) => r.json());\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": "yKAAA,OAAQ,iBAAAA,MAAoB,iBAiBrB,IAAMC,EAAe,MAC1BC,GACqC,CACrC,IAAMC,EAAUC,EAAY,EAE5B,GAAI,WAAYF,EAAQ,CACtB,GAAM,CACJ,OAAQ,CACN,SAAU,CAAC,YAAaG,CAAe,EACvC,KAAAC,CACF,CACF,EAAIJ,EAEE,CAAC,YAAAK,CAAW,EAAIC,EAEtB,OAAO,MAAMC,EAAkC,CAC7C,YAAaJ,GAAmBE,EAChC,KAAAD,EACA,QAAAH,CACF,CAAC,CACH,CAEA,GAAM,CAAC,OAAAO,CAAM,EAAIR,EAEjB,GAAI,gBAAiBQ,EAAQ,CAC3B,GAAM,CACJ,YAAa,CAAC,IAAAC,CAAG,EACjB,KAAAL,CACF,EAAII,EAEJ,OAAO,MAAME,EAAoB,CAC/B,IAAAD,EACA,QAAAR,EACA,KAAAG,CACF,CAAC,CACH,CAEA,OAAO,MAAMO,EAAkC,CAAC,GAAGH,EAAQ,QAAAP,CAAO,CAAC,CACrE,EAEMU,EAAiC,MAAiC,CACtE,KAAAP,EACA,QAAAH,CACF,IAGwC,CACtC,GAAM,CACJ,SAAU,CAAC,KAAAW,CAAI,CACjB,EAAI,OAEJ,GAAIC,EAAcD,CAAI,GAAK,CAACA,EAAK,WAAW,GAAG,EAC7C,MAAM,IAAIE,EAA2B,2CAA2C,EAGlF,IAAMd,EAAS,IAAI,gBAAgBY,EAAK,MAAM,CAAC,CAAC,EAC1CG,EAAQf,EAAO,IAAI,OAAO,EAC1BgB,EAAUhB,EAAO,IAAI,UAAU,EAE/B,CAAC,MAAOiB,CAAU,EAAIhB,EAE5B,GAAIY,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,KAAAZ,EACA,QAAAH,CACF,CAAC,CACH,EAEMM,EAAiC,MAAiC,CACtE,KAAAH,EACA,QAAAH,EACA,YAAAI,CACF,IAGoF,CAClF,GAAM,CACJ,SAAU,CAAC,OAAAe,CAAM,CACnB,EAAI,OAEEC,EAAY,IAAI,gBAAgBD,CAAM,EACtCE,EAAOD,EAAU,IAAI,MAAM,EAC3BN,EAAQM,EAAU,IAAI,OAAO,EAG7B,CAAC,MAAOL,CAAO,EAAI,MAAM,MAAMX,EAAa,CAChD,OAAQ,OACR,YAAa,UACb,QAAS,CAAC,eAAgB,kBAAkB,EAC5C,KAAM,KAAK,UAAU,CAAC,KAAAiB,EAAM,MAAAP,CAAK,CAAC,CACpC,CAAC,EAAE,KAAMQ,GAAMA,EAAE,KAAK,CAAC,EAGvB,GAAIV,EAAcG,CAAO,EACvB,MAAM,IAAIG,EAGZ,OAAO,MAAMT,EAAoB,CAC/B,IAAKM,EACL,KAAAZ,EACA,QAAAH,CACF,CAAC,CACH",
|
|
6
|
+
"names": ["isEmptyString", "authenticate", "params", "context", "loadContext", "userFinalizeUrl", "auth", "finalizeUrl", "GITHUB_PROVIDER", "authenticateGitHubWithRedirect", "google", "jwt", "authenticateSession", "authenticateGoogleWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "search", "urlParams", "code", "r"]
|
|
7
|
+
}
|
package/dist/browser/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as y}from"./chunk-
|
|
1
|
+
import{a as y}from"./chunk-TIYP5THJ.js";import"./chunk-WLTG7SQV.js";import"./chunk-Y4QA5UKR.js";import"./chunk-4OXP7K62.js";import"./chunk-WFK7CGLR.js";import{a as x}from"./chunk-X4UUWFNR.js";import"./chunk-AWCR2PAA.js";import"./chunk-FXVGSODN.js";import"./chunk-RLSIVIYR.js";import"./chunk-PIJCHIUI.js";import{a as r,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 g=()=>{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,r as InvalidUrlError,x as authenticate,g as isFedCMSupported,y as requestJwt};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/browser/request.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-TIYP5THJ.js";import"./chunk-WLTG7SQV.js";import"./chunk-Y4QA5UKR.js";import"./chunk-4OXP7K62.js";import"./chunk-WFK7CGLR.js";import"./chunk-AWCR2PAA.js";import"./chunk-FXVGSODN.js";import"./chunk-RLSIVIYR.js";import"./chunk-2BORB4XM.js";export{a as requestJwt};
|
|
2
2
|
//# sourceMappingURL=request.js.map
|
package/dist/node/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as topLevelCreateRequire } from 'module';
|
|
2
2
|
const require = topLevelCreateRequire(import.meta.url);
|
|
3
|
-
import{isEmptyString as C}from"@dfinity/utils";
|
|
3
|
+
import{isEmptyString as C}from"@dfinity/utils";var G="juno:auth:openid",_={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},d={authUrl:"https://github.com/login/oauth/authorize",authScopes:["read:user","repo"],initUrl:"http://localhost:3000/v1/auth/init/github",finalizeUrl:"http://localhost:3000/v1/auth/finalize/github"};import{isNullish as ot}from"@dfinity/utils";import{Ed25519KeyIdentity as nt}from"@icp-sdk/core/identity";var g=class extends Error{},h=class extends Error{},y=class extends Error{},f=class extends Error{},w=class extends Error{},x=class extends Error{},A=class extends Error{},u=class extends Error{},P=class extends Error{},S=class extends Error{};import{arrayBufferToUint8Array as $}from"@dfinity/utils";import{uint8ArrayToBase64 as X}from"@dfinity/utils";var R=t=>X(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),l=({url:t})=>{try{return new URL(t)}catch{throw new g("Cannot parse authURL",{cause:t})}};var Q=()=>window.crypto.getRandomValues(new Uint8Array(32)),Z=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 i=await window.crypto.subtle.digest("SHA-256",o);return R($(i))},D=async({caller:t})=>{let e=Q();return{nonce:await Z({salt:e,caller:t}),salt:e}};import{base64ToUint8Array as tt,uint8ArrayToBase64 as et}from"@dfinity/utils";import{Ed25519KeyIdentity as rt}from"@icp-sdk/core/identity";var T="__caller__",q="__salt__",N="__state__",v=({caller:t,state:e,salt:r})=>{let o={[T]:t.toJSON(),[q]:et(r),[N]:e};return JSON.stringify(o)},K=t=>{let{[T]:e,[q]:r,[N]:o}=JSON.parse(t);return{caller:rt.fromParsedJson(e),salt:tt(r),state:o}};var b=async({generateState:t})=>{let e=nt.generate(),{nonce:r,salt:o}=await D({caller:e}),i=await t({nonce:r}),n=v({caller:e,salt:o,state:i});return sessionStorage.setItem(G,n),{nonce:r,state:i}},k=()=>{let t=sessionStorage.getItem(G);if(ot(t))throw new h;return K(t)};import{fromNullable as pt}from"@dfinity/utils";import{Delegation as mt,ECDSAKeyIdentity as lt}from"@icp-sdk/core/identity";import{getConsoleActor as it,getSatelliteActor as st}from"@junobuild/ic-client/actor";var J=({auth:t,identity:e})=>"satellite"in t?st({...t.satellite,identity:e}):it({...t.console,identity:e});var L=async({actorParams:t,args:e})=>{let{authenticate:r}=await J(t);return await r(e)},H=async({actorParams:t,args:e})=>{let{get_delegation:r}=await J(t);return await r(e)};import{DelegationChain as at,DelegationIdentity as ct}from"@icp-sdk/core/identity";var W=({delegations:t,sessionKey:e})=>{let[r,o]=t,i=at.fromDelegations(o,Uint8Array.from(r));return{identity:ct.fromDelegation(e,i),delegationChain:i,sessionKey:e}};var U=async({jwt:t,context:e,auth:r})=>{let o=await lt.generate({extractable:!1}),i=new Uint8Array(o.getPublicKey().toDer()),{delegations:n,data:a}=await ut({jwt:t,publicKey:i,context:e,auth:r});return{identity:W({sessionKey:o,delegations:n}),data:a}},ut=async({jwt:t,publicKey:e,context:{caller:r,salt:o},auth:i})=>{let n=await L({args:{OpenId:{jwt:t,session_key:e,salt:o}},actorParams:{auth:i,identity:r}});if("Err"in n)throw new w("Authentication failed",{cause:n});let{delegation:{user_key:a,expiration:s},...c}=n.Ok,p=await dt({jwt:t,context:{caller:r,salt:o},auth:i,publicKey:e,expiration:s}),{delegation:m,signature:I}=p,{pubkey:O,expiration:E,targets:M}=m;return{delegations:[a,[{delegation:new mt(Uint8Array.from(O),E,pt(M)),signature:Uint8Array.from(I)}]],data:c}},dt=async({jwt:t,publicKey:e,context:{salt:r,caller:o},auth:i,expiration:n,maxRetries:a=5})=>{for(let s=0;s<a;s++){await new Promise(m=>{setInterval(m,1e3*s)});let p=await H({args:{OpenId:{jwt:t,session_key:e,salt:r,expiration:n}},actorParams:{auth:i,identity:o}});if("Err"in p){let{Err:m}=p;if("NoSuchDelegation"in m||"GetCachedJwks"in m)continue;throw new P("Getting delegation failed",{cause:p})}return p.Ok}throw new S};var te=async t=>{let e=k();if("github"in t){let{github:{redirect:{finalizeUrl:o},auth:i}}=t,{finalizeUrl:n}=d;return await ht({finalizeUrl:o??n,auth:i,context:e})}let{google:r}=t;if("credentials"in r){let{credentials:{jwt:o},auth:i}=r;return await U({jwt:o,context:e,auth:i})}return await gt({...r,context:e})},gt=async({auth:t,context:e})=>{let{location:{hash:r}}=window;if(C(r)||!r.startsWith("#"))throw new x("No hash found in the current location URL");let o=new URLSearchParams(r.slice(1)),i=o.get("state"),n=o.get("id_token"),{state:a}=e;if(C(a)||i!==a)throw new A("The provided state is invalid",{cause:i});if(C(n))throw new u;return await U({jwt:n,auth:t,context:e})},ht=async({auth:t,context:e,finalizeUrl:r})=>{let{location:{search:o}}=window,i=new URLSearchParams(o),n=i.get("code"),a=i.get("state"),{token:s}=await fetch(r,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n,state:a})}).then(c=>c.json());if(C(s))throw new u;return await U({jwt:s,auth:t,context:e})};var j=({initUrl:t})=>async({nonce:r})=>{let o=l({url:t});o.searchParams.set("nonce",r);let{state:i}=await fetch(o.toString(),{credentials:"include"}).then(n=>n.json());return i};var B=()=>R(window.crypto.getRandomValues(new Uint8Array(12)));var z=async t=>B();var Y=({authUrl:t,clientId:e,authScopes:r,state:o,redirectUrl:i})=>{let n=l({url:t});n.searchParams.set("client_id",e);let{location:{origin:a}}=window;n.searchParams.set("redirect_uri",i??a),n.searchParams.set("scope",r.join(" ")),n.searchParams.set("state",o),window.location.href=n.toString()};import{isNullish as yt,notEmptyString as ft}from"@dfinity/utils";var V=({authUrl:t,clientId:e,nonce:r,loginHint:o,authScopes:i,state:n,redirectUrl:a})=>{let s=l({url:t});s.searchParams.set("client_id",e);let{location:{origin:c}}=window;s.searchParams.set("redirect_uri",a??c),s.searchParams.set("response_type","code id_token"),s.searchParams.set("scope",i.join(" ")),s.searchParams.set("state",n),s.searchParams.set("nonce",r),ft(o)?s.searchParams.set("login_hint",o):s.searchParams.set("prompt","select_account"),window.location.href=s.toString()},F=async({configUrl:t,clientId:e,nonce:r,loginHint:o,domainHint:i})=>{let n=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:t,clientId:e,nonce:r,loginHint:o,domainHint:i}],mode:"active"},mediation:"required"});if(yt(n))throw new y;let{type:a}=n;if(a!=="identity"||!("token"in n)||typeof n.token!="string")throw new f("Invalid credential received from FedCM API",{cause:n});let{token:s}=n;return{jwt:s}};async function Pe(t){if("github"in t){let{github:a}=t,{redirect:s}=a,{initUrl:c,...p}=s,{authUrl:m,authScopes:I,initUrl:O}=d,E=await b({generateState:j({initUrl:c??O})});Y({...p,...E,authUrl:m,authScopes:I});return}let e=await b({generateState:z}),{google:r}=t;if("credentials"in r){let{credentials:a}=r,{configUrl:s}=_;return await F({...a,...e,configUrl:s})}let{redirect:o}=r,{authUrl:i,authScopes:n}=_;V({...o,...e,authUrl:i,authScopes:n})}var Re=()=>{let{userAgent:t}=navigator;return/SamsungBrowser/i.test(t)?!1:"IdentityCredential"in window};export{w as AuthenticationError,A as AuthenticationInvalidStateError,u as AuthenticationUndefinedJwtError,x as AuthenticationUrlHashError,h as ContextUndefinedError,f as FedCMIdentityCredentialInvalidError,y as FedCMIdentityCredentialUndefinedError,P as GetDelegationError,S as GetDelegationRetryError,g as InvalidUrlError,te as authenticate,Re as isFedCMSupported,Pe as requestJwt};
|
|
4
4
|
//# sourceMappingURL=index.mjs.map
|
package/dist/node/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/authenticate.ts", "../../src/
|
|
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 {AuthenticationGitHubRedirect} from './types/authenticate.github';\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 ('github' in params) {\n const {github} = params;\n return await authenticateGitHubWithRedirect<T>({...github, context});\n }\n\n const {google} = params;\n\n if ('credentials' in google) {\n const {\n credentials: {jwt},\n auth\n } = google;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateGoogleWithRedirect<T>({...google, context});\n};\n\nconst authenticateGoogleWithRedirect = 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\nconst authenticateGitHubWithRedirect = async <T extends AuthParameters>({\n auth,\n context,\n redirect: {finalizeUrl}\n}: {\n auth: AuthParameters;\n context: Omit<OpenIdAuthContext, 'state'>;\n redirect: AuthenticationGitHubRedirect;\n}): Promise<AuthenticatedSession<T>> => {\n const {\n location: {search}\n } = window;\n\n const urlParams = new URLSearchParams(search);\n const code = urlParams.get('code');\n const state = urlParams.get('state');\n\n // TODO: handle error\n const {token: idToken} = await fetch(finalizeUrl, {\n method: 'POST',\n credentials: 'include',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({code, state})\n }).then((r) => r.json());\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';\n\nexport const initContext = async ({\n generateState\n}: {\n generateState: (params: {nonce: Nonce}) => Promise<string>;\n}): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n\n const state = await generateState({nonce});\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';\nimport {OpenIdGitHubProvider} from './types/provider.github';\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\nexport const GITHUB_PROVIDER: Omit<OpenIdGitHubProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: 'http://accounts.google.com/o/o/oauth2/v2/auth',\n authScopes: ['read:user', 'repo'],\n initUrl: 'http://localhost:3000/v1/auth/init/github',\n finalizeUrl: 'http://localhost:3000/v1/auth/finalize/github'\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';\nimport {InvalidUrlError} from '../errors';\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\nexport const parseUrl = ({url}: {url: string}): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(url);\n } catch (_error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: url});\n }\n};\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 {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 type {Nonce} from './types/nonce';\nimport {OpenIdGitHubProvider} from './types/provider.github';\nimport {parseUrl} from './utils/url.utils';\n\nexport const buildGenerateState = ({initUrl}: Pick<OpenIdGitHubProvider, 'initUrl'>) => {\n const generateState = async ({nonce}: {nonce: Nonce}): Promise<string> => {\n const requestUrl = parseUrl({url: initUrl});\n requestUrl.searchParams.set('nonce', nonce);\n\n // TODO: handle error\n const {state} = await fetch(requestUrl.toString(), {\n credentials: 'include'\n }).then((r) => r.json());\n\n return state;\n };\n\n return generateState;\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n", "import type {Nonce} from './types/nonce';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const generateState = async (_params: {nonce: Nonce}): Promise<string> =>\n generateRandomState();\n", "import {RequestGitHubJwtWithRedirect} from './types/openid.github';\nimport {parseUrl} from './utils/url.utils';\n\n// https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#1-request-a-users-github-identity\n\nexport const requestGitHubJwtWithRedirect = ({\n authUrl,\n clientId,\n authScopes,\n state,\n redirectUrl\n}: RequestGitHubJwtWithRedirect) => {\n const requestUrl = parseUrl({url: authUrl});\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 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 by the proxy backend with the value it initiated.\n requestUrl.searchParams.set('state', state);\n\n window.location.href = requestUrl.toString();\n};\n", "import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestGoogleJwtWithCredentials, RequestGoogleJwtWithRedirect} from './types/openid.google';\nimport {parseUrl} from './utils/url.utils';\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 requestGoogleJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestGoogleJwtWithRedirect) => {\n const requestUrl = parseUrl({url: authUrl});\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 requestGoogleJwtWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestGoogleJwtWithCredentials): 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 {GITHUB_PROVIDER, GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {buildGenerateState} from './_context.github';\nimport {generateState} from './_context.google';\nimport {requestGitHubJwtWithRedirect} from './_openid.github';\nimport {requestGoogleJwtWithCredentials, requestGoogleJwtWithRedirect} from './_openid.google';\nimport {RequestJwtCredentialsResult} from './types/request';\nimport {RequestGitHubJwtRedirectParams} from './types/request.github';\nimport type {\n RequestGoogleJwtCredentialsParams,\n RequestGoogleJwtParams,\n RequestGoogleJwtRedirectParams\n} from './types/request.google';\n\nexport function requestJwt(args: {\n google: RequestGoogleJwtCredentialsParams;\n}): Promise<RequestJwtCredentialsResult>;\n\nexport function requestJwt(\n args: {google: RequestGoogleJwtRedirectParams} | {github: RequestGitHubJwtRedirectParams}\n): Promise<void>;\n\nexport async function requestJwt(\n args:\n | {\n google: RequestGoogleJwtParams;\n }\n | {github: RequestGitHubJwtRedirectParams}\n): Promise<RequestJwtCredentialsResult | void> {\n if ('github' in args) {\n const {github} = args;\n\n const {redirect} = github;\n const {initUrl: userInitUrl, ...restRedirect} = redirect;\n\n const {authUrl, authScopes, initUrl} = GITHUB_PROVIDER;\n\n const context = await initContext({\n generateState: buildGenerateState({initUrl: userInitUrl ?? initUrl})\n });\n\n requestGitHubJwtWithRedirect({\n ...restRedirect,\n ...context,\n authUrl,\n authScopes\n });\n return;\n }\n\n const context = await initContext({generateState});\n\n const {google} = args;\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestGoogleJwtWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestGoogleJwtWithRedirect({\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,
|
|
6
|
-
"names": ["isEmptyString", "
|
|
3
|
+
"sources": ["../../src/authenticate.ts", "../../src/_constants.ts", "../../src/_context.ts", "../../src/errors.ts", "../../src/utils/auth.utils.ts", "../../src/utils/url.utils.ts", "../../src/utils/session-storage.utils.ts", "../../src/_session.ts", "../../src/api/_actor.api.ts", "../../src/api/auth.api.ts", "../../src/utils/session.utils.ts", "../../src/_context.github.ts", "../../src/utils/state.utils.ts", "../../src/_context.google.ts", "../../src/_openid.github.ts", "../../src/_openid.google.ts", "../../src/request.ts", "../../src/utils/openid.utils.ts"],
|
|
4
|
+
"sourcesContent": ["import {isEmptyString} from '@dfinity/utils';\nimport {GITHUB_PROVIDER} from './_constants';\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';\nimport {OpenIdGitHubProvider} from './types/provider.github';\n\nexport const authenticate = async <T extends AuthParameters>(\n params: AuthenticationParams<T>\n): Promise<AuthenticatedSession<T>> => {\n const context = loadContext();\n\n if ('github' in params) {\n const {\n github: {\n redirect: {finalizeUrl: userFinalizeUrl},\n auth\n }\n } = params;\n\n const {finalizeUrl} = GITHUB_PROVIDER;\n\n return await authenticateGitHubWithRedirect<T>({\n finalizeUrl: userFinalizeUrl ?? finalizeUrl,\n auth,\n context\n });\n }\n\n const {google} = params;\n\n if ('credentials' in google) {\n const {\n credentials: {jwt},\n auth\n } = google;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateGoogleWithRedirect<T>({...google, context});\n};\n\nconst authenticateGoogleWithRedirect = 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\nconst authenticateGitHubWithRedirect = async <T extends AuthParameters>({\n auth,\n context,\n finalizeUrl\n}: {\n auth: AuthParameters;\n context: Omit<OpenIdAuthContext, 'state'>;\n} & Pick<OpenIdGitHubProvider, 'finalizeUrl'>): Promise<AuthenticatedSession<T>> => {\n const {\n location: {search}\n } = window;\n\n const urlParams = new URLSearchParams(search);\n const code = urlParams.get('code');\n const state = urlParams.get('state');\n\n // TODO: handle error\n const {token: idToken} = await fetch(finalizeUrl, {\n method: 'POST',\n credentials: 'include',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({code, state})\n }).then((r) => r.json());\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 type {OpenIdProvider} from './types/provider';\nimport {OpenIdGitHubProvider} from './types/provider.github';\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\nexport const GITHUB_PROVIDER: Omit<OpenIdGitHubProvider, 'clientId' | 'redirectUrl'> = {\n authUrl: 'https://github.com/login/oauth/authorize',\n authScopes: ['read:user', 'repo'],\n initUrl: 'http://localhost:3000/v1/auth/init/github',\n finalizeUrl: 'http://localhost:3000/v1/auth/finalize/github'\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';\n\nexport const initContext = async ({\n generateState\n}: {\n generateState: (params: {nonce: Nonce}) => Promise<string>;\n}): Promise<{nonce: Nonce} & Pick<OpenIdAuthContext, 'state'>> => {\n const caller = Ed25519KeyIdentity.generate();\n const {nonce, salt} = await generateNonce({caller});\n\n const state = await generateState({nonce});\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", "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';\nimport {InvalidUrlError} from '../errors';\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\nexport const parseUrl = ({url}: {url: string}): URL => {\n try {\n // Use the URL constructor, for backwards compatibility with older Android/WebView.\n return new URL(url);\n } catch (_error: unknown) {\n throw new InvalidUrlError('Cannot parse authURL', {cause: url});\n }\n};\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 {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 type {Nonce} from './types/nonce';\nimport {OpenIdGitHubProvider} from './types/provider.github';\nimport {parseUrl} from './utils/url.utils';\n\nexport const buildGenerateState = ({initUrl}: Pick<OpenIdGitHubProvider, 'initUrl'>) => {\n const generateState = async ({nonce}: {nonce: Nonce}): Promise<string> => {\n const requestUrl = parseUrl({url: initUrl});\n requestUrl.searchParams.set('nonce', nonce);\n\n // TODO: handle error\n const {state} = await fetch(requestUrl.toString(), {\n credentials: 'include'\n }).then((r) => r.json());\n\n return state;\n };\n\n return generateState;\n};\n", "import {toBase64URL} from './url.utils';\n\nexport const generateRandomState = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n", "import type {Nonce} from './types/nonce';\nimport {generateRandomState} from './utils/state.utils';\n\nexport const generateState = async (_params: {nonce: Nonce}): Promise<string> =>\n generateRandomState();\n", "import {RequestGitHubJwtWithRedirect} from './types/openid.github';\nimport {parseUrl} from './utils/url.utils';\n\n// https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#1-request-a-users-github-identity\n\nexport const requestGitHubJwtWithRedirect = ({\n authUrl,\n clientId,\n authScopes,\n state,\n redirectUrl\n}: RequestGitHubJwtWithRedirect) => {\n const requestUrl = parseUrl({url: authUrl});\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 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 by the proxy backend with the value it initiated.\n requestUrl.searchParams.set('state', state);\n\n window.location.href = requestUrl.toString();\n};\n", "import {isNullish, notEmptyString} from '@dfinity/utils';\nimport {\n FedCMIdentityCredentialInvalidError,\n FedCMIdentityCredentialUndefinedError,\n InvalidUrlError\n} from './errors';\nimport type {RequestGoogleJwtWithCredentials, RequestGoogleJwtWithRedirect} from './types/openid.google';\nimport {parseUrl} from './utils/url.utils';\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 requestGoogleJwtWithRedirect = ({\n authUrl,\n clientId,\n nonce,\n loginHint,\n authScopes,\n state,\n redirectUrl\n}: RequestGoogleJwtWithRedirect) => {\n const requestUrl = parseUrl({url: authUrl});\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 requestGoogleJwtWithCredentials = async ({\n configUrl: configURL,\n clientId,\n nonce,\n loginHint,\n domainHint\n}: RequestGoogleJwtWithCredentials): 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 {GITHUB_PROVIDER, GOOGLE_PROVIDER} from './_constants';\nimport {initContext} from './_context';\nimport {buildGenerateState} from './_context.github';\nimport {generateState} from './_context.google';\nimport {requestGitHubJwtWithRedirect} from './_openid.github';\nimport {requestGoogleJwtWithCredentials, requestGoogleJwtWithRedirect} from './_openid.google';\nimport {RequestJwtCredentialsResult} from './types/request';\nimport {RequestGitHubJwtRedirectParams} from './types/request.github';\nimport type {\n RequestGoogleJwtCredentialsParams,\n RequestGoogleJwtParams,\n RequestGoogleJwtRedirectParams\n} from './types/request.google';\n\nexport function requestJwt(args: {\n google: RequestGoogleJwtCredentialsParams;\n}): Promise<RequestJwtCredentialsResult>;\n\nexport function requestJwt(\n args: {google: RequestGoogleJwtRedirectParams} | {github: RequestGitHubJwtRedirectParams}\n): Promise<void>;\n\nexport async function requestJwt(\n args:\n | {\n google: RequestGoogleJwtParams;\n }\n | {github: RequestGitHubJwtRedirectParams}\n): Promise<RequestJwtCredentialsResult | void> {\n if ('github' in args) {\n const {github} = args;\n\n const {redirect} = github;\n const {initUrl: userInitUrl, ...restRedirect} = redirect;\n\n const {authUrl, authScopes, initUrl} = GITHUB_PROVIDER;\n\n const context = await initContext({\n generateState: buildGenerateState({initUrl: userInitUrl ?? initUrl})\n });\n\n requestGitHubJwtWithRedirect({\n ...restRedirect,\n ...context,\n authUrl,\n authScopes\n });\n return;\n }\n\n const context = await initContext({generateState});\n\n const {google} = args;\n\n if ('credentials' in google) {\n const {credentials} = google;\n const {configUrl} = GOOGLE_PROVIDER;\n\n return await requestGoogleJwtWithCredentials({\n ...credentials,\n ...context,\n configUrl\n });\n }\n\n const {redirect} = google;\n const {authUrl, authScopes} = GOOGLE_PROVIDER;\n\n requestGoogleJwtWithRedirect({\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,iBCGrB,IAAMC,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb,EAEaC,EAA0E,CACrF,QAAS,2CACT,WAAY,CAAC,YAAa,MAAM,EAChC,QAAS,4CACT,YAAa,+CACf,ECjBA,OAAQ,aAAAC,OAAgB,iBACxB,OAAQ,sBAAAC,OAAyB,yBCD1B,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,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C,CACF,CAAC,CACH,CClEO,IAAMc,GAAmB,IAAe,CAC7C,GAAM,CAAC,UAAAC,CAAS,EAAI,UAKpB,MADyB,kBAAkB,KAAKA,CAAS,EAEhD,GAGF,uBAAwB,MACjC",
|
|
6
|
+
"names": ["isEmptyString", "CONTEXT_KEY", "GOOGLE_PROVIDER", "GITHUB_PROVIDER", "isNullish", "Ed25519KeyIdentity", "InvalidUrlError", "ContextUndefinedError", "FedCMIdentityCredentialUndefinedError", "FedCMIdentityCredentialInvalidError", "AuthenticationError", "AuthenticationUrlHashError", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "GetDelegationError", "GetDelegationRetryError", "arrayBufferToUint8Array", "uint8ArrayToBase64", "toBase64URL", "uint8Array", "uint8ArrayToBase64", "parseUrl", "url", "InvalidUrlError", "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", "initContext", "generateState", "caller", "Ed25519KeyIdentity", "nonce", "salt", "generateNonce", "state", "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", "userFinalizeUrl", "auth", "finalizeUrl", "GITHUB_PROVIDER", "authenticateGitHubWithRedirect", "google", "jwt", "authenticateSession", "authenticateGoogleWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "search", "urlParams", "code", "r", "buildGenerateState", "initUrl", "nonce", "requestUrl", "parseUrl", "state", "r", "generateRandomState", "toBase64URL", "generateState", "_params", "generateRandomState", "requestGitHubJwtWithRedirect", "authUrl", "clientId", "authScopes", "state", "redirectUrl", "requestUrl", "parseUrl", "currentUrl", "isNullish", "notEmptyString", "requestGoogleJwtWithRedirect", "authUrl", "clientId", "nonce", "loginHint", "authScopes", "state", "redirectUrl", "requestUrl", "parseUrl", "currentUrl", "notEmptyString", "requestGoogleJwtWithCredentials", "configURL", "domainHint", "identityCredential", "isNullish", "FedCMIdentityCredentialUndefinedError", "type", "FedCMIdentityCredentialInvalidError", "jwt", "requestJwt", "args", "github", "redirect", "userInitUrl", "restRedirect", "authUrl", "authScopes", "initUrl", "GITHUB_PROVIDER", "context", "initContext", "buildGenerateState", "requestGitHubJwtWithRedirect", "generateState", "google", "credentials", "configUrl", "GOOGLE_PROVIDER", "requestGoogleJwtWithCredentials", "requestGoogleJwtWithRedirect", "isFedCMSupported", "userAgent"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { OpenIdGitHubProvider } from './provider.github';
|
|
2
|
-
export type AuthenticationGitHubRedirect = Pick<OpenIdGitHubProvider,
|
|
2
|
+
export type AuthenticationGitHubRedirect = Partial<Pick<OpenIdGitHubProvider, 'finalizeUrl'>>;
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as w}from"./chunk-OW2LUQYD.js";import{a as s}from"./chunk-PIJCHIUI.js";import{f as d,g as m,h}from"./chunk-2BORB4XM.js";import{isEmptyString as c}from"@dfinity/utils";var g=async i=>{let e=w();if("github"in i){let{github:n}=i;return await f({...n,context:e})}let{google:t}=i;if("credentials"in t){let{credentials:{jwt:n},auth:a}=t;return await s({jwt:n,context:e,auth:a})}return await p({...t,context:e})},p=async({auth:i,context:e})=>{let{location:{hash:t}}=window;if(c(t)||!t.startsWith("#"))throw new d("No hash found in the current location URL");let n=new URLSearchParams(t.slice(1)),a=n.get("state"),o=n.get("id_token"),{state:r}=e;if(c(r)||a!==r)throw new m("The provided state is invalid",{cause:a});if(c(o))throw new h;return await s({jwt:o,auth:i,context:e})},f=async({auth:i,context:e,redirect:{finalizeUrl:t}})=>{let{location:{search:n}}=window,a=new URLSearchParams(n),o=a.get("code"),r=a.get("state"),{token:u}=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o,state:r})}).then(A=>A.json());if(c(u))throw new h;return await s({jwt:u,auth:i,context:e})};export{g as a};
|
|
2
|
-
//# sourceMappingURL=chunk-BATUXMHN.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 {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 {AuthenticationGitHubRedirect} from './types/authenticate.github';\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 ('github' in params) {\n const {github} = params;\n return await authenticateGitHubWithRedirect<T>({...github, context});\n }\n\n const {google} = params;\n\n if ('credentials' in google) {\n const {\n credentials: {jwt},\n auth\n } = google;\n\n return await authenticateSession({\n jwt,\n context,\n auth\n });\n }\n\n return await authenticateGoogleWithRedirect<T>({...google, context});\n};\n\nconst authenticateGoogleWithRedirect = 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\nconst authenticateGitHubWithRedirect = async <T extends AuthParameters>({\n auth,\n context,\n redirect: {finalizeUrl}\n}: {\n auth: AuthParameters;\n context: Omit<OpenIdAuthContext, 'state'>;\n redirect: AuthenticationGitHubRedirect;\n}): Promise<AuthenticatedSession<T>> => {\n const {\n location: {search}\n } = window;\n\n const urlParams = new URLSearchParams(search);\n const code = urlParams.get('code');\n const state = urlParams.get('state');\n\n // TODO: handle error\n const {token: idToken} = await fetch(finalizeUrl, {\n method: 'POST',\n credentials: 'include',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({code, state})\n }).then((r) => r.json());\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,iBAgBrB,IAAMC,EAAe,MAC1BC,GACqC,CACrC,IAAMC,EAAUC,EAAY,EAE5B,GAAI,WAAYF,EAAQ,CACtB,GAA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,IAAI,OAAO,EAG7B,CAAC,MAAON,CAAO,EAAI,MAAM,MAAMI,EAAa,CAChD,OAAQ,OACR,YAAa,UACb,QAAS,CAAC,eAAgB,kBAAkB,EAC5C,KAAM,KAAK,UAAU,CAAC,KAAAG,EAAM,MAAAR,CAAK,CAAC,CACpC,CAAC,EAAE,KAAMS,GAAMA,EAAE,KAAK,CAAC,EAGvB,GAAIX,EAAcG,CAAO,EACvB,MAAM,IAAIG,EAGZ,OAAO,MAAMT,EAAoB,CAC/B,IAAKM,EACL,KAAAP,EACA,QAAAN,CACF,CAAC,CACH",
|
|
6
|
-
"names": ["isEmptyString", "authenticate", "params", "context", "loadContext", "github", "authenticateGitHubWithRedirect", "google", "jwt", "auth", "authenticateSession", "authenticateGoogleWithRedirect", "hash", "isEmptyString", "AuthenticationUrlHashError", "state", "idToken", "savedState", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "finalizeUrl", "search", "urlParams", "code", "r"]
|
|
7
|
-
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var t="juno:auth:openid",o={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},e={authUrl:"http://accounts.google.com/o/o/oauth2/v2/auth",authScopes:["read:user","repo"],initUrl:"http://localhost:3000/v1/auth/init/github",finalizeUrl:"http://localhost:3000/v1/auth/finalize/github"};export{t as a,o as b,e as c};
|
|
2
|
-
//# sourceMappingURL=chunk-ZM3NK2BE.js.map
|
|
File without changes
|
|
File without changes
|