signify-ts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +25 -0
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +8 -0
  5. package/dist/keri/core/cigar.d.ts +8 -0
  6. package/dist/keri/core/cipher.d.ts +5 -0
  7. package/dist/keri/core/core.d.ts +68 -0
  8. package/dist/keri/core/decrypter.d.ts +10 -0
  9. package/dist/keri/core/diger.d.ts +21 -0
  10. package/dist/keri/core/encrypter.d.ts +9 -0
  11. package/dist/keri/core/indexer.d.ts +88 -0
  12. package/dist/keri/core/keeping.d.ts +1 -0
  13. package/dist/keri/core/kering.d.ts +5 -0
  14. package/dist/keri/core/manager.d.ts +151 -0
  15. package/dist/keri/core/matter.d.ts +47 -0
  16. package/dist/keri/core/siger.d.ts +22 -0
  17. package/dist/keri/core/signer.d.ts +34 -0
  18. package/dist/keri/core/utils.d.ts +16 -0
  19. package/dist/signify-ts.cjs.development.js +13 -0
  20. package/dist/signify-ts.cjs.development.js.map +1 -0
  21. package/dist/signify-ts.cjs.production.min.js +2 -0
  22. package/dist/signify-ts.cjs.production.min.js.map +1 -0
  23. package/dist/signify-ts.esm.js +9 -0
  24. package/dist/signify-ts.esm.js.map +1 -0
  25. package/package.json +66 -0
  26. package/src/index.ts +6 -0
  27. package/src/keri/core/cigar.ts +19 -0
  28. package/src/keri/core/cipher.ts +25 -0
  29. package/src/keri/core/core.ts +174 -0
  30. package/src/keri/core/decrypter.ts +66 -0
  31. package/src/keri/core/diger.ts +82 -0
  32. package/src/keri/core/encrypter.ts +60 -0
  33. package/src/keri/core/indexer.ts +406 -0
  34. package/src/keri/core/keeping.ts +9 -0
  35. package/src/keri/core/kering.ts +12 -0
  36. package/src/keri/core/manager.ts +874 -0
  37. package/src/keri/core/matter.ts +252 -0
  38. package/src/keri/core/salter.ts +85 -0
  39. package/src/keri/core/siger.ts +39 -0
  40. package/src/keri/core/signer.ts +112 -0
  41. package/src/keri/core/tsconfig.json +100 -0
  42. package/src/keri/core/utils.ts +94 -0
  43. package/src/keri/core/verfer.ts +33 -0
