@junobuild/ic-client 8.0.2 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/actor.js +1 -1
  2. package/actor.js.map +3 -3
  3. package/actor.mjs +1 -1
  4. package/actor.mjs.map +3 -3
  5. package/declarations/console/console.did.d.ts +18 -18
  6. package/declarations/console/console.factory.certified.did.js +10 -10
  7. package/declarations/console/console.factory.did.js +10 -10
  8. package/declarations/console/console.factory.did.mjs +10 -10
  9. package/declarations/mission_control/mission_control.did.d.ts +17 -17
  10. package/declarations/mission_control/mission_control.factory.certified.did.js +12 -12
  11. package/declarations/mission_control/mission_control.factory.did.js +12 -12
  12. package/declarations/observatory/observatory.did.d.ts +10 -10
  13. package/declarations/observatory/observatory.factory.certified.did.js +10 -10
  14. package/declarations/observatory/observatory.factory.did.js +10 -10
  15. package/declarations/observatory/observatory.factory.did.mjs +10 -10
  16. package/declarations/orbiter/orbiter.did.d.ts +17 -17
  17. package/declarations/orbiter/orbiter.factory.certified.did.js +12 -12
  18. package/declarations/orbiter/orbiter.factory.did.js +12 -12
  19. package/declarations/orbiter/orbiter.factory.did.mjs +12 -12
  20. package/declarations/satellite/satellite.did.d.ts +44 -20
  21. package/declarations/satellite/satellite.factory.certified.did.js +46 -20
  22. package/declarations/satellite/satellite.factory.did.js +46 -20
  23. package/declarations/satellite/satellite.factory.did.mjs +46 -20
  24. package/declarations/sputnik/sputnik.did.d.ts +44 -20
  25. package/declarations/sputnik/sputnik.factory.certified.did.js +46 -20
  26. package/declarations/sputnik/sputnik.factory.did.js +46 -20
  27. package/package.json +2 -2
  28. package/webauthn.js +1 -1
  29. package/webauthn.js.map +3 -3
  30. package/webauthn.mjs +1 -1
  31. package/webauthn.mjs.map +3 -3
@@ -111,6 +111,31 @@ export const idlFactory = ({IDL}) => {
111
111
  Ok: IDL.Tuple(IDL.Principal, AutomationController),
112
112
  Err: AuthenticationAutomationError
113
113
  });
114
+ const AssetKey = IDL.Record({
115
+ token: IDL.Opt(IDL.Text),
116
+ collection: IDL.Text,
117
+ owner: IDL.Principal,
118
+ name: IDL.Text,
119
+ description: IDL.Opt(IDL.Text),
120
+ full_path: IDL.Text
121
+ });
122
+ const CertifyAssetsCursor = IDL.Variant({
123
+ Heap: IDL.Record({offset: IDL.Nat64}),
124
+ Stable: IDL.Record({key: IDL.Opt(AssetKey)})
125
+ });
126
+ const CertifyAssetsStrategy = IDL.Variant({
127
+ Append: IDL.Null,
128
+ Clear: IDL.Null,
129
+ AppendWithRouting: IDL.Null
130
+ });
131
+ const CertifyAssetsArgs = IDL.Record({
132
+ cursor: CertifyAssetsCursor,
133
+ strategy: CertifyAssetsStrategy,
134
+ chunk_size: IDL.Opt(IDL.Nat32)
135
+ });
136
+ const CertifyAssetsResult = IDL.Record({
137
+ next_cursor: IDL.Opt(CertifyAssetsCursor)
138
+ });
114
139
  const CommitBatch = IDL.Record({
115
140
  batch_id: IDL.Nat,
116
141
  headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),
@@ -151,21 +176,21 @@ export const idlFactory = ({IDL}) => {
151
176
  const DeleteControllersArgs = IDL.Record({
152
177
  controllers: IDL.Vec(IDL.Principal)
153
178
  });
154
- const ControllerKind = IDL.Variant({
179
+ const AccessKeyKind = IDL.Variant({
155
180
  Emulator: IDL.Null,
156
181
  Automation: IDL.Null
157
182
  });
158
- const ControllerScope = IDL.Variant({
183
+ const AccessKeyScope = IDL.Variant({
159
184
  Write: IDL.Null,
160
185
  Admin: IDL.Null,
161
186
  Submit: IDL.Null
162
187
  });
163
- const Controller = IDL.Record({
188
+ const AccessKey = IDL.Record({
164
189
  updated_at: IDL.Nat64,
165
190
  metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),
166
- kind: IDL.Opt(ControllerKind),
191
+ kind: IDL.Opt(AccessKeyKind),
167
192
  created_at: IDL.Nat64,
168
- scope: ControllerScope,
193
+ scope: AccessKeyScope,
169
194
  expires_at: IDL.Opt(IDL.Nat64)
170
195
  });
171
196
  const DelDoc = IDL.Record({version: IDL.Opt(IDL.Nat64)});
@@ -178,14 +203,6 @@ export const idlFactory = ({IDL}) => {
178
203
  cycles: IDL.Nat,
179
204
  destination_id: IDL.Principal
180
205
  });
181
- const AssetKey = IDL.Record({
182
- token: IDL.Opt(IDL.Text),
183
- collection: IDL.Text,
184
- owner: IDL.Principal,
185
- name: IDL.Text,
186
- description: IDL.Opt(IDL.Text),
187
- full_path: IDL.Text
188
- });
189
206
  const AssetEncodingNoContent = IDL.Record({
190
207
  modified: IDL.Nat64,
191
208
  sha256: IDL.Vec(IDL.Nat8),
@@ -469,14 +486,14 @@ export const idlFactory = ({IDL}) => {
469
486
  openid: IDL.Opt(AutomationConfigOpenId),
470
487
  version: IDL.Opt(IDL.Nat64)
471
488
  });
472
- const SetController = IDL.Record({
489
+ const SetAccessKey = IDL.Record({
473
490
  metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),
474
- kind: IDL.Opt(ControllerKind),
475
- scope: ControllerScope,
491
+ kind: IDL.Opt(AccessKeyKind),
492
+ scope: AccessKeyScope,
476
493
  expires_at: IDL.Opt(IDL.Nat64)
477
494
  });
478
495
  const SetControllersArgs = IDL.Record({
479
- controller: SetController,
496
+ controller: SetAccessKey,
480
497
  controllers: IDL.Vec(IDL.Principal)
481
498
  });
482
499
  const SetDbConfig = IDL.Record({
@@ -508,6 +525,13 @@ export const idlFactory = ({IDL}) => {
508
525
  raw_access: IDL.Opt(StorageConfigRawAccess),
509
526
  redirects: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, StorageConfigRedirect)))
510
527
  });
528
+ const SetStorageConfigOptions = IDL.Record({
529
+ skip_certification: IDL.Opt(IDL.Bool)
530
+ });
531
+ const SetStorageConfigWithOptions = IDL.Record({
532
+ config: SetStorageConfig,
533
+ options: SetStorageConfigOptions
534
+ });
511
535
  const UploadChunk = IDL.Record({
512
536
  content: IDL.Vec(IDL.Nat8),
513
537
  batch_id: IDL.Nat,
@@ -522,6 +546,7 @@ export const idlFactory = ({IDL}) => {
522
546
  [AuthenticateAutomationResultResponse],
523
547
  []
524
548
  ),
549
+ certify_assets_chunk: IDL.Func([CertifyAssetsArgs], [CertifyAssetsResult], []),
525
550
  commit_asset_upload: IDL.Func([CommitBatch], [], []),
526
551
  commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),
527
552
  commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),
@@ -536,7 +561,7 @@ export const idlFactory = ({IDL}) => {
536
561
  del_controller_self: IDL.Func([], [], []),
537
562
  del_controllers: IDL.Func(
538
563
  [DeleteControllersArgs],
539
- [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],
564
+ [IDL.Vec(IDL.Tuple(IDL.Principal, AccessKey))],
540
565
  []
541
566
  ),
542
567
  del_custom_domain: IDL.Func([IDL.Text], [], []),
@@ -584,7 +609,7 @@ export const idlFactory = ({IDL}) => {
584
609
  []
585
610
  ),
586
611
  list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], ['query']),
587
- list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),
612
+ list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, AccessKey))], ['query']),
588
613
  list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], ['query']),
589
614
  list_docs: IDL.Func([IDL.Text, ListParams], [ListResults_1], ['query']),
590
615
  list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),
@@ -596,7 +621,7 @@ export const idlFactory = ({IDL}) => {
596
621
  set_automation_config: IDL.Func([SetAutomationConfig], [AutomationConfig], []),
597
622
  set_controllers: IDL.Func(
598
623
  [SetControllersArgs],
599
- [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],
624
+ [IDL.Vec(IDL.Tuple(IDL.Principal, AccessKey))],
600
625
  []
601
626
  ),
602
627
  set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),
@@ -609,6 +634,7 @@ export const idlFactory = ({IDL}) => {
609
634
  ),
610
635
  set_rule: IDL.Func([CollectionType, IDL.Text, SetRule], [Rule], []),
611
636
  set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),
637
+ set_storage_config_with_options: IDL.Func([SetStorageConfigWithOptions], [StorageConfig], []),
612
638
  submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),
613
639
  switch_storage_system_memory: IDL.Func([], [], []),
614
640
  upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@junobuild/ic-client",
3
- "version": "8.0.2",
3
+ "version": "8.1.0",
4
4
  "description": "Agent and actor with generated bindings for Juno on the Internet Computer",
5
5
  "author": "David Dal Busco (https://daviddalbusco.com)",
6
6
  "license": "MIT",
@@ -77,8 +77,8 @@
77
77
  ],
78
78
  "homepage": "https://juno.build",
79
79
  "peerDependencies": {
80
- "@dfinity/utils": "^4.1",
81
80
  "@icp-sdk/core": "^5",
81
+ "@junobuild/utils": "^1",
82
82
  "idb-keyval": "^6.2.2"
83
83
  }
84
84
  }
