@enbox/api 0.3.1 → 0.4.0
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/README.md +63 -0
- package/dist/browser.mjs +11 -28
- package/dist/browser.mjs.map +4 -4
- package/dist/esm/advanced.js +1 -1
- package/dist/esm/define-protocol.js +3 -3
- package/dist/esm/did-api.js +1 -1
- package/dist/esm/did-api.js.map +1 -1
- package/dist/esm/dwn-api.js +6 -6
- package/dist/esm/dwn-api.js.map +1 -1
- package/dist/esm/dwn-reader-api.js +2 -2
- package/dist/esm/enbox.js +205 -0
- package/dist/esm/enbox.js.map +1 -0
- package/dist/esm/index.js +16 -15
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/protocol.js +2 -2
- package/dist/esm/protocol.js.map +1 -1
- package/dist/esm/record-data.js +79 -5
- package/dist/esm/record-data.js.map +1 -1
- package/dist/esm/record.js +49 -10
- package/dist/esm/record.js.map +1 -1
- package/dist/esm/repository.js +7 -7
- package/dist/esm/repository.js.map +1 -1
- package/dist/esm/typed-enbox.js +583 -0
- package/dist/esm/typed-enbox.js.map +1 -0
- package/dist/esm/typed-live-query.js +1 -1
- package/dist/esm/typed-record.js +370 -46
- package/dist/esm/typed-record.js.map +1 -1
- package/dist/esm/utils.js +25 -0
- package/dist/esm/utils.js.map +1 -1
- package/dist/esm/vc-api.js.map +1 -1
- package/dist/types/advanced.d.ts +1 -1
- package/dist/types/define-protocol.d.ts +3 -3
- package/dist/types/did-api.d.ts +4 -4
- package/dist/types/did-api.d.ts.map +1 -1
- package/dist/types/dwn-api.d.ts +12 -7
- package/dist/types/dwn-api.d.ts.map +1 -1
- package/dist/types/dwn-reader-api.d.ts +2 -2
- package/dist/types/enbox.d.ts +202 -0
- package/dist/types/enbox.d.ts.map +1 -0
- package/dist/types/grant-revocation.d.ts +2 -2
- package/dist/types/grant-revocation.d.ts.map +1 -1
- package/dist/types/index.d.ts +16 -15
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/live-query.d.ts +2 -2
- package/dist/types/live-query.d.ts.map +1 -1
- package/dist/types/permission-grant.d.ts +2 -2
- package/dist/types/permission-grant.d.ts.map +1 -1
- package/dist/types/permission-request.d.ts +2 -2
- package/dist/types/permission-request.d.ts.map +1 -1
- package/dist/types/protocol-types.d.ts +2 -2
- package/dist/types/protocol.d.ts +7 -7
- package/dist/types/protocol.d.ts.map +1 -1
- package/dist/types/record-data.d.ts +17 -0
- package/dist/types/record-data.d.ts.map +1 -1
- package/dist/types/record.d.ts +24 -10
- package/dist/types/record.d.ts.map +1 -1
- package/dist/types/repository-types.d.ts +19 -11
- package/dist/types/repository-types.d.ts.map +1 -1
- package/dist/types/repository.d.ts +7 -7
- package/dist/types/repository.d.ts.map +1 -1
- package/dist/types/typed-enbox.d.ts +613 -0
- package/dist/types/typed-enbox.d.ts.map +1 -0
- package/dist/types/typed-live-query.d.ts +1 -1
- package/dist/types/typed-record.d.ts +427 -53
- package/dist/types/typed-record.d.ts.map +1 -1
- package/dist/types/utils.d.ts +23 -0
- package/dist/types/utils.d.ts.map +1 -1
- package/dist/types/vc-api.d.ts +3 -3
- package/dist/types/vc-api.d.ts.map +1 -1
- package/package.json +12 -11
- package/src/advanced.ts +1 -1
- package/src/define-protocol.ts +3 -3
- package/src/did-api.ts +5 -5
- package/src/dwn-api.ts +22 -17
- package/src/dwn-reader-api.ts +2 -2
- package/src/enbox.ts +281 -0
- package/src/grant-revocation.ts +3 -3
- package/src/index.ts +17 -16
- package/src/live-query.ts +2 -2
- package/src/permission-grant.ts +4 -4
- package/src/permission-request.ts +3 -3
- package/src/protocol-types.ts +2 -2
- package/src/protocol.ts +8 -8
- package/src/record-data.ts +86 -5
- package/src/record.ts +54 -13
- package/src/repository-types.ts +19 -7
- package/src/repository.ts +15 -15
- package/src/typed-enbox.ts +1169 -0
- package/src/typed-live-query.ts +1 -1
- package/src/typed-record.ts +431 -53
- package/src/utils.ts +27 -0
- package/src/vc-api.ts +4 -4
- package/dist/esm/typed-web5.js +0 -339
- package/dist/esm/typed-web5.js.map +0 -1
- package/dist/esm/web5.js +0 -410
- package/dist/esm/web5.js.map +0 -1
- package/dist/types/typed-web5.d.ts +0 -221
- package/dist/types/typed-web5.d.ts.map +0 -1
- package/dist/types/web5.d.ts +0 -346
- package/dist/types/web5.d.ts.map +0 -1
- package/src/typed-web5.ts +0 -598
- package/src/web5.ts +0 -754
package/dist/esm/web5.js
DELETED
|
@@ -1,410 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NOTE: Added reference types here to avoid a `pnpm` bug during build.
|
|
3
|
-
* https://github.com/enboxorg/enbox/pull/507
|
|
4
|
-
*/
|
|
5
|
-
/// <reference types="@enbox/dwn-sdk-js" />
|
|
6
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
7
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
8
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
9
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
10
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
11
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
12
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
13
|
-
});
|
|
14
|
-
};
|
|
15
|
-
var __rest = (this && this.__rest) || function (s, e) {
|
|
16
|
-
var t = {};
|
|
17
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
18
|
-
t[p] = s[p];
|
|
19
|
-
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
20
|
-
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
21
|
-
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
22
|
-
t[p[i]] = s[p[i]];
|
|
23
|
-
}
|
|
24
|
-
return t;
|
|
25
|
-
};
|
|
26
|
-
import { AnonymousDwnApi, WalletConnect, Web5UserAgent } from '@enbox/agent';
|
|
27
|
-
import { DidDht, DidJwk, DidKey, DidResolverCacheMemory, DidWeb, UniversalResolver } from '@enbox/dids';
|
|
28
|
-
import { DwnRegistrar, Web5RpcClient } from '@enbox/dwn-clients';
|
|
29
|
-
import { DidApi } from './did-api.js';
|
|
30
|
-
import { DwnApi } from './dwn-api.js';
|
|
31
|
-
import { DwnReaderApi } from './dwn-reader-api.js';
|
|
32
|
-
import { PermissionGrant } from './permission-grant.js';
|
|
33
|
-
import { TypedWeb5 } from './typed-web5.js';
|
|
34
|
-
import { VcApi } from './vc-api.js';
|
|
35
|
-
/**
|
|
36
|
-
* The main Web5 API interface. It manages the creation of a DID if needed, the connection to the
|
|
37
|
-
* local DWN and all the web5 main foundational APIs such as VC, syncing, etc.
|
|
38
|
-
*/
|
|
39
|
-
export class Web5 {
|
|
40
|
-
constructor({ agent, connectedDid, delegateDid }) {
|
|
41
|
-
this.agent = agent;
|
|
42
|
-
this.did = new DidApi({ agent, connectedDid });
|
|
43
|
-
this._dwn = new DwnApi({ agent, connectedDid, delegateDid });
|
|
44
|
-
this.vc = new VcApi({ agent, connectedDid });
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Returns a {@link TypedWeb5} instance scoped to the given protocol.
|
|
48
|
-
*
|
|
49
|
-
* This is the **primary developer interface** for interacting with
|
|
50
|
-
* protocol-backed records. It auto-injects the protocol URI, protocolPath,
|
|
51
|
-
* and schema into every operation, and provides compile-time path
|
|
52
|
-
* autocompletion plus typed data payloads via the schema map.
|
|
53
|
-
*
|
|
54
|
-
* @param protocol - A typed protocol created via `defineProtocol()`.
|
|
55
|
-
* @returns A `TypedWeb5` instance bound to the given protocol.
|
|
56
|
-
*
|
|
57
|
-
* @example
|
|
58
|
-
* ```ts
|
|
59
|
-
* const social = web5.using(SocialProtocol);
|
|
60
|
-
*
|
|
61
|
-
* await social.configure();
|
|
62
|
-
*
|
|
63
|
-
* const { record } = await social.records.write('friend', {
|
|
64
|
-
* data: { did: 'did:example:alice', alias: 'Alice' },
|
|
65
|
-
* });
|
|
66
|
-
*
|
|
67
|
-
* const { records } = await social.records.query('friend');
|
|
68
|
-
* ```
|
|
69
|
-
*/
|
|
70
|
-
using(protocol) {
|
|
71
|
-
return new TypedWeb5(this._dwn, protocol);
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Creates a lightweight, read-only Web5 instance for querying public DWN data.
|
|
75
|
-
*
|
|
76
|
-
* No identity, vault, password, or signing keys are required. The returned
|
|
77
|
-
* API supports querying and reading published records and protocols from any
|
|
78
|
-
* remote DWN, using **unsigned** (anonymous) DWN messages.
|
|
79
|
-
*
|
|
80
|
-
* @param options - Optional configuration overrides.
|
|
81
|
-
* @returns A {@link Web5AnonymousApi} with a read-only `dwn` property.
|
|
82
|
-
*
|
|
83
|
-
* @example
|
|
84
|
-
* ```ts
|
|
85
|
-
* const { dwn } = Web5.anonymous();
|
|
86
|
-
*
|
|
87
|
-
* const { records } = await dwn.records.query({
|
|
88
|
-
* from: 'did:dht:alice...',
|
|
89
|
-
* filter: { protocol: 'https://social.example/posts', protocolPath: 'post' },
|
|
90
|
-
* });
|
|
91
|
-
*
|
|
92
|
-
* for (const record of records) {
|
|
93
|
-
* console.log(record.id, await record.data.text());
|
|
94
|
-
* }
|
|
95
|
-
* ```
|
|
96
|
-
*
|
|
97
|
-
* @beta
|
|
98
|
-
*/
|
|
99
|
-
static anonymous(options) {
|
|
100
|
-
var _a;
|
|
101
|
-
const didResolver = new UniversalResolver({
|
|
102
|
-
didResolvers: (_a = options === null || options === void 0 ? void 0 : options.didResolvers) !== null && _a !== void 0 ? _a : [DidDht, DidJwk, DidKey, DidWeb],
|
|
103
|
-
cache: new DidResolverCacheMemory(),
|
|
104
|
-
});
|
|
105
|
-
const rpcClient = new Web5RpcClient();
|
|
106
|
-
const anonymousDwn = new AnonymousDwnApi({ didResolver, rpcClient });
|
|
107
|
-
return {
|
|
108
|
-
dwn: new DwnReaderApi(anonymousDwn),
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Connects to a {@link Web5Agent}. Defaults to creating a local {@link Web5UserAgent} if one
|
|
113
|
-
* isn't provided.
|
|
114
|
-
*
|
|
115
|
-
* If `walletConnectOptions` are provided, a WalletConnect flow will be initiated to import a delegated DID from an external wallet.
|
|
116
|
-
* If there is a failure at any point during connecting and processing grants, all created DIDs and Identities as well as the provided grants
|
|
117
|
-
* will be cleaned up and an error thrown. This allows for subsequent Connect attempts to be made without any errors.
|
|
118
|
-
*
|
|
119
|
-
* @param options - Optional overrides that can be provided when calling {@link Web5.connect}.
|
|
120
|
-
* @returns A promise that resolves to a {@link Web5} instance and the connected DID.
|
|
121
|
-
*/
|
|
122
|
-
static connect() {
|
|
123
|
-
return __awaiter(this, arguments, void 0, function* ({ agent, agentVault, connectedDid, password, recoveryPhrase, sync, techPreview, didCreateOptions, registration, walletConnectOptions, } = {}) {
|
|
124
|
-
var _a, _b, _c, _d;
|
|
125
|
-
let delegateDid;
|
|
126
|
-
if (agent === undefined) {
|
|
127
|
-
let registerSync = false;
|
|
128
|
-
// A custom Web5Agent implementation was not specified, so use default managed user agent.
|
|
129
|
-
const userAgent = yield Web5UserAgent.create({ agentVault });
|
|
130
|
-
agent = userAgent;
|
|
131
|
-
// Warn the developer and application user of the security risks of using a static password.
|
|
132
|
-
if (password === undefined) {
|
|
133
|
-
password = 'insecure-static-phrase';
|
|
134
|
-
console.warn('%cSECURITY WARNING:%c ' +
|
|
135
|
-
'You have not set a password, which defaults to a static, guessable value. ' +
|
|
136
|
-
'This significantly compromises the security of your data. ' +
|
|
137
|
-
'Please configure a secure, unique password.', 'font-weight: bold; color: red;', 'font-weight: normal; color: inherit;');
|
|
138
|
-
}
|
|
139
|
-
// Use the specified DWN endpoints or the latest TBD hosted DWN
|
|
140
|
-
const serviceEndpointNodes = (_b = (_a = techPreview === null || techPreview === void 0 ? void 0 : techPreview.dwnEndpoints) !== null && _a !== void 0 ? _a : didCreateOptions === null || didCreateOptions === void 0 ? void 0 : didCreateOptions.dwnEndpoints) !== null && _b !== void 0 ? _b : ['https://enbox-dwn.fly.dev'];
|
|
141
|
-
// Initialize, if necessary, and start the agent.
|
|
142
|
-
if (yield userAgent.firstLaunch()) {
|
|
143
|
-
recoveryPhrase = yield userAgent.initialize({ password, recoveryPhrase, dwnEndpoints: serviceEndpointNodes });
|
|
144
|
-
}
|
|
145
|
-
yield userAgent.start({ password });
|
|
146
|
-
// Attempt to retrieve the connected Identity if it exists.
|
|
147
|
-
const connectedIdentity = yield userAgent.identity.connectedIdentity();
|
|
148
|
-
let identity;
|
|
149
|
-
let connectedProtocols = [];
|
|
150
|
-
if (connectedIdentity) {
|
|
151
|
-
// if a connected identity is found, use it
|
|
152
|
-
// TODO: In the future, implement a way to re-connect an already connected identity and apply additional grants/protocols
|
|
153
|
-
identity = connectedIdentity;
|
|
154
|
-
}
|
|
155
|
-
else if (walletConnectOptions) {
|
|
156
|
-
if (sync === 'off') {
|
|
157
|
-
// Currently we require sync to be enabled when using WalletConnect
|
|
158
|
-
// This is to ensure a connected app is not in a disjointed state from any other clients/app using the connectedDid
|
|
159
|
-
throw new Error('Sync must not be disabled when using WalletConnect');
|
|
160
|
-
}
|
|
161
|
-
// Since we are connecting a new identity, we will want to register sync for the connectedDid
|
|
162
|
-
registerSync = true;
|
|
163
|
-
// No connected identity found and connectOptions are provided, attempt to import a delegated DID from an external wallet
|
|
164
|
-
try {
|
|
165
|
-
const { permissionRequests } = walletConnectOptions, connectOptions = __rest(walletConnectOptions, ["permissionRequests"]);
|
|
166
|
-
const walletPermissionRequests = permissionRequests.map(({ protocolDefinition, permissions }) => WalletConnect.createPermissionRequestForProtocol({
|
|
167
|
-
definition: protocolDefinition,
|
|
168
|
-
permissions: permissions !== null && permissions !== void 0 ? permissions : [
|
|
169
|
-
'read', 'write', 'delete', 'query', 'subscribe',
|
|
170
|
-
],
|
|
171
|
-
}));
|
|
172
|
-
const { delegatePortableDid, connectedDid, delegateGrants } = yield WalletConnect.initClient(Object.assign(Object.assign({}, connectOptions), { permissionRequests: walletPermissionRequests }));
|
|
173
|
-
// Import the delegated DID as an Identity in the User Agent.
|
|
174
|
-
// Setting the connectedDID in the metadata applies a relationship between the signer identity and the one it is impersonating.
|
|
175
|
-
identity = yield userAgent.identity.import({ portableIdentity: {
|
|
176
|
-
portableDid: delegatePortableDid,
|
|
177
|
-
metadata: {
|
|
178
|
-
connectedDid,
|
|
179
|
-
name: 'Default',
|
|
180
|
-
uri: delegatePortableDid.uri,
|
|
181
|
-
tenant: agent.agentDid.uri,
|
|
182
|
-
}
|
|
183
|
-
} });
|
|
184
|
-
// Attempts to process the connected grants to be used by the delegateDID
|
|
185
|
-
// If the process fails, we want to clean up the identity
|
|
186
|
-
// the connected grants will return a de-duped array of protocol URIs that are used to register sync for those protocols
|
|
187
|
-
connectedProtocols = yield this.processConnectedGrants({ agent, delegateDid: delegatePortableDid.uri, grants: delegateGrants });
|
|
188
|
-
}
|
|
189
|
-
catch (error) {
|
|
190
|
-
// clean up the DID and Identity if import fails and throw
|
|
191
|
-
// TODO: Implement the ability to purge all of our messages as a tenant
|
|
192
|
-
yield this.cleanUpIdentity({ identity, userAgent });
|
|
193
|
-
throw new Error(`Failed to connect to wallet: ${error.message}`);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
else {
|
|
197
|
-
// No connected (WalletConnect) identity and no walletConnectOptions provided.
|
|
198
|
-
// Look for an existing local identity, or create one on first use.
|
|
199
|
-
const identities = yield userAgent.identity.list();
|
|
200
|
-
if (identities.length === 0) {
|
|
201
|
-
registerSync = true;
|
|
202
|
-
// First use — generate a new Identity for the end-user.
|
|
203
|
-
identity = yield userAgent.identity.create({
|
|
204
|
-
didMethod: 'dht',
|
|
205
|
-
metadata: { name: 'Default' },
|
|
206
|
-
didOptions: {
|
|
207
|
-
services: [
|
|
208
|
-
{
|
|
209
|
-
id: 'dwn',
|
|
210
|
-
type: 'DecentralizedWebNode',
|
|
211
|
-
serviceEndpoint: serviceEndpointNodes,
|
|
212
|
-
enc: '#enc',
|
|
213
|
-
sig: '#sig',
|
|
214
|
-
}
|
|
215
|
-
],
|
|
216
|
-
verificationMethods: [
|
|
217
|
-
{
|
|
218
|
-
algorithm: 'Ed25519',
|
|
219
|
-
id: 'sig',
|
|
220
|
-
purposes: ['assertionMethod', 'authentication']
|
|
221
|
-
},
|
|
222
|
-
{
|
|
223
|
-
algorithm: 'X25519',
|
|
224
|
-
id: 'enc',
|
|
225
|
-
purposes: ['keyAgreement']
|
|
226
|
-
}
|
|
227
|
-
]
|
|
228
|
-
}
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
else {
|
|
232
|
-
// Reconnecting — use the first local identity. When the agent manages
|
|
233
|
-
// multiple identities (e.g. created via agent.identity.create()), the
|
|
234
|
-
// first one returned by the store is used as the default for connect().
|
|
235
|
-
identity = identities[0];
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
// If the stored identity has a connected DID, use it as the connected DID, otherwise use the identity's DID.
|
|
239
|
-
connectedDid = (_c = identity.metadata.connectedDid) !== null && _c !== void 0 ? _c : identity.did.uri;
|
|
240
|
-
// If the stored identity has a connected DID, use the identity DID as the delegated DID, otherwise it is undefined.
|
|
241
|
-
delegateDid = identity.metadata.connectedDid ? identity.did.uri : undefined;
|
|
242
|
-
if (registration !== undefined) {
|
|
243
|
-
const updatedTokens = Object.assign({}, ((_d = registration.registrationTokens) !== null && _d !== void 0 ? _d : {}));
|
|
244
|
-
try {
|
|
245
|
-
for (const dwnEndpoint of serviceEndpointNodes) {
|
|
246
|
-
const serverInfo = yield userAgent.rpc.getServerInfo(dwnEndpoint);
|
|
247
|
-
if (serverInfo.registrationRequirements.length === 0) {
|
|
248
|
-
continue;
|
|
249
|
-
}
|
|
250
|
-
// Deduplicate DIDs to register.
|
|
251
|
-
const didsToRegister = [agent.agentDid.uri, connectedDid]
|
|
252
|
-
.filter((did, i, arr) => arr.indexOf(did) === i);
|
|
253
|
-
const hasProviderAuth = serverInfo.registrationRequirements.includes('provider-auth-v0')
|
|
254
|
-
&& serverInfo.providerAuth !== undefined;
|
|
255
|
-
if (hasProviderAuth && registration.onProviderAuthRequired) {
|
|
256
|
-
// --- Provider Auth Path ---
|
|
257
|
-
let tokenData = updatedTokens[dwnEndpoint];
|
|
258
|
-
// Refresh expired tokens.
|
|
259
|
-
if ((tokenData === null || tokenData === void 0 ? void 0 : tokenData.expiresAt) !== undefined && tokenData.expiresAt < Date.now()) {
|
|
260
|
-
if (tokenData.refreshUrl && tokenData.refreshToken) {
|
|
261
|
-
const refreshed = yield DwnRegistrar.refreshRegistrationToken(tokenData.refreshUrl, tokenData.refreshToken);
|
|
262
|
-
tokenData = {
|
|
263
|
-
registrationToken: refreshed.registrationToken,
|
|
264
|
-
refreshToken: refreshed.refreshToken,
|
|
265
|
-
expiresAt: refreshed.expiresIn !== undefined
|
|
266
|
-
? Date.now() + (refreshed.expiresIn * 1000) : undefined,
|
|
267
|
-
tokenUrl: tokenData.tokenUrl,
|
|
268
|
-
refreshUrl: tokenData.refreshUrl,
|
|
269
|
-
};
|
|
270
|
-
updatedTokens[dwnEndpoint] = tokenData;
|
|
271
|
-
}
|
|
272
|
-
else {
|
|
273
|
-
tokenData = undefined;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
// Run the auth flow if no valid token exists.
|
|
277
|
-
if (tokenData === undefined) {
|
|
278
|
-
const state = crypto.randomUUID();
|
|
279
|
-
const providerAuth = serverInfo.providerAuth;
|
|
280
|
-
const separator = providerAuth.authorizeUrl.includes('?') ? '&' : '?';
|
|
281
|
-
const authorizeUrl = `${providerAuth.authorizeUrl}${separator}`
|
|
282
|
-
+ `redirect_uri=${encodeURIComponent(dwnEndpoint)}`
|
|
283
|
-
+ `&state=${encodeURIComponent(state)}`;
|
|
284
|
-
const authResult = yield registration.onProviderAuthRequired({
|
|
285
|
-
authorizeUrl,
|
|
286
|
-
dwnEndpoint,
|
|
287
|
-
state,
|
|
288
|
-
});
|
|
289
|
-
if (authResult.state !== state) {
|
|
290
|
-
throw new Error('Provider auth state mismatch — possible CSRF attack.');
|
|
291
|
-
}
|
|
292
|
-
const tokenResponse = yield DwnRegistrar.exchangeAuthCode(providerAuth.tokenUrl, authResult.code, dwnEndpoint);
|
|
293
|
-
tokenData = {
|
|
294
|
-
registrationToken: tokenResponse.registrationToken,
|
|
295
|
-
refreshToken: tokenResponse.refreshToken,
|
|
296
|
-
expiresAt: tokenResponse.expiresIn !== undefined
|
|
297
|
-
? Date.now() + (tokenResponse.expiresIn * 1000) : undefined,
|
|
298
|
-
tokenUrl: providerAuth.tokenUrl,
|
|
299
|
-
refreshUrl: providerAuth.refreshUrl,
|
|
300
|
-
};
|
|
301
|
-
updatedTokens[dwnEndpoint] = tokenData;
|
|
302
|
-
}
|
|
303
|
-
// Register each DID using the provider auth token.
|
|
304
|
-
for (const did of didsToRegister) {
|
|
305
|
-
yield DwnRegistrar.registerTenantWithToken(dwnEndpoint, did, tokenData.registrationToken);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
else {
|
|
309
|
-
// --- Default Path (PoW / general registration) ---
|
|
310
|
-
for (const did of didsToRegister) {
|
|
311
|
-
yield DwnRegistrar.registerTenant(dwnEndpoint, did);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
// Notify app of updated tokens for persistence.
|
|
316
|
-
if (registration.onRegistrationTokens) {
|
|
317
|
-
registration.onRegistrationTokens(updatedTokens);
|
|
318
|
-
}
|
|
319
|
-
registration.onSuccess();
|
|
320
|
-
}
|
|
321
|
-
catch (error) {
|
|
322
|
-
registration.onFailure(error);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
// Enable sync, unless explicitly disabled.
|
|
326
|
-
if (sync !== 'off') {
|
|
327
|
-
// First, register the user identity for sync.
|
|
328
|
-
// The connected protocols are used to register sync for only a subset of protocols from the connectedDid's DWN
|
|
329
|
-
if (registerSync) {
|
|
330
|
-
yield userAgent.sync.registerIdentity({
|
|
331
|
-
did: connectedDid,
|
|
332
|
-
options: {
|
|
333
|
-
delegateDid,
|
|
334
|
-
protocols: connectedProtocols
|
|
335
|
-
}
|
|
336
|
-
});
|
|
337
|
-
if (walletConnectOptions !== undefined) {
|
|
338
|
-
// If we are using WalletConnect, we should do a one-shot sync to pull down any messages that are associated with the connectedDid
|
|
339
|
-
yield userAgent.sync.sync('pull');
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
// Enable sync using the specified interval or default.
|
|
343
|
-
// When sync is unset (undefined), default to live mode.
|
|
344
|
-
// When sync is an interval string (e.g. '2m', '30s'), use poll mode with that interval.
|
|
345
|
-
const syncMode = sync === undefined ? 'live' : 'poll';
|
|
346
|
-
const syncInterval = sync !== null && sync !== void 0 ? sync : (syncMode === 'live' ? '5m' : '2m');
|
|
347
|
-
userAgent.sync.startSync({ mode: syncMode, interval: syncInterval })
|
|
348
|
-
.catch((error) => {
|
|
349
|
-
console.error(`Sync failed: ${error}`);
|
|
350
|
-
});
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
const web5 = new Web5({ agent, connectedDid, delegateDid });
|
|
354
|
-
return { web5, did: connectedDid, delegateDid, recoveryPhrase };
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Cleans up the DID, Keys and Identity. Primarily used by a failed WalletConnect import.
|
|
359
|
-
* Does not throw on error, but logs to console.
|
|
360
|
-
*/
|
|
361
|
-
static cleanUpIdentity(_a) {
|
|
362
|
-
return __awaiter(this, arguments, void 0, function* ({ identity, userAgent }) {
|
|
363
|
-
try {
|
|
364
|
-
// Delete the DID and the Associated Keys
|
|
365
|
-
yield userAgent.did.delete({
|
|
366
|
-
didUri: identity.did.uri,
|
|
367
|
-
tenant: identity.metadata.tenant,
|
|
368
|
-
deleteKey: true,
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
catch (error) {
|
|
372
|
-
console.error(`Failed to delete DID ${identity.did.uri}: ${error.message}`);
|
|
373
|
-
}
|
|
374
|
-
try {
|
|
375
|
-
// Delete the Identity
|
|
376
|
-
yield userAgent.identity.delete({ didUri: identity.did.uri });
|
|
377
|
-
}
|
|
378
|
-
catch (error) {
|
|
379
|
-
console.error(`Failed to delete Identity ${identity.metadata.name}: ${error.message}`);
|
|
380
|
-
}
|
|
381
|
-
});
|
|
382
|
-
}
|
|
383
|
-
/**
|
|
384
|
-
* A static method to process connected grants for a delegate DID.
|
|
385
|
-
*
|
|
386
|
-
* This will store the grants as the DWN owner to be used later when impersonating the connected DID.
|
|
387
|
-
*/
|
|
388
|
-
static processConnectedGrants(_a) {
|
|
389
|
-
return __awaiter(this, arguments, void 0, function* ({ grants, agent, delegateDid }) {
|
|
390
|
-
const connectedProtocols = new Set();
|
|
391
|
-
for (const grantMessage of grants) {
|
|
392
|
-
// use the delegateDid as the connectedDid of the grant as they do not yet support impersonation/delegation
|
|
393
|
-
const grant = PermissionGrant.parse({ connectedDid: delegateDid, agent, message: grantMessage });
|
|
394
|
-
// store the grant as the owner of the DWN, this will allow the delegateDid to use the grant when impersonating the connectedDid
|
|
395
|
-
const { status } = yield grant.store(true);
|
|
396
|
-
if (status.code !== 202) {
|
|
397
|
-
throw new Error(`AgentDwnApi: Failed to process connected grant: ${status.detail}`);
|
|
398
|
-
}
|
|
399
|
-
const protocol = grant.scope.protocol;
|
|
400
|
-
if (protocol) {
|
|
401
|
-
connectedProtocols.add(protocol);
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
// currently we return a de-duped set of protocols represented by these grants, this is used to register protocols for sync
|
|
405
|
-
// we expect that any connected protocols will include MessagesSync and MessagesRead grants that will allow it to sync
|
|
406
|
-
return [...connectedProtocols];
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
//# sourceMappingURL=web5.js.map
|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AI,QAAQ,EAAE,CAAC;oBACb,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACnC,CAAC;YACH,CAAC;YAED,2HAA2H;YAC3H,sHAAsH;YACtH,OAAO,CAAC,GAAG,kBAAkB,CAAC,CAAC;QACjC,CAAC;KAAA;CACF"}
|
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A protocol-scoped API returned by {@link Web5.using}.
|
|
3
|
-
*
|
|
4
|
-
* `TypedWeb5` is the **primary developer interface** for interacting with
|
|
5
|
-
* protocol-backed records. It auto-injects the protocol URI, protocolPath,
|
|
6
|
-
* and schema into every operation, and provides compile-time path
|
|
7
|
-
* autocompletion plus typed data payloads via the schema map.
|
|
8
|
-
*
|
|
9
|
-
* All record-returning methods wrap the underlying `Record` instances in
|
|
10
|
-
* {@link TypedRecord} so that type information flows through reads, queries,
|
|
11
|
-
* updates, and subscriptions without manual casts.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```ts
|
|
15
|
-
* const social = web5.using(SocialProtocol);
|
|
16
|
-
*
|
|
17
|
-
* // Install the protocol
|
|
18
|
-
* await social.configure();
|
|
19
|
-
*
|
|
20
|
-
* // Create — path and data type are checked at compile time
|
|
21
|
-
* const { record } = await social.records.create('thread', {
|
|
22
|
-
* data: { title: 'Hello World', body: '...' },
|
|
23
|
-
* });
|
|
24
|
-
* // record is TypedRecord<ThreadData>
|
|
25
|
-
*
|
|
26
|
-
* const data = await record.data.json(); // ThreadData — no cast needed
|
|
27
|
-
*
|
|
28
|
-
* // Query — protocol and protocolPath are auto-injected
|
|
29
|
-
* const { records } = await social.records.query('thread');
|
|
30
|
-
* // records is TypedRecord<ThreadData>[]
|
|
31
|
-
*
|
|
32
|
-
* // Subscribe — real-time changes via TypedLiveQuery
|
|
33
|
-
* const { liveQuery } = await social.records.subscribe('thread/reply');
|
|
34
|
-
* liveQuery.on('create', (record) => {
|
|
35
|
-
* // record is TypedRecord<ReplyData>
|
|
36
|
-
* });
|
|
37
|
-
* ```
|
|
38
|
-
*/
|
|
39
|
-
import type { DwnApi } from './dwn-api.js';
|
|
40
|
-
import type { Protocol } from './protocol.js';
|
|
41
|
-
import type { DateSort, ProtocolDefinition, ProtocolType, RecordsFilter } from '@enbox/dwn-sdk-js';
|
|
42
|
-
import type { DwnPaginationCursor, DwnResponseStatus } from '@enbox/agent';
|
|
43
|
-
import type { ProtocolPaths, SchemaMap, TypedProtocol, TypeNameAtPath } from './protocol-types.js';
|
|
44
|
-
import { TypedLiveQuery } from './typed-live-query.js';
|
|
45
|
-
import { TypedRecord } from './typed-record.js';
|
|
46
|
-
/**
|
|
47
|
-
* Resolves the TypeScript data type for a given protocol path.
|
|
48
|
-
*
|
|
49
|
-
* If the schema map contains a mapping for the type name at the given path,
|
|
50
|
-
* that type is returned. Otherwise falls back to `unknown`.
|
|
51
|
-
*/
|
|
52
|
-
export type DataForPath<_D extends ProtocolDefinition, M extends SchemaMap, Path extends string> = TypeNameAtPath<Path> extends keyof M ? M[TypeNameAtPath<Path>] : unknown;
|
|
53
|
-
/**
|
|
54
|
-
* Resolves the `ProtocolType` entry for a given protocol path.
|
|
55
|
-
*/
|
|
56
|
-
type ProtocolTypeForPath<D extends ProtocolDefinition, Path extends string> = TypeNameAtPath<Path> extends keyof D['types'] ? D['types'][TypeNameAtPath<Path>] extends ProtocolType ? D['types'][TypeNameAtPath<Path>] : undefined : undefined;
|
|
57
|
-
/**
|
|
58
|
-
* Resolves a `dataFormat` string literal union for a path, or `string` if none.
|
|
59
|
-
*/
|
|
60
|
-
type DataFormatForPath<D extends ProtocolDefinition, Path extends string> = ProtocolTypeForPath<D, Path> extends {
|
|
61
|
-
dataFormats: infer F;
|
|
62
|
-
} ? F extends readonly string[] ? F[number] : string : string;
|
|
63
|
-
/** Options for {@link TypedWeb5} `records.create()`. */
|
|
64
|
-
export type TypedCreateRequest<D extends ProtocolDefinition, M extends SchemaMap, Path extends string> = {
|
|
65
|
-
/** The data payload. Type-checked against the schema map. */
|
|
66
|
-
data: DataForPath<D, M, Path>;
|
|
67
|
-
parentContextId?: string;
|
|
68
|
-
published?: boolean;
|
|
69
|
-
datePublished?: string;
|
|
70
|
-
recipient?: string;
|
|
71
|
-
protocolRole?: string;
|
|
72
|
-
dataFormat?: DataFormatForPath<D, Path>;
|
|
73
|
-
tags?: globalThis.Record<string, string | number | boolean | string[] | number[]>;
|
|
74
|
-
/** Whether to persist immediately (defaults to `true`). */
|
|
75
|
-
store?: boolean;
|
|
76
|
-
/** Whether to auto-encrypt (follows protocol definition if omitted). */
|
|
77
|
-
encryption?: boolean;
|
|
78
|
-
};
|
|
79
|
-
/** Response from {@link TypedWeb5} `records.create()`. */
|
|
80
|
-
export type TypedCreateResponse<T = unknown> = DwnResponseStatus & {
|
|
81
|
-
record: TypedRecord<T>;
|
|
82
|
-
};
|
|
83
|
-
/** Filter options for {@link TypedWeb5} `records.query()`. */
|
|
84
|
-
export type TypedQueryFilter = Omit<RecordsFilter, 'protocol' | 'protocolPath' | 'schema'> & {
|
|
85
|
-
tags?: globalThis.Record<string, string | number | boolean | (string | number)[]>;
|
|
86
|
-
};
|
|
87
|
-
/** Options for {@link TypedWeb5} `records.query()`. */
|
|
88
|
-
export type TypedQueryRequest = {
|
|
89
|
-
/** Optional remote DWN DID to query from. */
|
|
90
|
-
from?: string;
|
|
91
|
-
/** Query filter (protocol, protocolPath, schema are injected). */
|
|
92
|
-
filter?: TypedQueryFilter;
|
|
93
|
-
dateSort?: DateSort;
|
|
94
|
-
pagination?: {
|
|
95
|
-
limit?: number;
|
|
96
|
-
cursor?: DwnPaginationCursor;
|
|
97
|
-
};
|
|
98
|
-
protocolRole?: string;
|
|
99
|
-
/** When true, automatically decrypts encrypted records. */
|
|
100
|
-
encryption?: boolean;
|
|
101
|
-
};
|
|
102
|
-
/** Response from {@link TypedWeb5} `records.query()`. */
|
|
103
|
-
export type TypedQueryResponse<T = unknown> = DwnResponseStatus & {
|
|
104
|
-
records: TypedRecord<T>[];
|
|
105
|
-
cursor?: DwnPaginationCursor;
|
|
106
|
-
};
|
|
107
|
-
/** Options for {@link TypedWeb5} `records.read()`. */
|
|
108
|
-
export type TypedReadRequest = {
|
|
109
|
-
/** Optional remote DWN DID to read from. */
|
|
110
|
-
from?: string;
|
|
111
|
-
/** Filter to identify the record (protocol and protocolPath are injected). */
|
|
112
|
-
filter: Omit<RecordsFilter, 'protocol' | 'protocolPath' | 'schema'>;
|
|
113
|
-
/** When true, automatically decrypts the record. */
|
|
114
|
-
encryption?: boolean;
|
|
115
|
-
};
|
|
116
|
-
/** Response from {@link TypedWeb5} `records.read()`. */
|
|
117
|
-
export type TypedReadResponse<T = unknown> = DwnResponseStatus & {
|
|
118
|
-
record: TypedRecord<T>;
|
|
119
|
-
};
|
|
120
|
-
/** Options for {@link TypedWeb5} `records.delete()`. */
|
|
121
|
-
export type TypedDeleteRequest = {
|
|
122
|
-
/** Optional remote DWN DID to delete from. */
|
|
123
|
-
from?: string;
|
|
124
|
-
/** The `recordId` of the record to delete. */
|
|
125
|
-
recordId: string;
|
|
126
|
-
};
|
|
127
|
-
/** Options for {@link TypedWeb5} `records.subscribe()`. */
|
|
128
|
-
export type TypedSubscribeRequest = {
|
|
129
|
-
/** Optional remote DWN DID to subscribe to. */
|
|
130
|
-
from?: string;
|
|
131
|
-
/** Subscription filter (protocol, protocolPath, schema are injected). */
|
|
132
|
-
filter?: TypedQueryFilter;
|
|
133
|
-
protocolRole?: string;
|
|
134
|
-
};
|
|
135
|
-
/** Response from {@link TypedWeb5} `records.subscribe()`. */
|
|
136
|
-
export type TypedSubscribeResponse<T = unknown> = DwnResponseStatus & {
|
|
137
|
-
/** The typed live query instance, or `undefined` if the request failed. */
|
|
138
|
-
liveQuery?: TypedLiveQuery<T>;
|
|
139
|
-
};
|
|
140
|
-
/**
|
|
141
|
-
* A protocol-scoped API that auto-injects `protocol`, `protocolPath`, and
|
|
142
|
-
* `schema` into every DWN operation.
|
|
143
|
-
*
|
|
144
|
-
* All record-returning methods wrap results in {@link TypedRecord} so that
|
|
145
|
-
* the data type `T` (resolved from the schema map) flows end-to-end — from
|
|
146
|
-
* write through read, query, update, and subscribe — without manual casts.
|
|
147
|
-
*
|
|
148
|
-
* Obtain an instance via `web5.using(typedProtocol)`.
|
|
149
|
-
*
|
|
150
|
-
* @example
|
|
151
|
-
* ```ts
|
|
152
|
-
* const social = web5.using(SocialProtocol);
|
|
153
|
-
*
|
|
154
|
-
* await social.configure();
|
|
155
|
-
*
|
|
156
|
-
* const { record } = await social.records.create('friend', {
|
|
157
|
-
* data: { did: 'did:example:alice', alias: 'Alice' },
|
|
158
|
-
* });
|
|
159
|
-
* const data = await record.data.json(); // FriendData — no cast
|
|
160
|
-
*
|
|
161
|
-
* const { records } = await social.records.query('friend', {
|
|
162
|
-
* filter: { tags: { did: 'did:example:alice' } },
|
|
163
|
-
* });
|
|
164
|
-
* for (const r of records) {
|
|
165
|
-
* const d = await r.data.json(); // FriendData
|
|
166
|
-
* }
|
|
167
|
-
* ```
|
|
168
|
-
*/
|
|
169
|
-
export declare class TypedWeb5<D extends ProtocolDefinition = ProtocolDefinition, M extends SchemaMap = SchemaMap> {
|
|
170
|
-
private _dwn;
|
|
171
|
-
private _definition;
|
|
172
|
-
private _configured;
|
|
173
|
-
private _validPaths;
|
|
174
|
-
private _records?;
|
|
175
|
-
constructor(dwn: DwnApi, protocol: TypedProtocol<D, M>);
|
|
176
|
-
/** The protocol URI. */
|
|
177
|
-
get protocol(): string;
|
|
178
|
-
/** The raw protocol definition. */
|
|
179
|
-
get definition(): D;
|
|
180
|
-
/**
|
|
181
|
-
* Configures (installs) this protocol on the local DWN.
|
|
182
|
-
*
|
|
183
|
-
* If the protocol is already installed with an identical definition,
|
|
184
|
-
* this is a no-op and returns the existing protocol. If the definition
|
|
185
|
-
* has changed (e.g. new types, modified structure), the protocol is
|
|
186
|
-
* re-configured with the updated definition.
|
|
187
|
-
*
|
|
188
|
-
* @param options - Optional overrides like `encryption`.
|
|
189
|
-
*/
|
|
190
|
-
configure(options?: {
|
|
191
|
-
encryption?: boolean;
|
|
192
|
-
}): Promise<DwnResponseStatus & {
|
|
193
|
-
protocol?: Protocol;
|
|
194
|
-
}>;
|
|
195
|
-
/** Whether the protocol has been configured (installed) on the local DWN. */
|
|
196
|
-
get isConfigured(): boolean;
|
|
197
|
-
/**
|
|
198
|
-
* Validates that the protocol has been configured and that the path is
|
|
199
|
-
* recognized. Throws a descriptive error if either check fails.
|
|
200
|
-
*/
|
|
201
|
-
private _assertReady;
|
|
202
|
-
/**
|
|
203
|
-
* Protocol-scoped record operations.
|
|
204
|
-
*
|
|
205
|
-
* Every method auto-injects the protocol URI, protocolPath, and schema
|
|
206
|
-
* from the protocol definition. Path parameters provide compile-time
|
|
207
|
-
* autocompletion via `ProtocolPaths<D>`.
|
|
208
|
-
*
|
|
209
|
-
* All methods return {@link TypedRecord} or {@link TypedLiveQuery} instances
|
|
210
|
-
* that carry the resolved data type from the schema map.
|
|
211
|
-
*/
|
|
212
|
-
get records(): {
|
|
213
|
-
create: <Path extends ProtocolPaths<D> & string>(path: Path, request: TypedCreateRequest<D, M, Path>) => Promise<TypedCreateResponse<DataForPath<D, M, Path>>>;
|
|
214
|
-
query: <Path extends ProtocolPaths<D> & string>(path: Path, request?: TypedQueryRequest) => Promise<TypedQueryResponse<DataForPath<D, M, Path>>>;
|
|
215
|
-
read: <Path extends ProtocolPaths<D> & string>(path: Path, request: TypedReadRequest) => Promise<TypedReadResponse<DataForPath<D, M, Path>>>;
|
|
216
|
-
delete: <Path extends ProtocolPaths<D> & string>(path: Path, request: TypedDeleteRequest) => Promise<DwnResponseStatus>;
|
|
217
|
-
subscribe: <Path extends ProtocolPaths<D> & string>(path: Path, request?: TypedSubscribeRequest) => Promise<TypedSubscribeResponse<DataForPath<D, M, Path>>>;
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
export {};
|
|
221
|
-
//# sourceMappingURL=typed-web5.d.ts.map
|