signify-ts 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +48 -1
  2. package/dist/index.d.ts +3 -1
  3. package/dist/keri/app/accountant.d.ts +10 -0
  4. package/dist/keri/app/apping.d.ts +1 -0
  5. package/dist/keri/app/client.d.ts +7 -0
  6. package/dist/keri/app/habery.d.ts +47 -0
  7. package/dist/keri/app/signify.d.ts +6 -0
  8. package/dist/keri/core/authing.d.ts +9 -0
  9. package/dist/keri/core/cigar.d.ts +3 -3
  10. package/dist/keri/core/core.d.ts +19 -34
  11. package/dist/keri/core/counter.d.ts +43 -0
  12. package/dist/keri/core/eventing.d.ts +21 -0
  13. package/dist/keri/core/httping.d.ts +34 -0
  14. package/dist/keri/core/manager.d.ts +38 -17
  15. package/dist/keri/core/matter.d.ts +23 -1
  16. package/dist/keri/core/number.d.ts +6 -0
  17. package/dist/keri/core/prefixer.d.ts +15 -0
  18. package/dist/keri/core/saider.d.ts +23 -0
  19. package/dist/keri/core/salter.d.ts +23 -0
  20. package/dist/keri/core/serder.d.ts +23 -0
  21. package/dist/keri/core/siger.d.ts +1 -1
  22. package/dist/keri/core/signer.d.ts +2 -2
  23. package/dist/keri/core/tholder.d.ts +14 -0
  24. package/dist/keri/core/utils.d.ts +2 -1
  25. package/dist/keri/core/verfer.d.ts +12 -0
  26. package/dist/keri/end/ending.d.ts +13 -0
  27. package/dist/signify-ts.cjs.development.js +3380 -5
  28. package/dist/signify-ts.cjs.development.js.map +1 -1
  29. package/dist/signify-ts.cjs.production.min.js +1 -1
  30. package/dist/signify-ts.cjs.production.min.js.map +1 -1
  31. package/dist/signify-ts.esm.js +3365 -5
  32. package/dist/signify-ts.esm.js.map +1 -1
  33. package/package.json +4 -2
  34. package/src/index.ts +5 -6
  35. package/src/keri/app/accountant.ts +35 -0
  36. package/src/keri/app/apping.ts +12 -0
  37. package/src/keri/app/client.ts +30 -0
  38. package/src/keri/app/habery.ts +152 -0
  39. package/src/keri/app/signify.ts +12 -0
  40. package/src/keri/app/tsconfig.json +100 -0
  41. package/src/keri/core/authing.ts +129 -0
  42. package/src/keri/core/cigar.ts +4 -4
  43. package/src/keri/core/core.ts +53 -43
  44. package/src/keri/core/counter.ts +207 -0
  45. package/src/keri/core/diger.ts +5 -5
  46. package/src/keri/core/eventing.ts +219 -0
  47. package/src/keri/core/httping.ts +163 -0
  48. package/src/keri/core/indexer.ts +2 -1
  49. package/src/keri/core/keeping.ts +0 -1
  50. package/src/keri/core/manager.ts +238 -90
  51. package/src/keri/core/matter.ts +46 -11
  52. package/src/keri/core/number.ts +21 -0
  53. package/src/keri/core/prefixer.ts +212 -0
  54. package/src/keri/core/saider.ts +158 -0
  55. package/src/keri/core/salter.ts +9 -5
  56. package/src/keri/core/serder.ts +99 -0
  57. package/src/keri/core/siger.ts +2 -2
  58. package/src/keri/core/signer.ts +4 -3
  59. package/src/keri/core/tholder.ts +52 -0
  60. package/src/keri/core/tsconfig.json +2 -2
  61. package/src/keri/core/utils.ts +10 -6
  62. package/src/keri/core/verfer.ts +6 -5
  63. package/src/keri/end/ending.ts +160 -0
  64. package/src/keri/end/tsconfig.json +100 -0
