@substrate-system/keys 0.3.0 → 0.3.2
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/README.md +54 -18
- package/dist/_base.cjs +4 -4
- package/dist/_base.cjs.map +2 -2
- package/dist/_base.d.ts +6 -3
- package/dist/_base.d.ts.map +1 -1
- package/dist/_base.js +4 -4
- package/dist/_base.js.map +2 -2
- package/dist/_base.min.cjs.map +2 -2
- package/dist/_base.min.js +2 -2
- package/dist/_base.min.js.map +3 -3
- package/dist/aes/index.min.js +2 -2
- package/dist/aes/index.min.js.map +3 -3
- package/dist/browser/index.js +102 -23
- package/dist/browser/index.min.js +2 -2
- package/dist/crypto.min.js +2 -2
- package/dist/crypto.min.js.map +3 -3
- package/dist/ecc/index.cjs +16 -1
- package/dist/ecc/index.cjs.map +2 -2
- package/dist/ecc/index.d.ts +6 -1
- package/dist/ecc/index.d.ts.map +1 -1
- package/dist/ecc/index.js +16 -1
- package/dist/ecc/index.js.map +2 -2
- package/dist/ecc/index.min.cjs +1 -1
- package/dist/ecc/index.min.cjs.map +3 -3
- package/dist/ecc/index.min.js +2 -2
- package/dist/ecc/index.min.js.map +3 -3
- package/dist/index.min.js +2 -2
- package/dist/index.min.js.map +3 -3
- package/dist/meta.json +12 -12
- package/dist/rsa/index.cjs +24 -1
- package/dist/rsa/index.cjs.map +2 -2
- package/dist/rsa/index.d.ts +16 -1
- package/dist/rsa/index.d.ts.map +1 -1
- package/dist/rsa/index.js +24 -1
- package/dist/rsa/index.js.map +2 -2
- package/dist/rsa/index.min.cjs +1 -1
- package/dist/rsa/index.min.cjs.map +3 -3
- package/dist/rsa/index.min.js +2 -2
- package/dist/rsa/index.min.js.map +3 -3
- package/dist/util.min.js +1 -1
- package/dist/util.min.js.map +3 -3
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
[](LICENSE)
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
Create and store keypairs in the browser with the
|
|
11
|
+
Create and store keypairs in the browser with the
|
|
12
|
+
[web crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API).
|
|
12
13
|
|
|
13
14
|
Use [`indexedDB`](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
|
|
14
|
-
to store
|
|
15
|
+
to store
|
|
16
|
+
[non-extractable keypairs](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey#extractable)
|
|
15
17
|
in the browser. "Non-extractable" means that the browser prevents you from ever
|
|
16
18
|
reading the private key, but the keys can still be persisted and
|
|
17
19
|
re-used indefinitely.
|
|
@@ -19,13 +21,14 @@ re-used indefinitely.
|
|
|
19
21
|
>
|
|
20
22
|
> [!TIP]
|
|
21
23
|
> Use the [persist method](https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist)
|
|
22
|
-
> to
|
|
24
|
+
> to request that the browser not delete from `indexedDB`.
|
|
23
25
|
>
|
|
24
26
|
|
|
25
27
|
Each instance of `Keys` has two keypairs — one for signing, and another
|
|
26
28
|
for encrypting.
|
|
27
29
|
|
|
28
|
-
See also,
|
|
30
|
+
See also,
|
|
31
|
+
[the API docs generated from typescript](https://substrate-system.github.io/keys/).
|
|
29
32
|
|
|
30
33
|
<details><summary><h2>Contents</h2></summary>
|
|
31
34
|
|
|
@@ -46,7 +49,7 @@ See also, [the API docs generated from typescript](https://substrate-system.gith
|
|
|
46
49
|
+ [`crypto.verify`](#cryptoverify)
|
|
47
50
|
+ [`crypto.keyTypeFromDid`](#cryptokeytypefromdid)
|
|
48
51
|
- [Get started](#get-started)
|
|
49
|
-
* [
|
|
52
|
+
* [Storage](#storage)
|
|
50
53
|
* [ECC keys](#ecc-keys)
|
|
51
54
|
+ [Create a keypair](#create-a-keypair)
|
|
52
55
|
+ [Encrypt a Message](#encrypt-a-message)
|
|
@@ -68,6 +71,7 @@ See also, [the API docs generated from typescript](https://substrate-system.gith
|
|
|
68
71
|
+ [`keys.encryptAsString` methods](#keysencryptasstring-methods)
|
|
69
72
|
* [decrypt something](#decrypt-something)
|
|
70
73
|
- [Examples](#examples)
|
|
74
|
+
* [Verify a signature](#verify-a-signature)
|
|
71
75
|
* [Create a new `Keys` instance](#create-a-new-keys-instance)
|
|
72
76
|
+ [Parameters](#parameters)
|
|
73
77
|
+ [`.create()` example](#create-example)
|
|
@@ -243,20 +247,30 @@ const rsaType = keyTypeFromDid(rsaKeys.DID)
|
|
|
243
247
|
|
|
244
248
|
## Get started
|
|
245
249
|
|
|
246
|
-
###
|
|
250
|
+
### Storage
|
|
247
251
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
verify something.
|
|
252
|
+
Can use `dbKey` in `.create` or `.load` to add a prefix to both stored key
|
|
253
|
+
names:
|
|
251
254
|
|
|
252
|
-
```
|
|
253
|
-
|
|
255
|
+
```ts
|
|
256
|
+
const keys = await EccKeys.create(false, false, { dbKey: 'alice' })
|
|
257
|
+
await keys.persist()
|
|
258
|
+
```
|
|
254
259
|
|
|
255
|
-
|
|
256
|
-
|
|
260
|
+
For `.create`, pass `dbKey` in the third argument to prefix both IndexedDB
|
|
261
|
+
key names. For example, `dbKey: 'alice'` stores ECC keypairs as
|
|
262
|
+
`alice.ecc-exchange` and `alice.ecc-write`, or RSA keypairs as
|
|
263
|
+
`alice.rsa-exchange-key` and `alice.rsa-write-key`.
|
|
257
264
|
|
|
258
|
-
|
|
259
|
-
const
|
|
265
|
+
```ts
|
|
266
|
+
const rsaKeys = await RsaKeys.create(false, false, { dbKey: 'alice' })
|
|
267
|
+
await rsaKeys.persist()
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
For `.load`, pass `dbKey` in the options.
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
const keys = await EccKeys.load({ dbKey: 'alice' })
|
|
260
274
|
```
|
|
261
275
|
|
|
262
276
|
### ECC keys
|
|
@@ -673,11 +687,26 @@ const decrypted = await keys.decrypt(encryptedMsg)
|
|
|
673
687
|
|
|
674
688
|
## Examples
|
|
675
689
|
|
|
690
|
+
### Verify a signature
|
|
691
|
+
|
|
692
|
+
This is exposed as a separate import so that you do not need to bundle all of
|
|
693
|
+
`keys` just to verify a signature.
|
|
694
|
+
|
|
695
|
+
```js
|
|
696
|
+
import { verify } from '@substrate-system/keys/crypto'
|
|
697
|
+
|
|
698
|
+
// ed25519
|
|
699
|
+
const isOk = await verify({ message, publicKey: ecc.DID, signature })
|
|
700
|
+
|
|
701
|
+
// RSA
|
|
702
|
+
const isOk = await verify({ message, publicKey: rsa.DID, signature })
|
|
703
|
+
```
|
|
704
|
+
|
|
676
705
|
### Create a new `Keys` instance
|
|
677
706
|
|
|
678
|
-
Use the factory function `EccKeys.create` or `RsaKeys.create`. The optional
|
|
679
|
-
`
|
|
680
|
-
`
|
|
707
|
+
Use the factory function `EccKeys.create` or `RsaKeys.create`. The optional
|
|
708
|
+
`dbKey` parameter prefixes the names used to save both keypairs in
|
|
709
|
+
`indexedDB`.
|
|
681
710
|
|
|
682
711
|
**ECC:**
|
|
683
712
|
```ts
|
|
@@ -689,6 +718,7 @@ class EccKeys {
|
|
|
689
718
|
session?:boolean, // default false
|
|
690
719
|
extractable?:boolean,
|
|
691
720
|
keys?:{
|
|
721
|
+
dbKey?:string,
|
|
692
722
|
exchangeKeys?:CryptoKeyPair|null,
|
|
693
723
|
writeKeys?:CryptoKeyPair|null,
|
|
694
724
|
}
|
|
@@ -705,6 +735,7 @@ class RsaKeys {
|
|
|
705
735
|
session?:boolean, // defaut false
|
|
706
736
|
extractable?:boolean,
|
|
707
737
|
keys?:{
|
|
738
|
+
dbKey?:string,
|
|
708
739
|
exchangeKeys?:CryptoKeyPair|null,
|
|
709
740
|
writeKeys?:CryptoKeyPair|null,
|
|
710
741
|
}
|
|
@@ -716,6 +747,9 @@ class RsaKeys {
|
|
|
716
747
|
|
|
717
748
|
- `session` (optional, boolean): If `true`, keys are created in memory only and won't be saved to `indexedDB` even if `persist()` is called.
|
|
718
749
|
- `extractable` (optional, boolean): If `true`, creates extractable keys that can be exported/read. Defaults to `false` for security.
|
|
750
|
+
- `keys.dbKey` (optional, string): Prefix for both IndexedDB key names.
|
|
751
|
+
- `keys.exchangeKeys` (optional): Existing exchange keypair to use.
|
|
752
|
+
- `keys.writeKeys` (optional): Existing signing keypair to use.
|
|
719
753
|
|
|
720
754
|
>
|
|
721
755
|
> [!WARNING]
|
|
@@ -815,6 +849,7 @@ remember. Pass `{ persist: false }` if you want the old two-step behavior.
|
|
|
815
849
|
```ts
|
|
816
850
|
class EccKeys { // or RsaKeys
|
|
817
851
|
static async load (opts?:{
|
|
852
|
+
dbKey?:string,
|
|
818
853
|
encryptionKeyName?:string,
|
|
819
854
|
writeKeyName?:string,
|
|
820
855
|
session?:boolean,
|
|
@@ -828,6 +863,7 @@ class EccKeys { // or RsaKeys
|
|
|
828
863
|
|
|
829
864
|
- `encryptionKeyName` (optional, string): Custom name for the encryption key in `indexedDB`
|
|
830
865
|
- `writeKeyName` (optional, string): Custom name for the signing key in `indexedDB`
|
|
866
|
+
- `dbKey` (optional, string): Prefix for both default IndexedDB key names.
|
|
831
867
|
- `session` (optional, boolean): If `true`, creates session-only keys if no keys exist in `indexedDB`
|
|
832
868
|
- `extractable` (optional, boolean): If `true` and keys don't exist in `indexedDB`, new keys will be created as extractable. Defaults to `false`.
|
|
833
869
|
- `persist` (optional, boolean): Save the keys to `indexedDB` before returning. Defaults to `true`. Session keys are never written, so `session: true` wins over this.
|
package/dist/_base.cjs
CHANGED
|
@@ -238,9 +238,10 @@ const _AbstractKeys = class _AbstractKeys {
|
|
|
238
238
|
* to skip that and call `.persist()` yourself. Session keys are never
|
|
239
239
|
* written to `indexedDB`, so `{ session: true }` wins over `persist`.
|
|
240
240
|
*
|
|
241
|
-
* @param {{ encryptionKeyName, signingKeyName,
|
|
242
|
-
*
|
|
243
|
-
*
|
|
241
|
+
* @param {{ dbKey, encryptionKeyName, signingKeyName,
|
|
242
|
+
* session, persist }} opts
|
|
243
|
+
* `dbKey` prefixes both default indexedDB names. Other strings are
|
|
244
|
+
* custom names, plus session and persist options.
|
|
244
245
|
* @returns {Promise<AbstractKeys>}
|
|
245
246
|
*/
|
|
246
247
|
static async load(opts = {
|
|
@@ -284,7 +285,6 @@ const _AbstractKeys = class _AbstractKeys {
|
|
|
284
285
|
}
|
|
285
286
|
};
|
|
286
287
|
__name(_AbstractKeys, "AbstractKeys");
|
|
287
|
-
// type:'ecc'|'rsa'
|
|
288
288
|
__publicField(_AbstractKeys, "EXCHANGE_KEY_NAME");
|
|
289
289
|
// needs to be defined by child class
|
|
290
290
|
__publicField(_AbstractKeys, "WRITE_KEY_NAME");
|
package/dist/_base.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/_base.ts"],
|
|
4
|
-
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\nimport { KeysDeletedError } from './errors.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport { KeysDeletedError }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n pulicExchangeKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n hasPersisted:boolean\n isSessionOnly:boolean\n /**\n * Have these keys been deleted? A deleted keypair is terminal -- the key\n * material is gone, and any use of it throws.\n */\n destroyed:boolean\n /**\n * The `indexedDB` names this keypair was loaded from, and the names\n * `persist` and `delete` will use.\n */\n readonly exchangeKeyName:string\n readonly writeKeyName:string\n // type:'ecc'|'rsa'\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n // the key material -- read it via the `exchangeKey`/`writeKey` getters,\n // which throw if this instance was deleted\n protected _exchangeKey:CryptoKeyPair|null\n protected _writeKey:CryptoKeyPair|null\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n const ctor = this.constructor as typeof AbstractKeys\n this.DID = opts.did\n this._exchangeKey = keys.exchange\n this._writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n this.destroyed = false\n this.exchangeKeyName = opts.exchangeKeyName || ctor.EXCHANGE_KEY_NAME\n this.writeKeyName = opts.writeKeyName || ctor.WRITE_KEY_NAME\n }\n\n get exchangeKey ():CryptoKeyPair {\n if (this.destroyed || !this._exchangeKey) throw new KeysDeletedError()\n return this._exchangeKey\n }\n\n get writeKey ():CryptoKeyPair {\n if (this.destroyed || !this._writeKey) throw new KeysDeletedError()\n return this._writeKey\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.destroyed) throw new KeysDeletedError()\n if (this.isSessionOnly) return\n\n await Promise.all([\n set(this.exchangeKeyName, this.exchangeKey),\n set(this.writeKeyName, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete this keypair. This deletes the keys from indexedDB, drops the\n * in-memory key material, and clears the instance cache, so `load` will\n * not hand out these keys again.\n *\n * After this, the instance is `destroyed` -- using it throws\n * a `KeysDeletedError`.\n */\n async delete ():Promise<void> {\n const exchangeName = this.exchangeKeyName\n const writeName = this.writeKeyName\n await delMany([exchangeName, writeName])\n const ctor = this.constructor as typeof AbstractKeys\n ctor._invalidate(exchangeName, writeName)\n this._destroy()\n }\n\n /**\n * Drop the in-memory key material. Internal -- call `delete` instead.\n */\n _destroy ():void {\n this.destroyed = true\n this.hasPersisted = false\n this._exchangeKey = null\n this._writeKey = null\n }\n\n /**\n * If the cached instance was loaded from the given names, then its keys\n * are gone too. Destroy it, and clear the cache. Internal.\n */\n static _invalidate (exchangeName:string, writeName:string):void {\n const cached:AbstractKeys|null = this._instance\n if (!cached) return\n if (cached.exchangeKeyName !== exchangeName) return\n if (cached.writeKeyName !== writeName) return\n cached._destroy()\n this._instance = null\n }\n\n /**\n * Delete a stored keypair without loading it first. Deletes the keys from\n * indexedDB, and destroys the cached instance, if there is one for\n * these names.\n *\n * @param {{ encryptionKeyName, writeKeyName }} [opts] The indexedDB names\n * to delete. Defaults to this class's names.\n */\n static async delete (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<void> {\n const exchangeName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeName = opts.writeKeyName || this.WRITE_KEY_NAME\n await delMany([exchangeName, writeName])\n this._invalidate(exchangeName, writeName)\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n static async exist (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<boolean> {\n const keys = await get(opts.writeKeyName || this.WRITE_KEY_NAME)\n const excahngeKeys = await get(opts.encryptionKeyName || this.EXCHANGE_KEY_NAME)\n if (!keys || !excahngeKeys) return false\n return true\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * By default this saves the keys to `indexedDB` before returning, so the\n * keypair you get back survives a page reload. Pass `{ persist: false }`\n * to skip that and call `.persist()` yourself. Session keys are never\n * written to `indexedDB`, so `{ session: true }` wins over `persist`.\n *\n * @param {{ encryptionKeyName, signingKeyName, session, persist }} opts\n * Strings to use as keys in indexedDB, a session boolean -- is this in\n * memory only? Or can it be persisted -- and a persist boolean.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n const shouldPersist = opts.persist !== false\n const exchangeKeyName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeKeyName = opts.writeKeyName || this.WRITE_KEY_NAME\n\n // cache -- only if it is for the same indexedDB entries\n const cached:AbstractKeys|null = this._instance\n if (\n cached &&\n !cached.destroyed &&\n cached.exchangeKeyName === exchangeKeyName &&\n cached.writeKeyName === writeKeyName\n ) {\n if (shouldPersist && !cached.hasPersisted) await cached.persist()\n return cached as T\n }\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(exchangeKeyName)\n let writeKeys:CryptoKeyPair|undefined = await get(writeKeyName)\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session,\n exchangeKeyName,\n writeKeyName\n }) as T\n\n this._instance = keys\n if (shouldPersist && !hasPersisted) await keys.persist()\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().encode(did.normalize('NFD'))\n )\n\n return toString(hashedUsername, 'base32').slice(0, 32)\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA8D;AAC9D,wBAAkC;AAQlC,iBAAoB;AACpB,kBAIO;AACP,oBAIO;AACP,oBAAiC;AAIjC,yBAAc,2BAxBd;AA0BA,IAAAA,iBAAyC;AAkFlC,MAAe,gBAAf,MAAe,cAAa;AAAA,
|
|
4
|
+
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\nimport { KeysDeletedError } from './errors.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport { KeysDeletedError }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n pulicExchangeKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n hasPersisted:boolean\n isSessionOnly:boolean\n /**\n * Have these keys been deleted? A deleted keypair is terminal -- the key\n * material is gone, and any use of it throws.\n */\n destroyed:boolean\n /**\n * The `indexedDB` names this keypair was loaded from, and the names\n * `persist` and `delete` will use.\n */\n readonly exchangeKeyName:string\n readonly writeKeyName:string\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n // the key material -- read it via the `exchangeKey`/`writeKey` getters,\n // which throw if this instance was deleted\n protected _exchangeKey:CryptoKeyPair|null\n protected _writeKey:CryptoKeyPair|null\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n const ctor = this.constructor as typeof AbstractKeys\n this.DID = opts.did\n this._exchangeKey = keys.exchange\n this._writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n this.destroyed = false\n this.exchangeKeyName = opts.exchangeKeyName || ctor.EXCHANGE_KEY_NAME\n this.writeKeyName = opts.writeKeyName || ctor.WRITE_KEY_NAME\n }\n\n get exchangeKey ():CryptoKeyPair {\n if (this.destroyed || !this._exchangeKey) throw new KeysDeletedError()\n return this._exchangeKey\n }\n\n get writeKey ():CryptoKeyPair {\n if (this.destroyed || !this._writeKey) throw new KeysDeletedError()\n return this._writeKey\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.destroyed) throw new KeysDeletedError()\n if (this.isSessionOnly) return\n\n await Promise.all([\n set(this.exchangeKeyName, this.exchangeKey),\n set(this.writeKeyName, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete this keypair. This deletes the keys from indexedDB, drops the\n * in-memory key material, and clears the instance cache, so `load` will\n * not hand out these keys again.\n *\n * After this, the instance is `destroyed` -- using it throws\n * a `KeysDeletedError`.\n */\n async delete ():Promise<void> {\n const exchangeName = this.exchangeKeyName\n const writeName = this.writeKeyName\n await delMany([exchangeName, writeName])\n const ctor = this.constructor as typeof AbstractKeys\n ctor._invalidate(exchangeName, writeName)\n this._destroy()\n }\n\n /**\n * Drop the in-memory key material. Internal -- call `delete` instead.\n */\n _destroy ():void {\n this.destroyed = true\n this.hasPersisted = false\n this._exchangeKey = null\n this._writeKey = null\n }\n\n /**\n * If the cached instance was loaded from the given names, then its keys\n * are gone too. Destroy it, and clear the cache. Internal.\n */\n static _invalidate (exchangeName:string, writeName:string):void {\n const cached:AbstractKeys|null = this._instance\n if (!cached) return\n if (cached.exchangeKeyName !== exchangeName) return\n if (cached.writeKeyName !== writeName) return\n cached._destroy()\n this._instance = null\n }\n\n /**\n * Delete a stored keypair without loading it first. Deletes the keys from\n * indexedDB, and destroys the cached instance, if there is one for\n * these names.\n *\n * @param {{ encryptionKeyName, writeKeyName }} [opts] The indexedDB names\n * to delete. Defaults to this class's names.\n */\n static async delete (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<void> {\n const exchangeName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeName = opts.writeKeyName || this.WRITE_KEY_NAME\n await delMany([exchangeName, writeName])\n this._invalidate(exchangeName, writeName)\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n dbKey?:string,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n static async exist (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<boolean> {\n const keys = await get(opts.writeKeyName || this.WRITE_KEY_NAME)\n const excahngeKeys = await get(opts.encryptionKeyName || this.EXCHANGE_KEY_NAME)\n if (!keys || !excahngeKeys) return false\n return true\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * By default this saves the keys to `indexedDB` before returning, so the\n * keypair you get back survives a page reload. Pass `{ persist: false }`\n * to skip that and call `.persist()` yourself. Session keys are never\n * written to `indexedDB`, so `{ session: true }` wins over `persist`.\n *\n * @param {{ dbKey, encryptionKeyName, signingKeyName,\n * session, persist }} opts\n * `dbKey` prefixes both default indexedDB names. Other strings are\n * custom names, plus session and persist options.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n const shouldPersist = opts.persist !== false\n const exchangeKeyName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeKeyName = opts.writeKeyName || this.WRITE_KEY_NAME\n\n // cache -- only if it is for the same indexedDB entries\n const cached:AbstractKeys|null = this._instance\n if (\n cached &&\n !cached.destroyed &&\n cached.exchangeKeyName === exchangeKeyName &&\n cached.writeKeyName === writeKeyName\n ) {\n if (shouldPersist && !cached.hasPersisted) await cached.persist()\n return cached as T\n }\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(exchangeKeyName)\n let writeKeys:CryptoKeyPair|undefined = await get(writeKeyName)\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session,\n exchangeKeyName,\n writeKeyName\n }) as T\n\n this._instance = keys\n if (shouldPersist && !hasPersisted) await keys.persist()\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().enc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,OAAO;AACH,WAAO;AAAA,EACX;AAEA,QAAM,MAAM,MAAM,4BAAc,QAAQ,MAAM,SAAS;AACvD,MAAI,UAAU,WAAW,cAAe,QAAO;AAC/C,SAAO,IAAI,WAAW,GAAG;AAC7B;AAdsB;AAgBtB,aAAa,WAAW,eAAgB,EAAE,KAAK,UAAU,GAGtD,QAA4C;AAC3C,QAAM,QAAQ,MAAM,aAAa,EAAE,KAAK,UAAU,CAAC;AACnD,SAAO,aAAS,6BAAS,OAAO,MAAM,QAAI,sBAAS,KAAK;AAC5D;AAkCA,eAAsB,cAAe,KAAgB;AACjD,QAAM,iBAAiB,UAAM;AAAA,IACzB,IAAI,YAAY,EAAE,OAAO,IAAI,UAAU,KAAK,CAAC;AAAA,EACjD;AAEA,aAAO,6BAAS,gBAAgB,QAAQ,EAAE,MAAM,GAAG,EAAE;AACzD;AANsB;",
|
|
6
6
|
"names": ["import_crypto"]
|
|
7
7
|
}
|
package/dist/_base.d.ts
CHANGED
|
@@ -167,6 +167,7 @@ export declare abstract class AbstractKeys {
|
|
|
167
167
|
static create<T extends AbstractKeys>(this: ChildKeys, session?: boolean, extractable?: boolean, keys?: {
|
|
168
168
|
exchangeKeys?: CryptoKeyPair | null;
|
|
169
169
|
writeKeys?: CryptoKeyPair | null;
|
|
170
|
+
dbKey?: string;
|
|
170
171
|
}): Promise<T>;
|
|
171
172
|
static exist(opts?: {
|
|
172
173
|
encryptionKeyName?: string;
|
|
@@ -181,12 +182,14 @@ export declare abstract class AbstractKeys {
|
|
|
181
182
|
* to skip that and call `.persist()` yourself. Session keys are never
|
|
182
183
|
* written to `indexedDB`, so `{ session: true }` wins over `persist`.
|
|
183
184
|
*
|
|
184
|
-
* @param {{ encryptionKeyName, signingKeyName,
|
|
185
|
-
*
|
|
186
|
-
*
|
|
185
|
+
* @param {{ dbKey, encryptionKeyName, signingKeyName,
|
|
186
|
+
* session, persist }} opts
|
|
187
|
+
* `dbKey` prefixes both default indexedDB names. Other strings are
|
|
188
|
+
* custom names, plus session and persist options.
|
|
187
189
|
* @returns {Promise<AbstractKeys>}
|
|
188
190
|
*/
|
|
189
191
|
static load<T extends AbstractKeys = AbstractKeys>(this: ChildKeys & typeof AbstractKeys, opts?: Partial<{
|
|
192
|
+
dbKey: string;
|
|
190
193
|
encryptionKeyName: string;
|
|
191
194
|
writeKeyName: string;
|
|
192
195
|
session: boolean;
|
package/dist/_base.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_base.d.ts","sourceRoot":"","sources":["../src/_base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,kBAAkB,EAAY,MAAM,aAAa,CAAA;AAE3E,OAAO,KAAK,EACR,QAAQ,EACR,GAAG,EACH,aAAa,EACb,GAAG,EACH,OAAO,EACV,MAAM,YAAY,CAAA;AAOnB,OAAO,EAEH,cAAc,EACd,yBAAyB,EAC5B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAE9C,OAAO,EAAE,cAAc,EAAE,yBAAyB,EAAE,CAAA;AACpD,OAAO,EAAE,gBAAgB,EAAE,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,YAAY,EAAE,GAAG,EAAE,CAAA;AACnB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AACtD,MAAM,MAAM,cAAc,GAAG;IACzB,GAAG,EAAC,GAAG,CAAC;IACR,gBAAgB,EAAC,MAAM,CAAC;CAC3B,CAAA;AAED,MAAM,WAAW,YAAY;IACzB,CACI,OAAO,EAAC,MAAM,GAAC,UAAU,EACzB,SAAS,CAAC,EAAC,SAAS,GAAC,MAAM,EAC3B,MAAM,CAAC,EAAC,OAAO,GAAC,UAAU,GAAC,MAAM,EACjC,OAAO,CAAC,EAAC,aAAa,GACxB,OAAO,CAAC,UAAU,CAAC,CAAA;CACxB;AAED,MAAM,WAAW,YAAY;IACzB,CACI,OAAO,EAAC,MAAM,GAAC,UA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SAAS,GAAE,OAAO,CAAC,UAAU,CAAC,CAAA;yBAHnB,YAAY;uCA6ByB;QACvD,GAAG,EAAC,MAAM,GAAC,UAAU,GAAC,SAAS,CAAC;QAChC,SAAS,EAAC,SAAS,GAAC,MAAM,GAAC,UAAU,CAAC;KACzC,WAAU,kBAAkB,KAAE,OAAO,CAAC,MAAM,CAAC;;AAqC9C,wBAAsB,aAAa,CAAE,GAAG,EAAC,GAAG,GAAC,MAAM,mBAMlD"}
|
package/dist/_base.js
CHANGED
|
@@ -216,9 +216,10 @@ const _AbstractKeys = class _AbstractKeys {
|
|
|
216
216
|
* to skip that and call `.persist()` yourself. Session keys are never
|
|
217
217
|
* written to `indexedDB`, so `{ session: true }` wins over `persist`.
|
|
218
218
|
*
|
|
219
|
-
* @param {{ encryptionKeyName, signingKeyName,
|
|
220
|
-
*
|
|
221
|
-
*
|
|
219
|
+
* @param {{ dbKey, encryptionKeyName, signingKeyName,
|
|
220
|
+
* session, persist }} opts
|
|
221
|
+
* `dbKey` prefixes both default indexedDB names. Other strings are
|
|
222
|
+
* custom names, plus session and persist options.
|
|
222
223
|
* @returns {Promise<AbstractKeys>}
|
|
223
224
|
*/
|
|
224
225
|
static async load(opts = {
|
|
@@ -262,7 +263,6 @@ const _AbstractKeys = class _AbstractKeys {
|
|
|
262
263
|
}
|
|
263
264
|
};
|
|
264
265
|
__name(_AbstractKeys, "AbstractKeys");
|
|
265
|
-
// type:'ecc'|'rsa'
|
|
266
266
|
__publicField(_AbstractKeys, "EXCHANGE_KEY_NAME");
|
|
267
267
|
// needs to be defined by child class
|
|
268
268
|
__publicField(_AbstractKeys, "WRITE_KEY_NAME");
|
package/dist/_base.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/_base.ts"],
|
|
4
|
-
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\nimport { KeysDeletedError } from './errors.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport { KeysDeletedError }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n pulicExchangeKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n hasPersisted:boolean\n isSessionOnly:boolean\n /**\n * Have these keys been deleted? A deleted keypair is terminal -- the key\n * material is gone, and any use of it throws.\n */\n destroyed:boolean\n /**\n * The `indexedDB` names this keypair was loaded from, and the names\n * `persist` and `delete` will use.\n */\n readonly exchangeKeyName:string\n readonly writeKeyName:string\n // type:'ecc'|'rsa'\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n // the key material -- read it via the `exchangeKey`/`writeKey` getters,\n // which throw if this instance was deleted\n protected _exchangeKey:CryptoKeyPair|null\n protected _writeKey:CryptoKeyPair|null\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n const ctor = this.constructor as typeof AbstractKeys\n this.DID = opts.did\n this._exchangeKey = keys.exchange\n this._writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n this.destroyed = false\n this.exchangeKeyName = opts.exchangeKeyName || ctor.EXCHANGE_KEY_NAME\n this.writeKeyName = opts.writeKeyName || ctor.WRITE_KEY_NAME\n }\n\n get exchangeKey ():CryptoKeyPair {\n if (this.destroyed || !this._exchangeKey) throw new KeysDeletedError()\n return this._exchangeKey\n }\n\n get writeKey ():CryptoKeyPair {\n if (this.destroyed || !this._writeKey) throw new KeysDeletedError()\n return this._writeKey\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.destroyed) throw new KeysDeletedError()\n if (this.isSessionOnly) return\n\n await Promise.all([\n set(this.exchangeKeyName, this.exchangeKey),\n set(this.writeKeyName, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete this keypair. This deletes the keys from indexedDB, drops the\n * in-memory key material, and clears the instance cache, so `load` will\n * not hand out these keys again.\n *\n * After this, the instance is `destroyed` -- using it throws\n * a `KeysDeletedError`.\n */\n async delete ():Promise<void> {\n const exchangeName = this.exchangeKeyName\n const writeName = this.writeKeyName\n await delMany([exchangeName, writeName])\n const ctor = this.constructor as typeof AbstractKeys\n ctor._invalidate(exchangeName, writeName)\n this._destroy()\n }\n\n /**\n * Drop the in-memory key material. Internal -- call `delete` instead.\n */\n _destroy ():void {\n this.destroyed = true\n this.hasPersisted = false\n this._exchangeKey = null\n this._writeKey = null\n }\n\n /**\n * If the cached instance was loaded from the given names, then its keys\n * are gone too. Destroy it, and clear the cache. Internal.\n */\n static _invalidate (exchangeName:string, writeName:string):void {\n const cached:AbstractKeys|null = this._instance\n if (!cached) return\n if (cached.exchangeKeyName !== exchangeName) return\n if (cached.writeKeyName !== writeName) return\n cached._destroy()\n this._instance = null\n }\n\n /**\n * Delete a stored keypair without loading it first. Deletes the keys from\n * indexedDB, and destroys the cached instance, if there is one for\n * these names.\n *\n * @param {{ encryptionKeyName, writeKeyName }} [opts] The indexedDB names\n * to delete. Defaults to this class's names.\n */\n static async delete (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<void> {\n const exchangeName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeName = opts.writeKeyName || this.WRITE_KEY_NAME\n await delMany([exchangeName, writeName])\n this._invalidate(exchangeName, writeName)\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n static async exist (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<boolean> {\n const keys = await get(opts.writeKeyName || this.WRITE_KEY_NAME)\n const excahngeKeys = await get(opts.encryptionKeyName || this.EXCHANGE_KEY_NAME)\n if (!keys || !excahngeKeys) return false\n return true\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * By default this saves the keys to `indexedDB` before returning, so the\n * keypair you get back survives a page reload. Pass `{ persist: false }`\n * to skip that and call `.persist()` yourself. Session keys are never\n * written to `indexedDB`, so `{ session: true }` wins over `persist`.\n *\n * @param {{ encryptionKeyName, signingKeyName, session, persist }} opts\n * Strings to use as keys in indexedDB, a session boolean -- is this in\n * memory only? Or can it be persisted -- and a persist boolean.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n const shouldPersist = opts.persist !== false\n const exchangeKeyName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeKeyName = opts.writeKeyName || this.WRITE_KEY_NAME\n\n // cache -- only if it is for the same indexedDB entries\n const cached:AbstractKeys|null = this._instance\n if (\n cached &&\n !cached.destroyed &&\n cached.exchangeKeyName === exchangeKeyName &&\n cached.writeKeyName === writeKeyName\n ) {\n if (shouldPersist && !cached.hasPersisted) await cached.persist()\n return cached as T\n }\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(exchangeKeyName)\n let writeKeys:CryptoKeyPair|undefined = await get(writeKeyName)\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session,\n exchangeKeyName,\n writeKeyName\n }) as T\n\n this._instance = keys\n if (shouldPersist && !hasPersisted) await keys.persist()\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().encode(did.normalize('NFD'))\n )\n\n return toString(hashedUsername, 'base32').slice(0, 32)\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAAA,SAAS,YAAqC,gBAAgB;AAC9D,SAAS,KAAK,KAAK,eAAe;AAQlC,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,wBAAwB;AAIjC,cAAc;AAEd,SAAS,gCAAgC;AAkFlC,MAAe,gBAAf,MAAe,cAAa;AAAA,
|
|
4
|
+
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\nimport { KeysDeletedError } from './errors.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport { KeysDeletedError }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n pulicExchangeKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n hasPersisted:boolean\n isSessionOnly:boolean\n /**\n * Have these keys been deleted? A deleted keypair is terminal -- the key\n * material is gone, and any use of it throws.\n */\n destroyed:boolean\n /**\n * The `indexedDB` names this keypair was loaded from, and the names\n * `persist` and `delete` will use.\n */\n readonly exchangeKeyName:string\n readonly writeKeyName:string\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n // the key material -- read it via the `exchangeKey`/`writeKey` getters,\n // which throw if this instance was deleted\n protected _exchangeKey:CryptoKeyPair|null\n protected _writeKey:CryptoKeyPair|null\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n const ctor = this.constructor as typeof AbstractKeys\n this.DID = opts.did\n this._exchangeKey = keys.exchange\n this._writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n this.destroyed = false\n this.exchangeKeyName = opts.exchangeKeyName || ctor.EXCHANGE_KEY_NAME\n this.writeKeyName = opts.writeKeyName || ctor.WRITE_KEY_NAME\n }\n\n get exchangeKey ():CryptoKeyPair {\n if (this.destroyed || !this._exchangeKey) throw new KeysDeletedError()\n return this._exchangeKey\n }\n\n get writeKey ():CryptoKeyPair {\n if (this.destroyed || !this._writeKey) throw new KeysDeletedError()\n return this._writeKey\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null,\n aesKeyOrInfo?:SymmKey|Uint8Array|string|null,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength|null,\n aesAlgorithm?:string|null,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.destroyed) throw new KeysDeletedError()\n if (this.isSessionOnly) return\n\n await Promise.all([\n set(this.exchangeKeyName, this.exchangeKey),\n set(this.writeKeyName, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete this keypair. This deletes the keys from indexedDB, drops the\n * in-memory key material, and clears the instance cache, so `load` will\n * not hand out these keys again.\n *\n * After this, the instance is `destroyed` -- using it throws\n * a `KeysDeletedError`.\n */\n async delete ():Promise<void> {\n const exchangeName = this.exchangeKeyName\n const writeName = this.writeKeyName\n await delMany([exchangeName, writeName])\n const ctor = this.constructor as typeof AbstractKeys\n ctor._invalidate(exchangeName, writeName)\n this._destroy()\n }\n\n /**\n * Drop the in-memory key material. Internal -- call `delete` instead.\n */\n _destroy ():void {\n this.destroyed = true\n this.hasPersisted = false\n this._exchangeKey = null\n this._writeKey = null\n }\n\n /**\n * If the cached instance was loaded from the given names, then its keys\n * are gone too. Destroy it, and clear the cache. Internal.\n */\n static _invalidate (exchangeName:string, writeName:string):void {\n const cached:AbstractKeys|null = this._instance\n if (!cached) return\n if (cached.exchangeKeyName !== exchangeName) return\n if (cached.writeKeyName !== writeName) return\n cached._destroy()\n this._instance = null\n }\n\n /**\n * Delete a stored keypair without loading it first. Deletes the keys from\n * indexedDB, and destroys the cached instance, if there is one for\n * these names.\n *\n * @param {{ encryptionKeyName, writeKeyName }} [opts] The indexedDB names\n * to delete. Defaults to this class's names.\n */\n static async delete (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<void> {\n const exchangeName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeName = opts.writeKeyName || this.WRITE_KEY_NAME\n await delMany([exchangeName, writeName])\n this._invalidate(exchangeName, writeName)\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n dbKey?:string,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n static async exist (opts:{\n encryptionKeyName?:string,\n writeKeyName?:string\n } = {}):Promise<boolean> {\n const keys = await get(opts.writeKeyName || this.WRITE_KEY_NAME)\n const excahngeKeys = await get(opts.encryptionKeyName || this.EXCHANGE_KEY_NAME)\n if (!keys || !excahngeKeys) return false\n return true\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * By default this saves the keys to `indexedDB` before returning, so the\n * keypair you get back survives a page reload. Pass `{ persist: false }`\n * to skip that and call `.persist()` yourself. Session keys are never\n * written to `indexedDB`, so `{ session: true }` wins over `persist`.\n *\n * @param {{ dbKey, encryptionKeyName, signingKeyName,\n * session, persist }} opts\n * `dbKey` prefixes both default indexedDB names. Other strings are\n * custom names, plus session and persist options.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n const shouldPersist = opts.persist !== false\n const exchangeKeyName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n const writeKeyName = opts.writeKeyName || this.WRITE_KEY_NAME\n\n // cache -- only if it is for the same indexedDB entries\n const cached:AbstractKeys|null = this._instance\n if (\n cached &&\n !cached.destroyed &&\n cached.exchangeKeyName === exchangeKeyName &&\n cached.writeKeyName === writeKeyName\n ) {\n if (shouldPersist && !cached.hasPersisted) await cached.persist()\n return cached as T\n }\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(exchangeKeyName)\n let writeKeys:CryptoKeyPair|undefined = await get(writeKeyName)\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session,\n exchangeKeyName,\n writeKeyName\n }) as T\n\n this._instance = keys\n if (shouldPersist && !hasPersisted) await keys.persist()\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().encode(did.normalize('NFD'))\n )\n\n return toString(hashedUsername, 'base32').slice(0, 32)\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAAA,SAAS,YAAqC,gBAAgB;AAC9D,SAAS,KAAK,KAAK,eAAe;AAQlC,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,wBAAwB;AAIjC,cAAc;AAEd,SAAS,gCAAgC;AAkFlC,MAAe,gBAAf,MAAe,cAAa;AAAA,EAwB/B,YAAa,MAAc;AAvB3B;AACA;AACA;AAKA;AAAA;AAAA;AAAA;AAAA;AAKA;AAAA;AAAA;AAAA;AAAA,wBAAS;AACT,wBAAS;AAOT;AAAA;AAAA;AAAA,wBAAU;AACV,wBAAU;AAGN,UAAM,EAAE,KAAK,IAAI;AACjB,UAAM,OAAO,KAAK;AAClB,SAAK,MAAM,KAAK;AAChB,SAAK,eAAe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