package/webauthn.js CHANGED
@@ -1,2 +1,2 @@
1
- import{uint8ArrayToArrayOfNumber as H}from"@dfinity/utils";var I=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),n=K({bytes:t});return"aaguid"in n?{aaguidBytes:t,aaguidText:n.aaguid}:{unknownProvider:null}},K=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let n=(e instanceof Uint8Array?H(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return n==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:n}};import{DER_COSE_OID as V,wrapDER as j}from"@icp-sdk/core/agent";function S(e){let t=new DataView(new ArrayBuffer(2)),n=e.slice(53,55);[...new Uint8Array(n)].forEach((a,s)=>t.setUint8(s,a));let r=t.getUint16(0);return e.slice(55+r)}function U(e){return j(e,V)}var y=class{constructor(t){this._cose=t;this.#t=U(t)}#t;toDer(){return this.#t}toRaw(){return new Uint8Array(this.#t)}};import{uint8ArrayToBase64 as $}from"@dfinity/utils";var p=class{#t;#e;constructor({rawId:t,cose:n}){this.#t=t,this.#e=new y(n)}getPublicKey(){return this.#e}getCredentialId(){return this.#t}getCredentialIdText(){return $(this.#t)}},h=class extends p{#t;#e;constructor({authData:t,...n}){super(n);let r=I({authData:t});this.#t="aaguidText"in r?r.aaguidText:void 0,this.#e="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#e}getAAGUIDText(){return this.#t}},g=class extends p{};var A=class extends Error{},b=class extends Error{},f=class extends Error{},m=class extends Error{},C=class extends Error{},P=class extends Error{},w=class extends Error{},l=class extends Error{},E=class extends Error{};import{arrayBufferToUint8Array as d,isNullish as u,uint8ArraysEqual as Q}from"@dfinity/utils";import{Cbor as N,SignIdentity as X}from"@icp-sdk/core/agent";var O={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},v=6e4;var k=()=>window.crypto.getRandomValues(new Uint8Array(16)),M=()=>k(),Y=()=>k(),J=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new A}},D=({appId:e})=>e?.id??J(),R=({appId:e,user:t}={})=>{let{document:{title:n}}=window,r=()=>({rp:{name:e?.name??n,id:D({appId:e})}}),a=()=>({user:{id:Y(),name:t?.name??t?.displayName??n,displayName:t?.displayName??n}});return{attestation:"direct",challenge:M(),...r(),...a(),pubKeyCredParams:Object.values(O).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},_=(e={})=>({rpId:D(e),allowCredentials:[],userVerification:"required"});var x=async({fn:e,step:t,onProgress:n})=>{n?.({step:t,state:"in_progress"});try{let r=await e();return n?.({step:t,state:"success"}),r}catch(r){throw n?.({step:t,state:"error"}),r}};var B=(r=>(r[r.RequestingUserCredential=0]="RequestingUserCredential",r[r.FinalizingCredential=1]="FinalizingCredential",r[r.Signing=2]="Signing",r))(B||{});var G=({timeout:e})=>AbortSignal.timeout(e??v),Z=async({challenge:e,credentialIds:t,passkeyOptions:n,timeout:r})=>await navigator.credentials.get({publicKey:{..._(n),challenge:e.buffer,allowCredentials:(t??[]).map(a=>({id:a.buffer,type:"public-key"}))},signal:G({timeout:r})}),z=e=>{if(e.status!=="initialized")throw new b},q=e=>{if(u(e))throw new f},L=({type:e})=>{if(e!=="public-key")throw new m},F=class e extends X{#t;#e;constructor({onProgress:t,...n}){if(super(),this.#t=t,"retrievePublicKey"in n){let{retrievePublicKey:r}=n;this.#e={status:"pending",retrievePublicKey:r};return}this.#e=e.#r({credential:new h(n)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:n,...r}={}){let a=await navigator.credentials.create({publicKey:R(t),signal:G({timeout:n})});q(a),L(a);let{response:{attestationObject:s},rawId:i}=a;if(u(s))throw new C;let{authData:o}=N.decode(d(s)),c=S(o);return new e({...r,rawId:d(i),cose:c,authData:o})}static async createWithExistingCredential(t){return new e(t)}getPublicKey(){z(this.#e);let{credential:t}=this.#e;return t.getPublicKey()}getCredential(){z(this.#e);let{credential:t}=this.#e;return t}async sign(t){let r=await x({fn:async()=>{let i=await Z({challenge:t,...this.#e.status==="initialized"&&{credentialIds:[this.#e.credential.getCredentialId()]}});return q(i),L(i),i},step:0,onProgress:this.#t});return await x({fn:async()=>{let{rawId:i}=r;if(this.#e.status==="initialized"){if(!Q({a:this.#e.credential.getCredentialId(),b:d(i)}))throw new P;return}let{retrievePublicKey:o}=this.#e,c=await o({credentialId:d(i)});this.#e=e.#r({credential:new g({rawId:d(i),cose:c})})},step:1,onProgress:this.#t}),await x({fn:async()=>{let{response:i}=r,{clientDataJSON:o}=i,{authenticatorData:c,signature:T}="authenticatorData"in i&&"signature"in i?i:{};if(u(c))throw new l;if(u(T))throw new l;let W=N.encode({authenticator_data:c,client_data_json:new TextDecoder().decode(o),signature:d(T)});if(u(W))throw new w;return Object.assign(W,{__signature__:void 0}),W},step:2,onProgress:this.#t})}};import{nonNullish as ee}from"@dfinity/utils";var Ue=async()=>ee(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;export{y as CosePublicKey,p as WebAuthnCredential,g as WebAuthnExistingCredential,F as WebAuthnIdentity,f as WebAuthnIdentityCreateCredentialOnTheDeviceError,b as WebAuthnIdentityCredentialNotInitializedError,m as WebAuthnIdentityCredentialNotPublicKeyError,w as WebAuthnIdentityEncodeCborSignatureError,A as WebAuthnIdentityHostnameError,P as WebAuthnIdentityInvalidCredentialIdError,C as WebAuthnIdentityNoAttestationError,l as WebAuthnIdentityNoAuthenticatorDataError,E as WebAuthnIdentityNoSignatureError,h as WebAuthnNewCredential,B as WebAuthnSignProgressStep,K as bytesToAAGUID,Ue as isWebAuthnAvailable};
1
+ import{uint8ArrayToArrayOfNumber as H}from"@junobuild/utils";var I=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),n=K({bytes:t});return"aaguid"in n?{aaguidBytes:t,aaguidText:n.aaguid}:{unknownProvider:null}},K=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let n=(e instanceof Uint8Array?H(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return n==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:n}};import{DER_COSE_OID as V,wrapDER as j}from"@icp-sdk/core/agent";function S(e){let t=new DataView(new ArrayBuffer(2)),n=e.slice(53,55);[...new Uint8Array(n)].forEach((a,s)=>t.setUint8(s,a));let r=t.getUint16(0);return e.slice(55+r)}function U(e){return j(e,V)}var y=class{constructor(t){this._cose=t;this.#t=U(t)}_cose;#t;toDer(){return this.#t}toRaw(){return new Uint8Array(this.#t)}};import{uint8ArrayToBase64 as $}from"@junobuild/utils";var p=class{#t;#e;constructor({rawId:t,cose:n}){this.#t=t,this.#e=new y(n)}getPublicKey(){return this.#e}getCredentialId(){return this.#t}getCredentialIdText(){return $(this.#t)}},h=class extends p{#t;#e;constructor({authData:t,...n}){super(n);let r=I({authData:t});this.#t="aaguidText"in r?r.aaguidText:void 0,this.#e="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#e}getAAGUIDText(){return this.#t}},g=class extends p{};var A=class extends Error{},b=class extends Error{},f=class extends Error{},m=class extends Error{},C=class extends Error{},P=class extends Error{},w=class extends Error{},l=class extends Error{},E=class extends Error{};import{Cbor as N,SignIdentity as Q}from"@icp-sdk/core/agent";import{arrayBufferToUint8Array as d,isNullish as u,uint8ArraysEqual as X}from"@junobuild/utils";var O={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},v=6e4;var k=()=>window.crypto.getRandomValues(new Uint8Array(16)),M=()=>k(),Y=()=>k(),J=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new A}},D=({appId:e})=>e?.id??J(),R=({appId:e,user:t}={})=>{let{document:{title:n}}=window,r=()=>({rp:{name:e?.name??n,id:D({appId:e})}}),a=()=>({user:{id:Y(),name:t?.name??t?.displayName??n,displayName:t?.displayName??n}});return{attestation:"direct",challenge:M(),...r(),...a(),pubKeyCredParams:Object.values(O).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},_=(e={})=>({rpId:D(e),allowCredentials:[],userVerification:"required"});var x=async({fn:e,step:t,onProgress:n})=>{n?.({step:t,state:"in_progress"});try{let r=await e();return n?.({step:t,state:"success"}),r}catch(r){throw n?.({step:t,state:"error"}),r}};var B=(r=>(r[r.RequestingUserCredential=0]="RequestingUserCredential",r[r.FinalizingCredential=1]="FinalizingCredential",r[r.Signing=2]="Signing",r))(B||{});var G=({timeout:e})=>AbortSignal.timeout(e??v),Z=async({challenge:e,credentialIds:t,passkeyOptions:n,timeout:r})=>await navigator.credentials.get({publicKey:{..._(n),challenge:e.buffer,allowCredentials:(t??[]).map(a=>({id:a.buffer,type:"public-key"}))},signal:G({timeout:r})}),z=e=>{if(e.status!=="initialized")throw new b},q=e=>{if(u(e))throw new f},L=({type:e})=>{if(e!=="public-key")throw new m},F=class e extends Q{#t;#e;constructor({onProgress:t,...n}){if(super(),this.#t=t,"retrievePublicKey"in n){let{retrievePublicKey:r}=n;this.#e={status:"pending",retrievePublicKey:r};return}this.#e=e.#r({credential:new h(n)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:n,...r}={}){let a=await navigator.credentials.create({publicKey:R(t),signal:G({timeout:n})});q(a),L(a);let{response:{attestationObject:s},rawId:i}=a;if(u(s))throw new C;let{authData:o}=N.decode(d(s)),c=S(o);return new e({...r,rawId:d(i),cose:c,authData:o})}static async createWithExistingCredential(t){return new e(t)}getPublicKey(){z(this.#e);let{credential:t}=this.#e;return t.getPublicKey()}getCredential(){z(this.#e);let{credential:t}=this.#e;return t}async sign(t){let r=await x({fn:async()=>{let i=await Z({challenge:t,...this.#e.status==="initialized"&&{credentialIds:[this.#e.credential.getCredentialId()]}});return q(i),L(i),i},step:0,onProgress:this.#t});return await x({fn:async()=>{let{rawId:i}=r;if(this.#e.status==="initialized"){if(!X({a:this.#e.credential.getCredentialId(),b:d(i)}))throw new P;return}let{retrievePublicKey:o}=this.#e,c=await o({credentialId:d(i)});this.#e=e.#r({credential:new g({rawId:d(i),cose:c})})},step:1,onProgress:this.#t}),await x({fn:async()=>{let{response:i}=r,{clientDataJSON:o}=i,{authenticatorData:c,signature:T}="authenticatorData"in i&&"signature"in i?i:{};if(u(c))throw new l;if(u(T))throw new l;let W=N.encode({authenticator_data:c,client_data_json:new TextDecoder().decode(o),signature:d(T)});if(u(W))throw new w;return Object.assign(W,{__signature__:void 0}),W},step:2,onProgress:this.#t})}};import{nonNullish as ee}from"@junobuild/utils";var Ue=async()=>ee(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;export{y as CosePublicKey,p as WebAuthnCredential,g as WebAuthnExistingCredential,F as WebAuthnIdentity,f as WebAuthnIdentityCreateCredentialOnTheDeviceError,b as WebAuthnIdentityCredentialNotInitializedError,m as WebAuthnIdentityCredentialNotPublicKeyError,w as WebAuthnIdentityEncodeCborSignatureError,A as WebAuthnIdentityHostnameError,P as WebAuthnIdentityInvalidCredentialIdError,C as WebAuthnIdentityNoAttestationError,l as WebAuthnIdentityNoAuthenticatorDataError,E as WebAuthnIdentityNoSignatureError,h as WebAuthnNewCredential,B as WebAuthnSignProgressStep,K as bytesToAAGUID,Ue as isWebAuthnAvailable};
2
2
  //# sourceMappingURL=webauthn.js.map
package/webauthn.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["src/webauthn/aaguid.ts", "src/webauthn/agent-js/cose-utils.ts", "src/webauthn/agent-js/cose-key.ts", "src/webauthn/credential.ts", "src/webauthn/errors.ts", "src/webauthn/identity.ts", "src/webauthn/_constants.ts", "src/webauthn/_options.ts", "src/webauthn/_progress.ts", "src/webauthn/types/progress.ts", "src/webauthn/utils.ts"],
4
- "sourcesContent": ["import {uint8ArrayToArrayOfNumber} from '@dfinity/utils';\n\n/**\n * Extracts the AAGUID (Authenticator Attestation GUID) from a WebAuthn data buffer.\n *\n * The AAGUID is a 16-byte value located at offsets 37..53 within `authenticatorData`\n * when **attested credential data** is present (i.e., during registration/attestation).\n *\n * For assertion (sign-in) responses, `authenticatorData` is typically 37 bytes and\n * does not include an AAGUID.\n *\n * If the extracted value is all zeros (`00000000-0000-0000-0000-000000000000`),\n * this function returns `{ unknownProvider: null }` since some passkey providers\n * intentionally use a zero AAGUID.\n *\n * @param {Object} params\n * @param {Uint8Array} params.authData - The WebAuthn `authenticatorData` bytes.\n * @returns {{aaguid: string; bytes: Uint8Array} | {invalidAuthData: null} | {unknownProvider: null}}\n * - { aaguidText, aaguidBytes } for valid AAGUID\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidAuthData: null } if `authData` is invalid (too short, too long, etc.)\n *\n * @see https://web.dev/articles/webauthn-aaguid\n */\nexport const extractAAGUID = ({\n authData\n}: {\n authData: Uint8Array;\n}):\n | {aaguidText: string; aaguidBytes: Uint8Array}\n | {invalidAuthData: null}\n | {unknownProvider: null} => {\n if (authData.byteLength < 37) {\n return {invalidAuthData: null};\n }\n\n if (authData.byteLength < 53) {\n return {invalidAuthData: null};\n }\n\n const bytes = authData.slice(37, 53);\n\n const result = bytesToAAGUID({bytes});\n\n if ('aaguid' in result) {\n return {aaguidBytes: bytes, aaguidText: result.aaguid};\n }\n\n return {unknownProvider: null};\n};\n\n/**\n * Convert 16 AAGUID bytes to canonical UUID string (lowercase, hyphenated).\n *\n * Returns:\n * - { aaguid } for non-zero AAGUIDs\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidBytes: null } if length \u2260 16\n *\n * @param {{bytes: Uint8Array | number[]}} params\n * @returns {{aaguid: string} | {invalidBytes: null} | {unknownProvider: null}}\n */\nexport const bytesToAAGUID = ({\n bytes\n}: {\n bytes: Uint8Array | number[];\n}): {aaguid: string} | {invalidBytes: null} | {unknownProvider: null} => {\n if (bytes.length !== 16) {\n return {invalidBytes: null};\n }\n\n const hex = (bytes instanceof Uint8Array ? uint8ArrayToArrayOfNumber(bytes) : bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n\n const aaguid = hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n\n // \"00000000-0000-0000-0000-0000000000000\" represents an unknown passkey provider. Some passkey providers use this AAGUID intentionally.\n // Source: https://web.dev/articles/webauthn-aaguid\n if (aaguid === '00000000-0000-0000-0000-000000000000') {\n return {unknownProvider: null};\n }\n\n return {aaguid};\n};\n", "import {DER_COSE_OID, wrapDER, type DerEncodedPublicKey} from '@icp-sdk/core/agent';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn functions not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * From the documentation;\n * The authData is a byte array described in the spec. Parsing it will involve slicing bytes from\n * the array and converting them into usable objects.\n *\n * See https://webauthn.guide/#registration (subsection \"Example: Parsing the authenticator data\").\n * @param authData The authData field of the attestation response.\n * @returns The COSE key of the authData.\n */\nexport function _authDataToCose(authData: Uint8Array): Uint8Array {\n const dataView = new DataView(new ArrayBuffer(2));\n const idLenBytes = authData.slice(53, 55);\n [...new Uint8Array(idLenBytes)].forEach((v, i) => dataView.setUint8(i, v));\n const credentialIdLength = dataView.getUint16(0);\n\n // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\n\nexport function _coseToDerEncodedBlob(cose: Uint8Array): DerEncodedPublicKey {\n return wrapDER(cose, DER_COSE_OID) as DerEncodedPublicKey;\n}\n", "import type {DerEncodedPublicKey} from '@icp-sdk/core/agent';\nimport type {PublicKeyWithToRaw} from '../types/identity';\nimport {_coseToDerEncodedBlob} from './cose-utils';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn classes not exposed by Agent-js\n * extended with mandatory toRaw() and encodedKey made private.\n * It is therefore not covered by that many tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * COSE-encoded key (CBOR Object Signing and Encryption).\n * serialized as a Uint8Array.\n */\nexport type CoseEncodedKey = Uint8Array;\n\nexport class CosePublicKey implements PublicKeyWithToRaw {\n readonly #encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: CoseEncodedKey) {\n this.#encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.#encodedKey;\n }\n\n public toRaw(): Uint8Array {\n return new Uint8Array(this.#encodedKey); // Strip __derEncodedPublicKey__\n }\n}\n", "import {uint8ArrayToBase64} from '@dfinity/utils';\nimport {extractAAGUID} from './aaguid';\nimport {type CoseEncodedKey, CosePublicKey} from './agent-js/cose-key';\nimport type {PublicKeyWithToRaw} from './types/identity';\n\n/**\n * Arguments to initialize a WebAuthn object.\n */\nexport interface InitWebAuthnCredentialArgs {\n /**\n * The credential ID (authenticator\u2019s `rawId`) as bytes.\n */\n rawId: Uint8Array;\n\n /**\n * COSE-encoded public key extracted from attestation/authData.\n */\n cose: CoseEncodedKey;\n}\n\nexport interface InitWebAuthnNewCredentialArgs extends InitWebAuthnCredentialArgs {\n /**\n * The authenticator data from the attestation.\n */\n authData: Uint8Array;\n}\n\n/**\n * A wrapper around a WebAuthn credential that provides various base information such as its ID or public key.\n */\nexport abstract class WebAuthnCredential {\n readonly #credentialId: Uint8Array;\n readonly #publicKey: CosePublicKey;\n\n /**\n * @param args - {@link InitWebAuthnCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n */\n constructor({rawId: credentialId, cose}: InitWebAuthnCredentialArgs) {\n this.#credentialId = credentialId;\n this.#publicKey = new CosePublicKey(cose);\n }\n\n /**\n * Returns the public key for this credential.\n */\n getPublicKey(): PublicKeyWithToRaw {\n return this.#publicKey;\n }\n\n /**\n * Returns the credential ID as bytes.\n */\n getCredentialId(): Uint8Array {\n return this.#credentialId;\n }\n\n /**\n * Returns the credential ID as textual representation (a base64 string).\n */\n getCredentialIdText(): string {\n return uint8ArrayToBase64(this.#credentialId);\n }\n}\n\n/**\n * A wrapper around a newly created WebAuthn credential.\n * It is created using `navigator.credentials.create` which provides an attestation.\n */\nexport class WebAuthnNewCredential extends WebAuthnCredential {\n readonly #aaguidText: string | undefined;\n readonly #aaguidBytes: Uint8Array | undefined;\n\n /**\n * @param args - {@link InitWebAuthnNewCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n * @params args.authData - Authenticator data from the attestation.\n */\n constructor({authData, ...rest}: InitWebAuthnNewCredentialArgs) {\n super(rest);\n\n const optionAaguid = extractAAGUID({authData});\n this.#aaguidText = 'aaguidText' in optionAaguid ? optionAaguid.aaguidText : undefined;\n this.#aaguidBytes = 'aaguidBytes' in optionAaguid ? optionAaguid.aaguidBytes : undefined;\n }\n\n /**\n * Returns AAGUID (Authenticator Attestation GUID).\n */\n getAAGUID(): Uint8Array | undefined {\n return this.#aaguidBytes;\n }\n\n /**\n * Returns the textual representation of the AAGUID (Authenticator Attestation GUID).\n */\n getAAGUIDText(): string | undefined {\n return this.#aaguidText;\n }\n}\n\n/**\n * A wrapper around a retrieval of existing WebAuthn credential.\n * It is created using `navigator.credentials.get` which provides an assertion.\n */\nexport class WebAuthnExistingCredential extends WebAuthnCredential {}\n", "export class WebAuthnIdentityHostnameError extends Error {}\nexport class WebAuthnIdentityCredentialNotInitializedError extends Error {}\nexport class WebAuthnIdentityCreateCredentialOnTheDeviceError extends Error {}\nexport class WebAuthnIdentityCredentialNotPublicKeyError extends Error {}\nexport class WebAuthnIdentityNoAttestationError extends Error {}\nexport class WebAuthnIdentityInvalidCredentialIdError extends Error {}\nexport class WebAuthnIdentityEncodeCborSignatureError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/authenticatorData\nexport class WebAuthnIdentityNoAuthenticatorDataError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/signature\nexport class WebAuthnIdentityNoSignatureError extends Error {}\n", "import {arrayBufferToUint8Array, isNullish, uint8ArraysEqual} from '@dfinity/utils';\nimport {Cbor, type Signature, SignIdentity} from '@icp-sdk/core/agent';\nimport {AUTHENTICATOR_ABORT_TIMEOUT} from './_constants';\nimport {createPasskeyOptions, retrievePasskeyOptions} from './_options';\nimport {execute} from './_progress';\nimport {_authDataToCose} from './agent-js/cose-utils';\nimport {\n type InitWebAuthnNewCredentialArgs,\n type WebAuthnCredential,\n WebAuthnExistingCredential,\n WebAuthnNewCredential\n} from './credential';\nimport {\n WebAuthnIdentityCreateCredentialOnTheDeviceError,\n WebAuthnIdentityCredentialNotInitializedError,\n WebAuthnIdentityCredentialNotPublicKeyError,\n WebAuthnIdentityEncodeCborSignatureError,\n WebAuthnIdentityInvalidCredentialIdError,\n WebAuthnIdentityNoAttestationError,\n WebAuthnIdentityNoAuthenticatorDataError\n} from './errors';\nimport type {\n AuthenticatorOptions,\n CreateWebAuthnIdentityWithExistingCredentialArgs,\n CreateWebAuthnIdentityWithNewCredentialArgs,\n PublicKeyWithToRaw,\n RetrievePublicKeyFn\n} from './types/identity';\nimport type {PasskeyOptions} from './types/passkey';\nimport {\n type WebAuthnSignProgressArgs,\n type WebAuthnSignProgressFn,\n WebAuthnSignProgressStep\n} from './types/progress';\n\ntype PublicKeyCredentialWithAttachment = Omit<PublicKeyCredential, 'response'> & {\n response: AuthenticatorAssertionResponse & {\n attestationObject?: ArrayBuffer;\n };\n};\n\nconst createAbortSignal = ({\n timeout\n}: Pick<AuthenticatorOptions<PasskeyOptions>, 'timeout'>): AbortSignal =>\n AbortSignal.timeout(timeout ?? AUTHENTICATOR_ABORT_TIMEOUT);\n\nconst retrieveCredentials = async ({\n challenge,\n credentialIds,\n passkeyOptions,\n timeout\n}: {\n challenge: Uint8Array;\n credentialIds?: Uint8Array[];\n} & AuthenticatorOptions<PasskeyOptions>): Promise<Credential | null> =>\n await navigator.credentials.get({\n publicKey: {\n ...retrievePasskeyOptions(passkeyOptions),\n challenge: challenge.buffer as BufferSource,\n allowCredentials: (credentialIds ?? []).map((id) => ({\n id: id.buffer as BufferSource,\n type: 'public-key'\n }))\n },\n signal: createAbortSignal({timeout})\n });\n\ntype WebAuthnState<T extends WebAuthnCredential> =\n | {status: 'pending'; retrievePublicKey: RetrievePublicKeyFn}\n | {status: 'initialized'; credential: T};\n\nconst assertWebAuthnStateInitialized: <T extends WebAuthnCredential>(\n state: WebAuthnState<T>\n) => asserts state is {\n status: 'initialized';\n credential: T;\n} = <T extends WebAuthnCredential>(state: WebAuthnState<T>): void => {\n if (state.status !== 'initialized') {\n throw new WebAuthnIdentityCredentialNotInitializedError();\n }\n};\n\nconst assertNonNullishCredential: (\n credential: Credential | null\n) => asserts credential is Credential = (credential: Credential | null): void => {\n if (isNullish(credential)) {\n throw new WebAuthnIdentityCreateCredentialOnTheDeviceError();\n }\n};\n\nconst assertCredentialPublicKey: (\n credential: Credential\n) => asserts credential is PublicKeyCredentialWithAttachment = ({type}: Credential): void => {\n if (type !== 'public-key') {\n throw new WebAuthnIdentityCredentialNotPublicKeyError();\n }\n};\n\n/**\n * A signing identity for the Internet Computer, backed by a WebAuthn credential.\n *\n * Use one of the factory methods to construct an instance:\n * - {@link WebAuthnIdentity.createWithNewCredential} to create a new passkey on the device.\n * - {@link WebAuthnIdentity.createWithExistingCredential} to use an existing passkey.\n *\n * @template T Concrete credential type for this identity\n * ({@link WebAuthnNewCredential} or {@link WebAuthnExistingCredential}).\n */\nexport class WebAuthnIdentity<T extends WebAuthnCredential> extends SignIdentity {\n readonly #onSignProgress: WebAuthnSignProgressFn | undefined;\n #state: WebAuthnState<T>;\n\n /**\n * @hidden Use the factory methods instead.\n *\n * Initializes the identity in either:\n * - **pending** state (existing-credential path; public key not yet known), or\n * - **initialized** state (new-credential path; public key known immediately).\n *\n * @private\n */\n private constructor({\n onProgress,\n ...args\n }: WebAuthnSignProgressArgs &\n (\n | InitWebAuthnNewCredentialArgs\n | Pick<CreateWebAuthnIdentityWithExistingCredentialArgs, 'retrievePublicKey'>\n )) {\n super();\n\n this.#onSignProgress = onProgress;\n\n if ('retrievePublicKey' in args) {\n const {retrievePublicKey} = args;\n\n this.#state = {\n status: 'pending',\n retrievePublicKey\n };\n\n return;\n }\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnNewCredential(args)\n });\n }\n\n static #createInitializedState<T extends WebAuthnCredential>({\n credential\n }: {\n credential: WebAuthnNewCredential | WebAuthnExistingCredential;\n }): WebAuthnState<T> {\n return {\n status: 'initialized',\n credential: credential as T\n };\n }\n\n /**\n * Creates a new passkey on the device and returns an initialized identity.\n *\n * If you chain `create` and `sign`, the user will be prompted twice to authenticate\n * with their authenticator. You can track progress via the `onProgress` callback.\n *\n * @param args {@link CreateWebAuthnIdentityWithNewCredentialArgs} Options to create the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnNewCredential}.\n */\n static async createWithNewCredential({\n passkeyOptions,\n timeout,\n ...restArgs\n }: CreateWebAuthnIdentityWithNewCredentialArgs = {}): Promise<\n WebAuthnIdentity<WebAuthnNewCredential>\n > {\n const credential = await navigator.credentials.create({\n publicKey: createPasskeyOptions(passkeyOptions),\n signal: createAbortSignal({timeout})\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n const {\n response: {attestationObject},\n rawId\n } = credential;\n\n if (isNullish(attestationObject)) {\n throw new WebAuthnIdentityNoAttestationError();\n }\n\n // We have to parse the attestationObject as CBOR to ultimately retrieve the public key.\n // Similar as what's implemented in AgentJS.\n const {authData} = Cbor.decode<{authData: Uint8Array}>(\n arrayBufferToUint8Array(attestationObject)\n );\n\n const cose = _authDataToCose(authData);\n\n return new WebAuthnIdentity<WebAuthnNewCredential>({\n ...restArgs,\n rawId: arrayBufferToUint8Array(rawId),\n cose,\n authData\n });\n }\n\n /**\n * Creates an identity for an existing passkey.\n *\n * @param args {@link CreateWebAuthnIdentityWithExistingCredentialArgs} Options to retrieve the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnExistingCredential}.\n */\n // We use async for consistency reason and because it might be future prone.\n // eslint-disable-next-line require-await\n static async createWithExistingCredential(\n args: CreateWebAuthnIdentityWithExistingCredentialArgs\n ): Promise<WebAuthnIdentity<WebAuthnExistingCredential>> {\n return new WebAuthnIdentity<WebAuthnExistingCredential>(args);\n }\n\n /**\n * Returns the credential\u2019s public key.\n *\n * @returns {PublicKey}\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n override getPublicKey(): PublicKeyWithToRaw {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential.getPublicKey();\n }\n\n /**\n * Returns the concrete credential wrapper for this identity.\n *\n * For identities created with:\n * - `createWithNewCredential` \u2192 {@link WebAuthnNewCredential}\n * - `createWithExistingCredential` \u2192 {@link WebAuthnExistingCredential}\n *\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n getCredential(): T {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential;\n }\n\n /**\n * Signs an arbitrary blob using the platform authenticator.\n *\n * @param blob Bytes to sign (used as the WebAuthn challenge).\n * @returns {Promise<Signature>} CBOR-encoded signature payload.\n */\n override async sign(blob: Uint8Array): Promise<Signature> {\n // 1. Request user credential (navigator.credentials.get)\n const requestCredential = async (): Promise<PublicKeyCredential> => {\n const credential = await retrieveCredentials({\n challenge: blob,\n ...(this.#state.status === 'initialized' && {\n credentialIds: [this.#state.credential.getCredentialId()]\n })\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n return credential;\n };\n\n const credential = await execute({\n fn: requestCredential,\n step: WebAuthnSignProgressStep.RequestingUserCredential,\n onProgress: this.#onSignProgress\n });\n\n // 2. Assert credential ID if already initialized or load public key from backend and init state\n const finalizingCredential = async () => {\n const {rawId} = credential;\n\n // If the state was already initialized - credentials.create - then we \"only\"\n // assert that the rawId retrieved by credentials.get is equals to the one already known.\n if (this.#state.status === 'initialized') {\n if (\n !uint8ArraysEqual({\n a: this.#state.credential.getCredentialId(),\n b: arrayBufferToUint8Array(rawId)\n })\n ) {\n throw new WebAuthnIdentityInvalidCredentialIdError();\n }\n\n return;\n }\n\n // If the state was pending, we need to retrieve the public key for the credential\n // that was saved during a previous sign-up\n // because credentials.get does not provide an attestation.\n const {retrievePublicKey} = this.#state;\n\n const cose = await retrievePublicKey({\n credentialId: arrayBufferToUint8Array(rawId)\n });\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnExistingCredential({\n rawId: arrayBufferToUint8Array(rawId),\n cose\n })\n });\n };\n\n await execute({\n fn: finalizingCredential,\n step: WebAuthnSignProgressStep.FinalizingCredential,\n onProgress: this.#onSignProgress\n });\n\n // 3. Sign the request\n // eslint-disable-next-line require-await\n const encodeSignature = async (): Promise<Signature> => {\n const {response} = credential;\n\n const {clientDataJSON} = response;\n\n // Only the response of type AuthenticatorAssertionResponse provides authenticatorData and signature\n // which is the type of response we are expecting.\n const {authenticatorData, signature} =\n 'authenticatorData' in response && 'signature' in response\n ? (response as AuthenticatorAssertionResponse)\n : {};\n\n if (isNullish(authenticatorData)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n if (isNullish(signature)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n const encoded = Cbor.encode({\n authenticator_data: authenticatorData,\n client_data_json: new TextDecoder().decode(clientDataJSON),\n signature: arrayBufferToUint8Array(signature)\n });\n\n if (isNullish(encoded)) {\n throw new WebAuthnIdentityEncodeCborSignatureError();\n }\n\n // Similar as AgentJS code.\n Object.assign(encoded, {\n __signature__: undefined\n });\n\n return encoded as Signature;\n };\n\n return await execute({\n fn: encodeSignature,\n step: WebAuthnSignProgressStep.Signing,\n onProgress: this.#onSignProgress\n });\n }\n}\n", "// See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for a complete\n// list of these algorithms. We only list the ones we support here.\n//\n// According Google tutorial, https://web.dev/articles/passkey-registration, specifying\n// support for ECDSA with P-256 (-7) and RSA PKCS#1 (-257) gives complete coverage.\nexport const PUBLIC_KEY_COSE_ALGORITHMS = {\n ECDSA_WITH_SHA256: -7,\n RSA_WITH_SHA256: -257\n};\n\nexport const AUTHENTICATOR_ABORT_TIMEOUT = 60000;\n", "import {PUBLIC_KEY_COSE_ALGORITHMS} from './_constants';\nimport {WebAuthnIdentityHostnameError} from './errors';\nimport type {CreatePasskeyOptions, PasskeyOptions} from './types/passkey';\n\nconst randomValue = (): BufferSource => window.crypto.getRandomValues(new Uint8Array(16));\n\n/**\n * When creating a passkey, the challenge can simply be a random value.\n * Since the server doesn\u2019t need to verify the authenticity of the key,\n * it doesn\u2019t have to generate the challenge itself.\n *\n * In contrast, when signing a request with our credentials,\n * the request itself becomes the data (blob), the challenge, that must be signed.\n */\nconst createChallenge = (): BufferSource => randomValue();\n\n/**\n * The user ID is set to a random value, which holds little relevance\n * for the end user beyond being unique.\n *\n * Ultimately, once signed in, the user's actual identifier will be\n * the public key (principal) of the identity used to interact with the IC.\n */\nconst createUserId = (): BufferSource => randomValue();\n\nconst hostname = (): string => {\n const {\n location: {href}\n } = window;\n\n try {\n const {hostname} = new URL(href);\n return hostname;\n } catch {\n throw new WebAuthnIdentityHostnameError();\n }\n};\n\nconst relyingPartyId = ({appId}: Pick<PasskeyOptions, 'appId'>): string => appId?.id ?? hostname();\n\nexport const createPasskeyOptions = ({\n appId,\n user: userOptions\n}: CreatePasskeyOptions = {}): PublicKeyCredentialCreationOptions => {\n const {\n document: {title: name}\n } = window;\n\n const relyingParty = (): Pick<PublicKeyCredentialCreationOptions, 'rp'> => ({\n rp: {\n // Note: deprecated in WebAuthn L3\n name: appId?.name ?? name,\n id: relyingPartyId({appId})\n }\n });\n\n const user = (): Pick<PublicKeyCredentialCreationOptions, 'user'> => ({\n user: {\n id: createUserId(),\n name: userOptions?.name ?? userOptions?.displayName ?? name,\n displayName: userOptions?.displayName ?? name\n }\n });\n\n return {\n // We want to receive the attestation statement as generated by the authenticator\n attestation: 'direct',\n challenge: createChallenge(),\n ...relyingParty(),\n ...user(),\n pubKeyCredParams: Object.values(PUBLIC_KEY_COSE_ALGORITHMS).map((algorithm) => ({\n type: 'public-key',\n alg: algorithm\n })),\n excludeCredentials: [],\n authenticatorSelection: {\n // At least for now, we want a simplified flow and therefore indicates that we want a\n // platform authenticator ((an authenticator embedded to the platform device).\n authenticatorAttachment: 'platform',\n userVerification: 'preferred',\n // Along with requireResidentKey, make passkey discoverable,\n residentKey: 'required',\n requireResidentKey: true\n }\n };\n};\n\nexport const retrievePasskeyOptions = (\n options: PasskeyOptions = {}\n): Omit<PublicKeyCredentialRequestOptions, 'challenge'> => ({\n rpId: relyingPartyId(options),\n allowCredentials: [],\n userVerification: 'required'\n});\n", "import type {WebAuthnSignProgress, WebAuthnSignProgressArgs} from './types/progress';\n\nexport const execute = async <T>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n} & Pick<WebAuthnSignProgress, 'step'> &\n WebAuthnSignProgressArgs): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "/**\n * Progress steps in the WebAuthn signing flow.\n */\nexport enum WebAuthnSignProgressStep {\n /** Calling `navigator.credentials.get` to obtain an assertion. */\n RequestingUserCredential,\n /** Verifying/initializing the credential (e.g., ID match, loading public key). */\n FinalizingCredential,\n /** Producing the signature and encoding the result. */\n Signing\n}\n\n/**\n * Status of the current step.\n */\nexport type WebAuthnSignProgressState = 'in_progress' | 'success' | 'error';\n\n/**\n * Payload emitted on progress updates.\n */\nexport interface WebAuthnSignProgress {\n /** The step being executed. */\n step: WebAuthnSignProgressStep;\n /** State of that step. */\n state: WebAuthnSignProgressState;\n}\n\n/**\n * Callback invoked on each progress update.\n */\nexport type WebAuthnSignProgressFn = (progress: WebAuthnSignProgress) => void;\n\n/**\n * Optional handler for progress updates.\n */\nexport interface WebAuthnSignProgressArgs {\n onProgress?: WebAuthnSignProgressFn;\n}\n", "import {nonNullish} from '@dfinity/utils';\n\n/**\n * Checks if a user-verifying platform authenticator (passkeys) is available on this device / browser.\n *\n * Returns `true` when:\n * 1) `window.PublicKeyCredential` exists, and\n * 2) the browser reports a user-verifying **platform** authenticator is available\n * (e.g., Touch ID, Windows Hello, Android biometrics/PIN).\n *\n * @returns {Promise<boolean>} `true` if an authenticator is available, otherwise `false`.\n */\nexport const isWebAuthnAvailable = async (): Promise<boolean> => {\n if (\n nonNullish(window.PublicKeyCredential) &&\n 'isUserVerifyingPlatformAuthenticatorAvailable' in PublicKeyCredential\n ) {\n return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n};\n"],
5
- "mappings": "AAAA,OAAQ,6BAAAA,MAAgC,iBAwBjC,IAAMC,EAAgB,CAAC,CAC5B,SAAAC,CACF,IAK+B,CAC7B,GAAIA,EAAS,WAAa,GACxB,MAAO,CAAC,gBAAiB,IAAI,EAG/B,GAAIA,EAAS,WAAa,GACxB,MAAO,CAAC,gBAAiB,IAAI,EAG/B,IAAMC,EAAQD,EAAS,MAAM,GAAI,EAAE,EAE7BE,EAASC,EAAc,CAAC,MAAAF,CAAK,CAAC,EAEpC,MAAI,WAAYC,EACP,CAAC,YAAaD,EAAO,WAAYC,EAAO,MAAM,EAGhD,CAAC,gBAAiB,IAAI,CAC/B,EAaaC,EAAgB,CAAC,CAC5B,MAAAF,CACF,IAEyE,CACvE,GAAIA,EAAM,SAAW,GACnB,MAAO,CAAC,aAAc,IAAI,EAO5B,IAAMG,GAJOH,aAAiB,WAAaH,EAA0BG,CAAK,EAAIA,GAC3E,IAAKI,GAASA,EAAK,SA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,CAAiB,EAAI,KAAKH,GAE3Bc,EAAO,MAAMX,EAAkB,CACnC,aAAcU,EAAwBJ,CAAK,CAC7C,CAAC,EAED,KAAKT,GAASH,EAAiBO,GAAwB,CACrD,WAAY,IAAIgB,EAA2B,CACzC,MAAOP,EAAwBJ,CAAK,EACpC,KAAAK,CACF,CAAC,CACH,CAAC,CACH,EAIE,OACA,WAAY,KAAKf,EACnB,CAAC,EA0CM,MAAMkB,EAAQ,CACnB,GAvCsB,SAAgC,CACtD,GAAM,CAAC,SAAAI,CAAQ,EAAI/B,EAEb,CAAC,eAAAgC,CAAc,EAAID,EAInB,CAAC,kBAAAE,EAAmB,UAAAC,CAAS,EACjC,sBAAuBH,GAAY,cAAeA,EAC7CA,EACD,CAAC,EAEP,GAAI9B,EAAUgC,CAAiB,EAC7B,MAAM,IAAIE,EAGZ,GAAIlC,EAAUiC,CAAS,EACrB,MAAM,IAAIC,EAGZ,IAAMC,EAAUd,EAAK,OAAO,CAC1B,mBAAoBW,EACpB,iBAAkB,IAAI,YAAY,EAAE,OAAOD,CAAc,EACzD,UAAWT,EAAwBW,CAAS,CAC9C,CAAC,EAED,GAAIjC,EAAUmC,CAAO,EACnB,MAAM,IAAIC,EAIZ,cAAO,OAAOD,EAAS,CACrB,cAAe,MACjB,CAAC,EAEMA,CACT,EAIE,OACA,WAAY,KAAK3B,EACnB,CAAC,CACH,CACF,EKpXA,OAAQ,cAAA6B,OAAiB,iBAYlB,IAAMC,GAAsB,SAE/BD,GAAW,OAAO,mBAAmB,GACrC,kDAAmD,oBAE5C,MAAM,oBAAoB,8CAA8C,EAG1E",
6
- "names": ["uint8ArrayToArrayOfNumber", "extractAAGUID", "authData", "bytes", "result", "bytesToAAGUID", "aaguid", "byte", "DER_COSE_OID", "wrapDER", "_authDataToCose", "authData", "dataView", "idLenBytes", "v", "i", "credentialIdLength", "_coseToDerEncodedBlob", "cose", "CosePublicKey", "_cose", "#encodedKey", "_coseToDerEncodedBlob", "uint8ArrayToBase64", "WebAuthnCredential", "#credentialId", "#publicKey", "credentialId", "cose", "CosePublicKey", "uint8ArrayToBase64", "WebAuthnNewCredential", "#aaguidText", "#aaguidBytes", "authData", "rest", "optionAaguid", "extractAAGUID", "WebAuthnExistingCredential", "WebAuthnIdentityHostnameError", "WebAuthnIdentityCredentialNotInitializedError", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentityNoAttestationError", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnIdentityEncodeCborSignatureError", "WebAuthnIdentityNoAuthenticatorDataError", "WebAuthnIdentityNoSignatureError", "arrayBufferToUint8Array", "isNullish", "uint8ArraysEqual", "Cbor", "SignIdentity", "PUBLIC_KEY_COSE_ALGORITHMS", "AUTHENTICATOR_ABORT_TIMEOUT", "randomValue", "createChallenge", "createUserId", "hostname", "href", "WebAuthnIdentityHostnameError", "relyingPartyId", "appId", "createPasskeyOptions", "userOptions", "name", "relyingParty", "user", "PUBLIC_KEY_COSE_ALGORITHMS", "algorithm", "retrievePasskeyOptions", "options", "execute", "fn", "step", "onProgress", "result", "err", "WebAuthnSignProgressStep", "createAbortSignal", "timeout", "AUTHENTICATOR_ABORT_TIMEOUT", "retrieveCredentials", "challenge", "credentialIds", "passkeyOptions", "retrievePasskeyOptions", "id", "assertWebAuthnStateInitialized", "state", "WebAuthnIdentityCredentialNotInitializedError", "assertNonNullishCredential", "credential", "isNullish", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "assertCredentialPublicKey", "type", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentity", "_WebAuthnIdentity", "SignIdentity", "#onSignProgress", "#state", "onProgress", "args", "retrievePublicKey", "#createInitializedState", "WebAuthnNewCredential", "restArgs", "createPasskeyOptions", "attestationObject", "rawId", "WebAuthnIdentityNoAttestationError", "authData", "Cbor", "arrayBufferToUint8Array", "cose", "_authDataToCose", "blob", "execute", "uint8ArraysEqual", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnExistingCredential", "response", "clientDataJSON", "authenticatorData", "signature", "WebAuthnIdentityNoAuthenticatorDataError", "encoded", "WebAuthnIdentityEncodeCborSignatureError", "nonNullish", "isWebAuthnAvailable"]
4
+ "sourcesContent": ["import {uint8ArrayToArrayOfNumber} from '@junobuild/utils';\n\n/**\n * Extracts the AAGUID (Authenticator Attestation GUID) from a WebAuthn data buffer.\n *\n * The AAGUID is a 16-byte value located at offsets 37..53 within `authenticatorData`\n * when **attested credential data** is present (i.e., during registration/attestation).\n *\n * For assertion (sign-in) responses, `authenticatorData` is typically 37 bytes and\n * does not include an AAGUID.\n *\n * If the extracted value is all zeros (`00000000-0000-0000-0000-000000000000`),\n * this function returns `{ unknownProvider: null }` since some passkey providers\n * intentionally use a zero AAGUID.\n *\n * @param {Object} params\n * @param {Uint8Array} params.authData - The WebAuthn `authenticatorData` bytes.\n * @returns {{aaguid: string; bytes: Uint8Array} | {invalidAuthData: null} | {unknownProvider: null}}\n * - { aaguidText, aaguidBytes } for valid AAGUID\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidAuthData: null } if `authData` is invalid (too short, too long, etc.)\n *\n * @see https://web.dev/articles/webauthn-aaguid\n */\nexport const extractAAGUID = ({\n authData\n}: {\n authData: Uint8Array;\n}):\n | {aaguidText: string; aaguidBytes: Uint8Array}\n | {invalidAuthData: null}\n | {unknownProvider: null} => {\n if (authData.byteLength < 37) {\n return {invalidAuthData: null};\n }\n\n if (authData.byteLength < 53) {\n return {invalidAuthData: null};\n }\n\n const bytes = authData.slice(37, 53);\n\n const result = bytesToAAGUID({bytes});\n\n if ('aaguid' in result) {\n return {aaguidBytes: bytes, aaguidText: result.aaguid};\n }\n\n return {unknownProvider: null};\n};\n\n/**\n * Convert 16 AAGUID bytes to canonical UUID string (lowercase, hyphenated).\n *\n * Returns:\n * - { aaguid } for non-zero AAGUIDs\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidBytes: null } if length \u2260 16\n *\n * @param {{bytes: Uint8Array | number[]}} params\n * @returns {{aaguid: string} | {invalidBytes: null} | {unknownProvider: null}}\n */\nexport const bytesToAAGUID = ({\n bytes\n}: {\n bytes: Uint8Array | number[];\n}): {aaguid: string} | {invalidBytes: null} | {unknownProvider: null} => {\n if (bytes.length !== 16) {\n return {invalidBytes: null};\n }\n\n const hex = (bytes instanceof Uint8Array ? uint8ArrayToArrayOfNumber(bytes) : bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n\n const aaguid = hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n\n // \"00000000-0000-0000-0000-0000000000000\" represents an unknown passkey provider. Some passkey providers use this AAGUID intentionally.\n // Source: https://web.dev/articles/webauthn-aaguid\n if (aaguid === '00000000-0000-0000-0000-000000000000') {\n return {unknownProvider: null};\n }\n\n return {aaguid};\n};\n", "import {DER_COSE_OID, wrapDER, type DerEncodedPublicKey} from '@icp-sdk/core/agent';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn functions not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * From the documentation;\n * The authData is a byte array described in the spec. Parsing it will involve slicing bytes from\n * the array and converting them into usable objects.\n *\n * See https://webauthn.guide/#registration (subsection \"Example: Parsing the authenticator data\").\n * @param authData The authData field of the attestation response.\n * @returns The COSE key of the authData.\n */\nexport function _authDataToCose(authData: Uint8Array): Uint8Array {\n const dataView = new DataView(new ArrayBuffer(2));\n const idLenBytes = authData.slice(53, 55);\n [...new Uint8Array(idLenBytes)].forEach((v, i) => dataView.setUint8(i, v));\n const credentialIdLength = dataView.getUint16(0);\n\n // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\n\nexport function _coseToDerEncodedBlob(cose: Uint8Array): DerEncodedPublicKey {\n return wrapDER(cose, DER_COSE_OID) as DerEncodedPublicKey;\n}\n", "import type {DerEncodedPublicKey} from '@icp-sdk/core/agent';\nimport type {PublicKeyWithToRaw} from '../types/identity';\nimport {_coseToDerEncodedBlob} from './cose-utils';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn classes not exposed by Agent-js\n * extended with mandatory toRaw() and encodedKey made private.\n * It is therefore not covered by that many tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * COSE-encoded key (CBOR Object Signing and Encryption).\n * serialized as a Uint8Array.\n */\nexport type CoseEncodedKey = Uint8Array;\n\nexport class CosePublicKey implements PublicKeyWithToRaw {\n readonly #encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: CoseEncodedKey) {\n this.#encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.#encodedKey;\n }\n\n public toRaw(): Uint8Array {\n return new Uint8Array(this.#encodedKey); // Strip __derEncodedPublicKey__\n }\n}\n", "import {uint8ArrayToBase64} from '@junobuild/utils';\nimport {extractAAGUID} from './aaguid';\nimport {type CoseEncodedKey, CosePublicKey} from './agent-js/cose-key';\nimport type {PublicKeyWithToRaw} from './types/identity';\n\n/**\n * Arguments to initialize a WebAuthn object.\n */\nexport interface InitWebAuthnCredentialArgs {\n /**\n * The credential ID (authenticator\u2019s `rawId`) as bytes.\n */\n rawId: Uint8Array;\n\n /**\n * COSE-encoded public key extracted from attestation/authData.\n */\n cose: CoseEncodedKey;\n}\n\nexport interface InitWebAuthnNewCredentialArgs extends InitWebAuthnCredentialArgs {\n /**\n * The authenticator data from the attestation.\n */\n authData: Uint8Array;\n}\n\n/**\n * A wrapper around a WebAuthn credential that provides various base information such as its ID or public key.\n */\nexport abstract class WebAuthnCredential {\n readonly #credentialId: Uint8Array;\n readonly #publicKey: CosePublicKey;\n\n /**\n * @param args - {@link InitWebAuthnCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n */\n constructor({rawId: credentialId, cose}: InitWebAuthnCredentialArgs) {\n this.#credentialId = credentialId;\n this.#publicKey = new CosePublicKey(cose);\n }\n\n /**\n * Returns the public key for this credential.\n */\n getPublicKey(): PublicKeyWithToRaw {\n return this.#publicKey;\n }\n\n /**\n * Returns the credential ID as bytes.\n */\n getCredentialId(): Uint8Array {\n return this.#credentialId;\n }\n\n /**\n * Returns the credential ID as textual representation (a base64 string).\n */\n getCredentialIdText(): string {\n return uint8ArrayToBase64(this.#credentialId);\n }\n}\n\n/**\n * A wrapper around a newly created WebAuthn credential.\n * It is created using `navigator.credentials.create` which provides an attestation.\n */\nexport class WebAuthnNewCredential extends WebAuthnCredential {\n readonly #aaguidText: string | undefined;\n readonly #aaguidBytes: Uint8Array | undefined;\n\n /**\n * @param args - {@link InitWebAuthnNewCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n * @params args.authData - Authenticator data from the attestation.\n */\n constructor({authData, ...rest}: InitWebAuthnNewCredentialArgs) {\n super(rest);\n\n const optionAaguid = extractAAGUID({authData});\n this.#aaguidText = 'aaguidText' in optionAaguid ? optionAaguid.aaguidText : undefined;\n this.#aaguidBytes = 'aaguidBytes' in optionAaguid ? optionAaguid.aaguidBytes : undefined;\n }\n\n /**\n * Returns AAGUID (Authenticator Attestation GUID).\n */\n getAAGUID(): Uint8Array | undefined {\n return this.#aaguidBytes;\n }\n\n /**\n * Returns the textual representation of the AAGUID (Authenticator Attestation GUID).\n */\n getAAGUIDText(): string | undefined {\n return this.#aaguidText;\n }\n}\n\n/**\n * A wrapper around a retrieval of existing WebAuthn credential.\n * It is created using `navigator.credentials.get` which provides an assertion.\n */\nexport class WebAuthnExistingCredential extends WebAuthnCredential {}\n", "export class WebAuthnIdentityHostnameError extends Error {}\nexport class WebAuthnIdentityCredentialNotInitializedError extends Error {}\nexport class WebAuthnIdentityCreateCredentialOnTheDeviceError extends Error {}\nexport class WebAuthnIdentityCredentialNotPublicKeyError extends Error {}\nexport class WebAuthnIdentityNoAttestationError extends Error {}\nexport class WebAuthnIdentityInvalidCredentialIdError extends Error {}\nexport class WebAuthnIdentityEncodeCborSignatureError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/authenticatorData\nexport class WebAuthnIdentityNoAuthenticatorDataError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/signature\nexport class WebAuthnIdentityNoSignatureError extends Error {}\n", "import {Cbor, type Signature, SignIdentity} from '@icp-sdk/core/agent';\nimport {arrayBufferToUint8Array, isNullish, uint8ArraysEqual} from '@junobuild/utils';\nimport {AUTHENTICATOR_ABORT_TIMEOUT} from './_constants';\nimport {createPasskeyOptions, retrievePasskeyOptions} from './_options';\nimport {execute} from './_progress';\nimport {_authDataToCose} from './agent-js/cose-utils';\nimport {\n type InitWebAuthnNewCredentialArgs,\n type WebAuthnCredential,\n WebAuthnExistingCredential,\n WebAuthnNewCredential\n} from './credential';\nimport {\n WebAuthnIdentityCreateCredentialOnTheDeviceError,\n WebAuthnIdentityCredentialNotInitializedError,\n WebAuthnIdentityCredentialNotPublicKeyError,\n WebAuthnIdentityEncodeCborSignatureError,\n WebAuthnIdentityInvalidCredentialIdError,\n WebAuthnIdentityNoAttestationError,\n WebAuthnIdentityNoAuthenticatorDataError\n} from './errors';\nimport type {\n AuthenticatorOptions,\n CreateWebAuthnIdentityWithExistingCredentialArgs,\n CreateWebAuthnIdentityWithNewCredentialArgs,\n PublicKeyWithToRaw,\n RetrievePublicKeyFn\n} from './types/identity';\nimport type {PasskeyOptions} from './types/passkey';\nimport {\n type WebAuthnSignProgressArgs,\n type WebAuthnSignProgressFn,\n WebAuthnSignProgressStep\n} from './types/progress';\n\ntype PublicKeyCredentialWithAttachment = Omit<PublicKeyCredential, 'response'> & {\n response: AuthenticatorAssertionResponse & {\n attestationObject?: ArrayBuffer;\n };\n};\n\nconst createAbortSignal = ({\n timeout\n}: Pick<AuthenticatorOptions<PasskeyOptions>, 'timeout'>): AbortSignal =>\n AbortSignal.timeout(timeout ?? AUTHENTICATOR_ABORT_TIMEOUT);\n\nconst retrieveCredentials = async ({\n challenge,\n credentialIds,\n passkeyOptions,\n timeout\n}: {\n challenge: Uint8Array;\n credentialIds?: Uint8Array[];\n} & AuthenticatorOptions<PasskeyOptions>): Promise<Credential | null> =>\n await navigator.credentials.get({\n publicKey: {\n ...retrievePasskeyOptions(passkeyOptions),\n challenge: challenge.buffer as BufferSource,\n allowCredentials: (credentialIds ?? []).map((id) => ({\n id: id.buffer as BufferSource,\n type: 'public-key'\n }))\n },\n signal: createAbortSignal({timeout})\n });\n\ntype WebAuthnState<T extends WebAuthnCredential> =\n | {status: 'pending'; retrievePublicKey: RetrievePublicKeyFn}\n | {status: 'initialized'; credential: T};\n\nconst assertWebAuthnStateInitialized: <T extends WebAuthnCredential>(\n state: WebAuthnState<T>\n) => asserts state is {\n status: 'initialized';\n credential: T;\n} = <T extends WebAuthnCredential>(state: WebAuthnState<T>): void => {\n if (state.status !== 'initialized') {\n throw new WebAuthnIdentityCredentialNotInitializedError();\n }\n};\n\nconst assertNonNullishCredential: (\n credential: Credential | null\n) => asserts credential is Credential = (credential: Credential | null): void => {\n if (isNullish(credential)) {\n throw new WebAuthnIdentityCreateCredentialOnTheDeviceError();\n }\n};\n\nconst assertCredentialPublicKey: (\n credential: Credential\n) => asserts credential is PublicKeyCredentialWithAttachment = ({type}: Credential): void => {\n if (type !== 'public-key') {\n throw new WebAuthnIdentityCredentialNotPublicKeyError();\n }\n};\n\n/**\n * A signing identity for the Internet Computer, backed by a WebAuthn credential.\n *\n * Use one of the factory methods to construct an instance:\n * - {@link WebAuthnIdentity.createWithNewCredential} to create a new passkey on the device.\n * - {@link WebAuthnIdentity.createWithExistingCredential} to use an existing passkey.\n *\n * @template T Concrete credential type for this identity\n * ({@link WebAuthnNewCredential} or {@link WebAuthnExistingCredential}).\n */\nexport class WebAuthnIdentity<T extends WebAuthnCredential> extends SignIdentity {\n readonly #onSignProgress: WebAuthnSignProgressFn | undefined;\n #state: WebAuthnState<T>;\n\n /**\n * @hidden Use the factory methods instead.\n *\n * Initializes the identity in either:\n * - **pending** state (existing-credential path; public key not yet known), or\n * - **initialized** state (new-credential path; public key known immediately).\n *\n * @private\n */\n private constructor({\n onProgress,\n ...args\n }: WebAuthnSignProgressArgs &\n (\n | InitWebAuthnNewCredentialArgs\n | Pick<CreateWebAuthnIdentityWithExistingCredentialArgs, 'retrievePublicKey'>\n )) {\n super();\n\n this.#onSignProgress = onProgress;\n\n if ('retrievePublicKey' in args) {\n const {retrievePublicKey} = args;\n\n this.#state = {\n status: 'pending',\n retrievePublicKey\n };\n\n return;\n }\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnNewCredential(args)\n });\n }\n\n static #createInitializedState<T extends WebAuthnCredential>({\n credential\n }: {\n credential: WebAuthnNewCredential | WebAuthnExistingCredential;\n }): WebAuthnState<T> {\n return {\n status: 'initialized',\n credential: credential as T\n };\n }\n\n /**\n * Creates a new passkey on the device and returns an initialized identity.\n *\n * If you chain `create` and `sign`, the user will be prompted twice to authenticate\n * with their authenticator. You can track progress via the `onProgress` callback.\n *\n * @param args {@link CreateWebAuthnIdentityWithNewCredentialArgs} Options to create the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnNewCredential}.\n */\n static async createWithNewCredential({\n passkeyOptions,\n timeout,\n ...restArgs\n }: CreateWebAuthnIdentityWithNewCredentialArgs = {}): Promise<\n WebAuthnIdentity<WebAuthnNewCredential>\n > {\n const credential = await navigator.credentials.create({\n publicKey: createPasskeyOptions(passkeyOptions),\n signal: createAbortSignal({timeout})\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n const {\n response: {attestationObject},\n rawId\n } = credential;\n\n if (isNullish(attestationObject)) {\n throw new WebAuthnIdentityNoAttestationError();\n }\n\n // We have to parse the attestationObject as CBOR to ultimately retrieve the public key.\n // Similar as what's implemented in AgentJS.\n const {authData} = Cbor.decode<{authData: Uint8Array}>(\n arrayBufferToUint8Array(attestationObject)\n );\n\n const cose = _authDataToCose(authData);\n\n return new WebAuthnIdentity<WebAuthnNewCredential>({\n ...restArgs,\n rawId: arrayBufferToUint8Array(rawId),\n cose,\n authData\n });\n }\n\n /**\n * Creates an identity for an existing passkey.\n *\n * @param args {@link CreateWebAuthnIdentityWithExistingCredentialArgs} Options to retrieve the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnExistingCredential}.\n */\n // We use async for consistency reason and because it might be future prone.\n // eslint-disable-next-line require-await\n static async createWithExistingCredential(\n args: CreateWebAuthnIdentityWithExistingCredentialArgs\n ): Promise<WebAuthnIdentity<WebAuthnExistingCredential>> {\n return new WebAuthnIdentity<WebAuthnExistingCredential>(args);\n }\n\n /**\n * Returns the credential\u2019s public key.\n *\n * @returns {PublicKey}\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n override getPublicKey(): PublicKeyWithToRaw {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential.getPublicKey();\n }\n\n /**\n * Returns the concrete credential wrapper for this identity.\n *\n * For identities created with:\n * - `createWithNewCredential` \u2192 {@link WebAuthnNewCredential}\n * - `createWithExistingCredential` \u2192 {@link WebAuthnExistingCredential}\n *\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n getCredential(): T {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential;\n }\n\n /**\n * Signs an arbitrary blob using the platform authenticator.\n *\n * @param blob Bytes to sign (used as the WebAuthn challenge).\n * @returns {Promise<Signature>} CBOR-encoded signature payload.\n */\n override async sign(blob: Uint8Array): Promise<Signature> {\n // 1. Request user credential (navigator.credentials.get)\n const requestCredential = async (): Promise<PublicKeyCredential> => {\n const credential = await retrieveCredentials({\n challenge: blob,\n ...(this.#state.status === 'initialized' && {\n credentialIds: [this.#state.credential.getCredentialId()]\n })\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n return credential;\n };\n\n const credential = await execute({\n fn: requestCredential,\n step: WebAuthnSignProgressStep.RequestingUserCredential,\n onProgress: this.#onSignProgress\n });\n\n // 2. Assert credential ID if already initialized or load public key from backend and init state\n const finalizingCredential = async () => {\n const {rawId} = credential;\n\n // If the state was already initialized - credentials.create - then we \"only\"\n // assert that the rawId retrieved by credentials.get is equals to the one already known.\n if (this.#state.status === 'initialized') {\n if (\n !uint8ArraysEqual({\n a: this.#state.credential.getCredentialId(),\n b: arrayBufferToUint8Array(rawId)\n })\n ) {\n throw new WebAuthnIdentityInvalidCredentialIdError();\n }\n\n return;\n }\n\n // If the state was pending, we need to retrieve the public key for the credential\n // that was saved during a previous sign-up\n // because credentials.get does not provide an attestation.\n const {retrievePublicKey} = this.#state;\n\n const cose = await retrievePublicKey({\n credentialId: arrayBufferToUint8Array(rawId)\n });\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnExistingCredential({\n rawId: arrayBufferToUint8Array(rawId),\n cose\n })\n });\n };\n\n await execute({\n fn: finalizingCredential,\n step: WebAuthnSignProgressStep.FinalizingCredential,\n onProgress: this.#onSignProgress\n });\n\n // 3. Sign the request\n // eslint-disable-next-line require-await\n const encodeSignature = async (): Promise<Signature> => {\n const {response} = credential;\n\n const {clientDataJSON} = response;\n\n // Only the response of type AuthenticatorAssertionResponse provides authenticatorData and signature\n // which is the type of response we are expecting.\n const {authenticatorData, signature} =\n 'authenticatorData' in response && 'signature' in response\n ? (response as AuthenticatorAssertionResponse)\n : {};\n\n if (isNullish(authenticatorData)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n if (isNullish(signature)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n const encoded = Cbor.encode({\n authenticator_data: authenticatorData,\n client_data_json: new TextDecoder().decode(clientDataJSON),\n signature: arrayBufferToUint8Array(signature)\n });\n\n if (isNullish(encoded)) {\n throw new WebAuthnIdentityEncodeCborSignatureError();\n }\n\n // Similar as AgentJS code.\n Object.assign(encoded, {\n __signature__: undefined\n });\n\n return encoded as Signature;\n };\n\n return await execute({\n fn: encodeSignature,\n step: WebAuthnSignProgressStep.Signing,\n onProgress: this.#onSignProgress\n });\n }\n}\n", "// See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for a complete\n// list of these algorithms. We only list the ones we support here.\n//\n// According Google tutorial, https://web.dev/articles/passkey-registration, specifying\n// support for ECDSA with P-256 (-7) and RSA PKCS#1 (-257) gives complete coverage.\nexport const PUBLIC_KEY_COSE_ALGORITHMS = {\n ECDSA_WITH_SHA256: -7,\n RSA_WITH_SHA256: -257\n};\n\nexport const AUTHENTICATOR_ABORT_TIMEOUT = 60000;\n", "import {PUBLIC_KEY_COSE_ALGORITHMS} from './_constants';\nimport {WebAuthnIdentityHostnameError} from './errors';\nimport type {CreatePasskeyOptions, PasskeyOptions} from './types/passkey';\n\nconst randomValue = (): BufferSource => window.crypto.getRandomValues(new Uint8Array(16));\n\n/**\n * When creating a passkey, the challenge can simply be a random value.\n * Since the server doesn\u2019t need to verify the authenticity of the key,\n * it doesn\u2019t have to generate the challenge itself.\n *\n * In contrast, when signing a request with our credentials,\n * the request itself becomes the data (blob), the challenge, that must be signed.\n */\nconst createChallenge = (): BufferSource => randomValue();\n\n/**\n * The user ID is set to a random value, which holds little relevance\n * for the end user beyond being unique.\n *\n * Ultimately, once signed in, the user's actual identifier will be\n * the public key (principal) of the identity used to interact with the IC.\n */\nconst createUserId = (): BufferSource => randomValue();\n\nconst hostname = (): string => {\n const {\n location: {href}\n } = window;\n\n try {\n const {hostname} = new URL(href);\n return hostname;\n } catch {\n throw new WebAuthnIdentityHostnameError();\n }\n};\n\nconst relyingPartyId = ({appId}: Pick<PasskeyOptions, 'appId'>): string => appId?.id ?? hostname();\n\nexport const createPasskeyOptions = ({\n appId,\n user: userOptions\n}: CreatePasskeyOptions = {}): PublicKeyCredentialCreationOptions => {\n const {\n document: {title: name}\n } = window;\n\n const relyingParty = (): Pick<PublicKeyCredentialCreationOptions, 'rp'> => ({\n rp: {\n // Note: deprecated in WebAuthn L3\n name: appId?.name ?? name,\n id: relyingPartyId({appId})\n }\n });\n\n const user = (): Pick<PublicKeyCredentialCreationOptions, 'user'> => ({\n user: {\n id: createUserId(),\n name: userOptions?.name ?? userOptions?.displayName ?? name,\n displayName: userOptions?.displayName ?? name\n }\n });\n\n return {\n // We want to receive the attestation statement as generated by the authenticator\n attestation: 'direct',\n challenge: createChallenge(),\n ...relyingParty(),\n ...user(),\n pubKeyCredParams: Object.values(PUBLIC_KEY_COSE_ALGORITHMS).map((algorithm) => ({\n type: 'public-key',\n alg: algorithm\n })),\n excludeCredentials: [],\n authenticatorSelection: {\n // At least for now, we want a simplified flow and therefore indicates that we want a\n // platform authenticator ((an authenticator embedded to the platform device).\n authenticatorAttachment: 'platform',\n userVerification: 'preferred',\n // Along with requireResidentKey, make passkey discoverable,\n residentKey: 'required',\n requireResidentKey: true\n }\n };\n};\n\nexport const retrievePasskeyOptions = (\n options: PasskeyOptions = {}\n): Omit<PublicKeyCredentialRequestOptions, 'challenge'> => ({\n rpId: relyingPartyId(options),\n allowCredentials: [],\n userVerification: 'required'\n});\n", "import type {WebAuthnSignProgress, WebAuthnSignProgressArgs} from './types/progress';\n\nexport const execute = async <T>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n} & Pick<WebAuthnSignProgress, 'step'> &\n WebAuthnSignProgressArgs): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "/**\n * Progress steps in the WebAuthn signing flow.\n */\nexport enum WebAuthnSignProgressStep {\n /** Calling `navigator.credentials.get` to obtain an assertion. */\n RequestingUserCredential,\n /** Verifying/initializing the credential (e.g., ID match, loading public key). */\n FinalizingCredential,\n /** Producing the signature and encoding the result. */\n Signing\n}\n\n/**\n * Status of the current step.\n */\nexport type WebAuthnSignProgressState = 'in_progress' | 'success' | 'error';\n\n/**\n * Payload emitted on progress updates.\n */\nexport interface WebAuthnSignProgress {\n /** The step being executed. */\n step: WebAuthnSignProgressStep;\n /** State of that step. */\n state: WebAuthnSignProgressState;\n}\n\n/**\n * Callback invoked on each progress update.\n */\nexport type WebAuthnSignProgressFn = (progress: WebAuthnSignProgress) => void;\n\n/**\n * Optional handler for progress updates.\n */\nexport interface WebAuthnSignProgressArgs {\n onProgress?: WebAuthnSignProgressFn;\n}\n", "import {nonNullish} from '@junobuild/utils';\n\n/**\n * Checks if a user-verifying platform authenticator (passkeys) is available on this device / browser.\n *\n * Returns `true` when:\n * 1) `window.PublicKeyCredential` exists, and\n * 2) the browser reports a user-verifying **platform** authenticator is available\n * (e.g., Touch ID, Windows Hello, Android biometrics/PIN).\n *\n * @returns {Promise<boolean>} `true` if an authenticator is available, otherwise `false`.\n */\nexport const isWebAuthnAvailable = async (): Promise<boolean> => {\n if (\n nonNullish(window.PublicKeyCredential) &&\n 'isUserVerifyingPlatformAuthenticatorAvailable' in PublicKeyCredential\n ) {\n return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n};\n"],
5
+ "mappings": "AAAA,OAAQ,6BAAAA,MAAgC,mBAwBjC,IAAMC,EAAgB,CAAC,CAC5B,SAAAC,CACF,IAK+B,CAC7B,GAAIA,EAAS,WAAa,GACxB,MAAO,CAAC,gBAAiB,IAAI,EAG/B,GAAIA,EAAS,WAAa,GACxB,MAAO,CAAC,gBAAiB,IAAI,EAG/B,IAAMC,EAAQD,EAAS,MAAM,GAAI,EAAE,EAE7BE,EAAS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MC,GAAsB,SAE/BD,GAAW,OAAO,mBAAmB,GACrC,kDAAmD,oBAE5C,MAAM,oBAAoB,8CAA8C,EAG1E",
6
+ "names": ["uint8ArrayToArrayOfNumber", "extractAAGUID", "authData", "bytes", "result", "bytesToAAGUID", "aaguid", "byte", "DER_COSE_OID", "wrapDER", "_authDataToCose", "authData", "dataView", "idLenBytes", "v", "i", "credentialIdLength", "_coseToDerEncodedBlob", "cose", "CosePublicKey", "_cose", "#encodedKey", "_coseToDerEncodedBlob", "uint8ArrayToBase64", "WebAuthnCredential", "#credentialId", "#publicKey", "credentialId", "cose", "CosePublicKey", "uint8ArrayToBase64", "WebAuthnNewCredential", "#aaguidText", "#aaguidBytes", "authData", "rest", "optionAaguid", "extractAAGUID", "WebAuthnExistingCredential", "WebAuthnIdentityHostnameError", "WebAuthnIdentityCredentialNotInitializedError", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentityNoAttestationError", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnIdentityEncodeCborSignatureError", "WebAuthnIdentityNoAuthenticatorDataError", "WebAuthnIdentityNoSignatureError", "Cbor", "SignIdentity", "arrayBufferToUint8Array", "isNullish", "uint8ArraysEqual", "PUBLIC_KEY_COSE_ALGORITHMS", "AUTHENTICATOR_ABORT_TIMEOUT", "randomValue", "createChallenge", "createUserId", "hostname", "href", "WebAuthnIdentityHostnameError", "relyingPartyId", "appId", "createPasskeyOptions", "userOptions", "name", "relyingParty", "user", "PUBLIC_KEY_COSE_ALGORITHMS", "algorithm", "retrievePasskeyOptions", "options", "execute", "fn", "step", "onProgress", "result", "err", "WebAuthnSignProgressStep", "createAbortSignal", "timeout", "AUTHENTICATOR_ABORT_TIMEOUT", "retrieveCredentials", "challenge", "credentialIds", "passkeyOptions", "retrievePasskeyOptions", "id", "assertWebAuthnStateInitialized", "state", "WebAuthnIdentityCredentialNotInitializedError", "assertNonNullishCredential", "credential", "isNullish", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "assertCredentialPublicKey", "type", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentity", "_WebAuthnIdentity", "SignIdentity", "#onSignProgress", "#state", "onProgress", "args", "retrievePublicKey", "#createInitializedState", "WebAuthnNewCredential", "restArgs", "createPasskeyOptions", "attestationObject", "rawId", "WebAuthnIdentityNoAttestationError", "authData", "Cbor", "arrayBufferToUint8Array", "cose", "_authDataToCose", "blob", "execute", "uint8ArraysEqual", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnExistingCredential", "response", "clientDataJSON", "authenticatorData", "signature", "WebAuthnIdentityNoAuthenticatorDataError", "encoded", "WebAuthnIdentityEncodeCborSignatureError", "nonNullish", "isWebAuthnAvailable"]
7
7
  }
package/webauthn.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import { createRequire as topLevelCreateRequire } from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
- import{uint8ArrayToArrayOfNumber as H}from"@dfinity/utils";var I=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),n=K({bytes:t});return"aaguid"in n?{aaguidBytes:t,aaguidText:n.aaguid}:{unknownProvider:null}},K=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let n=(e instanceof Uint8Array?H(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return n==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:n}};import{DER_COSE_OID as V,wrapDER as j}from"@icp-sdk/core/agent";function S(e){let t=new DataView(new ArrayBuffer(2)),n=e.slice(53,55);[...new Uint8Array(n)].forEach((a,s)=>t.setUint8(s,a));let r=t.getUint16(0);return e.slice(55+r)}function U(e){return j(e,V)}var y=class{constructor(t){this._cose=t;this.#t=U(t)}#t;toDer(){return this.#t}toRaw(){return new Uint8Array(this.#t)}};import{uint8ArrayToBase64 as $}from"@dfinity/utils";var p=class{#t;#e;constructor({rawId:t,cose:n}){this.#t=t,this.#e=new y(n)}getPublicKey(){return this.#e}getCredentialId(){return this.#t}getCredentialIdText(){return $(this.#t)}},h=class extends p{#t;#e;constructor({authData:t,...n}){super(n);let r=I({authData:t});this.#t="aaguidText"in r?r.aaguidText:void 0,this.#e="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#e}getAAGUIDText(){return this.#t}},g=class extends p{};var A=class extends Error{},b=class extends Error{},f=class extends Error{},m=class extends Error{},C=class extends Error{},P=class extends Error{},w=class extends Error{},l=class extends Error{},E=class extends Error{};import{arrayBufferToUint8Array as d,isNullish as u,uint8ArraysEqual as Q}from"@dfinity/utils";import{Cbor as N,SignIdentity as X}from"@icp-sdk/core/agent";var O={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},v=6e4;var k=()=>window.crypto.getRandomValues(new Uint8Array(16)),M=()=>k(),Y=()=>k(),J=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new A}},D=({appId:e})=>e?.id??J(),R=({appId:e,user:t}={})=>{let{document:{title:n}}=window,r=()=>({rp:{name:e?.name??n,id:D({appId:e})}}),a=()=>({user:{id:Y(),name:t?.name??t?.displayName??n,displayName:t?.displayName??n}});return{attestation:"direct",challenge:M(),...r(),...a(),pubKeyCredParams:Object.values(O).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},_=(e={})=>({rpId:D(e),allowCredentials:[],userVerification:"required"});var x=async({fn:e,step:t,onProgress:n})=>{n?.({step:t,state:"in_progress"});try{let r=await e();return n?.({step:t,state:"success"}),r}catch(r){throw n?.({step:t,state:"error"}),r}};var B=(r=>(r[r.RequestingUserCredential=0]="RequestingUserCredential",r[r.FinalizingCredential=1]="FinalizingCredential",r[r.Signing=2]="Signing",r))(B||{});var G=({timeout:e})=>AbortSignal.timeout(e??v),Z=async({challenge:e,credentialIds:t,passkeyOptions:n,timeout:r})=>await navigator.credentials.get({publicKey:{..._(n),challenge:e.buffer,allowCredentials:(t??[]).map(a=>({id:a.buffer,type:"public-key"}))},signal:G({timeout:r})}),z=e=>{if(e.status!=="initialized")throw new b},q=e=>{if(u(e))throw new f},L=({type:e})=>{if(e!=="public-key")throw new m},F=class e extends X{#t;#e;constructor({onProgress:t,...n}){if(super(),this.#t=t,"retrievePublicKey"in n){let{retrievePublicKey:r}=n;this.#e={status:"pending",retrievePublicKey:r};return}this.#e=e.#r({credential:new h(n)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:n,...r}={}){let a=await navigator.credentials.create({publicKey:R(t),signal:G({timeout:n})});q(a),L(a);let{response:{attestationObject:s},rawId:i}=a;if(u(s))throw new C;let{authData:o}=N.decode(d(s)),c=S(o);return new e({...r,rawId:d(i),cose:c,authData:o})}static async createWithExistingCredential(t){return new e(t)}getPublicKey(){z(this.#e);let{credential:t}=this.#e;return t.getPublicKey()}getCredential(){z(this.#e);let{credential:t}=this.#e;return t}async sign(t){let r=await x({fn:async()=>{let i=await Z({challenge:t,...this.#e.status==="initialized"&&{credentialIds:[this.#e.credential.getCredentialId()]}});return q(i),L(i),i},step:0,onProgress:this.#t});return await x({fn:async()=>{let{rawId:i}=r;if(this.#e.status==="initialized"){if(!Q({a:this.#e.credential.getCredentialId(),b:d(i)}))throw new P;return}let{retrievePublicKey:o}=this.#e,c=await o({credentialId:d(i)});this.#e=e.#r({credential:new g({rawId:d(i),cose:c})})},step:1,onProgress:this.#t}),await x({fn:async()=>{let{response:i}=r,{clientDataJSON:o}=i,{authenticatorData:c,signature:T}="authenticatorData"in i&&"signature"in i?i:{};if(u(c))throw new l;if(u(T))throw new l;let W=N.encode({authenticator_data:c,client_data_json:new TextDecoder().decode(o),signature:d(T)});if(u(W))throw new w;return Object.assign(W,{__signature__:void 0}),W},step:2,onProgress:this.#t})}};import{nonNullish as ee}from"@dfinity/utils";var Ue=async()=>ee(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;export{y as CosePublicKey,p as WebAuthnCredential,g as WebAuthnExistingCredential,F as WebAuthnIdentity,f as WebAuthnIdentityCreateCredentialOnTheDeviceError,b as WebAuthnIdentityCredentialNotInitializedError,m as WebAuthnIdentityCredentialNotPublicKeyError,w as WebAuthnIdentityEncodeCborSignatureError,A as WebAuthnIdentityHostnameError,P as WebAuthnIdentityInvalidCredentialIdError,C as WebAuthnIdentityNoAttestationError,l as WebAuthnIdentityNoAuthenticatorDataError,E as WebAuthnIdentityNoSignatureError,h as WebAuthnNewCredential,B as WebAuthnSignProgressStep,K as bytesToAAGUID,Ue as isWebAuthnAvailable};
3
+ import{uint8ArrayToArrayOfNumber as H}from"@junobuild/utils";var I=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),n=K({bytes:t});return"aaguid"in n?{aaguidBytes:t,aaguidText:n.aaguid}:{unknownProvider:null}},K=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let n=(e instanceof Uint8Array?H(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return n==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:n}};import{DER_COSE_OID as V,wrapDER as j}from"@icp-sdk/core/agent";function S(e){let t=new DataView(new ArrayBuffer(2)),n=e.slice(53,55);[...new Uint8Array(n)].forEach((a,s)=>t.setUint8(s,a));let r=t.getUint16(0);return e.slice(55+r)}function U(e){return j(e,V)}var y=class{constructor(t){this._cose=t;this.#t=U(t)}_cose;#t;toDer(){return this.#t}toRaw(){return new Uint8Array(this.#t)}};import{uint8ArrayToBase64 as $}from"@junobuild/utils";var p=class{#t;#e;constructor({rawId:t,cose:n}){this.#t=t,this.#e=new y(n)}getPublicKey(){return this.#e}getCredentialId(){return this.#t}getCredentialIdText(){return $(this.#t)}},h=class extends p{#t;#e;constructor({authData:t,...n}){super(n);let r=I({authData:t});this.#t="aaguidText"in r?r.aaguidText:void 0,this.#e="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#e}getAAGUIDText(){return this.#t}},g=class extends p{};var A=class extends Error{},b=class extends Error{},f=class extends Error{},m=class extends Error{},C=class extends Error{},P=class extends Error{},w=class extends Error{},l=class extends Error{},E=class extends Error{};import{Cbor as N,SignIdentity as Q}from"@icp-sdk/core/agent";import{arrayBufferToUint8Array as d,isNullish as u,uint8ArraysEqual as X}from"@junobuild/utils";var O={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},v=6e4;var k=()=>window.crypto.getRandomValues(new Uint8Array(16)),M=()=>k(),Y=()=>k(),J=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new A}},D=({appId:e})=>e?.id??J(),R=({appId:e,user:t}={})=>{let{document:{title:n}}=window,r=()=>({rp:{name:e?.name??n,id:D({appId:e})}}),a=()=>({user:{id:Y(),name:t?.name??t?.displayName??n,displayName:t?.displayName??n}});return{attestation:"direct",challenge:M(),...r(),...a(),pubKeyCredParams:Object.values(O).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},_=(e={})=>({rpId:D(e),allowCredentials:[],userVerification:"required"});var x=async({fn:e,step:t,onProgress:n})=>{n?.({step:t,state:"in_progress"});try{let r=await e();return n?.({step:t,state:"success"}),r}catch(r){throw n?.({step:t,state:"error"}),r}};var B=(r=>(r[r.RequestingUserCredential=0]="RequestingUserCredential",r[r.FinalizingCredential=1]="FinalizingCredential",r[r.Signing=2]="Signing",r))(B||{});var G=({timeout:e})=>AbortSignal.timeout(e??v),Z=async({challenge:e,credentialIds:t,passkeyOptions:n,timeout:r})=>await navigator.credentials.get({publicKey:{..._(n),challenge:e.buffer,allowCredentials:(t??[]).map(a=>({id:a.buffer,type:"public-key"}))},signal:G({timeout:r})}),z=e=>{if(e.status!=="initialized")throw new b},q=e=>{if(u(e))throw new f},L=({type:e})=>{if(e!=="public-key")throw new m},F=class e extends Q{#t;#e;constructor({onProgress:t,...n}){if(super(),this.#t=t,"retrievePublicKey"in n){let{retrievePublicKey:r}=n;this.#e={status:"pending",retrievePublicKey:r};return}this.#e=e.#r({credential:new h(n)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:n,...r}={}){let a=await navigator.credentials.create({publicKey:R(t),signal:G({timeout:n})});q(a),L(a);let{response:{attestationObject:s},rawId:i}=a;if(u(s))throw new C;let{authData:o}=N.decode(d(s)),c=S(o);return new e({...r,rawId:d(i),cose:c,authData:o})}static async createWithExistingCredential(t){return new e(t)}getPublicKey(){z(this.#e);let{credential:t}=this.#e;return t.getPublicKey()}getCredential(){z(this.#e);let{credential:t}=this.#e;return t}async sign(t){let r=await x({fn:async()=>{let i=await Z({challenge:t,...this.#e.status==="initialized"&&{credentialIds:[this.#e.credential.getCredentialId()]}});return q(i),L(i),i},step:0,onProgress:this.#t});return await x({fn:async()=>{let{rawId:i}=r;if(this.#e.status==="initialized"){if(!X({a:this.#e.credential.getCredentialId(),b:d(i)}))throw new P;return}let{retrievePublicKey:o}=this.#e,c=await o({credentialId:d(i)});this.#e=e.#r({credential:new g({rawId:d(i),cose:c})})},step:1,onProgress:this.#t}),await x({fn:async()=>{let{response:i}=r,{clientDataJSON:o}=i,{authenticatorData:c,signature:T}="authenticatorData"in i&&"signature"in i?i:{};if(u(c))throw new l;if(u(T))throw new l;let W=N.encode({authenticator_data:c,client_data_json:new TextDecoder().decode(o),signature:d(T)});if(u(W))throw new w;return Object.assign(W,{__signature__:void 0}),W},step:2,onProgress:this.#t})}};import{nonNullish as ee}from"@junobuild/utils";var Ue=async()=>ee(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;export{y as CosePublicKey,p as WebAuthnCredential,g as WebAuthnExistingCredential,F as WebAuthnIdentity,f as WebAuthnIdentityCreateCredentialOnTheDeviceError,b as WebAuthnIdentityCredentialNotInitializedError,m as WebAuthnIdentityCredentialNotPublicKeyError,w as WebAuthnIdentityEncodeCborSignatureError,A as WebAuthnIdentityHostnameError,P as WebAuthnIdentityInvalidCredentialIdError,C as WebAuthnIdentityNoAttestationError,l as WebAuthnIdentityNoAuthenticatorDataError,E as WebAuthnIdentityNoSignatureError,h as WebAuthnNewCredential,B as WebAuthnSignProgressStep,K as bytesToAAGUID,Ue as isWebAuthnAvailable};
4
4
  //# sourceMappingURL=webauthn.mjs.map