passkey-kit 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passkey-kit",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A helper library for creating and using passkey accounts on the Stellar blockchain.",
5
5
  "author": "Tyler van der Hoeven",
6
6
  "license": "MIT",
@@ -9,7 +9,6 @@
9
9
  "types": "types/index.d.ts",
10
10
  "dependencies": {
11
11
  "@simplewebauthn/browser": "^10.0.0",
12
- "@simplewebauthn/types": "^10.0.0",
13
12
  "@stellar/stellar-sdk": "12.0.1",
14
13
  "base64url": "^3.0.1",
15
14
  "bigint-conversion": "^2.4.3",
package/src/base.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { Networks, Transaction, Horizon, FeeBumpTransaction } from '@stellar/stellar-sdk'
2
+
3
+ export class PasskeyBase {
4
+ public networkPassphrase: Networks
5
+ public horizonUrl: string
6
+ public horizon: Horizon.Server
7
+ public feeBumpUrl: string | undefined
8
+ public feeBumpJwt: string | undefined
9
+
10
+ constructor(options: {
11
+ networkPassphrase: Networks,
12
+ horizonUrl: string,
13
+ feeBumpUrl?: string,
14
+ feeBumpJwt?: string,
15
+ }) {
16
+ const {
17
+ networkPassphrase,
18
+ horizonUrl,
19
+ feeBumpUrl,
20
+ feeBumpJwt,
21
+ } = options
22
+
23
+ this.networkPassphrase = networkPassphrase
24
+ this.horizonUrl = horizonUrl
25
+ this.horizon = new Horizon.Server(horizonUrl)
26
+
27
+ if (feeBumpUrl)
28
+ this.feeBumpUrl = feeBumpUrl
29
+
30
+ if (feeBumpJwt)
31
+ this.feeBumpJwt = feeBumpJwt
32
+ }
33
+
34
+ public async send(txn: Transaction, fee: number = 10_000) {
35
+ const data = new FormData();
36
+
37
+ data.set('xdr', txn.toXDR());
38
+ data.set('fee', fee.toString());
39
+
40
+ const bumptxn = await fetch(this.feeBumpUrl!, {
41
+ method: 'POST',
42
+ headers: {
43
+ authorization: `Bearer ${this.feeBumpJwt}`,
44
+ },
45
+ body: data
46
+ }).then(async (res) => {
47
+ if (res.ok)
48
+ return res.text()
49
+ else throw await res.json()
50
+ })
51
+
52
+ return this.horizon.submitTransaction(new FeeBumpTransaction(bumptxn, this.networkPassphrase))
53
+ }
54
+ }
package/src/index.ts CHANGED
@@ -1,507 +1,4 @@
1
- import { Client as PasskeyClient } from 'passkey-kit-sdk'
2
- import { Client as FactoryClient, networks } from 'passkey-factory-sdk'
3
- import { Address, Networks, StrKey, hash, xdr, Transaction, Horizon, FeeBumpTransaction, SorobanRpc, Operation, scValToNative, TransactionBuilder } from '@stellar/stellar-sdk'
4
- import { bufToBigint, bigintToBuf } from 'bigint-conversion'
5
- import base64url from 'base64url'
6
- import { startRegistration, startAuthentication } from "@simplewebauthn/browser"
7
- import { decode } from 'cbor-x/decode'
8
- import type { RegistrationResponseJSON } from '@simplewebauthn/types';
9
- import { Buffer } from 'buffer'
1
+ import { PasskeyBase } from "./base"
2
+ import { PasskeyKit } from "./kit"
10
3
 
11
- /* TODO
12
- - Clean up these params and the interface as a whole
13
- Might put wallet activities and maybe factory as well into the root of the class vs buried inside this.wallet and this.factory
14
- @Later
15
-
16
- - Right now publicKey can mean a Stellar public key or a passkey public key, there should be a noted difference
17
- */
18
-
19
- export class PasskeyAccount {
20
- public keyId: string | undefined
21
- public sudoKeyId: string | undefined
22
- public wallet: PasskeyClient | undefined
23
- public factory: FactoryClient
24
- public sequencePublicKey: string
25
- public networkPassphrase: Networks
26
- public horizonUrl: string
27
- public horizon: Horizon.Server
28
- public rpcUrl: string
29
- public rpc: SorobanRpc.Server
30
- public feeBumpUrl: string | undefined
31
- public feeBumpJwt: string | undefined
32
- public factoryContractId: string = networks.testnet.contractId
33
-
34
- /* TODO
35
- - Consider adding the ability to pass in a keyId and maybe even a contractId in order to preconnect to a wallet
36
- If just a keyId call `connectWallet` in order to get the contractId
37
- If both keyId and contractId are passed in then we can skip the connectWallet call (though we won't get the sudoKeyId in that case)
38
- We don't stictly _need_ this as a dev can just call `connectWallet` after class instantiation but it might be a nice convenience
39
- @Later
40
- */
41
- constructor(options: {
42
- sequencePublicKey: string,
43
- networkPassphrase: Networks,
44
- horizonUrl: string,
45
- rpcUrl: string,
46
- feeBumpUrl?: string,
47
- feeBumpJwt?: string,
48
- /* TODO
49
- - Maybe remove this? The factory should likely be baked in a bit more tightly
50
- On the other hand once we have a standard interface the factory interface only uses the `deploy` method right now inside the interface
51
- @Later
52
- */
53
- factoryContractId?: string,
54
- }) {
55
- const {
56
- sequencePublicKey,
57
- networkPassphrase,
58
- horizonUrl,
59
- rpcUrl,
60
- feeBumpUrl,
61
- feeBumpJwt,
62
- factoryContractId
63
- } = options
64
-
65
- this.sequencePublicKey = sequencePublicKey
66
- this.networkPassphrase = networkPassphrase
67
- this.horizonUrl = horizonUrl
68
- this.horizon = new Horizon.Server(horizonUrl)
69
- this.rpcUrl = rpcUrl
70
- this.rpc = new SorobanRpc.Server(rpcUrl)
71
-
72
- if (feeBumpUrl)
73
- this.feeBumpUrl = feeBumpUrl
74
-
75
- if (feeBumpJwt)
76
- this.feeBumpJwt = feeBumpJwt
77
-
78
- if (factoryContractId)
79
- this.factoryContractId = factoryContractId
80
-
81
- this.factory = new FactoryClient({
82
- publicKey: sequencePublicKey,
83
- contractId: this.factoryContractId,
84
- networkPassphrase,
85
- rpcUrl
86
- })
87
- }
88
-
89
- public async createWallet(name: string, user: string) {
90
- const { keyId, publicKey } = await this.createKey(name, user)
91
-
92
- const { result, built } = await this.factory.deploy({
93
- id: keyId,
94
- pk: publicKey!
95
- })
96
-
97
- const contractId = result.unwrap() as string
98
-
99
- this.wallet = new PasskeyClient({
100
- publicKey: this.sequencePublicKey,
101
- contractId,
102
- networkPassphrase: this.networkPassphrase,
103
- rpcUrl: this.rpcUrl
104
- })
105
-
106
- return {
107
- keyId,
108
- contractId,
109
- xdr: built!.toXDR() as string
110
- }
111
- }
112
-
113
- public async createKey(name: string, user: string) {
114
- const startRegistrationResponse = await startRegistration({
115
- challenge: base64url("stellaristhebetterblockchain"),
116
- rp: {
117
- // id: undefined,
118
- name,
119
- },
120
- user: {
121
- id: base64url(user),
122
- name: user,
123
- displayName: user,
124
- },
125
- authenticatorSelection: {
126
- requireResidentKey: false,
127
- residentKey: "preferred",
128
- userVerification: "discouraged",
129
- },
130
- pubKeyCredParams: [{ alg: -7, type: "public-key" }],
131
- attestation: "none",
132
- });
133
-
134
- if (!this.keyId) {
135
- this.keyId = startRegistrationResponse.id
136
-
137
- // If there was no keyId we're likely about to deploy a new wallet so we should set the sudoKeyId
138
- if (!this.sudoKeyId)
139
- this.sudoKeyId = startRegistrationResponse.id
140
- }
141
-
142
- const { publicKeyObject } = this.getPublicKeyObject(startRegistrationResponse.response.attestationObject);
143
-
144
- const publicKey = Buffer.from([
145
- 4, // (0x04 prefix) https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm
146
- ...publicKeyObject.get('-2')!,
147
- ...publicKeyObject.get('-3')!
148
- ])
149
-
150
- return {
151
- keyId: base64url.toBuffer(startRegistrationResponse.id),
152
- publicKey
153
- }
154
- }
155
-
156
- public async connectWallet(id?: string) {
157
- /* TODO
158
- - Support passing in a contractId as well as a keyId
159
- Maybe not as we wouldn't have a keyId which could have interesting consequences
160
- Also not sure what the use case would be for this where keyId wouldn't also be possible and better
161
- @No
162
- */
163
-
164
- // @ts-ignore
165
- // https://github.com/stellar/js-stellar-base/issues/750
166
- // if (id && StrKey.isValidContract(id)) {
167
-
168
- // } else {
169
-
170
- // }
171
-
172
- const startAuthenticationResponse = id
173
- ? { id }
174
- : await startAuthentication({
175
- challenge: base64url("stellaristhebetterblockchain"),
176
- // rpId: undefined,
177
- userVerification: "discouraged",
178
- });
179
-
180
- if (!this.keyId)
181
- this.keyId = startAuthenticationResponse.id
182
-
183
- const keyIdBuffer = base64url.toBuffer(startAuthenticationResponse.id)
184
-
185
- // NOTE might not need this for derivation as all signers are stored in the factory and we can use that lookup as both primary and secondary
186
- let contractId = StrKey.encodeContract(hash(xdr.HashIdPreimage.envelopeTypeContractId(
187
- new xdr.HashIdPreimageContractId({
188
- networkId: hash(Buffer.from(this.networkPassphrase, 'utf-8')),
189
- contractIdPreimage: xdr.ContractIdPreimage.contractIdPreimageFromAddress(
190
- new xdr.ContractIdPreimageFromAddress({
191
- address: Address.fromString(this.factoryContractId).toScAddress(),
192
- salt: hash(keyIdBuffer),
193
- })
194
- )
195
- })
196
- ).toXDR()));
197
-
198
- // attempt passkey id derivation
199
- try {
200
- await this.rpc.getContractData(contractId, xdr.ScVal.scvLedgerKeyContractInstance())
201
- }
202
- // if that fails look up from the factory mapper
203
- catch {
204
- const { val } = await this.rpc.getContractData(this.factoryContractId, xdr.ScVal.scvBytes(keyIdBuffer))
205
- contractId = scValToNative(val.contractData().val())
206
- }
207
-
208
- this.wallet = new PasskeyClient({
209
- publicKey: this.sequencePublicKey,
210
- contractId,
211
- networkPassphrase: this.networkPassphrase,
212
- rpcUrl: this.rpcUrl
213
- })
214
-
215
- // get and set the sudo signer
216
- await this.getData()
217
-
218
- return {
219
- keyId: keyIdBuffer,
220
- contractId
221
- }
222
- }
223
-
224
- public async sign(
225
- txn: Transaction | string,
226
- options?: {
227
- keyId?: 'any' | 'sudo' | string | Uint8Array
228
- ledgersToLive?: number
229
- }
230
- ) {
231
- // Default mirrors DEFAULT_TIMEOUT (currently 5 minutes) https://github.com/stellar/js-stellar-sdk/blob/master/src/contract/utils.ts#L7
232
- let { keyId, ledgersToLive = 60 } = options || {}
233
-
234
- // hack to ensure we don't stack fees when simulating and assembling multiple times
235
- txn = TransactionBuilder.cloneFrom(new Transaction(
236
- typeof txn === 'string'
237
- ? txn
238
- : txn.toXDR(),
239
- this.networkPassphrase
240
- ), { fee: '0' }).build()
241
-
242
- // NOTE hard coded to sign only Soroban transactions and only and always the first auth
243
- // TODO switch to support signing multiple and specific auth entries. Possibly pass in auth entry vs the entire txn
244
- const op = txn.operations[0] as Operation.InvokeHostFunction
245
- const auth = op.auth![0]
246
- const lastLedger = await this.rpc.getLatestLedger().then(({ sequence }) => sequence)
247
- const authHash = hash(
248
- xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(
249
- new xdr.HashIdPreimageSorobanAuthorization({
250
- networkId: hash(Buffer.from(this.networkPassphrase, 'utf-8')),
251
- nonce: auth.credentials().address().nonce(),
252
- signatureExpirationLedger: lastLedger + ledgersToLive,
253
- invocation: auth.rootInvocation()
254
- })
255
- ).toXDR()
256
- )
257
-
258
- const authenticationResponse = await startAuthentication(
259
- keyId === 'any' || (keyId === 'sudo' && !this.sudoKeyId) || (!keyId && !this.keyId)
260
- ? {
261
- challenge: base64url(authHash),
262
- // rpId: undefined,
263
- userVerification: "discouraged",
264
- }
265
- : {
266
- challenge: base64url(authHash),
267
- // rpId: undefined,
268
- allowCredentials: [
269
- {
270
- id: keyId === 'sudo'
271
- ? this.sudoKeyId!
272
- : keyId instanceof Uint8Array
273
- ? base64url(keyId)
274
- : keyId || this.keyId!,
275
- type: "public-key",
276
- },
277
- ],
278
- userVerification: "discouraged",
279
- }
280
- );
281
-
282
- // set sudo if this is a sudo request
283
- if (keyId === 'sudo')
284
- this.sudoKeyId = authenticationResponse.id
285
-
286
- // reset this.keyId to be the most recently used passkey
287
- this.keyId = authenticationResponse.id
288
-
289
- const signatureRaw = base64url.toBuffer(authenticationResponse.response.signature);
290
- const signature = this.convertEcdsaSignatureAsnToCompact(signatureRaw);
291
- const creds = auth.credentials().address();
292
-
293
- creds.signatureExpirationLedger(lastLedger + ledgersToLive)
294
- creds.signature(xdr.ScVal.scvMap([
295
- new xdr.ScMapEntry({
296
- key: xdr.ScVal.scvSymbol('authenticator_data'),
297
- val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.response.authenticatorData)),
298
- }),
299
- new xdr.ScMapEntry({
300
- key: xdr.ScVal.scvSymbol('client_data_json'),
301
- val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.response.clientDataJSON)),
302
- }),
303
- new xdr.ScMapEntry({
304
- key: xdr.ScVal.scvSymbol('id'),
305
- val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.id)),
306
- }),
307
- new xdr.ScMapEntry({
308
- key: xdr.ScVal.scvSymbol('signature'),
309
- val: xdr.ScVal.scvBytes(signature),
310
- }),
311
- ]))
312
-
313
- const sim = await this.rpc.simulateTransaction(txn)
314
-
315
- if (
316
- SorobanRpc.Api.isSimulationError(sim)
317
- || SorobanRpc.Api.isSimulationRestore(sim) // TODO handle restore flow
318
- ) throw sim
319
-
320
- return SorobanRpc.assembleTransaction(txn, sim).build().toXDR()
321
- }
322
-
323
- public async send(txn: Transaction, fee: number = 10_000) {
324
- const data = new FormData();
325
-
326
- data.set('xdr', txn.toXDR());
327
- data.set('fee', fee.toString());
328
-
329
- const bumptxn = await fetch(this.feeBumpUrl!, {
330
- method: 'POST',
331
- headers: {
332
- authorization: `Bearer ${this.feeBumpJwt}`,
333
- },
334
- body: data
335
- }).then(async (res) => {
336
- if (res.ok)
337
- return res.text()
338
- else throw await res.json()
339
- })
340
-
341
- return this.horizon.submitTransaction(new FeeBumpTransaction(bumptxn, this.networkPassphrase))
342
- }
343
-
344
- public async getData() {
345
- const data: Map<string, any> = new Map()
346
-
347
- const { val } = await this.rpc.getContractData(
348
- this.wallet!.options.contractId,
349
- xdr.ScVal.scvLedgerKeyContractInstance(),
350
- );
351
-
352
- val.contractData()
353
- .val()
354
- .instance()
355
- .storage()
356
- ?.forEach((entry) => {
357
- data.set(
358
- scValToNative(entry.key()),
359
- scValToNative(entry.val()),
360
- );
361
- });
362
-
363
- this.sudoKeyId = base64url(data.get('sudo_sig'))
364
-
365
- return data
366
- }
367
-
368
- /* TODO
369
- - Add a getKeyInfo action to get info about a specific passkey
370
- Specifically looking for name, type, etc. data so a user could grok what signer mapped to what passkey
371
- @Later
372
- */
373
-
374
- private getPublicKeyObject(attestationObject: string) {
375
- const { authData } = decode(base64url.toBuffer(attestationObject));
376
- const authDataUint8Array = new Uint8Array(authData);
377
- const authDataView = new DataView(authDataUint8Array.buffer, 0, authDataUint8Array.length);
378
-
379
- let offset = 0;
380
-
381
- // RP ID Hash (32 bytes)
382
- const rpIdHash = authData.slice(offset, offset + 32);
383
- offset += 32;
384
-
385
- // Flags (1 byte)
386
- const flags = authDataView.getUint8(offset);
387
- offset += 1;
388
-
389
- // Sign Count (4 bytes, big endian)
390
- const signCount = authDataView.getUint32(offset, false);
391
- offset += 4;
392
-
393
- // Attested Credential Data, if present
394
- if (flags & 0x40) { // Checking the AT flag
395
- // AAGUID (16 bytes)
396
- const aaguid = authData.slice(offset, offset + 16);
397
- offset += 16;
398
-
399
- // Credential ID Length (2 bytes, big endian)
400
- const credIdLength = authDataView.getUint16(offset, false);
401
- offset += 2;
402
-
403
- // Credential ID (variable length)
404
- const credentialId = authData.slice(offset, offset + credIdLength);
405
- offset += credIdLength;
406
-
407
- // Credential Public Key - (77 bytes...I hope)
408
- const credentialPublicKey = authData.slice(offset, offset + 77);
409
- offset += 77;
410
-
411
- // Any leftover bytes. I found some when using a YubiKey
412
- const theRest = authData.slice(offset);
413
-
414
- // Decode the credential public key to COSE
415
- const publicKeyObject = new Map<string, any>(Object.entries(decode(credentialPublicKey)));
416
-
417
- return {
418
- rpIdHash,
419
- flags,
420
- signCount,
421
- aaguid,
422
- credIdLength,
423
- credentialId,
424
- credentialPublicKey,
425
- theRest,
426
- publicKeyObject
427
- };
428
- }
429
-
430
- throw new Error("Attested credential data not present in the flags.");
431
- }
432
-
433
- private convertEcdsaSignatureAsnToCompact(sig: Buffer) {
434
- // Define the order of the curve secp256k1
435
- // https://github.com/RustCrypto/elliptic-curves/blob/master/p256/src/lib.rs#L72
436
- const q = Buffer.from('ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551', 'hex')
437
-
438
- // ASN Sequence
439
- let offset = 0;
440
- if (sig[offset] != 0x30) {
441
- throw "signature is not a sequence";
442
- }
443
- offset += 1;
444
-
445
- // ASN Sequence Byte Length
446
- offset += 1;
447
-
448
- // ASN Integer (R)
449
- if (sig[offset] != 0x02) {
450
- throw "first element in sequence is not an integer";
451
- }
452
- offset += 1;
453
-
454
- // ASN Integer (R) Byte Length
455
- const rLen = sig[offset];
456
- offset += 1;
457
-
458
- // ASN Integer (R) Byte Value
459
- if (rLen >= 33) {
460
- if (rLen != 33 || sig[offset] != 0x00) {
461
- throw "can only handle larger than 32 byte R's that are len 33 and lead with zero";
462
- }
463
- offset += 1;
464
- }
465
- const r = sig.slice(offset, offset + 32);
466
- offset += 32;
467
-
468
- // ASN Integer (S)
469
- if (sig[offset] != 0x02) {
470
- throw "second element in sequence is not an integer";
471
- }
472
- offset += 1;
473
-
474
- // ASN Integer (S) Byte Length
475
- const sLen = sig[offset];
476
- offset += 1;
477
-
478
- // ASN Integer (S) Byte Value
479
- if (sLen >= 33) {
480
- if (sLen != 33 || sig[offset] != 0x00) {
481
- throw "can only handle larger than 32 byte R's that are len 33 and lead with zero";
482
- }
483
- offset += 1;
484
- }
485
-
486
- const s = sig.slice(offset, offset + 32);
487
-
488
- offset += 32;
489
-
490
- let signature64: Buffer
491
-
492
- // Force low S range
493
- // https://github.com/stellar/stellar-protocol/discussions/1435#discussioncomment-8809175
494
- // https://discord.com/channels/897514728459468821/1233048618571927693
495
- if (bufToBigint(s) > ((bufToBigint(q) - BigInt(1)) / BigInt(2))) {
496
- signature64 = Buffer.from([...r, ...Buffer.from(bigintToBuf(bufToBigint(q) - bufToBigint(s), true) as ArrayBuffer)]);
497
- } else {
498
- signature64 = Buffer.from([...r, ...s]);
499
- }
500
-
501
- return signature64;
502
- }
503
- }
504
-
505
- function isAuthentication(value: any): value is RegistrationResponseJSON {
506
- return value?.response?.attestationObject;
507
- }
4
+ export { PasskeyBase, PasskeyKit }
package/src/kit.ts ADDED
@@ -0,0 +1,487 @@
1
+ import { Client as PasskeyClient } from 'passkey-kit-sdk'
2
+ import { Client as FactoryClient, networks } from 'passkey-factory-sdk'
3
+ import { Address, Networks, StrKey, hash, xdr, Transaction, Horizon, SorobanRpc, Operation, scValToNative, TransactionBuilder } from '@stellar/stellar-sdk'
4
+ import { bufToBigint, bigintToBuf } from 'bigint-conversion'
5
+ import base64url from 'base64url'
6
+ import { startRegistration, startAuthentication } from "@simplewebauthn/browser"
7
+ import { decode } from 'cbor-x/decode'
8
+ import { Buffer } from 'buffer'
9
+ import { PasskeyBase } from './base'
10
+
11
+ /* TODO
12
+ - Clean up these params and the interface as a whole
13
+ Might put wallet activities and maybe factory as well into the root of the class vs buried inside this.wallet and this.factory
14
+ @Later
15
+
16
+ - Right now publicKey can mean a Stellar public key or a passkey public key, there should be a noted difference
17
+
18
+ - It's finally time to make a server and a client version of this package
19
+ Maybe. I want to support passing "bad" secret values on the client.
20
+ It's maybe only the server that could be smaller and cleaner by opting out out WebAuthN stuff
21
+ */
22
+
23
+ export class PasskeyKit extends PasskeyBase {
24
+ public keyId: string | undefined
25
+ public sudoKeyId: string | undefined
26
+ public wallet: PasskeyClient | undefined
27
+ public factory: FactoryClient
28
+ public sequencePublicKey: string
29
+ // public networkPassphrase: Networks
30
+ // public horizonUrl: string
31
+ public horizon: Horizon.Server
32
+ public rpcUrl: string
33
+ public rpc: SorobanRpc.Server
34
+ // public feeBumpUrl: string | undefined
35
+ // public feeBumpJwt: string | undefined
36
+ public factoryContractId: string = networks.testnet.contractId
37
+
38
+ /* TODO
39
+ - Consider adding the ability to pass in a keyId and maybe even a contractId in order to preconnect to a wallet
40
+ If just a keyId call `connectWallet` in order to get the contractId
41
+ If both keyId and contractId are passed in then we can skip the connectWallet call (though we won't get the sudoKeyId in that case)
42
+ We don't stictly _need_ this as a dev can just call `connectWallet` after class instantiation but it might be a nice convenience
43
+ @Later
44
+ */
45
+ constructor(options: {
46
+ sequencePublicKey: string,
47
+ networkPassphrase: Networks,
48
+ horizonUrl: string,
49
+ rpcUrl: string,
50
+ feeBumpUrl?: string,
51
+ feeBumpJwt?: string,
52
+ /* TODO
53
+ - Maybe remove this? The factory should likely be baked in a bit more tightly
54
+ On the other hand once we have a standard interface the factory interface only uses the `deploy` method right now inside the interface
55
+ @Later
56
+ */
57
+ factoryContractId?: string,
58
+ }) {
59
+ const {
60
+ sequencePublicKey,
61
+ networkPassphrase,
62
+ horizonUrl,
63
+ rpcUrl,
64
+ feeBumpUrl,
65
+ feeBumpJwt,
66
+ factoryContractId
67
+ } = options
68
+
69
+ super({
70
+ networkPassphrase,
71
+ horizonUrl,
72
+ feeBumpUrl,
73
+ feeBumpJwt,
74
+ })
75
+
76
+ this.sequencePublicKey = sequencePublicKey
77
+
78
+ this.horizon = new Horizon.Server(horizonUrl)
79
+ this.rpcUrl = rpcUrl
80
+ this.rpc = new SorobanRpc.Server(rpcUrl)
81
+
82
+ if (factoryContractId)
83
+ this.factoryContractId = factoryContractId
84
+
85
+ this.factory = new FactoryClient({
86
+ publicKey: sequencePublicKey,
87
+ contractId: this.factoryContractId,
88
+ networkPassphrase,
89
+ rpcUrl
90
+ })
91
+ }
92
+
93
+ public async createWallet(name: string, user: string) {
94
+ const { keyId, publicKey } = await this.createKey(name, user)
95
+
96
+ const { result, built } = await this.factory.deploy({
97
+ id: keyId,
98
+ pk: publicKey!
99
+ })
100
+
101
+ const contractId = result.unwrap() as string
102
+
103
+ this.wallet = new PasskeyClient({
104
+ publicKey: this.sequencePublicKey,
105
+ contractId,
106
+ networkPassphrase: this.networkPassphrase,
107
+ rpcUrl: this.rpcUrl
108
+ })
109
+
110
+ return {
111
+ keyId,
112
+ contractId,
113
+ xdr: built!.toXDR() as string
114
+ }
115
+ }
116
+
117
+ public async createKey(name: string, user: string) {
118
+ const startRegistrationResponse = await startRegistration({
119
+ challenge: base64url("stellaristhebetterblockchain"),
120
+ rp: {
121
+ // id: undefined,
122
+ name,
123
+ },
124
+ user: {
125
+ id: base64url(user),
126
+ name: user,
127
+ displayName: user,
128
+ },
129
+ authenticatorSelection: {
130
+ requireResidentKey: false,
131
+ residentKey: "preferred",
132
+ userVerification: "discouraged",
133
+ },
134
+ pubKeyCredParams: [{ alg: -7, type: "public-key" }],
135
+ attestation: "none",
136
+ });
137
+
138
+ if (!this.keyId) {
139
+ this.keyId = startRegistrationResponse.id
140
+
141
+ // If there was no keyId we're likely about to deploy a new wallet so we should set the sudoKeyId
142
+ if (!this.sudoKeyId)
143
+ this.sudoKeyId = startRegistrationResponse.id
144
+ }
145
+
146
+ const { publicKeyObject } = this.getPublicKeyObject(startRegistrationResponse.response.attestationObject);
147
+
148
+ const publicKey = Buffer.from([
149
+ 4, // (0x04 prefix) https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm
150
+ ...publicKeyObject.get('-2')!,
151
+ ...publicKeyObject.get('-3')!
152
+ ])
153
+
154
+ return {
155
+ keyId: base64url.toBuffer(startRegistrationResponse.id),
156
+ publicKey
157
+ }
158
+ }
159
+
160
+ public async connectWallet(id?: string) {
161
+ /* TODO
162
+ - Support passing in a contractId as well as a keyId
163
+ Maybe not as we wouldn't have a keyId which could have interesting consequences
164
+ Also not sure what the use case would be for this where keyId wouldn't also be possible and better
165
+ @No
166
+ */
167
+
168
+ // @ts-ignore
169
+ // https://github.com/stellar/js-stellar-base/issues/750
170
+ // if (id && StrKey.isValidContract(id)) {
171
+
172
+ // } else {
173
+
174
+ // }
175
+
176
+ const startAuthenticationResponse = id
177
+ ? { id }
178
+ : await startAuthentication({
179
+ challenge: base64url("stellaristhebetterblockchain"),
180
+ // rpId: undefined,
181
+ userVerification: "discouraged",
182
+ });
183
+
184
+ if (!this.keyId)
185
+ this.keyId = startAuthenticationResponse.id
186
+
187
+ const keyIdBuffer = base64url.toBuffer(startAuthenticationResponse.id)
188
+
189
+ // NOTE might not need this for derivation as all signers are stored in the factory and we can use that lookup as both primary and secondary
190
+ let contractId = StrKey.encodeContract(hash(xdr.HashIdPreimage.envelopeTypeContractId(
191
+ new xdr.HashIdPreimageContractId({
192
+ networkId: hash(Buffer.from(this.networkPassphrase, 'utf-8')),
193
+ contractIdPreimage: xdr.ContractIdPreimage.contractIdPreimageFromAddress(
194
+ new xdr.ContractIdPreimageFromAddress({
195
+ address: Address.fromString(this.factoryContractId).toScAddress(),
196
+ salt: hash(keyIdBuffer),
197
+ })
198
+ )
199
+ })
200
+ ).toXDR()));
201
+
202
+ // attempt passkey id derivation
203
+ try {
204
+ await this.rpc.getContractData(contractId, xdr.ScVal.scvLedgerKeyContractInstance())
205
+ }
206
+ // if that fails look up from the factory mapper
207
+ catch {
208
+ const { val } = await this.rpc.getContractData(this.factoryContractId, xdr.ScVal.scvBytes(keyIdBuffer))
209
+ contractId = scValToNative(val.contractData().val())
210
+ }
211
+
212
+ this.wallet = new PasskeyClient({
213
+ publicKey: this.sequencePublicKey,
214
+ contractId,
215
+ networkPassphrase: this.networkPassphrase,
216
+ rpcUrl: this.rpcUrl
217
+ })
218
+
219
+ // get and set the sudo signer
220
+ await this.getData()
221
+
222
+ return {
223
+ keyId: keyIdBuffer,
224
+ contractId
225
+ }
226
+ }
227
+
228
+ // TODO is there anything to be done with using the TS bindings `signAuthEntries` logic? Likely not but worth exploring
229
+ public async sign(
230
+ txn: Transaction | string,
231
+ options?: {
232
+ keyId?: 'any' | 'sudo' | string | Uint8Array
233
+ ledgersToLive?: number
234
+ }
235
+ ) {
236
+ // Default mirrors DEFAULT_TIMEOUT (currently 5 minutes) https://github.com/stellar/js-stellar-sdk/blob/master/src/contract/utils.ts#L7
237
+ let { keyId, ledgersToLive = 60 } = options || {}
238
+
239
+ // hack to ensure we don't stack fees when simulating and assembling multiple times
240
+ txn = TransactionBuilder.cloneFrom(new Transaction(
241
+ typeof txn === 'string'
242
+ ? txn
243
+ : txn.toXDR(),
244
+ this.networkPassphrase
245
+ ), { fee: '0' }).build()
246
+
247
+ // NOTE hard coded to sign only Soroban transactions and only and always the first auth
248
+ // TODO switch to support signing multiple and specific auth entries. Possibly pass in auth entry vs the entire txn
249
+ const op = txn.operations[0] as Operation.InvokeHostFunction
250
+ const auth = op.auth![0]
251
+ const lastLedger = await this.rpc.getLatestLedger().then(({ sequence }) => sequence)
252
+ const authHash = hash(
253
+ xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(
254
+ new xdr.HashIdPreimageSorobanAuthorization({
255
+ networkId: hash(Buffer.from(this.networkPassphrase, 'utf-8')),
256
+ nonce: auth.credentials().address().nonce(),
257
+ signatureExpirationLedger: lastLedger + ledgersToLive,
258
+ invocation: auth.rootInvocation()
259
+ })
260
+ ).toXDR()
261
+ )
262
+
263
+ const authenticationResponse = await startAuthentication(
264
+ keyId === 'any' || (keyId === 'sudo' && !this.sudoKeyId) || (!keyId && !this.keyId)
265
+ ? {
266
+ challenge: base64url(authHash),
267
+ // rpId: undefined,
268
+ userVerification: "discouraged",
269
+ }
270
+ : {
271
+ challenge: base64url(authHash),
272
+ // rpId: undefined,
273
+ allowCredentials: [
274
+ {
275
+ id: keyId === 'sudo'
276
+ ? this.sudoKeyId!
277
+ : keyId instanceof Uint8Array
278
+ ? base64url(keyId)
279
+ : keyId || this.keyId!,
280
+ type: "public-key",
281
+ },
282
+ ],
283
+ userVerification: "discouraged",
284
+ }
285
+ );
286
+
287
+ // set sudo if this is a sudo request
288
+ if (keyId === 'sudo')
289
+ this.sudoKeyId = authenticationResponse.id
290
+
291
+ // reset this.keyId to be the most recently used passkey
292
+ this.keyId = authenticationResponse.id
293
+
294
+ const signatureRaw = base64url.toBuffer(authenticationResponse.response.signature);
295
+ const signature = this.convertEcdsaSignatureAsnToCompact(signatureRaw);
296
+ const creds = auth.credentials().address();
297
+
298
+ creds.signatureExpirationLedger(lastLedger + ledgersToLive)
299
+ creds.signature(xdr.ScVal.scvMap([
300
+ new xdr.ScMapEntry({
301
+ key: xdr.ScVal.scvSymbol('authenticator_data'),
302
+ val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.response.authenticatorData)),
303
+ }),
304
+ new xdr.ScMapEntry({
305
+ key: xdr.ScVal.scvSymbol('client_data_json'),
306
+ val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.response.clientDataJSON)),
307
+ }),
308
+ new xdr.ScMapEntry({
309
+ key: xdr.ScVal.scvSymbol('id'),
310
+ val: xdr.ScVal.scvBytes(base64url.toBuffer(authenticationResponse.id)),
311
+ }),
312
+ new xdr.ScMapEntry({
313
+ key: xdr.ScVal.scvSymbol('signature'),
314
+ val: xdr.ScVal.scvBytes(signature),
315
+ }),
316
+ ]))
317
+
318
+ const sim = await this.rpc.simulateTransaction(txn)
319
+
320
+ if (
321
+ SorobanRpc.Api.isSimulationError(sim)
322
+ || SorobanRpc.Api.isSimulationRestore(sim) // TODO handle restore flow
323
+ ) throw sim
324
+
325
+ return SorobanRpc.assembleTransaction(txn, sim).build().toXDR()
326
+ }
327
+
328
+ public async getData() {
329
+ const data: Map<string, any> = new Map()
330
+
331
+ const { val } = await this.rpc.getContractData(
332
+ this.wallet!.options.contractId,
333
+ xdr.ScVal.scvLedgerKeyContractInstance(),
334
+ );
335
+
336
+ val.contractData()
337
+ .val()
338
+ .instance()
339
+ .storage()
340
+ ?.forEach((entry) => {
341
+ data.set(
342
+ scValToNative(entry.key()),
343
+ scValToNative(entry.val()),
344
+ );
345
+ });
346
+
347
+ this.sudoKeyId = base64url(data.get('sudo_sig'))
348
+
349
+ return data
350
+ }
351
+
352
+ /* TODO
353
+ - Add a getKeyInfo action to get info about a specific passkey
354
+ Specifically looking for name, type, etc. data so a user could grok what signer mapped to what passkey
355
+ @Later
356
+ */
357
+
358
+ private getPublicKeyObject(attestationObject: string) {
359
+ const { authData } = decode(base64url.toBuffer(attestationObject));
360
+ const authDataUint8Array = new Uint8Array(authData);
361
+ const authDataView = new DataView(authDataUint8Array.buffer, 0, authDataUint8Array.length);
362
+
363
+ let offset = 0;
364
+
365
+ // RP ID Hash (32 bytes)
366
+ const rpIdHash = authData.slice(offset, offset + 32);
367
+ offset += 32;
368
+
369
+ // Flags (1 byte)
370
+ const flags = authDataView.getUint8(offset);
371
+ offset += 1;
372
+
373
+ // Sign Count (4 bytes, big endian)
374
+ const signCount = authDataView.getUint32(offset, false);
375
+ offset += 4;
376
+
377
+ // Attested Credential Data, if present
378
+ if (flags & 0x40) { // Checking the AT flag
379
+ // AAGUID (16 bytes)
380
+ const aaguid = authData.slice(offset, offset + 16);
381
+ offset += 16;
382
+
383
+ // Credential ID Length (2 bytes, big endian)
384
+ const credIdLength = authDataView.getUint16(offset, false);
385
+ offset += 2;
386
+
387
+ // Credential ID (variable length)
388
+ const credentialId = authData.slice(offset, offset + credIdLength);
389
+ offset += credIdLength;
390
+
391
+ // Credential Public Key - (77 bytes...I hope)
392
+ const credentialPublicKey = authData.slice(offset, offset + 77);
393
+ offset += 77;
394
+
395
+ // Any leftover bytes. I found some when using a YubiKey
396
+ const theRest = authData.slice(offset);
397
+
398
+ // Decode the credential public key to COSE
399
+ const publicKeyObject = new Map<string, any>(Object.entries(decode(credentialPublicKey)));
400
+
401
+ return {
402
+ rpIdHash,
403
+ flags,
404
+ signCount,
405
+ aaguid,
406
+ credIdLength,
407
+ credentialId,
408
+ credentialPublicKey,
409
+ theRest,
410
+ publicKeyObject
411
+ };
412
+ }
413
+
414
+ throw new Error("Attested credential data not present in the flags.");
415
+ }
416
+
417
+ private convertEcdsaSignatureAsnToCompact(sig: Buffer) {
418
+ // Define the order of the curve secp256k1
419
+ // https://github.com/RustCrypto/elliptic-curves/blob/master/p256/src/lib.rs#L72
420
+ const q = Buffer.from('ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551', 'hex')
421
+
422
+ // ASN Sequence
423
+ let offset = 0;
424
+ if (sig[offset] != 0x30) {
425
+ throw "signature is not a sequence";
426
+ }
427
+ offset += 1;
428
+
429
+ // ASN Sequence Byte Length
430
+ offset += 1;
431
+
432
+ // ASN Integer (R)
433
+ if (sig[offset] != 0x02) {
434
+ throw "first element in sequence is not an integer";
435
+ }
436
+ offset += 1;
437
+
438
+ // ASN Integer (R) Byte Length
439
+ const rLen = sig[offset];
440
+ offset += 1;
441
+
442
+ // ASN Integer (R) Byte Value
443
+ if (rLen >= 33) {
444
+ if (rLen != 33 || sig[offset] != 0x00) {
445
+ throw "can only handle larger than 32 byte R's that are len 33 and lead with zero";
446
+ }
447
+ offset += 1;
448
+ }
449
+ const r = sig.slice(offset, offset + 32);
450
+ offset += 32;
451
+
452
+ // ASN Integer (S)
453
+ if (sig[offset] != 0x02) {
454
+ throw "second element in sequence is not an integer";
455
+ }
456
+ offset += 1;
457
+
458
+ // ASN Integer (S) Byte Length
459
+ const sLen = sig[offset];
460
+ offset += 1;
461
+
462
+ // ASN Integer (S) Byte Value
463
+ if (sLen >= 33) {
464
+ if (sLen != 33 || sig[offset] != 0x00) {
465
+ throw "can only handle larger than 32 byte R's that are len 33 and lead with zero";
466
+ }
467
+ offset += 1;
468
+ }
469
+
470
+ const s = sig.slice(offset, offset + 32);
471
+
472
+ offset += 32;
473
+
474
+ let signature64: Buffer
475
+
476
+ // Force low S range
477
+ // https://github.com/stellar/stellar-protocol/discussions/1435#discussioncomment-8809175
478
+ // https://discord.com/channels/897514728459468821/1233048618571927693
479
+ if (bufToBigint(s) > ((bufToBigint(q) - BigInt(1)) / BigInt(2))) {
480
+ signature64 = Buffer.from([...r, ...Buffer.from(bigintToBuf(bufToBigint(q) - bufToBigint(s), true) as ArrayBuffer)]);
481
+ } else {
482
+ signature64 = Buffer.from([...r, ...s]);
483
+ }
484
+
485
+ return signature64;
486
+ }
487
+ }
@@ -0,0 +1,15 @@
1
+ import { Networks, Transaction, Horizon } from '@stellar/stellar-sdk';
2
+ export declare class PasskeyBase {
3
+ networkPassphrase: Networks;
4
+ horizonUrl: string;
5
+ horizon: Horizon.Server;
6
+ feeBumpUrl: string | undefined;
7
+ feeBumpJwt: string | undefined;
8
+ constructor(options: {
9
+ networkPassphrase: Networks;
10
+ horizonUrl: string;
11
+ feeBumpUrl?: string;
12
+ feeBumpJwt?: string;
13
+ });
14
+ send(txn: Transaction, fee?: number): Promise<Horizon.HorizonApi.SubmitTransactionResponse>;
15
+ }
package/types/index.d.ts CHANGED
@@ -1,49 +1,3 @@
1
- import { Client as PasskeyClient } from 'passkey-kit-sdk';
2
- import { Client as FactoryClient } from 'passkey-factory-sdk';
3
- import { Networks, Transaction, Horizon, SorobanRpc } from '@stellar/stellar-sdk';
4
- import { Buffer } from 'buffer';
5
- export declare class PasskeyAccount {
6
- keyId: string | undefined;
7
- sudoKeyId: string | undefined;
8
- wallet: PasskeyClient | undefined;
9
- factory: FactoryClient;
10
- sequencePublicKey: string;
11
- networkPassphrase: Networks;
12
- horizonUrl: string;
13
- horizon: Horizon.Server;
14
- rpcUrl: string;
15
- rpc: SorobanRpc.Server;
16
- feeBumpUrl: string | undefined;
17
- feeBumpJwt: string | undefined;
18
- factoryContractId: string;
19
- constructor(options: {
20
- sequencePublicKey: string;
21
- networkPassphrase: Networks;
22
- horizonUrl: string;
23
- rpcUrl: string;
24
- feeBumpUrl?: string;
25
- feeBumpJwt?: string;
26
- factoryContractId?: string;
27
- });
28
- createWallet(name: string, user: string): Promise<{
29
- keyId: Buffer;
30
- contractId: string;
31
- xdr: string;
32
- }>;
33
- createKey(name: string, user: string): Promise<{
34
- keyId: Buffer;
35
- publicKey: Buffer;
36
- }>;
37
- connectWallet(id?: string): Promise<{
38
- keyId: Buffer;
39
- contractId: string;
40
- }>;
41
- sign(txn: Transaction | string, options?: {
42
- keyId?: 'any' | 'sudo' | string | Uint8Array;
43
- ledgersToLive?: number;
44
- }): Promise<string>;
45
- send(txn: Transaction, fee?: number): Promise<Horizon.HorizonApi.SubmitTransactionResponse>;
46
- getData(): Promise<Map<string, any>>;
47
- private getPublicKeyObject;
48
- private convertEcdsaSignatureAsnToCompact;
49
- }
1
+ import { PasskeyBase } from "./base";
2
+ import { PasskeyKit } from "./kit";
3
+ export { PasskeyBase, PasskeyKit };
@@ -2,19 +2,16 @@ import { Client as PasskeyClient } from 'passkey-kit-sdk';
2
2
  import { Client as FactoryClient } from 'passkey-factory-sdk';
