cojson 0.0.1 → 0.0.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/src/coValue.ts ADDED
@@ -0,0 +1,563 @@
1
+ import { randomBytes } from "@noble/hashes/utils";
2
+ import { CoList, CoMap, ContentType, Static, CoStream } from "./contentType";
3
+ import {
4
+ Encrypted,
5
+ Hash,
6
+ KeySecret,
7
+ RecipientID,
8
+ RecipientSecret,
9
+ SignatoryID,
10
+ SignatorySecret,
11
+ Signature,
12
+ StreamingHash,
13
+ getRecipientID,
14
+ getSignatoryID,
15
+ newRandomRecipient,
16
+ newRandomSignatory,
17
+ openAs,
18
+ shortHash,
19
+ sign,
20
+ verify,
21
+ encryptForTransaction,
22
+ decryptForTransaction,
23
+ KeyID,
24
+ unsealKeySecret,
25
+ } from "./crypto";
26
+ import { JsonValue } from "./jsonValue";
27
+ import { base58 } from "@scure/base";
28
+ import {
29
+ PermissionsDef as RulesetDef,
30
+ determineValidTransactions,
31
+ expectTeamContent,
32
+ } from "./permissions";
33
+ import { LocalNode } from "./node";
34
+ import { CoValueKnownState, NewContentMessage } from "./sync";
35
+
36
+ export type RawCoValueID = `co_z${string}` | `co_${string}_z${string}`;
37
+
38
+ export type CoValueHeader = {
39
+ type: ContentType["type"];
40
+ ruleset: RulesetDef;
41
+ meta: JsonValue;
42
+ publicNickname?: string;
43
+ };
44
+
45
+ function coValueIDforHeader(header: CoValueHeader): RawCoValueID {
46
+ const hash = shortHash(header);
47
+ if (header.publicNickname) {
48
+ return `co_${header.publicNickname}_z${hash.slice(
49
+ "shortHash_z".length
50
+ )}`;
51
+ } else {
52
+ return `co_z${hash.slice("shortHash_z".length)}`;
53
+ }
54
+ }
55
+
56
+ export type SessionID = `${AgentID}_session_z${string}`;
57
+
58
+ export function agentIDfromSessionID(sessionID: SessionID): AgentID {
59
+ return sessionID.split("_session")[0] as AgentID;
60
+ }
61
+
62
+ export function newRandomSessionID(agentID: AgentID): SessionID {
63
+ return `${agentID}_session_z${base58.encode(randomBytes(8))}`;
64
+ }
65
+
66
+ type SessionLog = {
67
+ transactions: Transaction[];
68
+ lastHash?: Hash;
69
+ streamingHash: StreamingHash;
70
+ lastSignature: Signature;
71
+ };
72
+
73
+ export type PrivateTransaction = {
74
+ privacy: "private";
75
+ madeAt: number;
76
+ keyUsed: KeyID;
77
+ encryptedChanges: Encrypted<
78
+ JsonValue[],
79
+ { in: RawCoValueID; tx: TransactionID }
80
+ >;
81
+ };
82
+
83
+ export type TrustingTransaction = {
84
+ privacy: "trusting";
85
+ madeAt: number;
86
+ changes: JsonValue[];
87
+ };
88
+
89
+ export type Transaction = PrivateTransaction | TrustingTransaction;
90
+
91
+ export type DecryptedTransaction = {
92
+ txID: TransactionID;
93
+ changes: JsonValue[];
94
+ madeAt: number;
95
+ };
96
+
97
+ export type TransactionID = { sessionID: SessionID; txIndex: number };
98
+
99
+ export class CoValue {
100
+ id: RawCoValueID;
101
+ node: LocalNode;
102
+ header: CoValueHeader;
103
+ sessions: { [key: SessionID]: SessionLog };
104
+ content?: ContentType;
105
+
106
+ constructor(header: CoValueHeader, node: LocalNode) {
107
+ this.id = coValueIDforHeader(header);
108
+ this.header = header;
109
+ this.sessions = {};
110
+ this.node = node;
111
+ }
112
+
113
+ testWithDifferentCredentials(
114
+ agentCredential: AgentCredential,
115
+ ownSessionID: SessionID
116
+ ): CoValue {
117
+ const newNode = this.node.testWithDifferentCredentials(
118
+ agentCredential,
119
+ ownSessionID
120
+ );
121
+
122
+ return newNode.expectCoValueLoaded(this.id);
123
+ }
124
+
125
+ knownState(): CoValueKnownState {
126
+ return {
127
+ coValueID: this.id,
128
+ header: true,
129
+ sessions: Object.fromEntries(
130
+ Object.entries(this.sessions).map(([k, v]) => [
131
+ k,
132
+ v.transactions.length,
133
+ ])
134
+ ),
135
+ };
136
+ }
137
+
138
+ get meta(): JsonValue {
139
+ return this.header?.meta ?? null;
140
+ }
141
+
142
+ nextTransactionID(): TransactionID {
143
+ const sessionID = this.node.ownSessionID;
144
+ return {
145
+ sessionID,
146
+ txIndex: this.sessions[sessionID]?.transactions.length || 0,
147
+ };
148
+ }
149
+
150
+ tryAddTransactions(
151
+ sessionID: SessionID,
152
+ newTransactions: Transaction[],
153
+ newHash: Hash,
154
+ newSignature: Signature
155
+ ): boolean {
156
+ const signatoryID = this.node.expectAgentLoaded(
157
+ agentIDfromSessionID(sessionID),
158
+ "Expected to know signatory of transaction"
159
+ ).signatoryID;
160
+
161
+ if (!signatoryID) {
162
+ console.warn("Unknown agent", agentIDfromSessionID(sessionID));
163
+ return false;
164
+ }
165
+
166
+ const { expectedNewHash, newStreamingHash } = this.expectedNewHashAfter(
167
+ sessionID,
168
+ newTransactions
169
+ );
170
+
171
+ if (newHash !== expectedNewHash) {
172
+ console.warn("Invalid hash", { newHash, expectedNewHash });
173
+ return false;
174
+ }
175
+
176
+ if (!verify(newSignature, newHash, signatoryID)) {
177
+ console.warn(
178
+ "Invalid signature",
179
+ newSignature,
180
+ newHash,
181
+ signatoryID
182
+ );
183
+ return false;
184
+ }
185
+
186
+ const transactions = this.sessions[sessionID]?.transactions ?? [];
187
+
188
+ transactions.push(...newTransactions);
189
+
190
+ this.sessions[sessionID] = {
191
+ transactions,
192
+ lastHash: newHash,
193
+ streamingHash: newStreamingHash,
194
+ lastSignature: newSignature,
195
+ };
196
+
197
+ this.content = undefined;
198
+
199
+ const _ = this.getCurrentContent();
200
+
201
+ return true;
202
+ }
203
+
204
+ expectedNewHashAfter(
205
+ sessionID: SessionID,
206
+ newTransactions: Transaction[]
207
+ ): { expectedNewHash: Hash; newStreamingHash: StreamingHash } {
208
+ const streamingHash =
209
+ this.sessions[sessionID]?.streamingHash.clone() ??
210
+ new StreamingHash();
211
+ for (const transaction of newTransactions) {
212
+ streamingHash.update(transaction);
213
+ }
214
+
215
+ const newStreamingHash = streamingHash.clone();
216
+
217
+ return {
218
+ expectedNewHash: streamingHash.digest(),
219
+ newStreamingHash,
220
+ };
221
+ }
222
+
223
+ makeTransaction(
224
+ changes: JsonValue[],
225
+ privacy: "private" | "trusting"
226
+ ): boolean {
227
+ const madeAt = Date.now();
228
+
229
+ let transaction: Transaction;
230
+
231
+ if (privacy === "private") {
232
+ const { secret: keySecret, id: keyID } = this.getCurrentReadKey();
233
+
234
+ if (!keySecret) {
235
+ throw new Error("Can't make transaction without read key secret");
236
+ }
237
+
238
+ transaction = {
239
+ privacy: "private",
240
+ madeAt,
241
+ keyUsed: keyID,
242
+ encryptedChanges: encryptForTransaction(changes, keySecret, {
243
+ in: this.id,
244
+ tx: this.nextTransactionID(),
245
+ }),
246
+ };
247
+ } else {
248
+ transaction = {
249
+ privacy: "trusting",
250
+ madeAt,
251
+ changes,
252
+ };
253
+ }
254
+
255
+ const sessionID = this.node.ownSessionID;
256
+
257
+ const { expectedNewHash } = this.expectedNewHashAfter(sessionID, [
258
+ transaction,
259
+ ]);
260
+
261
+ const signature = sign(
262
+ this.node.agentCredential.signatorySecret,
263
+ expectedNewHash
264
+ );
265
+
266
+ const success = this.tryAddTransactions(
267
+ sessionID,
268
+ [transaction],
269
+ expectedNewHash,
270
+ signature
271
+ );
272
+
273
+ if (success) {
274
+ void this.node.sync.syncCoValue(this);
275
+ }
276
+
277
+ return success;
278
+ }
279
+
280
+ getCurrentContent(): ContentType {
281
+ if (this.content) {
282
+ return this.content;
283
+ }
284
+
285
+ if (this.header.type === "comap") {
286
+ this.content = new CoMap(this);
287
+ } else if (this.header.type === "colist") {
288
+ this.content = new CoList(this);
289
+ } else if (this.header.type === "costream") {
290
+ this.content = new CoStream(this);
291
+ } else if (this.header.type === "static") {
292
+ this.content = new Static(this);
293
+ } else {
294
+ throw new Error(`Unknown coValue type ${this.header.type}`);
295
+ }
296
+
297
+ return this.content;
298
+ }
299
+
300
+ getValidSortedTransactions(): DecryptedTransaction[] {
301
+ const validTransactions = determineValidTransactions(this);
302
+
303
+ const allTransactions: DecryptedTransaction[] = validTransactions.map(
304
+ ({ txID, tx }) => {
305
+ if (tx.privacy === "trusting") {
306
+ return {
307
+ txID,
308
+ madeAt: tx.madeAt,
309
+ changes: tx.changes,
310
+ };
311
+ } else {
312
+ const readKey = this.getReadKey(tx.keyUsed);
313
+
314
+ if (!readKey) {
315
+ return undefined;
316
+ } else {
317
+ const decrytedChanges = decryptForTransaction(
318
+ tx.encryptedChanges,
319
+ readKey,
320
+ {
321
+ in: this.id,
322
+ tx: txID,
323
+ }
324
+ );
325
+
326
+ if (!decrytedChanges) {
327
+ console.error("Failed to decrypt transaction despite having key");
328
+ return undefined;
329
+ }
330
+ return {
331
+ txID,
332
+ madeAt: tx.madeAt,
333
+ changes: decrytedChanges,
334
+ };
335
+ }
336
+ }
337
+ }
338
+ ).filter((x): x is Exclude<typeof x, undefined> => !!x);
339
+ allTransactions.sort(
340
+ (a, b) =>
341
+ a.madeAt - b.madeAt ||
342
+ (a.txID.sessionID < b.txID.sessionID ? -1 : 1) ||
343
+ a.txID.txIndex - b.txID.txIndex
344
+ );
345
+
346
+ return allTransactions;
347
+ }
348
+
349
+ getCurrentReadKey(): { secret: KeySecret | undefined; id: KeyID } {
350
+ if (this.header.ruleset.type === "team") {
351
+ const content = expectTeamContent(this.getCurrentContent());
352
+
353
+ const currentKeyId = content.get("readKey")?.keyID;
354
+
355
+ if (!currentKeyId) {
356
+ throw new Error("No readKey set");
357
+ }
358
+
359
+ const secret = this.getReadKey(currentKeyId);
360
+
361
+ return {
362
+ secret: secret,
363
+ id: currentKeyId,
364
+ };
365
+ } else if (this.header.ruleset.type === "ownedByTeam") {
366
+ return this.node
367
+ .expectCoValueLoaded(this.header.ruleset.team)
368
+ .getCurrentReadKey();
369
+ } else {
370
+ throw new Error(
371
+ "Only teams or values owned by teams have read secrets"
372
+ );
373
+ }
374
+ }
375
+
376
+ getReadKey(keyID: KeyID): KeySecret | undefined {
377
+ if (this.header.ruleset.type === "team") {
378
+ const content = expectTeamContent(this.getCurrentContent());
379
+
380
+ const readKeyHistory = content.getHistory("readKey");
381
+
382
+ // Try to find direct relevation of key for us
383
+
384
+ for (const entry of readKeyHistory) {
385
+ if (entry.value?.keyID === keyID) {
386
+ const revealer = agentIDfromSessionID(entry.txID.sessionID);
387
+ const revealerAgent = this.node.expectAgentLoaded(
388
+ revealer,
389
+ "Expected to know revealer"
390
+ );
391
+
392
+ const secret = openAs(
393
+ entry.value.revelation,
394
+ this.node.agentCredential.recipientSecret,
395
+ revealerAgent.recipientID,
396
+ {
397
+ in: this.id,
398
+ tx: entry.txID,
399
+ }
400
+ );
401
+
402
+ if (secret) return secret as KeySecret;
403
+ }
404
+ }
405
+
406
+ // Try to find indirect revelation through previousKeys
407
+
408
+ for (const entry of readKeyHistory) {
409
+ const encryptedPreviousKey = entry.value?.previousKeys?.[keyID];
410
+ if (entry.value && encryptedPreviousKey) {
411
+ const sealingKeyID = entry.value.keyID;
412
+ const sealingKeySecret = this.getReadKey(sealingKeyID);
413
+
414
+ if (!sealingKeySecret) {
415
+ continue;
416
+ }
417
+
418
+ const secret = unsealKeySecret(
419
+ {
420
+ sealed: keyID,
421
+ sealing: sealingKeyID,
422
+ encrypted: encryptedPreviousKey,
423
+ },
424
+ sealingKeySecret
425
+ );
426
+
427
+ if (secret) {
428
+ return secret;
429
+ } else {
430
+ console.error(
431
+ `Sealing ${sealingKeyID} key didn't unseal ${keyID}`
432
+ );
433
+ }
434
+ }
435
+ }
436
+
437
+ return undefined;
438
+ } else if (this.header.ruleset.type === "ownedByTeam") {
439
+ return this.node
440
+ .expectCoValueLoaded(this.header.ruleset.team)
441
+ .getReadKey(keyID);
442
+ } else {
443
+ throw new Error(
444
+ "Only teams or values owned by teams have read secrets"
445
+ );
446
+ }
447
+ }
448
+
449
+ getTx(txID: TransactionID): Transaction | undefined {
450
+ return this.sessions[txID.sessionID]?.transactions[txID.txIndex];
451
+ }
452
+
453
+ newContentSince(
454
+ knownState: CoValueKnownState | undefined
455
+ ): NewContentMessage | undefined {
456
+ const newContent: NewContentMessage = {
457
+ action: "newContent",
458
+ coValueID: this.id,
459
+ header: knownState?.header ? undefined : this.header,
460
+ newContent: Object.fromEntries(
461
+ Object.entries(this.sessions)
462
+ .map(([sessionID, log]) => {
463
+ const newTransactions = log.transactions.slice(
464
+ knownState?.sessions[sessionID as SessionID] || 0
465
+ );
466
+
467
+ if (
468
+ newTransactions.length === 0 ||
469
+ !log.lastHash ||
470
+ !log.lastSignature
471
+ ) {
472
+ return undefined;
473
+ }
474
+
475
+ return [
476
+ sessionID,
477
+ {
478
+ after:
479
+ knownState?.sessions[
480
+ sessionID as SessionID
481
+ ] || 0,
482
+ newTransactions,
483
+ lastHash: log.lastHash,
484
+ lastSignature: log.lastSignature,
485
+ },
486
+ ];
487
+ })
488
+ .filter((x): x is Exclude<typeof x, undefined> => !!x)
489
+ ),
490
+ };
491
+
492
+ if (
493
+ !newContent.header &&
494
+ Object.keys(newContent.newContent).length === 0
495
+ ) {
496
+ return undefined;
497
+ }
498
+
499
+ return newContent;
500
+ }
501
+
502
+ getDependedOnCoValues(): RawCoValueID[] {
503
+ return this.header.ruleset.type === "team"
504
+ ? expectTeamContent(this.getCurrentContent())
505
+ .keys()
506
+ .filter((k): k is AgentID => k.startsWith("co_agent"))
507
+ : this.header.ruleset.type === "ownedByTeam"
508
+ ? [this.header.ruleset.team]
509
+ : [];
510
+ }
511
+ }
512
+
513
+ export type AgentID = `co_agent${string}_z${string}`;
514
+
515
+ export type Agent = {
516
+ signatoryID: SignatoryID;
517
+ recipientID: RecipientID;
518
+ publicNickname?: string;
519
+ };
520
+
521
+ export function getAgent(agentCredential: AgentCredential) {
522
+ return {
523
+ signatoryID: getSignatoryID(agentCredential.signatorySecret),
524
+ recipientID: getRecipientID(agentCredential.recipientSecret),
525
+ publicNickname: agentCredential.publicNickname,
526
+ };
527
+ }
528
+
529
+ export function getAgentCoValueHeader(agent: Agent): CoValueHeader {
530
+ return {
531
+ type: "comap",
532
+ ruleset: {
533
+ type: "agent",
534
+ initialSignatoryID: agent.signatoryID,
535
+ initialRecipientID: agent.recipientID,
536
+ },
537
+ meta: null,
538
+ publicNickname:
539
+ "agent" + (agent.publicNickname ? `-${agent.publicNickname}` : ""),
540
+ };
541
+ }
542
+
543
+ export function getAgentID(agent: Agent): AgentID {
544
+ return coValueIDforHeader(getAgentCoValueHeader(agent)) as AgentID;
545
+ }
546
+
547
+ export type AgentCredential = {
548
+ signatorySecret: SignatorySecret;
549
+ recipientSecret: RecipientSecret;
550
+ publicNickname?: string;
551
+ };
552
+
553
+ export function newRandomAgentCredential(
554
+ publicNickname: string
555
+ ): AgentCredential {
556
+ const signatorySecret = newRandomSignatory();
557
+ const recipientSecret = newRandomRecipient();
558
+ return { signatorySecret, recipientSecret, publicNickname };
559
+ }
560
+
561
+ // type Role = "admin" | "writer" | "reader";
562
+
563
+ // type PermissionsDef = CJMap<AgentID, Role, {[agent: AgentID]: Role}>;