@dwn-protocol/id-sdk 0.2.5 → 0.2.6

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 (99) hide show
  1. package/package.json +2 -3
  2. package/src/agent/app-data-store.ts +0 -365
  3. package/src/agent/did-manager.ts +0 -393
  4. package/src/agent/dwn-manager.ts +0 -548
  5. package/src/agent/identity-manager.ts +0 -165
  6. package/src/agent/index.ts +0 -19
  7. package/src/agent/json-rpc.ts +0 -107
  8. package/src/agent/key-manager.ts +0 -302
  9. package/src/agent/kms-local.ts +0 -412
  10. package/src/agent/outbox.ts +0 -128
  11. package/src/agent/rpc-client.ts +0 -223
  12. package/src/agent/store-managed-did.ts +0 -295
  13. package/src/agent/store-managed-identity.ts +0 -243
  14. package/src/agent/store-managed-key.ts +0 -754
  15. package/src/agent/sync-manager.ts +0 -631
  16. package/src/agent/test-managed-agent.ts +0 -299
  17. package/src/agent/types/agent.ts +0 -145
  18. package/src/agent/types/managed-key.ts +0 -442
  19. package/src/agent/utils.ts +0 -190
  20. package/src/common/convert.ts +0 -424
  21. package/src/common/index.ts +0 -9
  22. package/src/common/multicodec.ts +0 -176
  23. package/src/common/object.ts +0 -43
  24. package/src/common/stores.ts +0 -125
  25. package/src/common/stream-node.ts +0 -381
  26. package/src/common/stream.ts +0 -406
  27. package/src/common/type-utils.ts +0 -117
  28. package/src/common/types.ts +0 -48
  29. package/src/credentials/credential-bbs.ts +0 -419
  30. package/src/credentials/credential.ts +0 -324
  31. package/src/credentials/index.ts +0 -5
  32. package/src/credentials/presentation.ts +0 -182
  33. package/src/credentials/status-list.ts +0 -365
  34. package/src/credentials/utils.ts +0 -58
  35. package/src/credentials/validators.ts +0 -52
  36. package/src/crypto/algorithms-api/aes/base.ts +0 -49
  37. package/src/crypto/algorithms-api/aes/ctr.ts +0 -51
  38. package/src/crypto/algorithms-api/aes/index.ts +0 -2
  39. package/src/crypto/algorithms-api/crypto-algorithm.ts +0 -127
  40. package/src/crypto/algorithms-api/crypto-key.ts +0 -56
  41. package/src/crypto/algorithms-api/ec/base.ts +0 -39
  42. package/src/crypto/algorithms-api/ec/ecdh.ts +0 -53
  43. package/src/crypto/algorithms-api/ec/ecdsa.ts +0 -37
  44. package/src/crypto/algorithms-api/ec/eddsa.ts +0 -30
  45. package/src/crypto/algorithms-api/ec/index.ts +0 -4
  46. package/src/crypto/algorithms-api/errors.ts +0 -29
  47. package/src/crypto/algorithms-api/index.ts +0 -6
  48. package/src/crypto/algorithms-api/pbkdf/index.ts +0 -1
  49. package/src/crypto/algorithms-api/pbkdf/pbkdf2.ts +0 -91
  50. package/src/crypto/crypto-algorithms/aes-ctr.ts +0 -70
  51. package/src/crypto/crypto-algorithms/bbs.ts +0 -110
  52. package/src/crypto/crypto-algorithms/ecdh.ts +0 -115
  53. package/src/crypto/crypto-algorithms/ecdsa.ts +0 -111
  54. package/src/crypto/crypto-algorithms/eddsa.ts +0 -110
  55. package/src/crypto/crypto-algorithms/index.ts +0 -6
  56. package/src/crypto/crypto-algorithms/pbkdf2.ts +0 -54
  57. package/src/crypto/crypto-primitives/aes-ctr.ts +0 -131
  58. package/src/crypto/crypto-primitives/aes-gcm.ts +0 -138
  59. package/src/crypto/crypto-primitives/bbs.ts +0 -183
  60. package/src/crypto/crypto-primitives/concat-kdf.ts +0 -207
  61. package/src/crypto/crypto-primitives/ed25519.ts +0 -201
  62. package/src/crypto/crypto-primitives/index.ts +0 -10
  63. package/src/crypto/crypto-primitives/pbkdf2.ts +0 -78
  64. package/src/crypto/crypto-primitives/secp256k1.ts +0 -322
  65. package/src/crypto/crypto-primitives/x25519.ts +0 -101
  66. package/src/crypto/crypto-primitives/xchacha20-poly1305.ts +0 -46
  67. package/src/crypto/crypto-primitives/xchacha20.ts +0 -34
  68. package/src/crypto/index.ts +0 -8
  69. package/src/crypto/jose.ts +0 -948
  70. package/src/crypto/types/crypto-key.ts +0 -4
  71. package/src/crypto/types/iddwn-crypto.ts +0 -119
  72. package/src/crypto/utils.ts +0 -200
  73. package/src/did-api.ts +0 -72
  74. package/src/dids/dht.ts +0 -412
  75. package/src/dids/did-dht.ts +0 -436
  76. package/src/dids/did-ion.ts +0 -613
  77. package/src/dids/did-key.ts +0 -791
  78. package/src/dids/did-resolver.ts +0 -107
  79. package/src/dids/index.ts +0 -9
  80. package/src/dids/resolver-cache-level.ts +0 -82
  81. package/src/dids/resolver-cache-noop.ts +0 -25
  82. package/src/dids/types.ts +0 -278
  83. package/src/dids/utils.ts +0 -129
  84. package/src/dwn-api.ts +0 -584
  85. package/src/iddwn.ts +0 -241
  86. package/src/identity-agent/index.ts +0 -270
  87. package/src/index.ts +0 -26
  88. package/src/interfaces/metadata.ts +0 -163
  89. package/src/interfaces/queue.ts +0 -108
  90. package/src/interfaces/services.ts +0 -122
  91. package/src/interfaces/transactions.ts +0 -220
  92. package/src/protocol.ts +0 -68
  93. package/src/proxy-agent/index.ts +0 -255
  94. package/src/record.ts +0 -521
  95. package/src/service-options.ts +0 -62
  96. package/src/typings/decentralized-identity__ion-pow-sdk.d.ts +0 -7
  97. package/src/user-agent/index.ts +0 -295
  98. package/src/utils.ts +0 -29
  99. package/src/vc-api.ts +0 -505
