keri 0.0.0-dev.8b0703e → 0.0.0-dev.bf75350

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 (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +3 -0
  3. package/dist/cli/main.d.ts +2 -0
  4. package/dist/cli/main.js +177 -0
  5. package/dist/cli/main.js.map +1 -0
  6. package/dist/client.d.ts +21 -0
  7. package/dist/client.js +72 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/controller.d.ts +65 -0
  10. package/dist/controller.js +475 -0
  11. package/dist/controller.js.map +1 -0
  12. package/dist/data-type.js +1 -0
  13. package/dist/data-type.js.map +1 -0
  14. package/dist/db/storage-sqlite.d.ts +12 -0
  15. package/dist/db/storage-sqlite.js +57 -0
  16. package/dist/db/storage-sqlite.js.map +1 -0
  17. package/dist/db/storage.d.ts +18 -0
  18. package/dist/db/storage.js +37 -0
  19. package/dist/db/storage.js.map +1 -0
  20. package/dist/events/event-store.d.ts +133 -0
  21. package/dist/events/event-store.js +215 -0
  22. package/dist/events/event-store.js.map +1 -0
  23. package/dist/events/events.d.ts +251 -0
  24. package/dist/events/events.js +184 -0
  25. package/dist/events/events.js.map +1 -0
  26. package/dist/keystore/encrypt.d.ts +10 -2
  27. package/dist/keystore/encrypt.js +26 -25
  28. package/dist/keystore/encrypt.js.map +1 -0
  29. package/dist/keystore/keystore.d.ts +16 -2
  30. package/dist/keystore/keystore.js +72 -1
  31. package/dist/keystore/keystore.js.map +1 -0
  32. package/dist/main.d.ts +6 -2
  33. package/dist/main.js +7 -2
  34. package/dist/main.js.map +1 -0
  35. package/package.json +27 -24
  36. package/dist/db/sqlite-db.d.ts +0 -14
  37. package/dist/db/sqlite-db.js +0 -90
  38. package/dist/events/common.d.ts +0 -6
  39. package/dist/events/common.js +0 -1
  40. package/dist/events/incept.d.ts +0 -26
  41. package/dist/events/incept.js +0 -28
  42. package/dist/events/interact.d.ts +0 -14
  43. package/dist/events/interact.js +0 -20
  44. package/dist/events/main.d.ts +0 -4
  45. package/dist/events/main.js +0 -4
  46. package/dist/events/reply.d.ts +0 -15
  47. package/dist/events/reply.js +0 -20
  48. package/dist/keri.d.ts +0 -1
  49. package/dist/keri.js +0 -110
  50. package/dist/keystore/keystore-fs.d.ts +0 -13
  51. package/dist/keystore/keystore-fs.js +0 -50
  52. package/dist/keystore/keystore-web.d.ts +0 -12
  53. package/dist/keystore/keystore-web.js +0 -48
  54. package/dist/main-common.d.ts +0 -7
  55. package/dist/main-common.js +0 -7
  56. package/dist/main-web.d.ts +0 -2
  57. package/dist/main-web.js +0 -2
  58. package/dist/parser/base64.d.ts +0 -6
  59. package/dist/parser/base64.js +0 -74
  60. package/dist/parser/cesr-encoding.d.ts +0 -34
  61. package/dist/parser/cesr-encoding.js +0 -158
  62. package/dist/parser/codes.d.ts +0 -143
  63. package/dist/parser/codes.js +0 -266
  64. package/dist/parser/parser.d.ts +0 -11
  65. package/dist/parser/parser.js +0 -150
  66. package/dist/parser/version.d.ts +0 -11
  67. package/dist/parser/version.js +0 -56
@@ -1,14 +0,0 @@
1
- import type { DataArray } from "../data-type.ts";
2
- export interface InteractArgs {
3
- i: string;
4
- s: string;
5
- a: DataArray;
6
- }
7
- export interface InteractEvent {
8
- v: string;
9
- t: "ixn";
10
- d: string;
11
- i: string;
12
- a: DataArray;
13
- }
14
- export declare function interact(data: InteractArgs): InteractEvent;
@@ -1,20 +0,0 @@
1
- import { blake3 } from "@noble/hashes/blake3";
2
- import cesr from "../parser/cesr-encoding.js";
3
- import { MatterCode } from "../parser/codes.js";
4
- import { versify } from "../parser/version.js";
5
- export function interact(data) {
6
- const event = versify({
7
- t: "ixn",
8
- d: "#".repeat(44),
9
- i: data.i,
10
- s: data.s,
11
- a: data.a,
12
- });
13
- const encoder = new TextEncoder();
14
- const digest = cesr.encode(MatterCode.Blake3_256, blake3
15
- .create({ dkLen: 32 })
16
- .update(encoder.encode(JSON.stringify(event)))
17
- .digest());
18
- event["d"] = digest;
19
- return event;
20
- }
@@ -1,4 +0,0 @@
1
- export * from "./common.ts";
2
- export * from "./incept.ts";
3
- export * from "./reply.ts";
4
- export * from "./interact.ts";
@@ -1,4 +0,0 @@
1
- export * from "./common.js";
2
- export * from "./incept.js";
3
- export * from "./reply.js";
4
- export * from "./interact.js";
@@ -1,15 +0,0 @@
1
- import type { DataObject } from "../data-type.ts";
2
- export interface ReplyArgs {
3
- dt?: string;
4
- r: string;
5
- a: DataObject;
6
- }
7
- export interface ReplyEvent {
8
- v: string;
9
- t: "rpy";
10
- d: string;
11
- dt: string;
12
- r: string;
13
- a: DataObject;
14
- }
15
- export declare function reply(data: ReplyArgs): ReplyEvent;
@@ -1,20 +0,0 @@
1
- import { blake3 } from "@noble/hashes/blake3";
2
- import cesr from "../parser/cesr-encoding.js";
3
- import { MatterCode } from "../parser/codes.js";
4
- import { versify } from "../parser/version.js";
5
- export function reply(data) {
6
- const event = versify({
7
- t: "rpy",
8
- d: "#".repeat(44),
9
- dt: data.dt ?? new Date().toISOString(),
10
- r: data.r,
11
- a: data.a,
12
- });
13
- const encoder = new TextEncoder();
14
- const digest = cesr.encode(MatterCode.Blake3_256, blake3
15
- .create({ dkLen: 32 })
16
- .update(encoder.encode(JSON.stringify(event)))
17
- .digest());
18
- event["d"] = digest;
19
- return event;
20
- }
package/dist/keri.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/keri.js DELETED
@@ -1,110 +0,0 @@
1
- import { program } from "commander";
2
- import { parseStream } from "./parser/parser.js";
3
- import { CounterCode } from "./parser/codes.js";
4
- import { incept } from "./events/incept.js";
5
- import cesr from "./parser/cesr-encoding.js";
6
- import { encodeBase64Int } from "./parser/base64.js";
7
- import { FileSystemKeyStore } from "./keystore/keystore-fs.js";
8
- import { SqliteEventStore } from "./db/sqlite-db.js";
9
- const db = new SqliteEventStore({ filename: ".keri/db.sqlite" });
10
- db.init();
11
- program.command("parse").action(async () => {
12
- const stream = process.stdin;
13
- for await (const event of parseStream(ReadableStream.from(stream))) {
14
- console.log(event);
15
- }
16
- });
17
- program
18
- .command("keygen")
19
- .requiredOption("--passcode <passcode>")
20
- .action(async ({ passcode }) => {
21
- const keystore = new FileSystemKeyStore({ dir: ".keri/keys", passphrase: passcode });
22
- await keystore.incept();
23
- });
24
- program.command("resolve <oobi>").action(async (oobi) => {
25
- const response = await fetch(oobi);
26
- if (!response.ok) {
27
- throw new Error(`Failed to fetch oobi: ${response.status} ${response.statusText}`);
28
- }
29
- if (!response.body) {
30
- throw new Error(`No body in response`);
31
- }
32
- for await (const event of parseStream(response.body)) {
33
- db.insert(event.payload);
34
- }
35
- });
36
- program
37
- .command("incept")
38
- .requiredOption("--passcode <passcode>")
39
- .requiredOption("--name <name>")
40
- .option("--wit <wit>")
41
- .action(async ({ passcode, name, wit }) => {
42
- if (typeof passcode !== "string") {
43
- throw new Error(`Invalid passcode`);
44
- }
45
- if (typeof name !== "string") {
46
- throw new Error(`Invalid name`);
47
- }
48
- const keystore = new FileSystemKeyStore({ dir: ".keri/keys", passphrase: passcode });
49
- const keys = [await keystore.incept()];
50
- const wits = [];
51
- if (typeof wit === "string") {
52
- wits.push(wit);
53
- }
54
- const payload = incept({
55
- kt: "1",
56
- k: keys.map((key) => key.current),
57
- nt: "1",
58
- n: keys.map((key) => key.next),
59
- bt: "1",
60
- b: wits,
61
- });
62
- const witnessEndpoints = await Promise.all(wits.map(async (wit) => {
63
- const result = await db.locations(wit);
64
- if (result.length === 0) {
65
- throw new Error(`No location found for wit ${wit}`);
66
- }
67
- return result[0].a.url;
68
- }));
69
- const sigs = await Promise.all(keys.map(async (key, index) => {
70
- const sig = await keystore.sign(key.current, new TextEncoder().encode(JSON.stringify(payload)));
71
- return cesr.index(sig, index);
72
- }));
73
- const sigGroup = `${CounterCode.ControllerIdxSigs}${encodeBase64Int(sigs.length, 2)}${sigs.join("")}`;
74
- const attachmentSize = new TextEncoder().encode(sigGroup).length / 4;
75
- const attachment = `${CounterCode.AttachmentGroup}${encodeBase64Int(attachmentSize, 2)}${sigGroup}`;
76
- for (const wit of witnessEndpoints) {
77
- const url = new URL("/receipts", wit);
78
- const response = await fetch(url, {
79
- method: "POST",
80
- body: JSON.stringify(payload),
81
- headers: {
82
- "Content-Type": "application/cesr+json",
83
- "CESR-ATTACHMENT": attachment,
84
- },
85
- });
86
- if (!response.ok) {
87
- throw new Error(`Failed to send event to wit ${wit}: ${response.status} ${response.statusText}`);
88
- }
89
- if (response.status !== 200) {
90
- throw new Error(`Failed to send event to wit ${wit}: ${response.status} ${response.statusText}`);
91
- }
92
- if (response.body) {
93
- for await (const receipt of parseStream(response.body)) {
94
- await db.insert(receipt.payload);
95
- console.log(receipt);
96
- }
97
- }
98
- }
99
- console.dir({
100
- payload: payload,
101
- sigs,
102
- attachment,
103
- });
104
- });
105
- program.command("export").action(async () => {
106
- for (const event of await db.list()) {
107
- console.log(event);
108
- }
109
- });
110
- program.parse(process.argv);
@@ -1,13 +0,0 @@
1
- import type { KeyStore, Key } from "./keystore.ts";
2
- export interface FileSystemKeyStoreOptions {
3
- dir: string;
4
- passphrase: string;
5
- }
6
- export declare class FileSystemKeyStore implements KeyStore {
7
- private readonly options;
8
- constructor(options: FileSystemKeyStoreOptions);
9
- private load;
10
- incept(): Promise<Key>;
11
- rotate(currentKey: string): Promise<Key>;
12
- sign(publicKey: string, message: Uint8Array): Promise<string>;
13
- }
@@ -1,50 +0,0 @@
1
- import { ed25519 } from "@noble/curves/ed25519";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
- import cesr from "../parser/cesr-encoding.js";
4
- import { MatterCode } from "../parser/codes.js";
5
- import { decodeBase64, encodeBase64 } from "../parser/base64.js";
6
- import { decrypt, encrypt } from "./encrypt.js";
7
- import { join } from "node:path";
8
- import { blake3 } from "@noble/hashes/blake3";
9
- export class FileSystemKeyStore {
10
- constructor(options) {
11
- this.options = options;
12
- }
13
- async load(publicKey) {
14
- const value = await readFile(join(this.options.dir, publicKey), "utf-8");
15
- const [key0, key1] = value.split("\n");
16
- return [
17
- await decrypt(this.options.passphrase, decodeBase64(key0)),
18
- await decrypt(this.options.passphrase, decodeBase64(key1)),
19
- ];
20
- }
21
- async incept() {
22
- const key0 = ed25519.utils.randomPrivateKey();
23
- const key1 = ed25519.utils.randomPrivateKey();
24
- await mkdir(this.options.dir, { recursive: true });
25
- const current = cesr.encode(MatterCode.Ed25519, ed25519.getPublicKey(key0));
26
- const next = cesr.encode(MatterCode.Blake3_256, blake3.create({ dkLen: 32 }).update(current).digest());
27
- await writeFile(join(this.options.dir, current), [
28
- encodeBase64(await encrypt(this.options.passphrase, key0)),
29
- encodeBase64(await encrypt(this.options.passphrase, key1)),
30
- "\n",
31
- ].join("\n"));
32
- return { current, next };
33
- }
34
- async rotate(currentKey) {
35
- const [, key0] = await this.load(currentKey);
36
- const key1 = ed25519.utils.randomPrivateKey();
37
- const current = cesr.encode(MatterCode.Ed25519, ed25519.getPublicKey(key0));
38
- const next = cesr.encode(MatterCode.Blake3_256, blake3.create({ dkLen: 32 }).update(current).digest());
39
- await writeFile(join(this.options.dir, current), [
40
- encodeBase64(await encrypt(this.options.passphrase, key0)),
41
- encodeBase64(await encrypt(this.options.passphrase, key1)),
42
- "\n",
43
- ].join("\n"));
44
- return { current, next };
45
- }
46
- async sign(publicKey, message) {
47
- const [key] = await this.load(publicKey);
48
- return cesr.sign(message, key, "ed25519");
49
- }
50
- }
@@ -1,12 +0,0 @@
1
- import type { Key, KeyStore } from "./keystore.ts";
2
- export interface WebKeyStoreOptions {
3
- passphrase: string;
4
- }
5
- export declare class WebKeyStore implements KeyStore {
6
- private readonly options;
7
- constructor(options: WebKeyStoreOptions);
8
- private load;
9
- incept(): Promise<Key>;
10
- rotate(currentKey: string): Promise<Key>;
11
- sign(publicKey: string, message: Uint8Array): Promise<string>;
12
- }
@@ -1,48 +0,0 @@
1
- import { ed25519 } from "@noble/curves/ed25519";
2
- import cesr from "../parser/cesr-encoding.js";
3
- import { MatterCode } from "../parser/codes.js";
4
- import { decodeBase64, encodeBase64 } from "../parser/base64.js";
5
- import { decrypt, encrypt } from "./encrypt.js";
6
- import { blake3 } from "@noble/hashes/blake3";
7
- export class WebKeyStore {
8
- constructor(options) {
9
- this.options = options;
10
- }
11
- async load(publicKey) {
12
- const value = localStorage.getItem(publicKey);
13
- if (!value) {
14
- throw new Error("No such key");
15
- }
16
- const [key0, key1] = value.split("\n");
17
- return [
18
- await decrypt(this.options.passphrase, decodeBase64(key0)),
19
- await decrypt(this.options.passphrase, decodeBase64(key1)),
20
- ];
21
- }
22
- async incept() {
23
- const key0 = ed25519.utils.randomPrivateKey();
24
- const key1 = ed25519.utils.randomPrivateKey();
25
- const current = cesr.encode(MatterCode.Ed25519, ed25519.getPublicKey(key0));
26
- const next = cesr.encode(MatterCode.Blake3_256, blake3.create({ dkLen: 32 }).update(current).digest());
27
- localStorage.setItem(current, [
28
- encodeBase64(await encrypt(this.options.passphrase, key0)),
29
- encodeBase64(await encrypt(this.options.passphrase, key1)),
30
- ].join("\n"));
31
- return { current, next };
32
- }
33
- async rotate(currentKey) {
34
- const [, key0] = await this.load(currentKey);
35
- const key1 = ed25519.utils.randomPrivateKey();
36
- const current = cesr.encode(MatterCode.Ed25519, ed25519.getPublicKey(key0));
37
- const next = cesr.encode(MatterCode.Blake3_256, blake3.create({ dkLen: 32 }).update(current).digest());
38
- localStorage.setItem(current, [
39
- encodeBase64(await encrypt(this.options.passphrase, key0)),
40
- encodeBase64(await encrypt(this.options.passphrase, key1)),
41
- ].join("\n"));
42
- return { current, next };
43
- }
44
- async sign(publicKey, message) {
45
- const [key] = await this.load(publicKey);
46
- return cesr.sign(message, key, "ed25519");
47
- }
48
- }
@@ -1,7 +0,0 @@
1
- import cesr from "./parser/cesr-encoding.ts";
2
- import { incept } from "./events/incept.ts";
3
- export * from "./keystore/keystore.ts";
4
- export * from "./parser/codes.ts";
5
- export * from "./parser/base64.ts";
6
- export * from "./parser/parser.ts";
7
- export { incept, cesr };
@@ -1,7 +0,0 @@
1
- import cesr from "./parser/cesr-encoding.js";
2
- import { incept } from "./events/incept.js";
3
- export * from "./keystore/keystore.js";
4
- export * from "./parser/codes.js";
5
- export * from "./parser/base64.js";
6
- export * from "./parser/parser.js";
7
- export { incept, cesr };
@@ -1,2 +0,0 @@
1
- export * from "./keystore/keystore-web.ts";
2
- export * from "./main-common.ts";
package/dist/main-web.js DELETED
@@ -1,2 +0,0 @@
1
- export * from "./keystore/keystore-web.js";
2
- export * from "./main-common.js";
@@ -1,6 +0,0 @@
1
- export declare function encodeBase64(uint8: Uint8Array): string;
2
- export declare function decodeBase64(b64: string): Uint8Array;
3
- export declare function decodeBase64Int(value: string): number;
4
- export declare function encodeBase64Int(value: number, length?: number): string;
5
- export declare function encodeBase64Url(buffer: Uint8Array): string;
6
- export declare function decodeBase64Url(input: string): Uint8Array;
@@ -1,74 +0,0 @@
1
- const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2
- const B64_URL_MAP = ALPHABET.split("");
3
- const B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
4
- export function encodeBase64(uint8) {
5
- // CREDIT: https://github.com/denoland/std/blob/main/encoding/base64.ts
6
- // CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
7
- let result = "";
8
- let i;
9
- const l = uint8.length;
10
- for (i = 2; i < l; i += 3) {
11
- result += B64_ALPHABET[uint8[i - 2] >> 2];
12
- result += B64_ALPHABET[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
13
- result += B64_ALPHABET[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
14
- result += B64_ALPHABET[uint8[i] & 0x3f];
15
- }
16
- if (i === l + 1) {
17
- // 1 octet yet to write
18
- result += B64_ALPHABET[uint8[i - 2] >> 2];
19
- result += B64_ALPHABET[(uint8[i - 2] & 0x03) << 4];
20
- result += "==";
21
- }
22
- if (i === l) {
23
- // 2 octets yet to write
24
- result += B64_ALPHABET[uint8[i - 2] >> 2];
25
- result += B64_ALPHABET[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
26
- result += B64_ALPHABET[(uint8[i - 1] & 0x0f) << 2];
27
- result += "=";
28
- }
29
- return result;
30
- }
31
- export function decodeBase64(b64) {
32
- // CREDIT: https://github.com/denoland/std/blob/main/encoding/base64.ts
33
- const binString = atob(b64);
34
- const size = binString.length;
35
- const bytes = new Uint8Array(size);
36
- for (let i = 0; i < size; i++) {
37
- bytes[i] = binString.charCodeAt(i);
38
- }
39
- return bytes;
40
- }
41
- export function decodeBase64Int(value) {
42
- return value
43
- .split("")
44
- .reverse()
45
- .reduce((result, character, index) => {
46
- const value = ALPHABET.indexOf(character);
47
- const factor = 64 ** index;
48
- return result + value * factor;
49
- }, 0);
50
- }
51
- export function encodeBase64Int(value, length = 1) {
52
- let current = value;
53
- let result = "";
54
- while (length != 0) {
55
- result = B64_URL_MAP[current % 64] + result;
56
- current = Math.floor(current / 64);
57
- if (current == 0) {
58
- break;
59
- }
60
- }
61
- return result.padStart(length, "A");
62
- }
63
- export function encodeBase64Url(buffer) {
64
- return encodeBase64(buffer).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+/, "");
65
- }
66
- export function decodeBase64Url(input) {
67
- if (!(typeof input === "string")) {
68
- throw new TypeError("`input` must be a string.");
69
- }
70
- const n = input.length % 4;
71
- const padded = input + "=".repeat(n > 0 ? 4 - n : n);
72
- const base64String = padded.replace(/-/g, "+").replace(/_/g, "/");
73
- return decodeBase64(base64String);
74
- }
@@ -1,34 +0,0 @@
1
- /**
2
- * Represents the Raw domain
3
- */
4
- export interface Raw {
5
- code: string;
6
- buffer: Uint8Array;
7
- }
8
- export declare function decode(text: string): Raw;
9
- export declare function encodeDate(date: Date): string;
10
- export declare function encode(code: string, raw: Uint8Array): string;
11
- /**
12
- * Converts a cryptographic primitive to indexed material
13
- */
14
- export declare function index(text: string, index: number): string;
15
- export interface Indexed {
16
- value: string;
17
- index: number;
18
- }
19
- /**
20
- * Converts indexed material to primitive and index
21
- */
22
- export declare function deindex(text: string): Indexed;
23
- export declare function sign(message: Uint8Array, privateKey: Uint8Array, curve: "ed25519"): string;
24
- export declare function verify(message: Uint8Array, publicKey: string, signature: string): boolean;
25
- declare const cesr: {
26
- encode: typeof encode;
27
- decode: typeof decode;
28
- sign: typeof sign;
29
- verify: typeof verify;
30
- index: typeof index;
31
- deindex: typeof deindex;
32
- encodeDate: typeof encodeDate;
33
- };
34
- export default cesr;
@@ -1,158 +0,0 @@
1
- import { ed25519 } from "@noble/curves/ed25519";
2
- import { decodeBase64Int, decodeBase64Url, encodeBase64Int, encodeBase64Url } from "./base64.js";
3
- import { IndexerCode, IndexerCodeTable, MatterCode, MatterCodeTable } from "./codes.js";
4
- function padNumber(num, length) {
5
- return num.toString().padStart(length, "0");
6
- }
7
- function findPrimitiveCode(text) {
8
- let i = 0;
9
- let code = "";
10
- let size = null;
11
- while (!size && i <= 4) {
12
- code = text.slice(0, i);
13
- size = MatterCodeTable[text.slice(0, i)];
14
- ++i;
15
- }
16
- if (!size) {
17
- throw new Error(`Unable to find code table for ${text}`);
18
- }
19
- return [code, size];
20
- }
21
- function findIndexCode(text) {
22
- let i = 0;
23
- let code = "";
24
- let size = null;
25
- while (!size && i <= 4) {
26
- code = text.slice(0, i);
27
- size = IndexerCodeTable[text.slice(0, i)];
28
- ++i;
29
- }
30
- if (!size) {
31
- throw new Error(`Unable to find code table for ${text}`);
32
- }
33
- return [code, size];
34
- }
35
- export function decode(text) {
36
- const [code, size] = findPrimitiveCode(text);
37
- if (!size) {
38
- throw new Error(`Unable to find code table for ${text}`);
39
- }
40
- const padSize = (size.hs + size.ss) % 4;
41
- const padding = "A".repeat(padSize);
42
- const paw = decodeBase64Url(padding + text.substring(size.hs + size.ss));
43
- const buffer = paw.slice(padSize + (size.ls ?? 0));
44
- return { code, buffer };
45
- }
46
- export function encodeDate(date) {
47
- if (date.toString() === "Invalid Date") {
48
- throw new Error("Invalid date");
49
- }
50
- const YYYY = date.getFullYear();
51
- const MM = padNumber(date.getUTCMonth() + 1, 2);
52
- const dd = padNumber(date.getUTCDate(), 2);
53
- const hh = padNumber(date.getUTCHours(), 2);
54
- const mm = padNumber(date.getUTCMinutes(), 2);
55
- const ss = padNumber(date.getUTCSeconds(), 2);
56
- const ms = padNumber(date.getMilliseconds(), 3);
57
- const format = `${YYYY}-${MM}-${dd}T${hh}c${mm}c${ss}d${ms}000p00c00`;
58
- return `${MatterCode.DateTime}${format}`;
59
- }
60
- export function encode(code, raw) {
61
- const both = code;
62
- const rs = raw.byteLength;
63
- const size = MatterCodeTable[code];
64
- if (!size) {
65
- throw new Error(`Unable to find code table for ${code}`);
66
- }
67
- const { hs, ss, xs, fs } = size;
68
- const ls = size.ls ?? 0;
69
- const cs = hs + ss;
70
- let full;
71
- if (!fs) {
72
- if ((ls + rs) % 3 !== 0 || cs % 4 !== 0) {
73
- throw new Error(`Invalid full code=${both} with variable raw size=${rs} given cs=${cs}, hs=${hs}, ss=${ss}, fs=${fs}, and ls=${ls}.`);
74
- }
75
- const paddedRaw = new Uint8Array(ls + rs);
76
- paddedRaw.set(raw, ls);
77
- full = both + encodeBase64Url(paddedRaw);
78
- }
79
- else {
80
- const ps = (3 - ((rs + ls) % 3)) % 3;
81
- if (ps !== cs % 4) {
82
- throw new Error(`Invalid full code=${both} with fixed raw size=${rs} given cs=${cs}, hs=${hs}, ss=${ss}, fs=${fs}, and ls=${ls}.`);
83
- }
84
- const paddedRaw = new Uint8Array(ps + ls + rs);
85
- paddedRaw.set(raw, ps + ls);
86
- full = both + encodeBase64Url(paddedRaw).slice(ps);
87
- }
88
- if (full.length % 4 !== 0 || (fs && full.length !== fs)) {
89
- throw new Error(`Invalid full size given code=${both} with raw size=${rs}, cs=${cs}, hs=${hs}, ss=${ss}, xs=${xs}, fs=${fs}, and ls=${ls}.`);
90
- }
91
- return full;
92
- }
93
- function resolveIndexCode(primitiveCode) {
94
- switch (primitiveCode) {
95
- case MatterCode.Ed25519_Sig:
96
- return [IndexerCode.Ed25519_Sig, IndexerCodeTable[IndexerCode.Ed25519_Sig]];
97
- case MatterCode.Ed448_Sig:
98
- return [IndexerCode.Ed448_Sig, IndexerCodeTable[IndexerCode.Ed448_Sig]];
99
- }
100
- throw new Error(`Unable to find indexed code for '${primitiveCode}'`);
101
- }
102
- function resolvePrimitiveCode(indexCode) {
103
- switch (indexCode) {
104
- case IndexerCode.Ed25519_Sig:
105
- return [MatterCode.Ed25519_Sig, MatterCodeTable[IndexerCode.Ed25519_Sig]];
106
- case IndexerCode.Ed448_Sig:
107
- return [MatterCode.Ed448_Sig, MatterCodeTable[IndexerCode.Ed448_Sig]];
108
- }
109
- throw new Error(`Unable to find primitive code for '${indexCode}'`);
110
- }
111
- /**
112
- * Converts a cryptographic primitive to indexed material
113
- */
114
- export function index(text, index) {
115
- const [code, size] = findPrimitiveCode(text);
116
- const [indexCode, indexCodeSize] = resolveIndexCode(code);
117
- return indexCode + encodeBase64Int(index, indexCodeSize.ss) + text.slice(size.hs + size.ss);
118
- }
119
- /**
120
- * Converts indexed material to primitive and index
121
- */
122
- export function deindex(text) {
123
- const [indexCode, indexCodeSize] = findIndexCode(text);
124
- const [primitiveCode] = resolvePrimitiveCode(indexCode);
125
- const index = decodeBase64Int(text.slice(indexCodeSize.hs, indexCodeSize.ss));
126
- const value = primitiveCode + text.slice(indexCodeSize.hs + indexCodeSize.ss);
127
- return {
128
- index,
129
- value,
130
- };
131
- }
132
- export function sign(message, privateKey, curve) {
133
- switch (curve) {
134
- case "ed25519":
135
- return cesr.encode(MatterCode.Ed25519_Sig, ed25519.sign(message, privateKey));
136
- default:
137
- throw new Error(`Unsupported curve ${curve}`);
138
- }
139
- }
140
- export function verify(message, publicKey, signature) {
141
- const decodedPublicKey = cesr.decode(publicKey);
142
- const decodedSignature = cesr.decode(signature);
143
- switch (decodedSignature.code) {
144
- case MatterCode.Ed25519_Sig:
145
- return ed25519.verify(decodedSignature.buffer, message, decodedPublicKey.buffer);
146
- }
147
- throw new Error(`Unsupported signature code ${decodedSignature.code}`);
148
- }
149
- const cesr = {
150
- encode,
151
- decode,
152
- sign,
153
- verify,
154
- index,
155
- deindex,
156
- encodeDate,
157
- };
158
- export default cesr;