3
3
  import { Networks, Transaction, Horizon, SorobanRpc } from '@stellar/stellar-sdk';
4
4
  import { Buffer } from 'buffer';
5
- export declare class PasskeyAccount {
5
+ import { PasskeyBase } from './base';
6
+ export declare class PasskeyKit extends PasskeyBase {
6
7
  keyId: string | undefined;
7
8
  sudoKeyId: string | undefined;
8
9
  wallet: PasskeyClient | undefined;
9
10
  factory: FactoryClient;
10
11
  sequencePublicKey: string;
11
- networkPassphrase: Networks;
12
- horizonUrl: string;
13
12
  horizon: Horizon.Server;
14
13
  rpcUrl: string;
15
14
  rpc: SorobanRpc.Server;
16
- feeBumpUrl: string | undefined;
17
- feeBumpJwt: string | undefined;
18
15
  factoryContractId: string;
19
16
  constructor(options: {
20
17
  sequencePublicKey: string;
@@ -42,7 +39,6 @@ export declare class PasskeyAccount {
42
39
  keyId?: 'any' | 'sudo' | string | Uint8Array;
43
40
  ledgersToLive?: number;
44
41
  }): Promise<string>;
45
- send(txn: Transaction, fee?: number): Promise<Horizon.HorizonApi.SubmitTransactionResponse>;
46
42
  getData(): Promise<Map<string, any>>;
47
43
  private getPublicKeyObject;
48
44
  private convertEcdsaSignatureAsnToCompact;