@@ -0,0 +1,12 @@
1
+ import libsodium from "libsodium-wrappers-sumo";
2
+ import {Salter} from "../core/salter";
3
+
4
+
5
+ export function randomPasscode(): string {
6
+ let raw = libsodium.randombytes_buf(16);
7
+ let salter = new Salter({raw: raw})
8
+
9
+ return salter.qb64.substring(2)
10
+ }
11
+
12
+
@@ -0,0 +1,30 @@
1
+
2
+
3
+ export class Client {
4
+ private readonly _url: string
5
+
6
+ constructor(url: string) {
7
+ this._url = url
8
+ }
9
+
10
+ url(path: string): string {
11
+ let url = new URL(path, this._url)
12
+
13
+ return url.href
14
+ }
15
+
16
+ getAccount(name: string): Promise<Response> {
17
+ let url = this.url(`/account/${name}`)
18
+ let req = new Request(url, {method: "GET"})
19
+ return fetch(req)
20
+ }
21
+
22
+ createAccount(name: string, key: string, ndig: string): Promise<Response> {
23
+ let url = this.url(`/account/${name}`)
24
+ let body = {key, ndig}
25
+ let req = new Request(url, {method: "POST", body: JSON.stringify(body)})
26
+ return fetch(req)
27
+ }
28
+
29
+
30
+ }
@@ -0,0 +1,152 @@
1
+ import {Algos, Manager} from "../core/manager";
2
+ import {MtrDex} from "../core/matter";
3
+ import {Salter} from "../core/salter";
4
+ import {Verfer} from "../core/verfer";
5
+ import {Diger} from "../core/diger";
6
+ import {incept} from "../core/eventing";
7
+ import {Serder} from "../core/serder";
8
+
9
+
10
+ export class TraitCodex {
11
+ EstOnly: string = 'EO' // Only allow establishment events
12
+ DoNotDelegate: string = 'DND' // Dot not allow delegated identifiers
13
+ }
14
+
15
+ export const TraitDex = new TraitCodex()
16
+
17
+ export interface HaberyArgs {
18
+ name: string
19
+ passcode?: string
20
+ seed?: string | undefined
21
+ aeid?: string | undefined
22
+ pidx?: number | undefined
23
+ salt?: string | undefined
24
+ tier?: string | undefined
25
+
26
+ }
27
+
28
+ export interface MakeHabArgs {
29
+ code?: string
30
+ transferable?: boolean
31
+ isith?: string
32
+ icount?: number
33
+ nsith?: string
34
+ ncount?: number
35
+ toad?: string | number
36
+ wits?: Array<string>
37
+ delpre?: string
38
+ estOnly?: boolean
39
+ DnD?: boolean
40
+ data?: any
41
+ }
42
+
43
+ export class Hab {
44
+ public name: string
45
+ public serder: Serder
46
+
47
+ constructor(name: string, icp: Serder) {
48
+ this.name = name
49
+ this.serder = icp
50
+ }
51
+
52
+ get pre(): string {
53
+ return this.serder.ked["i"]
54
+ }
55
+ }
56
+
57
+
58
+ export class Habery {
59
+ private readonly _name: string;
60
+ private readonly _mgr: Manager;
61
+ private readonly _habs: Map<string, Hab> = new Map<string, Hab>()
62
+
63
+ constructor({name, passcode, seed, aeid, pidx, salt}: HaberyArgs) {
64
+ this._name = name
65
+ if (passcode != undefined && seed == undefined) {
66
+ if (passcode.length < 21) {
67
+ throw new Error("Bran (passcode seed material) too short.")
68
+ }
69
+
70
+ let bran = MtrDex.Salt_128 + 'A' + passcode.substring(0, 21) // qb64 salt for seed
71
+ let signer = new Salter({qb64: bran}).signer(MtrDex.Ed25519_Seed, false)
72
+ seed = signer.qb64
73
+ if (aeid == undefined) {
74
+ aeid = signer.verfer.qb64 // lest it remove encryption
75
+ }
76
+ }
77
+ let algo;
78
+
79
+ if (salt != undefined) {
80
+ algo = Algos.salty
81
+ salt = new Salter({qb64: salt}).qb64
82
+ } else {
83
+ algo = Algos.randy
84
+ }
85
+
86
+ this._mgr = new Manager({seed: seed, aeid: aeid, pidx: pidx, algo: algo, salt: salt})
87
+ }
88
+
89
+ get mgr(): Manager {
90
+ return this._mgr
91
+ }
92
+
93
+ get habs(): Array<Hab> {
94
+ return Array.from(this._habs.values())
95
+ }
96
+
97
+ habByName(name: string): Hab|undefined {
98
+ return this._habs.get(name)
99
+ }
100
+
101
+ makeHab(name:string, {code = MtrDex.Blake3_256, transferable = true, isith = undefined, icount = 1,
102
+ nsith = undefined, ncount = undefined, toad = undefined, wits = undefined, delpre = undefined,
103
+ estOnly = false, DnD = false, data = undefined}: MakeHabArgs): Hab {
104
+
105
+ if (nsith == undefined) {
106
+ nsith = isith
107
+ }
108
+ if (ncount == undefined) {
109
+ ncount = icount
110
+ }
111
+ if (!transferable) {
112
+ ncount = 0
113
+ nsith = "0"
114
+ code = MtrDex.Ed25519N
115
+ }
116
+
117
+ let [verfers, digers] = this._mgr.incept({
118
+ icount: icount, ncount: ncount, stem: this.name,
119
+ transferable: transferable, temp: false
120
+ })
121
+
122
+ icount = verfers.length
123
+ ncount = digers != undefined ? digers.length : 0
124
+ if (isith == undefined) {
125
+ isith = `${Math.max(1, Math.ceil(icount/2)).toString(16)}`
126
+ }
127
+ if (nsith == undefined) {
128
+ nsith = `${Math.max(1, Math.ceil(ncount/2)).toString(16)}`
129
+ }
130
+
131
+ let cnfg = new Array<string>()
132
+ if (estOnly) {
133
+ cnfg.push(TraitDex.EstOnly)
134
+ }
135
+ if(DnD) {
136
+ cnfg.push(TraitDex.DoNotDelegate)
137
+ }
138
+
139
+ let keys = Array.from(verfers, (verfer: Verfer) => verfer.qb64)
140
+ let ndigs = Array.from(digers, (diger: Diger) => diger.qb64)
141
+
142
+
143
+ const icp = incept({keys, isith, ndigs, nsith, toad, wits, cnfg, data, code, delpre})
144
+ const hab = new Hab(name, icp)
145
+ this._habs.set(name, hab)
146
+ return hab
147
+ }
148
+
149
+ get name(): string {
150
+ return this._name
151
+ }
152
+ }
@@ -0,0 +1,12 @@
1
+ import {Habery} from "./habery";
2
+ import {Accountant} from "./accountant";
3
+ import {Client} from "./client";
4
+
5
+
6
+ export class Signify {
7
+ private readonly _hby?: Habery
8
+ private readonly _act?: Accountant
9
+ private readonly _client?: Client
10
+ constructor(url:string, name:string, passcode: string) {
11
+ }
12
+ }
@@ -0,0 +1,100 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+
26
+ /* Modules */
27
+ "module": "commonjs", /* Specify what module code is generated. */
28
+ // "rootDir": "./", /* Specify the root folder within your source files. */
29
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
+
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
+
44
+ /* Emit */
45
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+
68
+ /* Interop Constraints */
69
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
70
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
71
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
72
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
73
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
74
+
75
+ /* Type Checking */
76
+ "strict": true, /* Enable all strict type-checking options. */
77
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
78
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
79
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
80
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
81
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
82
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
83
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
84
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
85
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
86
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
87
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
88
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
89
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
90
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
91
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
92
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
93
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
94
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
95
+
96
+ /* Completeness */
97
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
98
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
99
+ }
100
+ }
@@ -0,0 +1,129 @@
1
+ import {Signer} from "./signer";
2
+ import {Verfer} from "./verfer";
3
+ import {desiginput, normalize, siginput} from "./httping";
4
+ import {b} from "./core";
5
+ import {parseDictionary} from "structured-headers";
6
+ import {Signage, signature} from "../end/ending";
7
+ import {Cigar} from "./cigar";
8
+ import {Siger} from "./siger";
9
+
10
+ import Base64 from "urlsafe-base64"
11
+
12
+ export class Authenticater {
13
+
14
+ static DefaultFields = [
15
+ "Signify-Resource",
16
+ "@method",
17
+ "@path",
18
+ "Signify-Timestamp"
19
+ ]
20
+ private _verfer: Verfer;
21
+ private readonly _csig: Signer;
22
+
23
+ constructor(csig: Signer, aaid: string) {
24
+ this._csig = csig
25
+ this._verfer = new Verfer({qb64: aaid})
26
+ }
27
+
28
+ verify(headers: Headers, method: string, path: string): boolean {
29
+ let siginput = headers.get("Signature-Input")
30
+ if (siginput == null) {
31
+ return false
32
+ }
33
+ let signature = headers.get("Signature")
34
+ if (signature == null) {
35
+ return false
36
+ }
37
+
38
+ let inputs = desiginput(siginput)
39
+ inputs = inputs.filter((input) => input.name == "signify")
40
+
41
+ if (inputs.length == 0) {
42
+ return false
43
+ }
44
+
45
+ inputs.forEach((input) => {
46
+ let items = new Array<string>()
47
+ input.fields!.forEach((field: string) => {
48
+ if (field.startsWith("@")) {
49
+ if (field == "@method") {
50
+ items.push(`"${field}": ${method}`)
51
+ } else if (field == "@path") {
52
+ items.push(`"${field}": ${path}`)
53
+ }
54
+ } else {
55
+ if (headers.has(field)) {
56
+ let value = normalize(headers.get(field) as string)
57
+ items.push(`"${field}": ${value}`)
58
+ }
59
+ }
60
+ })
61
+
62
+ let values = new Array<string>()
63
+ values.push(`(${input.fields!.join(" ")})`)
64
+ values.push(`created=${input.created}`)
65
+
66
+ if (input.expires != undefined) {
67
+ values.push(`expires=${input.expires}`)
68
+ }
69
+ if (input.nonce != undefined) {
70
+ values.push(`nonce=${input.nonce}`)
71
+ }
72
+ if (input.keyid != undefined) {
73
+ values.push(`keyid=${input.keyid}`)
74
+ }
75
+ if (input.context != undefined) {
76
+ values.push(`context=${input.context}`)
77
+ }
78
+ if (input.alg != undefined) {
79
+ values.push(`alg=${input.alg}`)
80
+ }
81
+
82
+ let params = values.join(";")
83
+
84
+ items.push(`"@signature-params: ${params}"`)
85
+ let ser = b(items.join("\n"))
86
+
87
+ let signage = parseDictionary(signature!)
88
+ if (!signage.has("indexed")) {
89
+ throw new Error(`invalid signate ${signage}`)
90
+ }
91
+
92
+ let item = signage.get("indexed")!
93
+ let raw = Base64.decode(item[1].get(input.name) as string)
94
+
95
+ if (!this._verfer.verify(raw, ser)) {
96
+ throw new Error(`Signature for {inputage} invalid.`)
97
+ }
98
+ })
99
+
100
+ return true
101
+ }
102
+
103
+ sign(headers: Headers, method: string, path: string, fields?: Array<string>): Headers {
104
+ if (fields == undefined) {
105
+ fields = Authenticater.DefaultFields
106
+ }
107
+
108
+ let [header, sig] = siginput(this._csig, {
109
+ name: "signify", method, path, headers, fields, alg: "ed25519",
110
+ keyid: this._csig.verfer.qb64
111
+ })
112
+
113
+ header.forEach((value, key) => {
114
+ headers.append(key, value)
115
+ })
116
+
117
+ let markers = new Map<string, Siger|Cigar>()
118
+ markers.set("signify", sig)
119
+ let signage = new Signage(markers, false)
120
+ let signed = signature([signage])
121
+ signed.forEach((value, key) => {
122
+ headers.append(key, value)
123
+ })
124
+
125
+ return headers
126
+ }
127
+
128
+
129
+ }
@@ -3,17 +3,17 @@ import {Matter, MatterArgs} from "./matter";
3
3
 