@@ -0,0 +1,22 @@
1
+ import { Indexer, IndexerArgs } from "./indexer";
2
+ import { Verfer } from "./verfer";
3
+ /**
4
+ Siger is subclass of Indexer, indexed signature material,
5
+ Adds .verfer property which is instance of Verfer that provides
6
+ associated signature verifier.
7
+
8
+ See Indexer for inherited attributes and properties:
9
+
10
+ Attributes:
11
+
12
+ Properties:
13
+ .verfer is Verfer object instance
14
+
15
+ Methods:
16
+ **/
17
+ export declare class Siger extends Indexer {
18
+ private _verfer?;
19
+ constructor({ raw, code, qb64, qb64b, qb2 }: IndexerArgs, verfer?: Verfer);
20
+ get verfer(): Verfer | undefined;
21
+ set verfer(verfer: Verfer | undefined);
22
+ }
@@ -0,0 +1,34 @@
1
+ export {};
2
+ import { Matter } from './matter';
3
+ import { Verfer } from "./verfer";
4
+ import { Cigar } from "./cigar";
5
+ import { Siger } from "./siger";
6
+ /**
7
+ * @description Signer is Matter subclass with method to create signature of serialization
8
+ * It will use .raw as signing (private) key seed
9
+ * .code as cipher suite for signing and new property .verfer whose property
10
+ * .raw is public key for signing.
11
+ * If not provided .verfer is generated from private key seed using .code
12
+ as cipher suite for creating key-pair.
13
+ */
14
+ interface SignerArgs {
15
+ raw?: Uint8Array | undefined;
16
+ code?: string;
17
+ qb64b?: Uint8Array | undefined;
18
+ qb64?: string;
19
+ qb2?: Uint8Array | undefined;
20
+ transferable?: boolean;
21
+ }
22
+ export declare class Signer extends Matter {
23
+ private readonly _sign;
24
+ private readonly _verfer;
25
+ constructor({ raw, code, qb64, qb64b, qb2, transferable }: SignerArgs);
26
+ /**
27
+ * @description Property verfer:
28
+ Returns Verfer instance
29
+ Assumes ._verfer is correctly assigned
30
+ */
31
+ get verfer(): Verfer;
32
+ sign(ser: Uint8Array, index?: number | null, only?: boolean, ondex?: number | undefined): any;
33
+ _ed25519(ser: Uint8Array, seed: Uint8Array, verfer: Verfer, index: number | null, only: boolean | undefined, ondex: number | undefined): Cigar | Siger;
34
+ }
@@ -0,0 +1,16 @@
1
+ export declare function pad(n: any, width?: number, z?: number): string;
2
+ /**
3
+ * @description Returns list of depth first recursively extracted values from elements of
4
+ key event dict ked whose flabels are in lables list
5
+
6
+ * @param {*} ked ked is key event dict
7
+ * @param {*} labels labels is list of element labels in ked from which to extract values
8
+ */
9
+ export declare function extractValues(ked: any, labels: any): any;
10
+ export declare function arrayEquals(ar1: Uint8Array, ar2: Uint8Array): boolean;
11
+ /**
12
+ * @description Returns True if obj is non-string iterable, False otherwise
13
+
14
+ * @param {*} obj
15
+ */
16
+ export declare function range(start: any, stop: any, step: any): any[];
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var sum = function sum(a, b) {
6
+ {
7
+ console.log('boop');
8
+ }
9
+ return a + b;
10
+ };
11
+
12
+ exports.sum = sum;
13
+ //# sourceMappingURL=signify-ts.cjs.development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signify-ts.cjs.development.js","sources":["../src/index.ts"],"sourcesContent":["export const sum = (a: number, b: number) => {\n if ('development' === process.env.NODE_ENV) {\n console.log('boop');\n }\n return a + b;\n};\n"],"names":["sum","a","b","console","log"],"mappings":";;;;IAAaA,GAAG,GAAG,SAANA,GAAG,CAAIC,CAAS,EAAEC,CAAS;EACM;IAC1CC,OAAO,CAACC,GAAG,CAAC,MAAM,CAAC;;EAErB,OAAOH,CAAC,GAAGC,CAAC;AACd;;;;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.sum=function(e,t){return e+t};
2
+ //# sourceMappingURL=signify-ts.cjs.production.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signify-ts.cjs.production.min.js","sources":["../src/index.ts"],"sourcesContent":["export const sum = (a: number, b: number) => {\n if ('development' === process.env.NODE_ENV) {\n console.log('boop');\n }\n return a + b;\n};\n"],"names":["a","b"],"mappings":"gFAAmB,SAACA,EAAWC,GAI7B,OAAOD,EAAIC"}
@@ -0,0 +1,9 @@
1
+ var sum = function sum(a, b) {
2
+ if ('development' === process.env.NODE_ENV) {
3
+ console.log('boop');
4
+ }
5
+ return a + b;
6
+ };
7
+
8
+ export { sum };
9
+ //# sourceMappingURL=signify-ts.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signify-ts.esm.js","sources":["../src/index.ts"],"sourcesContent":["export const sum = (a: number, b: number) => {\n if ('development' === process.env.NODE_ENV) {\n console.log('boop');\n }\n return a + b;\n};\n"],"names":["sum","a","b","process","env","NODE_ENV","console","log"],"mappings":"IAAaA,GAAG,GAAG,SAANA,GAAG,CAAIC,CAAS,EAAEC,CAAS;EACtC,IAAI,aAAa,KAAKC,OAAO,CAACC,GAAG,CAACC,QAAQ,EAAE;IAC1CC,OAAO,CAACC,GAAG,CAAC,MAAM,CAAC;;EAErB,OAAON,CAAC,GAAGC,CAAC;AACd;;;;"}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "license": "Apache-2.0",
4
+ "main": "dist/index.js",
5
+ "typings": "dist/index.d.ts",
6
+ "files": [
7
+ "dist",
8
+ "src"
9
+ ],
10
+ "scripts": {
11
+ "start": "tsdx watch",
12
+ "build": "tsdx build",
13
+ "test": "tsdx test",
14
+ "lint": "tsdx lint",
15
+ "prepare": "tsdx build",
16
+ "size": "size-limit",
17
+ "analyze": "size-limit --why"
18
+ },
19
+ "husky": {
20
+ "hooks": {
21
+ "pre-commit": "tsdx lint"
22
+ }
23
+ },
24
+ "prettier": {
25
+ "printWidth": 80,
26
+ "semi": true,
27
+ "singleQuote": true,
28
+ "trailingComma": "es5"
29
+ },
30
+ "name": "signify-ts",
31
+ "author": "Phil Feairheller",
32
+ "module": "dist/signify-ts.js",
33
+ "size-limit": [
34
+ {
35
+ "path": "dist/signify-ts.cjs.production.min.js",
36
+ "limit": "10 KB"
37
+ },
38
+ {
39
+ "path": "dist/signify-ts.esm.js",
40
+ "limit": "10 KB"
41
+ }
42
+ ],
43
+ "devDependencies": {
44
+ "@size-limit/preset-small-lib": "^5.0.4",
45
+ "@types/lodash": "^4.14.185",
46
+ "@types/urlsafe-base64": "^1.0.28",
47
+ "husky": "^7.0.2",
48
+ "jest": "^29.3.1",
49
+ "size-limit": "^5.0.4",
50
+ "ts-migrate": "^0.1.23",
51
+ "tsdx": "^0.14.1",
52
+ "tslib": "^2.3.1",
53
+ "typescript": "^4.4.3"
54
+ },
55
+ "dependencies": {
56
+ "@types/libsodium-wrappers-sumo": "^0.7.5",
57
+ "blake3": "^2.1.7",
58
+ "cbor": "^8.0.0",
59
+ "collections": "^5.1.12",
60
+ "libsodium-wrappers-sumo": "^0.7.9",
61
+ "lodash": "^4.17.21",
62
+ "msgpack5": "^5.3.2",
63
+ "urlsafe-base64": "^1.0.0",
64
+ "xregexp": "^5.1.0"
65
+ }
66
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export const sum = (a: number, b: number) => {
2
+ if ('development' === process.env.NODE_ENV) {
3
+ console.log('boop');
4
+ }
5
+ return a + b;
6
+ };
@@ -0,0 +1,19 @@
1
+ import {Verfer} from "./verfer";
2
+ import {Matter, MatterArgs} from "./matter";
3
+
4
+
5
+ export class Cigar extends Matter {
6
+ private _verfer: Verfer
7
+ constructor({raw, code, qb64, qb64b, qb2}:MatterArgs, verfer: Verfer) {
8
+ super({raw, code, qb64, qb64b, qb2});
9
+ this._verfer = verfer
10
+ }
11
+
12
+ get verfer(): Verfer {
13
+ return this._verfer
14
+ }
15
+
16
+ set verfer(verfer:Verfer) {
17
+ this._verfer = verfer
18
+ }
19
+ }
@@ -0,0 +1,25 @@
1
+ import {Matter, MatterArgs, MtrDex} from "./matter";
2
+ import {Decrypter} from "./decrypter";
3
+
4
+
5
+ export class Cipher extends Matter {
6
+ constructor({raw, code, qb64, qb64b, qb2}:MatterArgs) {
7
+ if (raw != undefined && code == undefined) {
8
+ if (raw.length == Matter._rawSize(MtrDex.X25519_Cipher_Salt)) {
9
+ code = MtrDex.X25519_Cipher_Salt
10
+ } else if (raw.length == Matter._rawSize(MtrDex.X25519_Cipher_Seed)) {
11
+ code = MtrDex.X25519_Cipher_Salt
12
+ }
13
+ }
14
+ super({raw: raw, code: code, qb64b: qb64b, qb64: qb64, qb2: qb2});
15
+
16
+ if (!(Array.from([MtrDex.X25519_Cipher_Salt, MtrDex.X25519_Cipher_Seed]).includes(this.code))) {
17
+ throw new Error(`Unsupported Cipher code == ${this.code}`)
18
+ }
19
+ }
20
+
21
+ decrypt(prikey: Uint8Array | undefined = undefined, seed: Uint8Array | undefined = undefined) {
22
+ let decrypter = new Decrypter({qb64b: prikey}, seed)
23
+ return decrypter.decrypt(this.qb64b)
24
+ }
25
+ }
@@ -0,0 +1,174 @@
1
+ const util = require('./utils');
2
+ import {TextEncoder, TextDecoder} from 'util'
3
+
4
+ export const VERRAWSIZE = 6;
5
+ export const Versionage = {major: 1, minor: 0};
6
+ export const Serialage = {json: '', mgpk: '', cbor: ''};
7
+ export const Vstrings = Serialage;
8
+ export const Serials = {json: 'JSON', mgpk: 'MGPK', cbor: 'CBOR'};
9
+
10
+ // # element labels to exclude in digest or signature derivation from inception icp
11
+ export const IcpExcludes = ['pre'];
12
+ // # element labels to exclude in digest or signature derivation from delegated inception dip
13
+ export const DipExcludes = ['pre'];
14
+ export const Ilks = {
15
+ icp: 'icp',
16
+ rot: 'rot',
17
+ ixn: 'ixn',
18
+ dip: 'dip',
19
+ drt: 'drt',
20
+ rct: 'rct',
21
+ vrc: 'vrc',
22
+ };
23
+
24
+ export const IcpLabels = ["v", "i", "s", "t", "kt", "k", "n",
25
+ "bt", "b", "c", "a"];
26
+
27
+ export const DipLabels = ["v", "i", "s", "t", "kt", "k", "n",
28
+ "bt", "b", "c", "a", "di"];
29
+
30
+ export const RotLabels = ["v", "i", "s", "t", "p", "kt", "k", "n",
31
+ "bt", "br", "ba", "a"]
32
+ export const DrtLabels = ["v", "i", "s", "t", "p", "kt", "k", "n",
33
+ "bt", "br", "ba", "a"]
34
+ export const IxnLabels = ["v", "i", "s", "t", "p", "a"]
35
+
36
+ export const KsnLabels = ["v", "i", "s", "t", "p", "d", "f", "dt", "et", "kt", "k", "n",
37
+ "bt", "b", "c", "ee", "di", "r"]
38
+
39
+ export const RpyLabels = ["v", "t", "d", "dt", "r", "a"]
40
+
41
+ const encoder = new TextEncoder()
42
+ const decoder = new TextDecoder()
43
+
44
+ export const VERFULLSIZE = 17;
45
+ export const MINSNIFFSIZE = 12 + VERFULLSIZE;
46
+ export const MINSIGSIZE = 4;
47
+
48
+ /**
49
+ * @description It will return version string
50
+ */
51
+ export function versify(version: { major: number, minor: number }, kind = Serials.json, size: number) {
52
+ if (!(Object.values(Serials).indexOf(kind) > -1)) {
53
+ throw new Error('Invalid serialization kind =' + kind);
54
+ }
55
+
56
+ if (!version) {
57
+ version = Versionage;
58
+ }
59
+
60
+ const hex1 = version.major.toString(16);
61
+ const hex2 = version.minor.toString(16);
62
+ const kindHex = kind;
63
+ const hex3 = util.pad(size.toString(16), VERRAWSIZE);
64
+
65
+ return `KERI${hex1}${hex2}${kindHex}${hex3}_`;
66
+ }
67
+
68
+ Vstrings.json = versify(Versionage, Serials.json, 0);
69
+ Vstrings.mgpk = versify(Versionage, Serials.mgpk, 0);
70
+ Vstrings.cbor = versify(Versionage, Serials.cbor, 0);
71
+
72
+ // const version_pattern = 'KERI(?P<major>[0-9a-f])(?P<minor>[0-9a-f])
73
+ // (?P<kind>[A-Z]{4})(?P<size>[0-9a-f]{6})'
74
+ // const version_pattern1 = `KERI\(\?P<major>\[0\-9a\-f\]\)\(\?P<minor>\[0\-9a\-f\]\)\
75
+ // (\?P<kind>\[A\-Z\]\{4\}\)\(\?P<size>\[0\-9a\-f\]\{6\}\)_`
76
+
77
+ export const VEREX = 'KERI([0-9a-f])([0-9a-f])([A-Z]{4})([0-9a-f]{6})';
78
+
79
+ // Regex pattern matching
80
+
81
+ /**
82
+ * @description This function is use to deversify the version
83
+ * Here we will use regex to to validate and extract serialization kind,size and version
84
+ * @param {string} vs version string
85
+ * @return {Object} contaning kind of serialization like cbor,json,mgpk
86
+ * version = version of object ,size = raw size integer
87
+ */
88
+ export function deversify(versionString: string) {
89
+ let kind;
90
+ let size;
91
+ const version = Versionage;
92
+
93
+ // we need to identify how to match the buffers pattern ,like we do regex matching for strings
94
+ const re = new RegExp(VEREX);
95
+
96
+ const match = re.exec(versionString);
97
+
98
+ if (match) {
99
+ [version.major, version.minor, kind, size] = [
100
+ +match[1],
101
+ +match[2],
102
+ match[3],
103
+ match[4],
104
+ ];
105
+ if (!Object.values(Serials).includes(kind)) {
106
+ throw new Error(`Invalid serialization kind = ${kind}`);
107
+ }
108
+ return [kind, version, size];
109
+ }
110
+ throw new Error(`Invalid version string = ${versionString}`);
111
+ }
112
+
113
+ export const B64ChrByIdx = new Map<number, string>([[0, 'A'], [1, 'B'], [2, 'C'], [3, 'D'], [4, 'E'], [5, 'F'],
114
+ [6, 'G'], [7, 'H'], [8, 'I'], [9, 'J'], [10, 'K'], [11, 'L'], [12, 'M'], [13, 'N'], [14, 'O'], [15, 'P'],
115
+ [16, 'Q'], [17, 'R'], [18, 'S'], [19, 'T'], [20, 'U'], [21, 'V'], [22, 'W'], [23, 'X'], [24, 'Y'], [25, 'Z'],
116
+ [26, 'a'], [27, 'b'], [28, 'c'], [29, 'd'], [30, 'e'], [31, 'f'], [32, 'g'], [33, 'h'], [34, 'i'], [35, 'j'],
117
+ [36, 'k'], [37, 'l'], [38, 'm'], [39, 'n'], [40, 'o'], [41, 'p'], [42, 'q'], [43, 'r'], [44, 's'], [45, 't'],
118
+ [46, 'u'], [47, 'v'], [48, 'w'], [49, 'x'], [50, 'y'], [51, 'z'],[ 52, '0'], [53, '1'], [54, '2'], [55, '3'],
119
+ [56, '4'], [57, '5'], [58, '6'], [59, '7'], [60, '8'], [61, '9'], [62, '-'], [63, '_']]);
120
+
121
+ export const B64IdxByChr = new Map<string, number>(Array.from(B64ChrByIdx, entry => [entry[1], entry[0]]))
122
+
123
+ export function intToB64(i:number | undefined, l=1): string {
124
+ let out = ""
125
+ while(l != 0) {
126
+ out = B64ChrByIdx.get(i! % 64) + out
127
+ i = Math.floor(i! / 64)
128
+ if (i == 0) {
129
+ break
130
+ }
131
+ }
132
+
133
+ for(let i = 0; i < (l - out.length); i++) {
134
+ out = "A" + out
135
+ }
136
+
137
+ return out
138
+ }
139
+
140
+ export function intToB64b(n: number, l: number = 1): Uint8Array {
141
+ let s = intToB64(n, l)
142
+ return b(s)
143
+ }
144
+
145
+ export function b64ToInt(s: string): number {
146
+ if (s.length == 0) {
147
+ throw new Error("Empty string, conversion undefined.")
148
+ }
149
+
150
+ let i = 0
151
+ let rev = [...s].reverse()
152
+ rev.forEach((c: string, e: number) => {
153
+ i |= B64IdxByChr.get(c)! << (e * 6)
154
+ })
155
+
156
+ return i
157
+ }
158
+
159
+ export function b(s?: string): Uint8Array {
160
+ return encoder.encode(s)
161
+ }
162
+
163
+ export function d(u? :Uint8Array): string {
164
+ return decoder.decode(u)
165
+ }
166
+
167
+
168
+ export function readInt(array: Uint8Array) {
169
+ let value = 0;
170
+ for (let i = 0; i < array.length; i++) {
171
+ value = (value * 256) + array[i];
172
+ }
173
+ return value;
174
+ }
@@ -0,0 +1,66 @@
1
+ import libsodium from "libsodium-wrappers-sumo";
2
+
3
+ import {Matter, MatterArgs, MtrDex} from './matter';
4
+ import {Signer} from "./signer";
5
+ import {Cipher} from "./cipher";
6
+ import {EmptyMaterialError} from "./kering";
7
+ import {Salter} from "./salter";
8
+
9
+
10
+ export class Decrypter extends Matter {
11
+ private readonly _decrypt: any;
12
+ constructor({raw, code = MtrDex.X25519_Private, qb64, qb64b, qb2}:MatterArgs, seed: Uint8Array | undefined = undefined) {
13
+ try {
14
+ super({raw, code, qb64, qb64b, qb2})
15
+ } catch(e) {
16
+ if(e instanceof EmptyMaterialError) {
17
+ if (seed != undefined) {
18
+ let signer = new Signer({qb64b: seed})
19
+ if (signer.code != MtrDex.Ed25519_Seed) {
20
+ throw new Error(`Unsupported signing seed derivation code ${signer.code}`)
21
+ }
22
+ let sigkey = new Uint8Array(signer.raw.length + signer.verfer.raw.length)
23
+ sigkey.set(signer.raw)
24
+ sigkey.set(signer.verfer.raw, signer.raw.length)
25
+ raw = libsodium.crypto_sign_ed25519_sk_to_curve25519(sigkey)
26
+ super({raw, code, qb64, qb64b, qb2})
27
+ }
28
+ else {
29
+ throw e
30
+ }
31
+ } else {
32
+ throw e
33
+ }
34
+ }
35
+
36
+ if (this.code == MtrDex.X25519_Private) {
37
+ this._decrypt = this._x25519
38
+ } else {
39
+ throw new Error(`Unsupported decrypter code = ${this.code}.`)
40
+ }
41
+ }
42
+
43
+ decrypt(ser: Uint8Array | null = null, cipher: Cipher | null = null, transferable: boolean = false) {
44
+ if (ser == null && cipher == null) {
45
+ throw new EmptyMaterialError("Neither ser or cipher were provided")
46
+ }
47
+
48
+ if (ser != null) {
49
+ cipher = new Cipher({qb64b: ser})
50
+ }
51
+
52
+ return this._decrypt(cipher, this.raw, transferable)
53
+ }
54
+
55
+ _x25519(cipher: Cipher, prikey: Uint8Array, transferable: boolean = false) {
56
+ let pubkey = libsodium.crypto_scalarmult_base(prikey)
57
+ let plain = libsodium.crypto_box_seal_open(cipher.raw, pubkey, prikey)
58
+ if (cipher.code == MtrDex.X25519_Cipher_Salt) {
59
+ return new Salter({qb64b: plain})
60
+ } else if (cipher.code == MtrDex.X25519_Cipher_Seed) {
61
+ return new Signer({qb64b: plain, transferable: transferable})
62
+ } else {
63
+ throw new Error(`Unsupported cipher text code == ${cipher.code}`)
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,82 @@
1
+ const blake3 = require('blake3');
2
+ import {Matter, MatterArgs, MtrDex} from './matter';
3
+
4
+ /**
5
+ * @description : Diger is subset of Matter and is used to verify the digest of serialization
6
+ * It uses .raw : as digest
7
+ * .code as digest algorithm
8
+ *
9
+ */
10
+
11
+
12
+ export class Diger extends Matter {
13
+ private readonly _verify: any
14
+
15
+ // This constructor will assign digest verification function to ._verify
16
+ constructor({raw, code = MtrDex.Blake3_256, qb64, qb64b, qb2}: MatterArgs, ser: Uint8Array | null = null) {
17
+ try {
18
+ super({raw, code, qb64, qb64b, qb2});
19
+ } catch (error: any) {
20
+ if (ser == null) {
21
+ throw error;
22
+ }
23
+
24
+ if (code === MtrDex.Blake3_256) {
25
+ const hasher = blake3.createHash();
26
+ const dig = hasher.update(ser).digest('');
27
+ super({raw: dig, code: code});
28
+ } else {
29
+ throw new Error(`Unsupported code = ${code} for digester.`);
30
+ }
31
+ }
32
+
33
+ if (code === MtrDex.Blake3_256) {
34
+ this._verify = this.blake3_256;
35
+ } else {
36
+ throw new Error(`Unsupported code = ${code} for digester.`);
37
+ }
38
+ }
39
+
40
+
41
+ /**
42
+ *
43
+ * @param {Uint8Array} ser serialization bytes
44
+ * @description This method will return true if digest of bytes serialization ser matches .raw
45
+ * using .raw as reference digest for ._verify digest algorithm determined
46
+ by .code
47
+ */
48
+ verify(ser: Uint8Array): boolean {
49
+ return this._verify(ser, this.raw);
50
+ }
51
+
52
+ compare(ser: Uint8Array, dig: any = null, diger: Diger | null = null ) {
53
+ if (dig != null) {
54
+ if (dig.toString() == this.qb64) {
55
+ return true
56
+ }
57
+
58
+ diger = new Diger({qb64b: dig})
59
+ } else if (diger != null) {
60
+ if (diger.qb64b == this.qb64b) {
61
+ return true;
62
+ }
63
+ }
64
+
65
+ else {
66
+ throw new Error("Both dig and diger may not be None.")
67
+ }
68
+
69
+ if (diger.code == this.code) {
70
+ return false
71
+ }
72
+
73
+ return diger.verify(ser) && this.verify(ser)
74
+ }
75
+
76
+
77
+ blake3_256(ser: Uint8Array, dig: any) {
78
+ const hasher = blake3.createHash();
79
+ let digest = hasher.update(ser).digest('');
80
+ return (digest.toString() === dig.toString());
81
+ }
82
+ }
@@ -0,0 +1,60 @@
1
+ import libsodium from "libsodium-wrappers-sumo";
2
+
3
+ import {Matter, MatterArgs, MtrDex} from './matter';
4
+ import {Verfer} from "./verfer";
5
+ import {Signer} from "./signer";
6
+ import {Cipher} from "./cipher";
7
+ import {arrayEquals} from "./utils";
8
+
9
+
10
+ export class Encrypter extends Matter {
11
+ private _encrypt: any;
12
+ constructor({raw, code = MtrDex.X25519, qb64, qb64b, qb2}:MatterArgs, verkey: Uint8Array | null = null) {
13
+ if (raw == undefined && verkey != null) {
14
+ let verfer = new Verfer({qb64b: verkey})
15
+ if (!Array.from([MtrDex.Ed25519N, MtrDex.Ed25519]).includes(verfer.code)) {
16
+ throw new Error(`Unsupported verkey derivation code = ${verfer.code}.`)
17
+ }
18
+ raw = libsodium.crypto_sign_ed25519_pk_to_curve25519(verfer.raw)
19
+ }
20
+
21
+ super({raw, code, qb64, qb64b, qb2});
22
+
23
+ if (this.code == MtrDex.X25519) {
24
+ this._encrypt = this._x25519;
25
+ } else {
26
+ throw new Error(`Unsupported encrypter code = ${this.code}.`)
27
+ }
28
+ }
29
+
30
+ verifySeed(seed: Uint8Array) {
31
+ let signer = new Signer({qb64b: seed})
32
+ let keypair = libsodium.crypto_sign_seed_keypair(signer.raw);
33
+ let pubkey = libsodium.crypto_sign_ed25519_pk_to_curve25519(keypair.publicKey)
34
+ return arrayEquals(pubkey, this.raw)
35
+ }
36
+
37
+ encrypt(ser: Uint8Array | null = null, matter: Matter | null = null) {
38
+ if (ser == null && matter == null) {
39
+ throw new Error("Neither ser nor matter are provided.")
40
+ }
41
+
42
+ if (ser != null) {
43
+ matter = new Matter({qb64b: ser})
44
+ }
45
+
46
+ let code
47
+ if (matter!.code == MtrDex.Salt_128) {
48
+ code = MtrDex.X25519_Cipher_Salt
49
+ } else {
50
+ code = MtrDex.X25519_Cipher_Seed
51
+ }
52
+
53
+ return this._encrypt(matter!.qb64, this.raw, code)
54
+ }
55
+
56
+ _x25519(ser: Uint8Array, pubkey: Uint8Array, code: string) {
57
+ let raw = libsodium.crypto_box_seal(ser, pubkey)
58
+ return new Cipher({raw: raw, code: code})
59
+ }
60
+ }