generated from TBD54566975/tbd-project-template
/
message.ts
240 lines (204 loc) · 9.11 KB
/
message.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import type { GeneralJws } from '../types/jws-types.js';
import type { RecordsWriteMessage } from '../types/records-types.js';
import type { Signer } from '../types/signer.js';
import type { AuthorizationModel, Descriptor, GenericMessage, GenericSignaturePayload } from '../types/message-types.js';
import { Cid } from '../utils/cid.js';
import { Encoder } from '../utils/encoder.js';
import { GeneralJwsBuilder } from '../jose/jws/general/builder.js';
import { Jws } from '../utils/jws.js';
import { lexicographicalCompare } from '../utils/string.js';
import { removeUndefinedProperties } from '../utils/object.js';
import { validateJsonSchema } from '../schema-validator.js';
import { DwnError, DwnErrorCode } from './dwn-error.js';
/**
* A class containing utility methods for working with DWN messages.
*/
export class Message {
/**
* Validates the given message against the corresponding JSON schema.
* @throws {Error} if fails validation.
*/
public static validateJsonSchema(rawMessage: any): void {
const dwnInterface = rawMessage.descriptor.interface;
const dwnMethod = rawMessage.descriptor.method;
const schemaLookupKey = dwnInterface + dwnMethod;
// throws an error if message is invalid
validateJsonSchema(schemaLookupKey, rawMessage);
};
/**
* Gets the DID of the signer of the given message, returns `undefined` if message is not signed.
*/
public static getSigner(message: GenericMessage): string | undefined {
if (message.authorization === undefined) {
return undefined;
}
const signer = Jws.getSignerDid(message.authorization.signature.signatures[0]);
return signer;
}
/**
* Gets the CID of the given message.
*/
public static async getCid(message: GenericMessage): Promise<string> {
// NOTE: we wrap the `computeCid()` here in case that
// the message will contain properties that should not be part of the CID computation
// and we need to strip them out (like `encodedData` that we historically had for a long time),
// but we can remove this method entirely if the code becomes stable and it is apparent that the wrapper is not needed
// ^--- seems like we might need to keep this around for now.
const rawMessage = { ...message } as any;
if (rawMessage.encodedData) {
delete rawMessage.encodedData;
}
const cid = await Cid.computeCid(rawMessage as GenericMessage);
return cid;
}
/**
* Compares message CID in lexicographical order according to the spec.
* @returns 1 if `a` is larger than `b`; -1 if `a` is smaller/older than `b`; 0 otherwise (same message)
*/
public static async compareCid(a: GenericMessage, b: GenericMessage): Promise<number> {
// the < and > operators compare strings in lexicographical order
const cidA = await Message.getCid(a);
const cidB = await Message.getCid(b);
return lexicographicalCompare(cidA, cidB);
}
/**
* Creates the `authorization` property to be included in a DWN message.
* @param signer Message signer.
* @returns {AuthorizationModel} used as an `authorization` property.
*/
public static async createAuthorization(input: {
descriptor: Descriptor,
signer: Signer,
delegatedGrant?: RecordsWriteMessage,
permissionGrantId?: string,
protocolRole?: string
}): Promise<AuthorizationModel> {
const { descriptor, signer, delegatedGrant, permissionGrantId, protocolRole } = input;
let delegatedGrantId;
if (delegatedGrant !== undefined) {
delegatedGrantId = await Message.getCid(delegatedGrant);
}
const signature = await Message.createSignature(descriptor, signer, { delegatedGrantId, permissionGrantId, protocolRole });
const authorization: AuthorizationModel = {
signature
};
if (delegatedGrant !== undefined) {
authorization.authorDelegatedGrant = delegatedGrant;
}
return authorization;
}
/**
* Creates a generic signature from the given DWN message descriptor by including `descriptorCid` as the required property in the signature payload.
* NOTE: there is an opportunity to consolidate RecordsWrite.createSignerSignature() wth this method
*/
public static async createSignature(
descriptor: Descriptor,
signer: Signer,
additionalPayloadProperties?: { delegatedGrantId?: string, permissionGrantId?: string, protocolRole?: string }
): Promise<GeneralJws> {
const descriptorCid = await Cid.computeCid(descriptor);
const signaturePayload: GenericSignaturePayload = { descriptorCid, ...additionalPayloadProperties };
removeUndefinedProperties(signaturePayload);
const signaturePayloadBytes = Encoder.objectToBytes(signaturePayload);
const builder = await GeneralJwsBuilder.create(signaturePayloadBytes, [signer]);
const signature = builder.getJws();
return signature;
}
/**
* @returns newest message in the array. `undefined` if given array is empty.
*/
public static async getNewestMessage(messages: GenericMessage[]): Promise<GenericMessage | undefined> {
let currentNewestMessage: GenericMessage | undefined = undefined;
for (const message of messages) {
if (currentNewestMessage === undefined || await Message.isNewer(message, currentNewestMessage)) {
currentNewestMessage = message;
}
}
return currentNewestMessage;
}
/**
* @returns oldest message in the array. `undefined` if given array is empty.
*/
public static async getOldestMessage(messages: GenericMessage[]): Promise<GenericMessage | undefined> {
let currentOldestMessage: GenericMessage | undefined = undefined;
for (const message of messages) {
if (currentOldestMessage === undefined || await Message.isOlder(message, currentOldestMessage)) {
currentOldestMessage = message;
}
}
return currentOldestMessage;
}
/**
* Checks if first message is newer than second message.
* @returns `true` if `a` is newer than `b`; `false` otherwise
*/
public static async isNewer(a: GenericMessage, b: GenericMessage): Promise<boolean> {
const aIsNewer = (await Message.compareMessageTimestamp(a, b) > 0);
return aIsNewer;
}
/**
* Checks if first message is older than second message.
* @returns `true` if `a` is older than `b`; `false` otherwise
*/
public static async isOlder(a: GenericMessage, b: GenericMessage): Promise<boolean> {
const aIsOlder = (await Message.compareMessageTimestamp(a, b) < 0);
return aIsOlder;
}
/**
* See if the given message is signed by an author-delegate.
*/
public static isSignedByAuthorDelegate(message: GenericMessage): boolean {
return message.authorization?.authorDelegatedGrant !== undefined;
}
/**
* See if the given message is signed by an owner-delegate.
*/
public static isSignedByOwnerDelegate(message: GenericMessage): boolean {
return message.authorization?.ownerDelegatedGrant !== undefined;
}
/**
* Compares the `messageTimestamp` of the given messages with a fallback to message CID according to the spec.
* @returns 1 if `a` is larger/newer than `b`; -1 if `a` is smaller/older than `b`; 0 otherwise (same age)
*/
public static async compareMessageTimestamp(a: GenericMessage, b: GenericMessage): Promise<number> {
if (a.descriptor.messageTimestamp > b.descriptor.messageTimestamp) {
return 1;
} else if (a.descriptor.messageTimestamp < b.descriptor.messageTimestamp) {
return -1;
}
// else `messageTimestamp` is the same between a and b
// compare the `dataCid` instead, the < and > operators compare strings in lexicographical order
return Message.compareCid(a, b);
}
/**
* Validates the structural integrity of the message signature given:
* 1. The message signature must contain exactly 1 signature
* 2. Passes JSON schema validation
* 3. The `descriptorCid` property matches the CID of the message descriptor
* NOTE: signature is NOT verified.
* @param payloadJsonSchemaKey The key to look up the JSON schema referenced in `compile-validators.js` and perform payload schema validation on.
* @returns the parsed JSON payload object if validation succeeds.
*/
public static async validateSignatureStructure(
messageSignature: GeneralJws,
messageDescriptor: Descriptor,
payloadJsonSchemaKey: string = 'GenericSignaturePayload',
): Promise<GenericSignaturePayload> {
if (messageSignature.signatures.length !== 1) {
throw new DwnError(DwnErrorCode.AuthenticationMoreThanOneSignatureNotSupported, 'expected no more than 1 signature for authorization purpose');
}
// validate payload integrity
const payloadJson = Jws.decodePlainObjectPayload(messageSignature);
validateJsonSchema(payloadJsonSchemaKey, payloadJson);
// `descriptorCid` validation - ensure that the provided descriptorCid matches the CID of the actual message
const { descriptorCid } = payloadJson;
const expectedDescriptorCid = await Cid.computeCid(messageDescriptor);
if (descriptorCid !== expectedDescriptorCid) {
throw new DwnError(
DwnErrorCode.AuthenticateDescriptorCidMismatch,
`provided descriptorCid ${descriptorCid} does not match expected CID ${expectedDescriptorCid}`
);
}
return payloadJson;
}
}