4
4
 
5
5
  export class Cigar extends Matter {
6
- private _verfer: Verfer
7
- constructor({raw, code, qb64, qb64b, qb2}:MatterArgs, verfer: Verfer) {
6
+ private _verfer: Verfer | undefined
7
+ constructor({raw, code, qb64, qb64b, qb2}:MatterArgs, verfer?: Verfer) {
8
8
  super({raw, code, qb64, qb64b, qb2});
9
9
  this._verfer = verfer
10
10
  }
11
11
 
12
- get verfer(): Verfer {
12
+ get verfer(): Verfer | undefined {
13
13
  return this._verfer
14
14
  }
15
15
 
16
- set verfer(verfer:Verfer) {
16
+ set verfer(verfer:Verfer|undefined) {
17
17
  this._verfer = verfer
18
18
  }
19
19
  }
@@ -1,16 +1,26 @@
1
- const util = require('./utils');
2
1
  import {TextEncoder, TextDecoder} from 'util'
3
2
 
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'};
3
+ export enum Serials {
4
+ JSON = "JSON",
5
+ }
6
+
7
+ export enum Ident {
8
+ KERI = "KERI"
9
+ }
10
+
11
+ export class Version {
12
+ public major: number
13
+ public minor: number
14
+
15
+ constructor(major: number = 1, minor: number = 0) {
16
+ this.major = major
17
+ this.minor = minor
18
+ }
19
+ }
20
+
21
+ export const Versionage = new Version()
22
+
9
23
 
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
24
  export const Ilks = {
15
25
  icp: 'icp',
16
26
  rot: 'rot',
@@ -45,47 +55,27 @@ export const VERFULLSIZE = 17;
45
55
  export const MINSNIFFSIZE = 12 + VERFULLSIZE;
46
56
  export const MINSIGSIZE = 4;
47
57
 
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
58
  // const version_pattern = 'KERI(?P<major>[0-9a-f])(?P<minor>[0-9a-f])
73
59
  // (?P<kind>[A-Z]{4})(?P<size>[0-9a-f]{6})'
74
60
  // const version_pattern1 = `KERI\(\?P<major>\[0\-9a\-f\]\)\(\?P<minor>\[0\-9a\-f\]\)\
75
61
  // (\?P<kind>\[A\-Z\]\{4\}\)\(\?P<size>\[0\-9a\-f\]\{6\}\)_`
76
62
 
77
- export const VEREX = 'KERI([0-9a-f])([0-9a-f])([A-Z]{4})([0-9a-f]{6})';
63
+ export const VEREX = 'KERI([0-9a-f])([0-9a-f])([A-Z]{4})([0-9a-f]{6})_';
64
+
65
+ export interface Dict<TValue> {
66
+ [id: string]: TValue;
67
+ }
78
68
 
79
69
  // Regex pattern matching
80
70
 
81
71
  /**
82
72
  * @description This function is use to deversify the version
83
73
  * Here we will use regex to to validate and extract serialization kind,size and version
84
- * @param {string} vs version string
74
+ * @param {string} versionString version string
85
75
  * @return {Object} contaning kind of serialization like cbor,json,mgpk
86
76
  * version = version of object ,size = raw size integer
87
77
  */
88
- export function deversify(versionString: string) {
78
+ export function deversify(versionString: string): [Serials, Version, string] {
89
79
  let kind;
90
80
  let size;
91
81
  const version = Versionage;
@@ -102,14 +92,25 @@ export function deversify(versionString: string) {
102
92
  match[3],
103
93
  match[4],
104
94
  ];
105
- if (!Object.values(Serials).includes(kind)) {
95
+ if (!Object.values(Serials).includes(kind as Serials)) {
106
96
  throw new Error(`Invalid serialization kind = ${kind}`);
107
97
  }
98
+
99
+ let ta = kind as keyof typeof Serials
100
+ kind = Serials[ta]
101
+
108
102
  return [kind, version, size];
109
103
  }
110
104
  throw new Error(`Invalid version string = ${versionString}`);
111
105
  }
112
106
 
107
+ export function versify(ident: Ident = Ident.KERI, version?: Version, kind: Serials=Serials.JSON, size:number = 0) {
108
+ version = version == undefined ? Versionage : version
109
+
110
+ return `${ident}${version.major.toString(16)}${version.minor.toString()}${kind}${size.toString(16).padStart(6, '0')}_`
111
+ }
112
+
113
+
113
114
  export const B64ChrByIdx = new Map<number, string>([[0, 'A'], [1, 'B'], [2, 'C'], [3, 'D'], [4, 'E'], [5, 'F'],
114
115
  [6, 'G'], [7, 'H'], [8, 'I'], [9, 'J'], [10, 'K'], [11, 'L'], [12, 'M'], [13, 'N'], [14, 'O'], [15, 'P'],
115
116
  [16, 'Q'], [17, 'R'], [18, 'S'], [19, 'T'], [20, 'U'], [21, 'V'], [22, 'W'], [23, 'X'], [24, 'Y'], [25, 'Z'],
@@ -120,17 +121,19 @@ export const B64ChrByIdx = new Map<number, string>([[0, 'A'], [1, 'B'], [2, 'C']
120
121
 
121
122
  export const B64IdxByChr = new Map<string, number>(Array.from(B64ChrByIdx, entry => [entry[1], entry[0]]))
122
123
 
123
- export function intToB64(i:number | undefined, l=1): string {
124
+
125
+ export function intToB64(i:number, l=1): string {
124
126
  let out = ""
125
127
  while(l != 0) {
126
- out = B64ChrByIdx.get(i! % 64) + out
127
- i = Math.floor(i! / 64)
128
+ out = B64ChrByIdx.get(i % 64) + out
129
+ i = Math.floor(i / 64)
128
130
  if (i == 0) {
129
131
  break
130
132
  }
131
133
  }
132
134
 
133
- for(let i = 0; i < (l - out.length); i++) {
135
+ let x = (l - out.length)
136
+ for(let i = 0; i < x; i++) {
134
137
  out = "A" + out
135
138
  }
136
139
 
@@ -164,6 +167,13 @@ export function d(u? :Uint8Array): string {
164
167
  return decoder.decode(u)
165
168
  }
166
169
 
170
+ export function concat(one: Uint8Array, two: Uint8Array): Uint8Array {
171
+ let out = new Uint8Array(one.length + two.length)
172
+ out.set(one)
173
+ out.set(two, one.length)
174
+ return out
175
+ }
176
+
167
177
 
168
178
  export function readInt(array: Uint8Array) {
169
179
  let value = 0;
@@ -171,4 +181,4 @@ export function readInt(array: Uint8Array) {
171
181
  value = (value * 256) + array[i];
172
182
  }
173
183
  return value;
174
- }
184
+ }