@junobuild/auth 0.0.1
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/LICENSE +21 -0
- package/README.md +17 -0
- package/dist/browser/_constants.js +2 -0
- package/dist/browser/_constants.js.map +7 -0
- package/dist/browser/_context.js +2 -0
- package/dist/browser/_context.js.map +7 -0
- package/dist/browser/_openid.js +2 -0
- package/dist/browser/_openid.js.map +7 -0
- package/dist/browser/_session.js +2 -0
- package/dist/browser/_session.js.map +7 -0
- package/dist/browser/authenticate.js +2 -0
- package/dist/browser/authenticate.js.map +7 -0
- package/dist/browser/chunk-2BORB4XM.js +2 -0
- package/dist/browser/chunk-2BORB4XM.js.map +7 -0
- package/dist/browser/chunk-36KNLPQZ.js +2 -0
- package/dist/browser/chunk-36KNLPQZ.js.map +7 -0
- package/dist/browser/chunk-E4CYLKZY.js +2 -0
- package/dist/browser/chunk-E4CYLKZY.js.map +7 -0
- package/dist/browser/chunk-JOJCKPWQ.js +2 -0
- package/dist/browser/chunk-JOJCKPWQ.js.map +7 -0
- package/dist/browser/chunk-JOOQTYYG.js +2 -0
- package/dist/browser/chunk-JOOQTYYG.js.map +7 -0
- package/dist/browser/chunk-JTJJD55H.js +2 -0
- package/dist/browser/chunk-JTJJD55H.js.map +7 -0
- package/dist/browser/chunk-VYICNPPG.js +2 -0
- package/dist/browser/chunk-VYICNPPG.js.map +7 -0
- package/dist/browser/errors.js +2 -0
- package/dist/browser/errors.js.map +7 -0
- package/dist/browser/index.js +2 -0
- package/dist/browser/index.js.map +7 -0
- package/dist/browser/request.js +2 -0
- package/dist/browser/request.js.map +7 -0
- package/dist/index.js +1 -0
- package/dist/node/index.mjs +4 -0
- package/dist/node/index.mjs.map +7 -0
- package/dist/types/_constants.d.ts +3 -0
- package/dist/types/_context.d.ts +6 -0
- package/dist/types/_openid.d.ts +18 -0
- package/dist/types/_session.d.ts +12 -0
- package/dist/types/api/_actor.api.d.ts +3 -0
- package/dist/types/api/auth.api.d.ts +9 -0
- package/dist/types/authenticate.d.ts +2 -0
- package/dist/types/errors.d.ts +20 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/request.d.ts +6 -0
- package/dist/types/types/actor.d.ts +20 -0
- package/dist/types/types/authenticate.d.ts +16 -0
- package/dist/types/types/context.d.ts +7 -0
- package/dist/types/types/nonce.d.ts +2 -0
- package/dist/types/types/openid.d.ts +10 -0
- package/dist/types/types/provider.d.ts +8 -0
- package/dist/types/types/request.d.ts +16 -0
- package/dist/types/types/session.d.ts +3 -0
- package/dist/types/utils/auth.utils.d.ts +8 -0
- package/dist/types/utils/openid.utils.d.ts +9 -0
- package/dist/types/utils/session-storage.utils.d.ts +3 -0
- package/dist/types/utils/session.utils.d.ts +7 -0
- package/dist/types/utils/state.utils.d.ts +1 -0
- package/dist/types/utils/url.utils.d.ts +1 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 David Dal Busco
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[![npm][npm-badge]][npm-badge-url]
|
|
2
|
+
[![license][npm-license]][npm-license-url]
|
|
3
|
+
|
|
4
|
+
[npm-badge]: https://img.shields.io/npm/v/@junobuild/cdn
|
|
5
|
+
[npm-badge-url]: https://www.npmjs.com/package/@junobuild/cdn
|
|
6
|
+
[npm-license]: https://img.shields.io/npm/l/@junobuild/cdn
|
|
7
|
+
[npm-license-url]: https://github.com/junobuild/juno-js/blob/main/LICENSE
|
|
8
|
+
|
|
9
|
+
# Juno JavaScript CDN Toolkit
|
|
10
|
+
|
|
11
|
+
A toolkit for working with modules that implement [Juno]'s CDN functionality.
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
MIT © [David Dal Busco](mailto:david.dalbusco@outlook.com)
|
|
16
|
+
|
|
17
|
+
[juno]: https://juno.build
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var x=class extends Error{},p=class extends Error{},c=class extends Error{},r=class extends Error{},e=class extends Error{},o=class extends Error{},l=class extends Error{},b=class extends Error{},j=class extends Error{},k=class extends Error{};export{x as a,p as b,c,r as d,e,o as f,l as g,b as h,j as i,k as j};
|
|
2
|
+
//# sourceMappingURL=chunk-2BORB4XM.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/errors.ts"],
|
|
4
|
+
"sourcesContent": ["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"],
|
|
5
|
+
"mappings": "AAAO,IAAMA,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",
|
|
6
|
+
"names": ["InvalidUrlError", "ContextUndefinedError", "FedCMIdentityCredentialUndefinedError", "FedCMIdentityCredentialInvalidError", "AuthenticationError", "AuthenticationUrlHashError", "AuthenticationInvalidStateError", "AuthenticationUndefinedJwtError", "GetDelegationError", "GetDelegationRetryError"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
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
|
|
@@ -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 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"],
|
|
5
|
+
"mappings": "sDACA,OAAQ,cAAAA,EAAY,oBAAAC,MAAuB,oBAC3C,OAAQ,gBAAAC,MAAmB,iBCF3B,OAGE,mBAAAC,EACA,qBAAAC,MACK,6BAGA,IAAMC,EAAe,CAAC,CAC3B,KAAAC,EACA,SAAAC,CACF,IACE,cAAeD,EACXF,EAAkB,CAAC,GAAGE,EAAK,UAAW,SAAAC,CAAQ,CAAC,EAC/CJ,EAAgB,CAAC,GAAGG,EAAK,QAAS,SAAAC,CAAQ,CAAC,ECL1C,IAAMC,EAAe,MAAO,CACjC,YAAAC,EACA,KAAAC,CACF,IAGqC,CACnC,GAAM,CAAC,aAAAF,CAAY,EAAI,MAAMG,EAAaF,CAAW,EACrD,OAAO,MAAMD,EAAaE,CAAI,CAChC,EAEaE,EAAgB,MAAO,CAClC,YAAAH,EACA,KAAAC,CACF,IAGoC,CAClC,GAAM,CAAC,eAAAG,CAAc,EAAI,MAAMF,EAAaF,CAAW,EACvD,OAAO,MAAMI,EAAeH,CAAI,CAClC,EC7BA,OAAQ,mBAAAI,EAAiB,sBAAAC,MAAgD,oBAIlE,IAAMC,EAAmB,CAAC,CAC/B,YAAAC,EACA,WAAAC,CACF,IAG6B,CAC3B,GAAM,CAACC,EAASC,CAAiB,EAAIH,EAE/BI,EAAkBP,EAAgB,gBACtCM,EACA,WAAW,KAAKD,CAAO,CACzB,EAIA,MAAO,CAAC,SAFSJ,EAAmB,eAAeG,EAAYG,CAAe,EAE5D,gBAAAA,CAAe,CACnC,EHJO,IAAMC,EAAe,MAAO,CACjC,IAAAC,EACA,QAAAC,EACA,KAAAC,CACF,IAA0D,CACxD,IAAMC,EAAa,MAAMC,EAAiB,SAAS,CAAC,YAAa,EAAK,CAAC,EAEjEC,EAAY,IAAI,WAAWF,EAAW,aAAa,EAAE,MAAM,CAAC,EAE5DG,EAAc,MAAMC,EAAoB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AAMd,EAAS,MAAMgB,EAAiB,CACpC,KAV8B,CAC9B,OAAQ,CACN,IAAA3B,EACA,YAAaK,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
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
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
|
|
@@ -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 {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
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
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
|
|
@@ -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 {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
|
+
}
|
|
@@ -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 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
|
|
@@ -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: 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"],
|
|
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,OAASQ,EAAgB,CACvB,MAAM,IAAIC,EAAgB,uBAAwB,CAAC,MAAOD,CAAK,CAAC,CAClE,CACF,GAEgC,EAEhCD,EAAW,aAAa,IAAI,YAAaN,CAAQ,EAEjD,GAAM,CACJ,SAAU,CAAC,OAAQS,CAAU,CAC/B,EAAI,OAEJH,EAAW,aAAa,IAAI,eAAgBD,GAAeI,CAAU,EAIrEH,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,EAEtCS,EAAeR,CAAS,EAC1BI,EAAW,aAAa,IAAI,aAAcJ,CAAS,EAEnDI,EAAW,aAAa,IAAI,SAAU,gBAAgB,EAGxD,OAAO,SAAS,KAAOA,EAAW,SAAS,CAC7C,EAQaK,EAAyB,MAAO,CAC3C,UAAWC,EACX,SAAAZ,EACA,MAAAC,EACA,UAAAC,EACA,WAAAW,CACF,IAAyD,CACvD,IAAMC,EAAqB,MAAM,UAAU,YAAY,IAAI,CAGzD,SAAU,CACR,QAAS,MACT,UAAW,CACT,CACE,UAAAF,EACA,SAAAZ,EACA,MAAAC,EACA,UAAAC,EACA,WAAAW,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", "error", "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{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
|
|
@@ -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 {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 = (): string =>\n toBase64URL(window.crypto.getRandomValues(new Uint8Array(12)));\n"],
|
|
5
|
+
"mappings": "2EAAA,OAAQ,sBAAAA,MAAyB,oBACjC,OAAQ,aAAAC,MAAgB,iBCAxB,OAAQ,2BAAAC,MAA8B,iBCDtC,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,C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a,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
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/_constants.ts"],
|
|
4
|
+
"sourcesContent": ["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"],
|
|
5
|
+
"mappings": "AAEO,IAAMA,EAAc,mBAGdC,EAAoE,CAC/E,QAAS,+CACT,WAAY,CAAC,SAAU,UAAW,OAAO,EACzC,UAAW,4CACb",
|
|
6
|
+
"names": ["CONTEXT_KEY", "GOOGLE_PROVIDER"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-2BORB4XM.js";export{e as AuthenticationError,g as AuthenticationInvalidStateError,h as AuthenticationUndefinedJwtError,f as AuthenticationUrlHashError,b as ContextUndefinedError,d as FedCMIdentityCredentialInvalidError,c as FedCMIdentityCredentialUndefinedError,i as GetDelegationError,j as GetDelegationRetryError,a as InvalidUrlError};
|
|
2
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +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};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/openid.utils.ts"],
|
|
4
|
+
"sourcesContent": ["/**\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": "uSAQO,IAAMA,EAAmB,IAAe,CAC7C,GAAM,CAAC,UAAAC,CAAS,EAAI,UAKpB,MADyB,kBAAkB,KAAKA,CAAS,EAEhD,GAGF,uBAAwB,MACjC",
|
|
6
|
+
"names": ["isFedCMSupported", "userAgent"]
|
|
7
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './browser/index.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as topLevelCreateRequire } from 'module';
|
|
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};
|
|
4
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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,OAA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,CAAG,EAAIL,EACrB,MAAO,CAAC,IAAAK,CAAG,CACb,ECjHO,IAAMC,GAAa,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,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"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { OpenIdAuthContext } from './types/context';
|
|
2
|
+
import type { Nonce } from './types/nonce';
|
|
3
|
+
export declare const initContext: () => Promise<{
|
|
4
|
+
nonce: Nonce;
|
|
5
|
+
} & Pick<OpenIdAuthContext, "state">>;
|
|
6
|
+
export declare const loadContext: () => OpenIdAuthContext;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { RequestJwtWithCredentials, RequestJwtWithRedirect } from './types/openid';
|
|
2
|
+
/**
|
|
3
|
+
* Initiates an OpenID Connect authorization request by redirecting the browser.
|
|
4
|
+
*
|
|
5
|
+
* References:
|
|
6
|
+
* - OAuth 2.0 (Google): https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow
|
|
7
|
+
* - OpenID Connect: https://developers.google.com/identity/openid-connect/openid-connect
|
|
8
|
+
*/
|
|
9
|
+
export declare const requestJwtWithRedirect: ({ authUrl, clientId, nonce, loginHint, authScopes, state, redirectUrl }: RequestJwtWithRedirect) => void;
|
|
10
|
+
/**
|
|
11
|
+
* References:
|
|
12
|
+
* - identity spec: https://www.w3.org/TR/fedcm/#browser-api-credential-request-options
|
|
13
|
+
* - https://privacysandbox.google.com/cookies/fedcm/implement/identity-provider
|
|
14
|
+
* - https://privacysandbox.google.com/cookies/fedcm/why
|
|
15
|
+
*/
|
|
16
|
+
export declare const requestWithCredentials: ({ configUrl: configURL, clientId, nonce, loginHint, domainHint }: RequestJwtWithCredentials) => Promise<{
|
|
17
|
+
jwt: string;
|
|
18
|
+
}>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { AuthParameters } from './types/actor';
|
|
2
|
+
import type { AuthenticatedIdentity } from './types/authenticate';
|
|
3
|
+
import type { OpenIdAuthContext } from './types/context';
|
|
4
|
+
interface AuthContext {
|
|
5
|
+
context: Omit<OpenIdAuthContext, 'state'>;
|
|
6
|
+
auth: AuthParameters;
|
|
7
|
+
}
|
|
8
|
+
type AuthenticationArgs = {
|
|
9
|
+
jwt: string;
|
|
10
|
+
} & AuthContext;
|
|
11
|
+
export declare const authenticate: ({ jwt, context, auth }: AuthenticationArgs) => Promise<AuthenticatedIdentity>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ActorParameters, AuthenticationArgs, AuthenticationResult, GetDelegationArgs, GetDelegationResult } from '../types/actor';
|
|
2
|
+
export declare const authenticate: ({ actorParams, args }: {
|
|
3
|
+
args: AuthenticationArgs;
|
|
4
|
+
actorParams: ActorParameters;
|
|
5
|
+
}) => Promise<AuthenticationResult>;
|
|
6
|
+
export declare const getDelegation: ({ actorParams, args }: {
|
|
7
|
+
args: GetDelegationArgs;
|
|
8
|
+
actorParams: ActorParameters;
|
|
9
|
+
}) => Promise<GetDelegationResult>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare class InvalidUrlError extends Error {
|
|
2
|
+
}
|
|
3
|
+
export declare class ContextUndefinedError extends Error {
|
|
4
|
+
}
|
|
5
|
+
export declare class FedCMIdentityCredentialUndefinedError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export declare class FedCMIdentityCredentialInvalidError extends Error {
|
|
8
|
+
}
|
|
9
|
+
export declare class AuthenticationError extends Error {
|
|
10
|
+
}
|
|
11
|
+
export declare class AuthenticationUrlHashError extends Error {
|
|
12
|
+
}
|
|
13
|
+
export declare class AuthenticationInvalidStateError extends Error {
|
|
14
|
+
}
|
|
15
|
+
export declare class AuthenticationUndefinedJwtError extends Error {
|
|
16
|
+
}
|
|
17
|
+
export declare class GetDelegationError extends Error {
|
|
18
|
+
}
|
|
19
|
+
export declare class GetDelegationRetryError extends Error {
|
|
20
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
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
|
+
};
|
|
12
|
+
export interface ActorParameters {
|
|
13
|
+
auth: AuthParameters;
|
|
14
|
+
identity: Identity;
|
|
15
|
+
}
|
|
16
|
+
export type AuthenticationArgs = SatelliteDid.AuthenticationArgs | ConsoleDid.AuthenticationArgs;
|
|
17
|
+
export type GetDelegationArgs = SatelliteDid.GetDelegationArgs | ConsoleDid.GetDelegationArgs;
|
|
18
|
+
export type AuthenticationResult = SatelliteDid.AuthenticateResultResponse | ConsoleDid.Result;
|
|
19
|
+
export type GetDelegationResult = SatelliteDid.GetDelegationResultResponse | ConsoleDid.Result_1;
|
|
20
|
+
export type SignedDelegation = SatelliteDid.SignedDelegation | ConsoleDid.SignedDelegation;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { DelegationChain, DelegationIdentity } from '@dfinity/identity';
|
|
2
|
+
import type { AuthParameters } from './actor';
|
|
3
|
+
export interface AuthenticationCredentials {
|
|
4
|
+
jwt: string;
|
|
5
|
+
}
|
|
6
|
+
export type AuthenticationParams = {
|
|
7
|
+
redirect: null;
|
|
8
|
+
auth: AuthParameters;
|
|
9
|
+
} | {
|
|
10
|
+
credentials: AuthenticationCredentials;
|
|
11
|
+
auth: AuthParameters;
|
|
12
|
+
};
|
|
13
|
+
export interface AuthenticatedIdentity {
|
|
14
|
+
identity: DelegationIdentity;
|
|
15
|
+
delegationChain: DelegationChain;
|
|
16
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { OpenIdAuthContext } from './context';
|
|
2
|
+
import type { Nonce } from './nonce';
|
|
3
|
+
import type { OpenIdProvider } from './provider';
|
|
4
|
+
import type { RequestJwtCredentials, RequestJwtRedirect } from './request';
|
|
5
|
+
interface RequestOpenIdJwt {
|
|
6
|
+
nonce: Nonce;
|
|
7
|
+
}
|
|
8
|
+
export type RequestJwtWithRedirect = RequestOpenIdJwt & Pick<OpenIdAuthContext, 'state'> & RequestJwtRedirect & Pick<OpenIdProvider, 'clientId' | 'authUrl' | 'authScopes'> & Partial<Pick<OpenIdProvider, 'redirectUrl'>>;
|
|
9
|
+
export type RequestJwtWithCredentials = RequestOpenIdJwt & RequestJwtCredentials & Pick<OpenIdProvider, 'clientId' | 'configUrl'>;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { OpenIdProvider } from './provider';
|
|
2
|
+
export interface RequestJwt {
|
|
3
|
+
clientId: string;
|
|
4
|
+
}
|
|
5
|
+
export type RequestJwtRedirect = RequestJwt & Partial<Pick<OpenIdProvider, 'authScopes' | 'redirectUrl'>> & {
|
|
6
|
+
loginHint?: string;
|
|
7
|
+
};
|
|
8
|
+
export type RequestJwtCredentials = RequestJwt & {
|
|
9
|
+
loginHint?: string;
|
|
10
|
+
domainHint?: string | 'any';
|
|
11
|
+
};
|
|
12
|
+
export type RequestJwtParams = {
|
|
13
|
+
redirect: RequestJwtRedirect;
|
|
14
|
+
} | {
|
|
15
|
+
credentials: RequestJwtCredentials;
|
|
16
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detects whether the browser supports FedCM (Federated Credential Management).
|
|
3
|
+
*
|
|
4
|
+
* @returns {boolean} `true` if FedCM is supported, otherwise `false`.
|
|
5
|
+
*
|
|
6
|
+
* References:
|
|
7
|
+
* - MDN IdentityCredential: https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential
|
|
8
|
+
*/
|
|
9
|
+
export declare const isFedCMSupported: () => boolean;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ECDSAKeyIdentity } from '@dfinity/identity';
|
|
2
|
+
import type { AuthenticatedIdentity } from '../types/authenticate';
|
|
3
|
+
import type { Delegations } from '../types/session';
|
|
4
|
+
export declare const generateIdentity: ({ delegations, sessionKey }: {
|
|
5
|
+
delegations: Delegations;
|
|
6
|
+
sessionKey: ECDSAKeyIdentity;
|
|
7
|
+
}) => AuthenticatedIdentity;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const generateRandomState: () => string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const toBase64URL: (uint8Array: Uint8Array) => string;
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@junobuild/auth",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "A SDK for working with Juno authentication modules",
|
|
5
|
+
"author": "David Dal Busco (https://daviddalbusco.com)",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/node/index.mjs",
|
|
9
|
+
"module": "./dist/browser/index.js",
|
|
10
|
+
"types": "./dist/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": {
|
|
14
|
+
"types": "./dist/types/index.d.ts",
|
|
15
|
+
"default": "./dist/browser/index.js"
|
|
16
|
+
},
|
|
17
|
+
"require": {
|
|
18
|
+
"types": "./dist/types/index.d.ts",
|
|
19
|
+
"default": "./dist/node/index.mjs"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"rmdir": "node ../../scripts/rmdir.mjs",
|
|
30
|
+
"ts-declaration": "tsc --emitDeclarationOnly --outDir dist/types",
|
|
31
|
+
"build": "npm run rmdir && mkdir -p dist && node esbuild.mjs && npm run ts-declaration",
|
|
32
|
+
"prepack": "npm run build"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/junobuild/juno-js.git",
|
|
37
|
+
"directory": "packages/auth"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/junobuild/juno-js"
|
|
41
|
+
},
|
|
42
|
+
"keywords": [
|
|
43
|
+
"authentication",
|
|
44
|
+
"openid",
|
|
45
|
+
"jwt",
|
|
46
|
+
"fedcm"
|
|
47
|
+
],
|
|
48
|
+
"homepage": "https://juno.build",
|
|
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"
|
|
56
|
+
}
|
|
57
|
+
}
|