package/src/record.ts DELETED
@@ -1,521 +0,0 @@
1
- import type { IDAgent } from './agent/index.js';
2
- import type { Readable } from 'readable-stream';
3
- import type {
4
- RecordsWriteMessage,
5
- RecordsWriteOptions,
6
- RecordsWriteDescriptor
7
- } from '@dwn-protocol/id';
8
- import type { BbsSignedCredentialBundle } from './credentials/credential-bbs.js';
9
-
10
- import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
11
- import { DataStream, DwnInterfaceName, DwnMethodName, Encoder } from '@dwn-protocol/id';
12
- import { BbsCredential, VC_DATA_FORMAT_LDP } from './credentials/credential-bbs.js';
13
-
14
- import type { ResponseStatus } from './dwn-api.js';
15
-
16
- import { dataToBlob } from './utils.js';
17
-
18
- /**
19
- * Options that are passed to Record constructor.
20
- *
21
- * @beta
22
- */
23
- export type RecordOptions = RecordsWriteMessage & {
24
- author: string;
25
- target: string;
26
- encodedData?: string | Blob;
27
- data?: Readable | ReadableStream;
28
- };
29
- /**
30
- * Represents the record data model, without the auxiliary properties such as
31
- * the `descriptor` and the `authorization`
32
- *
33
- * @beta
34
- */
35
- export type RecordModel = RecordsWriteDescriptor
36
- & Omit<RecordsWriteMessage, 'descriptor' | 'recordId' | 'authorization'>
37
- & {
38
- author: string;
39
- recordId?: string;
40
- target: string;
41
- }
42
-
43
- /**
44
- * Options that are passed to update the record on the DWN
45
- *
46
- * @beta
47
- */
48
- export type RecordUpdateOptions = {
49
- data?: unknown;
50
- dataCid?: RecordsWriteDescriptor['dataCid'];
51
- dataSize?: RecordsWriteDescriptor['dataSize'];
52
- dateModified?: RecordsWriteDescriptor['messageTimestamp'];
53
- datePublished?: RecordsWriteDescriptor['datePublished'];
54
- published?: RecordsWriteDescriptor['published'];
55
- }
56
-
57
- /**
58
- * Record wrapper class with convenience methods to send, update,
59
- * and delete itself, aside from manipulating and reading the record data.
60
- *
61
- * Note: The `messageTimestamp` of the most recent RecordsWrite message is
62
- * logically equivalent to the date/time at which a Record was most
63
- * recently modified. Since this Record class implementation is
64
- * intended to simplify the developer experience of working with
65
- * logical records (and not individual DWN messages) the
66
- * `messageTimestamp` is mapped to `dateModified`.
67
- *
68
- * @beta
69
- */
70
- export class Record implements RecordModel {
71
- // mutable properties
72
-
73
- /** Record's author */
74
- author: string;
75
-
76
- /** Record's target (for sent records) */
77
- target: string;
78
-
79
- /** Record deleted status */
80
- isDeleted = false;
81
-
82
- private _agent: IDAgent;
83
- private _attestation?: RecordsWriteMessage['attestation'];
84
- private _contextId?: string;
85
- private _descriptor: RecordsWriteDescriptor;
86
- private _encodedData?: string | Blob | null;
87
- private _encryption?: RecordsWriteMessage['encryption'];
88
- private _readableStream?: Readable | Promise<Readable>;
89
- private _recordId: string;
90
-
91
- // Immutable DWN Record properties.
92
- get attestation(): RecordsWriteMessage['attestation'] { return this._attestation; }
93
- get contextId() { return this._contextId; }
94
- get dataFormat() { return this._descriptor.dataFormat; }
95
- get dateCreated() { return this._descriptor.dateCreated; }
96
- get encryption(): RecordsWriteMessage['encryption'] { return this._encryption; }
97
- get id() { return this._recordId; }
98
- get interface() { return this._descriptor.interface; }
99
- get method() { return this._descriptor.method; }
100
- get parentId() { return this._descriptor.parentId; }
101
- get protocol() { return this._descriptor.protocol; }
102
- get protocolPath() { return this._descriptor.protocolPath; }
103
- get recipient() { return this._descriptor.recipient; }
104
- get schema() { return this._descriptor.schema; }
105
-
106
- // Mutable DWN Record properties.
107
- get dataCid() { return this._descriptor.dataCid; }
108
- get dataSize() { return this._descriptor.dataSize; }
109
- get dateModified() { return this._descriptor.messageTimestamp; }
110
- get datePublished() { return this._descriptor.datePublished; }
111
- get messageTimestamp() { return this._descriptor.messageTimestamp; }
112
- get published() { return this._descriptor.published; }
113
-
114
- constructor(agent: IDAgent, options: RecordOptions) {
115
- this._agent = agent;
116
-
117
- // Store the target and author DIDs that were used to create the message to use for subsequent reads, etc.
118
- this.author = options.author;
119
- this.target = options.target;
120
-
121
- // RecordsWriteMessage properties.
122
- this._attestation = options.attestation;
123
- this._contextId = options.contextId;
124
- this._descriptor = options.descriptor;
125
- this._encryption = options.encryption;
126
- this._recordId = options.recordId;
127
-
128
-
129
- // options.encodedData will either be a base64url encoded string (in the case of RecordsQuery)
130
- // OR a Blob in the case of a RecordsWrite.
131
- this._encodedData = options.encodedData ?? null;
132
-
133
- // If the record was created from a RecordsRead reply then it will have a `data` property.
134
- if (options.data) {
135
- this._readableStream = Record.isReadableWebStream(options.data) ?
136
- new ReadableWebToNodeStream(<ReadableStream>options.data) as Readable : options.data as Readable;
137
- }
138
- }
139
-
140
- /**
141
- * Returns the data of the current record.
142
- * If the record data is not available, it attempts to fetch the data from the DWN.
143
- * @returns a data stream with convenience methods such as `blob()`, `json()`, `text()`, and `stream()`, similar to the fetch API response
144
- * @throws `Error` if the record has already been deleted.
145
- *
146
- */
147
- get data() {
148
- if (this.isDeleted) throw new Error('Operation failed: Attempted to access `data` of a record that has already been deleted.');
149
-
150
- if (!this._encodedData && !this._readableStream) {
151
- // `encodedData` will be set if the Record was instantiated by dwn.records.create()/write().
152
- // `readableStream` will be set if Record was instantiated by dwn.records.read().
153
- // If neither of the above are true, then the record must be fetched from the DWN.
154
- this._readableStream = this._agent.processDwnRequest({
155
- author : this.target,
156
- messageOptions : { filter: { recordId: this.id } },
157
- messageType : DwnInterfaceName.Records + DwnMethodName.Read,
158
- target : this.target,
159
- })
160
- .then(response => response.reply)
161
- .then(reply => reply.record.data)
162
- .catch(error => { throw new Error(`Error encountered while attempting to read data: ${error.message}`); });
163
- }
164
-
165
- if (typeof this._encodedData === 'string') {
166
- // If `encodedData` is set, then it is expected that:
167
- // type is Blob if the Record object was instantiated by dwn.records.create()/write().
168
- // type is Base64 URL encoded string if the Record object was instantiated by dwn.records.query().
169
- // If it is a string, we need to Base64 URL decode to bytes and instantiate a Blob.
170
- const dataBytes: any = Encoder.base64UrlToBytes(this._encodedData);
171
- this._encodedData = new Blob([dataBytes], { type: this.dataFormat });
172
- }
173
-
174
- // Explicitly cast `encodedData` as a Blob since, if non-null, it has been converted from string to Blob.
175
- const dataBlob = this._encodedData as Blob;
176
-
177
- // eslint-disable-next-line @typescript-eslint/no-this-alias
178
- const self = this; // Capture the context of the `Record` instance.
179
- const dataObj = {
180
- async blob(): Promise<Blob> {
181
- if (dataBlob) return dataBlob;
182
- if (self._readableStream) return new Blob([await this.stream().then(DataStream.toBytes)], { type: self.dataFormat });
183
- },
184
- async json() {
185
- if (dataBlob) return this.text().then(JSON.parse);
186
- if (self._readableStream) return this.text().then(JSON.parse);
187
- return null;
188
- },
189
- async text() {
190
- if (dataBlob) return dataBlob.text();
191
- if (self._readableStream) return this.stream().then(DataStream.toBytes).then(Encoder.bytesToString);
192
- return null;
193
- },
194
- async stream() {
195
- if (dataBlob) return new ReadableWebToNodeStream(dataBlob.stream());
196
- if (self._readableStream) return self._readableStream;
197
- return null;
198
- },
199
- then(...callbacks) {
200
- return this.stream().then(...callbacks);
201
- },
202
- catch(callback) {
203
- return dataObj.then().catch(callback);
204
- },
205
- };
206
- return dataObj;
207
- }
208
-
209
- /**
210
- * Delete the current record from the DWN.
211
- * @returns the status of the delete request
212
- * @throws `Error` if the record has already been deleted.
213
- */
214
- async delete(): Promise<ResponseStatus> {
215
- if (this.isDeleted) throw new Error('Operation failed: Attempted to call `delete()` on a record that has already been deleted.');
216
-
217
- // Attempt to delete the record from the DWN.
218
- const agentResponse = await this._agent.processDwnRequest({
219
- author : this.target,
220
- messageOptions : { recordId: this._recordId },
221
- messageType : DwnInterfaceName.Records + DwnMethodName.Delete,
222
- target : this.target,
223
- });
224
-
225
- const { reply: { status } } = agentResponse;
226
-
227
- if (status.code === 202) {
228
- // If the record was successfully deleted, mark the instance as deleted to prevent further modifications.
229
- this.setDeletedStatus(true);
230
- }
231
-
232
- return { status };
233
- }
234
-
235
- /**
236
- * Send the current record to a remote DWN by specifying their DID
237
- * (vs waiting for the regular DWN sync)
238
- * @param target - the DID to send the record to
239
- * @returns the status of the send record request
240
- * @throws `Error` if the record has already been deleted.
241
- */
242
- async send(target: any): Promise<ResponseStatus> {
243
- if (this.isDeleted) throw new Error('Operation failed: Attempted to call `send()` on a record that has already been deleted.');
244
-
245
- let result: any;
246
- let status: any;
247
-
248
- if (typeof target === 'string') {
249
- result = await this._agent.sendDwnRequest({
250
- messageType : DwnInterfaceName.Records + DwnMethodName.Write,
251
- author : this.target,
252
- dataStream : await this.data.blob(),
253
- target : target,
254
- messageOptions : this.toJSON(),
255
- });
256
- status = result.reply.status;
257
- } else if (Array.isArray(target)) {
258
- for (let t of target) {
259
- result = await this._agent.sendDwnRequest({
260
- messageType : DwnInterfaceName.Records + DwnMethodName.Write,
261
- author : this.target,
262
- dataStream : await this.data.blob(),
263
- target : t,
264
- messageOptions : this.toJSON(),
265
- });
266
- }
267
- status = result.reply.status;
268
- } else {
269
- status = {
270
- code : 400,
271
- detail : 'Cannot send the did is invalid',
272
- };
273
- }
274
-
275
- return { status };
276
- }
277
-
278
- /**
279
- * Sends a BBS+ credential to a remote DWN with selective disclosure.
280
- * Instead of sending the full credential, this method derives a
281
- * zero-knowledge proof that reveals only the specified attributes,
282
- * then writes the derived credential to the target DWN.
283
- *
284
- * The record's data must be a BbsSignedCredentialBundle (JSON).
285
- *
286
- * @param target - The DID (or array of DIDs) to send the derived credential to.
287
- * @param options.bundle - The BBS+ signed credential bundle.
288
- * @param options.revealedAttributes - Attribute names to disclose (e.g. ['country', 'over21']).
289
- * @param options.issuerPublicKey - The issuer's 96-byte BLS12-381 G2 public key.
290
- * @param options.nonce - A unique nonce to bind the proof to this verification session.
291
- * @param options.schema - Optional schema URI for the DWN record.
292
- * @param options.protocol - Optional protocol URI.
293
- * @param options.protocolPath - Optional protocol path.
294
- * @returns The status of the send operation.
295
- */
296
- async sendWithSelectiveDisclosure(
297
- target: string | string[],
298
- options: {
299
- bundle: BbsSignedCredentialBundle;
300
- revealedAttributes: string[];
301
- issuerPublicKey: Uint8Array;
302
- nonce: string;
303
- schema?: string;
304
- protocol?: string;
305
- protocolPath?: string;
306
- }
307
- ): Promise<ResponseStatus> {
308
- if (this.isDeleted) {
309
- throw new Error('Operation failed: Attempted to call `sendWithSelectiveDisclosure()` on a record that has already been deleted.');
310
- }
311
-
312
- const { bundle, revealedAttributes, issuerPublicKey, nonce, schema, protocol, protocolPath } = options;
313
-
314
- const derived = await BbsCredential.deriveProof(bundle, {
315
- issuerPublicKey,
316
- revealedAttributes,
317
- nonce,
318
- });
319
-
320
- const derivedJson = JSON.stringify(derived.credential);
321
- const derivedBlob = new Blob([derivedJson], { type: VC_DATA_FORMAT_LDP });
322
-
323
- const messageOptions: any = {
324
- ...this.toJSON(),
325
- dataFormat: VC_DATA_FORMAT_LDP,
326
- };
327
-
328
- if (schema) messageOptions.schema = schema;
329
- if (protocol) messageOptions.protocol = protocol;
330
- if (protocolPath) messageOptions.protocolPath = protocolPath;
331
-
332
- let result: any;
333
- let status: any;
334
- const targets = Array.isArray(target) ? target : [target];
335
-
336
- for (const t of targets) {
337
- result = await this._agent.sendDwnRequest({
338
- messageType: DwnInterfaceName.Records + DwnMethodName.Write,
339
- author: this.target,
340
- dataStream: derivedBlob,
341
- target: t,
342
- messageOptions,
343
- });
344
- status = result.reply.status;
345
- }
346
-
347
- return { status };
348
- }
349
-
350
- /**
351
- * Returns a JSON representation of the Record instance.
352
- * It's called by `JSON.stringify(...)` automatically.
353
- */
354
- toJSON(): RecordModel {
355
- //@ts-ignore
356
- return {
357
- attestation : this.attestation,
358
- author : this.author,
359
- contextId : this.contextId,
360
- dataCid : this.dataCid,
361
- dataFormat : this.dataFormat,
362
- dataSize : this.dataSize,
363
- dateCreated : this.dateCreated,
364
- messageTimestamp : this.dateModified,
365
- datePublished : this.datePublished,
366
- encryption : this.encryption,
367
- interface : this.interface,
368
- method : this.method,
369
- parentId : this.parentId,
370
- protocol : this.protocol,
371
- protocolPath : this.protocolPath,
372
- published : this.published,
373
- recipient : this.recipient,
374
- recordId : this.id,
375
- schema : this.schema,
376
- target : this.target,
377
- };
378
- }
379
-
380
- /**
381
- * Convenience method to return the string representation of the Record instance.
382
- * Called automatically in string concatenation, String() type conversion, and template literals.
383
- */
384
- toString() {
385
- let str = `Record: {\n`;
386
- str += ` id: ${this.id}\n`;
387
- str += this.contextId ? ` contextId: ${this.contextId}\n` : '';
388
- str += this.protocol ? ` protocol: ${this.protocol}\n` : '';
389
- str += this.schema ? ` schema: ${this.schema}\n` : '';
390
- str += ` dataCid: ${this.dataCid}\n`;
391
- str += ` dataFormat: ${this.dataFormat}\n`;
392
- str += ` dataSize: ${this.dataSize}\n`;
393
- str += ` created: ${this.dateCreated}\n`;
394
- str += ` modified: ${this.dateModified}\n`;
395
- str += `}`;
396
- return str;
397
- }
398
-
399
- /**
400
- * Update the current record on the DWN.
401
- * @param options - options to update the record, including the new data
402
- * @returns the status of the update request
403
- * @throws `Error` if the record has already been deleted.
404
- */
405
- async update(options: RecordUpdateOptions = {}): Promise<ResponseStatus> {
406
- if (this.isDeleted) throw new Error('Operation failed: Attempted to call `update()` on a record that has already been deleted.');
407
- // console.log('this', this);
408
- const { dateModified, ...updateOptions } = options as Partial<RecordsWriteOptions> & RecordUpdateOptions;
409
- //@ts-ignore
410
- updateOptions.messageTimestamp = dateModified;
411
-
412
- // Begin assembling update message.
413
- let updateMessage = {...this._descriptor, ...updateOptions } as Partial<RecordsWriteOptions>;
414
-
415
- let dataBlob: Blob;
416
- if (options.data !== undefined) {
417
- // If `data` is being updated then `dataCid` and `dataSize` must be undefined and the `data` property is passed as
418
- // a top-level property to `agent.processDwnRequest()`.
419
- delete updateMessage.dataCid;
420
- delete updateMessage.dataSize;
421
- delete updateMessage.data;
422
-
423
- ({ dataBlob } = dataToBlob(options.data, updateMessage.dataFormat));
424
- }
425
-
426
- // Throw an error if an attempt is made to modify immutable properties. `data` has already been handled.
427
- const mutableDescriptorProperties = new Set(['data', 'dataCid', 'dataSize', 'messageTimestamp', 'datePublished', 'published']);
428
- Record.verifyPermittedMutation(Object.keys(options), mutableDescriptorProperties);
429
-
430
- // If a new `messageTimestamp` was not provided, remove the equivalent `messageTimestamp` property from from the
431
- // updateMessage to let the DWN SDK auto-fill. This is necessary because otherwise DWN SDK throws an
432
- // Error 409 Conflict due to attempting to overwrite a record when the `dateModified` values are identical.
433
- if (options.dateModified === undefined) {
434
- delete updateMessage.messageTimestamp;
435
- }
436
-
437
- // If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
438
- // will throw an error if `published` is false but `datePublished` is set.
439
- if (options.published === false && updateMessage.datePublished !== undefined) {
440
- delete updateMessage.datePublished;
441
- }
442
-
443
- // Set the record ID and context ID, if any.
444
- updateMessage.recordId = this._recordId;
445
- updateMessage.contextId = this._contextId;
446
-
447
- const messageOptions: Partial<RecordsWriteOptions> = {
448
- ...updateMessage
449
- };
450
-
451
- const agentResponse = await this._agent.processDwnRequest({
452
- author : this.target,
453
- dataStream : dataBlob,
454
- messageOptions,
455
- messageType : DwnInterfaceName.Records + DwnMethodName.Write,
456
- target : this.target,
457
- });
458
-
459
- const { message, reply: { status } } = agentResponse;
460
- const responseMessage = message as RecordsWriteMessage;
461
-
462
- if (200 <= status.code && status.code <= 299) {
463
- // Only update the local Record instance mutable properties if the record was successfully (over)written.
464
- mutableDescriptorProperties.forEach(property => {
465
- this._descriptor[property] = responseMessage.descriptor[property];
466
- });
467
- // Cache data.
468
- if (options.data !== undefined) {
469
- this._encodedData = dataBlob;
470
- }
471
- }
472
-
473
- return { status };
474
- }
475
-
476
- /**
477
- * Set the deleted status
478
- */
479
- private setDeletedStatus(status: boolean): void {
480
- this.isDeleted = status;
481
- }
482
-
483
- /**
484
- * Check is stream is readable.
485
- */
486
- private static isReadableWebStream(stream: any) {
487
- return typeof stream._read !== 'function';
488
- }
489
-
490
- /**
491
- * Verify if mutations are permitted.
492
- */
493
- private static verifyPermittedMutation(propertiesToMutate: Iterable<string>, mutableDescriptorProperties: Set<string>) {
494
- for (const property of propertiesToMutate) {
495
- if (!mutableDescriptorProperties.has(property)) {
496
- throw new Error(`${property} is an immutable property. Its value cannot be changed.`);
497
- }
498
- }
499
- }
500
- }
501
-
502
- /* snippet
503
- this simplistic approach would use the first verification method key from the `authentication` property of the DID Document:
504
-
505
- public static async getDefaultSigningKey(options: {
506
- didDocument: DidDocument
507
- }): Promise<string | undefined> {
508
- const { didDocument } = options;
509
-
510
- if (didDocument.authentication
511
- && Array.isArray(didDocument.authentication)
512
- && didDocument.authentication.length > 0
513
- && typeof didDocument.authentication[0] === 'string') {
514
-
515
- const [verificationMethodId] = didDocument.authentication;
516
- const signingKeyId = verificationMethodId;
517
-
518
- return signingKeyId;
519
- }
520
- }
521
- */
@@ -1,62 +0,0 @@
1
- import * as didUtils from './dids/utils.js';
2
-
3
- /**
4
- * Dynamically selects DWN endpoints
5
- */
6
- export async function getServiceDwnEndpoints(): Promise<string[]> {
7
- let response: Response;
8
- try {
9
- response = await fetch('https://s3.amazonaws.com/dwn.id/.well-known/dwn.json', {
10
- method : 'GET',
11
- mode : 'cors',
12
- cache : 'no-cache',
13
- headers : {
14
- 'Accept' : '*/*',
15
- 'Content-Type' : 'application/json',
16
- },
17
- });
18
- // console.log('response', response);
19
- if (!response.ok) {
20
- throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
21
- }
22
- } catch(error: any) {
23
- // console.warn('failed to get dwn endpoints:', error.message);
24
- return [];
25
- }
26
-
27
- const didDocument = await response.json();
28
- const [ dwnService ] = didUtils.getServices({ didDocument, id: '#dwn', type: 'DecentralizedWebNode' });
29
-
30
- // allocate nodes for a user.
31
- const dwnEndpoints = new Set<string>();
32
-
33
- if ('serviceEndpoint' in dwnService
34
- && !Array.isArray(dwnService.serviceEndpoint)
35
- && typeof dwnService.serviceEndpoint !== 'string'
36
- && Array.isArray(dwnService.serviceEndpoint.nodes)) {
37
- const dwnUrls = dwnService.serviceEndpoint.nodes;
38
-
39
- const numNodesToAllocate = Math.min(dwnUrls.length, 3);
40
- for (let attempts = 0; attempts < dwnUrls.length && dwnEndpoints.size <= numNodesToAllocate; attempts += 1) {
41
- // when we have more relayers we can dynamically choose up to 3
42
- // const nodeIdx = getRandomInt(0, dwnUrls.length);
43
- const dwnUrl = dwnUrls[attempts];
44
- try {
45
- const healthCheck = await fetch(`${dwnUrl}/health`);
46
- if (healthCheck.ok) {
47
- dwnEndpoints.add(dwnUrl);
48
- }
49
- } catch(error: unknown) {
50
- // Ignore healthcheck failure and try the next node.
51
- }
52
- }
53
- }
54
-
55
- return Array.from(dwnEndpoints);
56
- }
57
-
58
- // function getRandomInt(min, max) {
59
- // min = Math.ceil(min);
60
- // max = Math.floor(max);
61
- // return Math.floor(Math.random() * (max - min)) + min;
62
- // }
@@ -1,7 +0,0 @@
1
- declare module '@decentralized-identity/ion-pow-sdk' {
2
- export default class IonProofOfWork {
3
- static randomHexString(): string;
4
- static submitIonRequestUntilSuccess(getChallengeUri: string, solveChallengeUri: string, requestBody: string): Promise<void>;
5
- static submitIonRequest(getChallengeUri: string, solveChallengeUri: string, requestBody: string): Promise<string | undefined>;
6
- }
7
- }