@renown/sdk 6.2.3-dev.1 → 6.2.3-dev.100
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/dist/{browser-key-storage-e3RQsnLS.js → browser-key-storage-wjSwTnhs.js} +3 -2
- package/dist/browser-key-storage-wjSwTnhs.js.map +1 -0
- package/dist/{constants-BexAR53F.js → constants-DVOF17NB.js} +1 -1
- package/dist/{constants-BexAR53F.js.map → constants-DVOF17NB.js.map} +1 -1
- package/dist/crypto.d.ts +4 -3
- package/dist/crypto.js +3 -2
- package/dist/{index-BLIpkdF7.d.ts → index-Bf53Cq6x.d.ts} +11 -20
- package/dist/index-Bf53Cq6x.d.ts.map +1 -0
- package/dist/index.d.ts +12 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/memory-key-storage-CVVAWWS4.js +145 -0
- package/dist/memory-key-storage-CVVAWWS4.js.map +1 -0
- package/dist/{meta-D-5kvwx8.js → meta-4NmijIbE.js} +2 -2
- package/dist/{meta-D-5kvwx8.js.map → meta-4NmijIbE.js.map} +1 -1
- package/dist/{meta-CHgd9Qd0.js → meta-B2fHYlPD.js} +2 -2
- package/dist/{meta-CHgd9Qd0.js.map → meta-B2fHYlPD.js.map} +1 -1
- package/dist/{meta-BesJP74N.d.ts → meta-Co-vmMo-.d.ts} +3 -3
- package/dist/meta-Co-vmMo-.d.ts.map +1 -0
- package/dist/{meta-bV7L-1yb.d.ts → meta-ScD9zeLt.d.ts} +3 -3
- package/dist/meta-ScD9zeLt.d.ts.map +1 -0
- package/dist/node.d.ts +42 -25
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +32 -71
- package/dist/node.js.map +1 -1
- package/dist/signed-message-DuAelefH.js +556 -0
- package/dist/signed-message-DuAelefH.js.map +1 -0
- package/dist/{signer-DrjINLqt.js → signer-9gB5YUMp.js} +40 -177
- package/dist/signer-9gB5YUMp.js.map +1 -0
- package/dist/signer-trust-B4XTKeZ2.d.ts +170 -0
- package/dist/signer-trust-B4XTKeZ2.d.ts.map +1 -0
- package/dist/signer-trust-aVg9lYAn.js +992 -0
- package/dist/signer-trust-aVg9lYAn.js.map +1 -0
- package/dist/trust.d.ts +3 -0
- package/dist/trust.js +2 -0
- package/dist/{types-DInveFLz.d.ts → types-BmdG67IZ.d.ts} +3 -3
- package/dist/types-BmdG67IZ.d.ts.map +1 -0
- package/dist/{types-C-hJrsQg.d.ts → types-CfSRJMyb.d.ts} +3 -3
- package/dist/types-CfSRJMyb.d.ts.map +1 -0
- package/dist/{types-BGQKPoUr.d.ts → types-CplBDMtV.d.ts} +77 -12
- package/dist/types-CplBDMtV.d.ts.map +1 -0
- package/dist/{types-C_qc_62W.js → types-Dwy6khXb.js} +1 -1
- package/dist/{types-C_qc_62W.js.map → types-Dwy6khXb.js.map} +1 -1
- package/dist/{utils-DtWREYeO.d.ts → utils-K2mtcxhD.d.ts} +47 -9
- package/dist/utils-K2mtcxhD.d.ts.map +1 -0
- package/dist/wallet/index.d.ts +5 -5
- package/dist/wallet/index.d.ts.map +1 -1
- package/dist/wallet/index.js +1 -1
- package/dist/wallet/index.js.map +1 -1
- package/dist/wallet/mock/factory.d.ts +4 -5
- package/dist/wallet/mock/factory.d.ts.map +1 -1
- package/dist/wallet/mock/factory.js +1 -1
- package/dist/wallet/mock/factory.js.map +1 -1
- package/dist/wallet/mock/index.d.ts +5 -5
- package/dist/wallet/mock/index.d.ts.map +1 -1
- package/dist/wallet/mock/index.js +1 -1
- package/dist/wallet/mock/index.js.map +1 -1
- package/dist/wallet/privy/factory.d.ts +9 -11
- package/dist/wallet/privy/factory.d.ts.map +1 -1
- package/dist/wallet/privy/factory.js +2 -2
- package/dist/wallet/privy/factory.js.map +1 -1
- package/dist/wallet/privy/index.d.ts +5 -5
- package/dist/wallet/privy/index.d.ts.map +1 -1
- package/dist/wallet/privy/index.js +1 -1
- package/dist/wallet/privy/index.js.map +1 -1
- package/dist/wallet/rainbow/factory.d.ts +5 -4
- package/dist/wallet/rainbow/factory.d.ts.map +1 -1
- package/dist/wallet/rainbow/factory.js +2 -2
- package/dist/wallet/rainbow/factory.js.map +1 -1
- package/dist/wallet/rainbow/index.d.ts +5 -5
- package/dist/wallet/rainbow/index.d.ts.map +1 -1
- package/dist/wallet/rainbow/index.js +1 -1
- package/dist/wallet/rainbow/index.js.map +1 -1
- package/package.json +12 -5
- package/dist/browser-key-storage-e3RQsnLS.js.map +0 -1
- package/dist/index-BLIpkdF7.d.ts.map +0 -1
- package/dist/local-credential-verifier-CU8hmFlR.js +0 -907
- package/dist/local-credential-verifier-CU8hmFlR.js.map +0 -1
- package/dist/meta-BesJP74N.d.ts.map +0 -1
- package/dist/meta-bV7L-1yb.d.ts.map +0 -1
- package/dist/signer-DrjINLqt.js.map +0 -1
- package/dist/types-BGQKPoUr.d.ts.map +0 -1
- package/dist/types-C-hJrsQg.d.ts.map +0 -1
- package/dist/types-DInveFLz.d.ts.map +0 -1
- package/dist/utils-DtWREYeO.d.ts.map +0 -1
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
import { a as DEFAULT_RENOWN_NETWORK_ID, r as CREDENTIAL_TYPES } from "./constants-DVOF17NB.js";
|
|
2
|
+
import { d as verifyAuthBearerToken, i as importDidPublicKey, u as parsePkhDid } from "./signer-9gB5YUMp.js";
|
|
3
|
+
import { recoverTypedDataAddress } from "viem";
|
|
4
|
+
import { actionSignerIdentity, createAction, signActionV2 } from "@powerhousedao/shared/document-model";
|
|
5
|
+
import { fromString, toString } from "uint8arrays";
|
|
6
|
+
//#region src/discovery.ts
|
|
7
|
+
const DEFAULT_DISCOVERY_TIMEOUT_MS = 3e3;
|
|
8
|
+
async function resolveSwitchboardEndpoint(options) {
|
|
9
|
+
const { switchboardUrl, baseUrl, timeoutMs } = options;
|
|
10
|
+
if (switchboardUrl) return switchboardUrl;
|
|
11
|
+
if (!baseUrl) return;
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs ?? DEFAULT_DISCOVERY_TIMEOUT_MS);
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL("/api/switchboard", baseUrl);
|
|
16
|
+
const response = await fetch(url, {
|
|
17
|
+
method: "GET",
|
|
18
|
+
signal: controller.signal
|
|
19
|
+
});
|
|
20
|
+
if (!response.ok) return;
|
|
21
|
+
return (await response.json()).endpoint || void 0;
|
|
22
|
+
} catch {
|
|
23
|
+
return;
|
|
24
|
+
} finally {
|
|
25
|
+
clearTimeout(timeout);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/switchboard.ts
|
|
30
|
+
/** Thrown by `signIn` when the instance has no switchboard to write the
|
|
31
|
+
* credential to, so a host can fall back to the Renown redirect flow. */
|
|
32
|
+
var MissingSwitchboardError = class MissingSwitchboardError extends Error {
|
|
33
|
+
constructor() {
|
|
34
|
+
super("signIn requires a switchboard endpoint. Set switchboardUrl or a discoverable baseUrl.");
|
|
35
|
+
this.name = "MissingSwitchboardError";
|
|
36
|
+
}
|
|
37
|
+
/** `instanceof` fails across duplicate SDK copies, so match by name too. */
|
|
38
|
+
static is(error) {
|
|
39
|
+
return error instanceof MissingSwitchboardError || error instanceof Error && error.name === "MissingSwitchboardError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function userDriveId(address) {
|
|
43
|
+
return `renown-${address.toLowerCase()}`;
|
|
44
|
+
}
|
|
45
|
+
const CREDENTIALS_QUERY = `
|
|
46
|
+
query RenownCredentials($input: RenownCredentialsInput!) {
|
|
47
|
+
renownCredentials(input: $input) {
|
|
48
|
+
documentId
|
|
49
|
+
credentialId
|
|
50
|
+
context
|
|
51
|
+
type
|
|
52
|
+
issuerId
|
|
53
|
+
issuerEthereumAddress
|
|
54
|
+
issuanceDate
|
|
55
|
+
expirationDate
|
|
56
|
+
credentialSubjectId
|
|
57
|
+
credentialSubjectApp
|
|
58
|
+
credentialStatusId
|
|
59
|
+
credentialStatusType
|
|
60
|
+
credentialSchemaId
|
|
61
|
+
credentialSchemaType
|
|
62
|
+
proofVerificationMethod
|
|
63
|
+
proofEthereumAddress
|
|
64
|
+
proofCreated
|
|
65
|
+
proofPurpose
|
|
66
|
+
proofType
|
|
67
|
+
proofValue
|
|
68
|
+
proofEip712Domain
|
|
69
|
+
proofEip712PrimaryType
|
|
70
|
+
revoked
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
`;
|
|
74
|
+
const USERS_QUERY = `
|
|
75
|
+
query RenownUsers($input: RenownUsersInput!) {
|
|
76
|
+
renownUsers(input: $input) {
|
|
77
|
+
documentId
|
|
78
|
+
username
|
|
79
|
+
ethAddress
|
|
80
|
+
userImage
|
|
81
|
+
createdAt
|
|
82
|
+
updatedAt
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
`;
|
|
86
|
+
const CREATE_EMPTY_DOCUMENT_MUTATION = `
|
|
87
|
+
mutation CreateEmptyDocument(
|
|
88
|
+
$documentType: String!
|
|
89
|
+
$parentIdentifier: String
|
|
90
|
+
) {
|
|
91
|
+
createEmptyDocument(
|
|
92
|
+
documentType: $documentType
|
|
93
|
+
parentIdentifier: $parentIdentifier
|
|
94
|
+
) {
|
|
95
|
+
id
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
`;
|
|
99
|
+
const MUTATE_DOCUMENT_MUTATION = `
|
|
100
|
+
mutation MutateDocument(
|
|
101
|
+
$documentIdentifier: String!
|
|
102
|
+
$actions: [ActionInput!]!
|
|
103
|
+
) {
|
|
104
|
+
mutateDocument: execute(
|
|
105
|
+
documentIdentifier: $documentIdentifier
|
|
106
|
+
actions: $actions
|
|
107
|
+
) {
|
|
108
|
+
id
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
`;
|
|
112
|
+
const LEGACY_MUTATE_DOCUMENT_MUTATION = `
|
|
113
|
+
mutation MutateDocument(
|
|
114
|
+
$documentIdentifier: String!
|
|
115
|
+
$actions: [JSONObject!]!
|
|
116
|
+
) {
|
|
117
|
+
mutateDocument(documentIdentifier: $documentIdentifier, actions: $actions) {
|
|
118
|
+
id
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
`;
|
|
122
|
+
function isUnknownExecuteField(error) {
|
|
123
|
+
return error instanceof Error && /Cannot query field "execute" on type "Mutation"/.test(error.message);
|
|
124
|
+
}
|
|
125
|
+
const ISSUE_CREDENTIAL_MUTATION = `
|
|
126
|
+
mutation RenownIssueCredential(
|
|
127
|
+
$input: RenownCredential_InitInput!
|
|
128
|
+
$username: String
|
|
129
|
+
$userImage: String
|
|
130
|
+
$userDocId: PHID
|
|
131
|
+
) {
|
|
132
|
+
renown_issueCredential(
|
|
133
|
+
input: $input
|
|
134
|
+
username: $username
|
|
135
|
+
userImage: $userImage
|
|
136
|
+
userDocId: $userDocId
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
`;
|
|
140
|
+
const UPSERT_PROFILE_MUTATION = `
|
|
141
|
+
mutation RenownUpsertProfile(
|
|
142
|
+
$address: String!
|
|
143
|
+
$username: String
|
|
144
|
+
$userImage: String
|
|
145
|
+
$signature: String
|
|
146
|
+
$timestamp: String
|
|
147
|
+
) {
|
|
148
|
+
renown_upsertProfile(
|
|
149
|
+
address: $address
|
|
150
|
+
username: $username
|
|
151
|
+
userImage: $userImage
|
|
152
|
+
signature: $signature
|
|
153
|
+
timestamp: $timestamp
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
`;
|
|
157
|
+
const REVOKE_CREDENTIAL_MUTATION = `
|
|
158
|
+
mutation RenownRevokeCredential(
|
|
159
|
+
$credentialId: String!
|
|
160
|
+
$signature: String
|
|
161
|
+
$timestamp: String
|
|
162
|
+
) {
|
|
163
|
+
renown_revokeCredential(
|
|
164
|
+
credentialId: $credentialId
|
|
165
|
+
signature: $signature
|
|
166
|
+
timestamp: $timestamp
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
`;
|
|
170
|
+
function authParts(auth) {
|
|
171
|
+
return "token" in auth ? {
|
|
172
|
+
token: auth.token,
|
|
173
|
+
signed: {}
|
|
174
|
+
} : { signed: {
|
|
175
|
+
signature: auth.signature,
|
|
176
|
+
timestamp: auth.timestamp
|
|
177
|
+
} };
|
|
178
|
+
}
|
|
179
|
+
const RENOWN_CREDENTIAL_DOC_TYPE = "powerhouse/renown-credential";
|
|
180
|
+
const RENOWN_USER_DOC_TYPE = "powerhouse/renown-user";
|
|
181
|
+
function quoted(name) {
|
|
182
|
+
return `\\\\?"${name}\\\\?"`;
|
|
183
|
+
}
|
|
184
|
+
function isUnknownSchemaError(error, field, ...types) {
|
|
185
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
186
|
+
if (new RegExp(`Cannot query field ${quoted(field)}`).test(message)) return true;
|
|
187
|
+
return !message.includes("got invalid value") && types.some((type) => new RegExp(`Unknown type ${quoted(type)}`).test(message));
|
|
188
|
+
}
|
|
189
|
+
function reshapeCredential(row) {
|
|
190
|
+
const domain = JSON.parse(row.proofEip712Domain);
|
|
191
|
+
return {
|
|
192
|
+
"@context": row.context,
|
|
193
|
+
type: row.type,
|
|
194
|
+
id: row.credentialId,
|
|
195
|
+
issuer: {
|
|
196
|
+
id: row.issuerId,
|
|
197
|
+
ethereumAddress: row.issuerEthereumAddress
|
|
198
|
+
},
|
|
199
|
+
credentialSubject: {
|
|
200
|
+
id: row.credentialSubjectId ?? "",
|
|
201
|
+
app: row.credentialSubjectApp
|
|
202
|
+
},
|
|
203
|
+
credentialSchema: {
|
|
204
|
+
id: row.credentialSchemaId,
|
|
205
|
+
type: row.credentialSchemaType
|
|
206
|
+
},
|
|
207
|
+
...row.credentialStatusId ? { credentialStatus: {
|
|
208
|
+
id: row.credentialStatusId,
|
|
209
|
+
type: row.credentialStatusType ?? ""
|
|
210
|
+
} } : {},
|
|
211
|
+
issuanceDate: row.issuanceDate,
|
|
212
|
+
expirationDate: row.expirationDate ?? "",
|
|
213
|
+
proof: {
|
|
214
|
+
type: row.proofType,
|
|
215
|
+
created: row.proofCreated,
|
|
216
|
+
verificationMethod: row.proofVerificationMethod,
|
|
217
|
+
proofPurpose: row.proofPurpose,
|
|
218
|
+
proofValue: row.proofValue,
|
|
219
|
+
ethereumAddress: row.proofEthereumAddress,
|
|
220
|
+
eip712: {
|
|
221
|
+
domain,
|
|
222
|
+
types: CREDENTIAL_TYPES,
|
|
223
|
+
primaryType: "VerifiableCredential"
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function issuerChainId(issuerId) {
|
|
229
|
+
return issuerId.split(":")[3];
|
|
230
|
+
}
|
|
231
|
+
function issuerDidAddress(issuerId) {
|
|
232
|
+
return issuerId.split(":")[4];
|
|
233
|
+
}
|
|
234
|
+
function bindsTo$1(row, address, chainId, appDid) {
|
|
235
|
+
return !row.revoked && issuedTo(row, address, chainId, appDid);
|
|
236
|
+
}
|
|
237
|
+
function issuedTo(row, address, chainId, appDid) {
|
|
238
|
+
const expected = address.toLowerCase();
|
|
239
|
+
return row.credentialSubjectId === appDid && issuerChainId(row.issuerId) === String(chainId) && issuerDidAddress(row.issuerId)?.toLowerCase() === expected && row.issuerEthereumAddress.toLowerCase() === expected;
|
|
240
|
+
}
|
|
241
|
+
var SwitchboardClient = class {
|
|
242
|
+
#endpoint;
|
|
243
|
+
#transport;
|
|
244
|
+
#legacyMutate = false;
|
|
245
|
+
constructor(source) {
|
|
246
|
+
if (typeof source === "string") {
|
|
247
|
+
this.#endpoint = source;
|
|
248
|
+
this.#transport = (query, variables, options) => this.#post(source, query, variables, options?.token);
|
|
249
|
+
} else this.#transport = source;
|
|
250
|
+
}
|
|
251
|
+
/** The HTTP endpoint, or undefined when reading through a local executor. */
|
|
252
|
+
get endpoint() {
|
|
253
|
+
return this.#endpoint;
|
|
254
|
+
}
|
|
255
|
+
async #post(endpoint, query, variables, token) {
|
|
256
|
+
const response = await fetch(endpoint, {
|
|
257
|
+
method: "POST",
|
|
258
|
+
headers: {
|
|
259
|
+
"Content-Type": "application/json",
|
|
260
|
+
...token ? { Authorization: `Bearer ${token}` } : {}
|
|
261
|
+
},
|
|
262
|
+
body: JSON.stringify({
|
|
263
|
+
query,
|
|
264
|
+
variables
|
|
265
|
+
})
|
|
266
|
+
});
|
|
267
|
+
const body = await response.json().catch(() => void 0);
|
|
268
|
+
if (body?.errors?.length) throw new Error(body.errors.map((e) => e.message).join("; "));
|
|
269
|
+
if (!response.ok || !body) throw new Error(`Switchboard request failed: ${response.status}`);
|
|
270
|
+
return body.data;
|
|
271
|
+
}
|
|
272
|
+
async #request(query, variables, token) {
|
|
273
|
+
const data = await (token ? this.#transport(query, variables, { token }) : this.#transport(query, variables));
|
|
274
|
+
if (!data) throw new Error("Switchboard returned no data");
|
|
275
|
+
return data;
|
|
276
|
+
}
|
|
277
|
+
async getCredential(params) {
|
|
278
|
+
const { address, chainId, appDid } = params;
|
|
279
|
+
const { renownCredentials } = await this.#request(CREDENTIALS_QUERY, { input: {
|
|
280
|
+
driveId: userDriveId(address),
|
|
281
|
+
ethAddress: address.toLowerCase(),
|
|
282
|
+
did: appDid,
|
|
283
|
+
includeRevoked: false
|
|
284
|
+
} });
|
|
285
|
+
const now = Date.now();
|
|
286
|
+
const mostRecent = renownCredentials.filter((row) => bindsTo$1(row, address, chainId, appDid)).filter((row) => {
|
|
287
|
+
if (!row.expirationDate) return true;
|
|
288
|
+
const expiresAt = Date.parse(row.expirationDate);
|
|
289
|
+
return !Number.isNaN(expiresAt) && expiresAt > now;
|
|
290
|
+
}).sort((a, b) => Date.parse(b.issuanceDate) - Date.parse(a.issuanceDate)).at(0);
|
|
291
|
+
return mostRecent ? reshapeCredential(mostRecent) : void 0;
|
|
292
|
+
}
|
|
293
|
+
async getIssuedCredentials(params) {
|
|
294
|
+
const { address, chainId, appDid } = params;
|
|
295
|
+
const { renownCredentials } = await this.#request(CREDENTIALS_QUERY, { input: {
|
|
296
|
+
driveId: userDriveId(address),
|
|
297
|
+
ethAddress: address.toLowerCase(),
|
|
298
|
+
did: appDid,
|
|
299
|
+
includeRevoked: true
|
|
300
|
+
} });
|
|
301
|
+
const credentials = [];
|
|
302
|
+
for (const row of renownCredentials) {
|
|
303
|
+
if (!issuedTo(row, address, chainId, appDid)) continue;
|
|
304
|
+
try {
|
|
305
|
+
credentials.push(reshapeCredential(row));
|
|
306
|
+
} catch {}
|
|
307
|
+
}
|
|
308
|
+
return credentials;
|
|
309
|
+
}
|
|
310
|
+
async getProfileByAddress(address) {
|
|
311
|
+
const { renownUsers } = await this.#request(USERS_QUERY, { input: {
|
|
312
|
+
driveId: userDriveId(address),
|
|
313
|
+
ethAddresses: [address.toLowerCase()]
|
|
314
|
+
} });
|
|
315
|
+
const user = renownUsers.at(0);
|
|
316
|
+
if (!user) return void 0;
|
|
317
|
+
return {
|
|
318
|
+
documentId: user.documentId,
|
|
319
|
+
username: user.username,
|
|
320
|
+
ethAddress: user.ethAddress,
|
|
321
|
+
userImage: user.userImage,
|
|
322
|
+
createdAt: user.createdAt,
|
|
323
|
+
updatedAt: user.updatedAt
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
async createEmptyDocument(documentType, parentIdentifier, token) {
|
|
327
|
+
const { createEmptyDocument } = await this.#request(CREATE_EMPTY_DOCUMENT_MUTATION, {
|
|
328
|
+
documentType,
|
|
329
|
+
parentIdentifier
|
|
330
|
+
}, token);
|
|
331
|
+
return createEmptyDocument.id;
|
|
332
|
+
}
|
|
333
|
+
async mutateDocument(documentIdentifier, actions, token) {
|
|
334
|
+
const variables = {
|
|
335
|
+
documentIdentifier,
|
|
336
|
+
actions
|
|
337
|
+
};
|
|
338
|
+
if (!this.#legacyMutate) try {
|
|
339
|
+
const { mutateDocument } = await this.#request(MUTATE_DOCUMENT_MUTATION, variables, token);
|
|
340
|
+
return mutateDocument.id;
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (!isUnknownExecuteField(error)) throw error;
|
|
343
|
+
this.#legacyMutate = true;
|
|
344
|
+
}
|
|
345
|
+
const { mutateDocument } = await this.#request(LEGACY_MUTATE_DOCUMENT_MUTATION, variables, token);
|
|
346
|
+
return mutateDocument.id;
|
|
347
|
+
}
|
|
348
|
+
async issueCredential(credential, parentIdentifier) {
|
|
349
|
+
const input = {
|
|
350
|
+
id: credential.id,
|
|
351
|
+
context: credential["@context"],
|
|
352
|
+
type: credential.type,
|
|
353
|
+
issuer: {
|
|
354
|
+
id: credential.issuer.id,
|
|
355
|
+
ethereumAddress: credential.issuer.ethereumAddress
|
|
356
|
+
},
|
|
357
|
+
credentialSubject: {
|
|
358
|
+
id: credential.credentialSubject.id,
|
|
359
|
+
app: credential.credentialSubject.app
|
|
360
|
+
},
|
|
361
|
+
credentialSchema: {
|
|
362
|
+
id: credential.credentialSchema.id,
|
|
363
|
+
type: credential.credentialSchema.type
|
|
364
|
+
},
|
|
365
|
+
issuanceDate: credential.issuanceDate,
|
|
366
|
+
expirationDate: credential.expirationDate || void 0,
|
|
367
|
+
proof: {
|
|
368
|
+
type: credential.proof.type,
|
|
369
|
+
created: credential.proof.created,
|
|
370
|
+
verificationMethod: credential.proof.verificationMethod,
|
|
371
|
+
proofPurpose: credential.proof.proofPurpose,
|
|
372
|
+
proofValue: credential.proof.proofValue,
|
|
373
|
+
ethereumAddress: credential.proof.ethereumAddress,
|
|
374
|
+
eip712: {
|
|
375
|
+
domain: {
|
|
376
|
+
version: credential.proof.eip712.domain.version,
|
|
377
|
+
chainId: credential.proof.eip712.domain.chainId
|
|
378
|
+
},
|
|
379
|
+
primaryType: credential.proof.eip712.primaryType
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
try {
|
|
384
|
+
const { renown_issueCredential } = await this.#request(ISSUE_CREDENTIAL_MUTATION, { input });
|
|
385
|
+
return renown_issueCredential;
|
|
386
|
+
} catch (error) {
|
|
387
|
+
if (!isUnknownSchemaError(error, "renown_issueCredential", "RenownCredential_InitInput")) throw error;
|
|
388
|
+
const documentId = await this.createEmptyDocument(RENOWN_CREDENTIAL_DOC_TYPE, parentIdentifier);
|
|
389
|
+
await this.mutateDocument(documentId, [createAction("INIT", input)]);
|
|
390
|
+
return documentId;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
async upsertUserProfile(address, profile, auth) {
|
|
394
|
+
const { token, signed } = authParts(auth);
|
|
395
|
+
try {
|
|
396
|
+
const { renown_upsertProfile } = await this.#request(UPSERT_PROFILE_MUTATION, {
|
|
397
|
+
address,
|
|
398
|
+
username: profile.username,
|
|
399
|
+
userImage: profile.userImage,
|
|
400
|
+
...signed
|
|
401
|
+
}, token);
|
|
402
|
+
return renown_upsertProfile;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (!isUnknownSchemaError(error, "renown_upsertProfile")) throw error;
|
|
405
|
+
return this.#legacyUpsertUserProfile(address, profile, token);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
async #legacyUpsertUserProfile(address, profile, token) {
|
|
409
|
+
const updates = [];
|
|
410
|
+
if (profile.username != null) updates.push(createAction("SET_USERNAME", { username: profile.username }));
|
|
411
|
+
if (profile.userImage != null) updates.push(createAction("SET_USER_IMAGE", { userImage: profile.userImage }));
|
|
412
|
+
const existing = await this.getProfileByAddress(address);
|
|
413
|
+
if (existing) {
|
|
414
|
+
if (updates.length) await this.mutateDocument(existing.documentId, updates, token);
|
|
415
|
+
return existing.documentId;
|
|
416
|
+
}
|
|
417
|
+
const documentId = await this.createEmptyDocument(RENOWN_USER_DOC_TYPE, void 0, token);
|
|
418
|
+
await this.mutateDocument(documentId, [createAction("SET_ETH_ADDRESS", { ethAddress: address }), ...updates], token);
|
|
419
|
+
return documentId;
|
|
420
|
+
}
|
|
421
|
+
async revokeCredential(credentialId, auth) {
|
|
422
|
+
const { token, signed } = authParts(auth);
|
|
423
|
+
try {
|
|
424
|
+
await this.#request(REVOKE_CREDENTIAL_MUTATION, {
|
|
425
|
+
credentialId,
|
|
426
|
+
...signed
|
|
427
|
+
}, token);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
if (!isUnknownSchemaError(error, "renown_revokeCredential")) throw error;
|
|
430
|
+
await this.#legacyRevokeCredential(credentialId, token);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
async #legacyRevokeCredential(credentialId, token) {
|
|
434
|
+
const { renownCredentials } = await this.#request(CREDENTIALS_QUERY, { input: { includeRevoked: false } }, token);
|
|
435
|
+
const documentIds = renownCredentials.filter((row) => row.credentialId === credentialId).map((row) => row.documentId);
|
|
436
|
+
if (!documentIds.length) throw new Error(`Credential not found: ${credentialId}`);
|
|
437
|
+
const revokedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
438
|
+
for (const documentId of documentIds) await this.mutateDocument(documentId, [createAction("REVOKE", {
|
|
439
|
+
revokedAt,
|
|
440
|
+
reason: null
|
|
441
|
+
})], token);
|
|
442
|
+
}
|
|
443
|
+
profileFetcher = (user) => this.getProfileByAddress(user.address).catch(() => void 0);
|
|
444
|
+
};
|
|
445
|
+
//#endregion
|
|
446
|
+
//#region src/credential.ts
|
|
447
|
+
/** Assemble a Renown delegation VC and sign it with the provided signer. */
|
|
448
|
+
async function buildAndSignCredential(params) {
|
|
449
|
+
const { signTypedData, address, chainId, app, appId, expiresInDays = 7 } = params;
|
|
450
|
+
const issuerId = `did:pkh:${DEFAULT_RENOWN_NETWORK_ID}:${chainId}:${address.toLowerCase()}`;
|
|
451
|
+
const credentialId = `urn:uuid:${globalThis.crypto.randomUUID()}`;
|
|
452
|
+
const now = /* @__PURE__ */ new Date();
|
|
453
|
+
const expirationDate = new Date(now.getTime() + expiresInDays * 24 * 60 * 60 * 1e3);
|
|
454
|
+
const message = {
|
|
455
|
+
"@context": ["https://www.w3.org/2018/credentials/v1"],
|
|
456
|
+
type: ["VerifiableCredential", "RenownCredential"],
|
|
457
|
+
id: credentialId,
|
|
458
|
+
issuer: {
|
|
459
|
+
id: issuerId,
|
|
460
|
+
ethereumAddress: address
|
|
461
|
+
},
|
|
462
|
+
credentialSubject: {
|
|
463
|
+
id: appId,
|
|
464
|
+
app
|
|
465
|
+
},
|
|
466
|
+
credentialSchema: {
|
|
467
|
+
id: "https://renown.id/schemas/renown-credential/v1",
|
|
468
|
+
type: "JsonSchemaValidator2018"
|
|
469
|
+
},
|
|
470
|
+
issuanceDate: now.toISOString(),
|
|
471
|
+
expirationDate: expirationDate.toISOString()
|
|
472
|
+
};
|
|
473
|
+
const domain = {
|
|
474
|
+
version: "1",
|
|
475
|
+
chainId
|
|
476
|
+
};
|
|
477
|
+
const { EIP712Domain, ...signTypes } = CREDENTIAL_TYPES;
|
|
478
|
+
const signature = await signTypedData({
|
|
479
|
+
domain,
|
|
480
|
+
types: signTypes,
|
|
481
|
+
primaryType: "VerifiableCredential",
|
|
482
|
+
message
|
|
483
|
+
});
|
|
484
|
+
return {
|
|
485
|
+
...message,
|
|
486
|
+
proof: {
|
|
487
|
+
type: "EthereumEip712Signature2021",
|
|
488
|
+
created: message.issuanceDate,
|
|
489
|
+
verificationMethod: issuerId,
|
|
490
|
+
proofPurpose: "assertionMethod",
|
|
491
|
+
proofValue: signature,
|
|
492
|
+
ethereumAddress: address,
|
|
493
|
+
eip712: {
|
|
494
|
+
domain,
|
|
495
|
+
types: CREDENTIAL_TYPES,
|
|
496
|
+
primaryType: "VerifiableCredential"
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
/** Recover the address that signed a credential's EIP-712 proof. */
|
|
502
|
+
async function recoverCredentialSigner(credential) {
|
|
503
|
+
const { proof, ...message } = credential;
|
|
504
|
+
const { EIP712Domain, ...types } = CREDENTIAL_TYPES;
|
|
505
|
+
return recoverTypedDataAddress({
|
|
506
|
+
domain: proof.eip712.domain,
|
|
507
|
+
types,
|
|
508
|
+
primaryType: "VerifiableCredential",
|
|
509
|
+
message,
|
|
510
|
+
signature: proof.proofValue
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
/** True when the proof was signed by the credential's declared issuer address. */
|
|
514
|
+
async function verifyCredentialSignature(credential) {
|
|
515
|
+
try {
|
|
516
|
+
return (await recoverCredentialSigner(credential)).toLowerCase() === credential.issuer.ethereumAddress.toLowerCase();
|
|
517
|
+
} catch {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
function withEip712Domain(credential, chainId) {
|
|
522
|
+
if (credential.proof.eip712?.domain) return credential;
|
|
523
|
+
return {
|
|
524
|
+
...credential,
|
|
525
|
+
proof: {
|
|
526
|
+
...credential.proof,
|
|
527
|
+
eip712: {
|
|
528
|
+
domain: {
|
|
529
|
+
version: "1",
|
|
530
|
+
chainId
|
|
531
|
+
},
|
|
532
|
+
types: CREDENTIAL_TYPES,
|
|
533
|
+
primaryType: "VerifiableCredential"
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
async function fetchDelegationCredentialRest(params) {
|
|
539
|
+
const { address, chainId, appDid, baseUrl } = params;
|
|
540
|
+
const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, baseUrl);
|
|
541
|
+
const response = await fetch(url, { method: "GET" });
|
|
542
|
+
if (!response.ok) return void 0;
|
|
543
|
+
const { credential } = await response.json();
|
|
544
|
+
if (!credential) return void 0;
|
|
545
|
+
if (!credentialIssuedTo(credential, address, chainId, appDid)) return;
|
|
546
|
+
if (credential.expirationDate) {
|
|
547
|
+
const expiresAt = Date.parse(credential.expirationDate);
|
|
548
|
+
if (Number.isNaN(expiresAt) || expiresAt <= Date.now()) return;
|
|
549
|
+
}
|
|
550
|
+
return credential;
|
|
551
|
+
}
|
|
552
|
+
/** True when the credential's EIP-712 proof, on `chainId`, was signed by its
|
|
553
|
+
* issuer address. Binding and expiry are the caller's to check. */
|
|
554
|
+
async function verifyDelegationProof(credential, chainId) {
|
|
555
|
+
const withDomain = withEip712Domain(credential, chainId);
|
|
556
|
+
return withDomain.proof.eip712.domain.chainId === chainId && await verifyCredentialSignature(withDomain);
|
|
557
|
+
}
|
|
558
|
+
async function finalizeCredential(credential, chainId, verifySignature) {
|
|
559
|
+
if (!verifySignature) return credential;
|
|
560
|
+
if (!await verifyDelegationProof(credential, chainId)) return;
|
|
561
|
+
return withEip712Domain(credential, chainId);
|
|
562
|
+
}
|
|
563
|
+
async function fetchDelegationCredential(options) {
|
|
564
|
+
const { address, chainId, appDid, switchboardUrl, switchboardRequest, discover = true, verifySignature = true } = options;
|
|
565
|
+
const explicitBaseUrl = options.baseUrl;
|
|
566
|
+
const baseUrl = explicitBaseUrl ?? "https://www.renown.id";
|
|
567
|
+
try {
|
|
568
|
+
const source = switchboardRequest ?? (switchboardUrl ? switchboardUrl : discover && explicitBaseUrl ? await resolveSwitchboardEndpoint({ baseUrl }) : void 0);
|
|
569
|
+
const credential = source ? await new SwitchboardClient(source).getCredential({
|
|
570
|
+
address,
|
|
571
|
+
chainId,
|
|
572
|
+
appDid
|
|
573
|
+
}) : await fetchDelegationCredentialRest({
|
|
574
|
+
address,
|
|
575
|
+
chainId,
|
|
576
|
+
appDid,
|
|
577
|
+
baseUrl
|
|
578
|
+
});
|
|
579
|
+
if (!credential) return void 0;
|
|
580
|
+
return await finalizeCredential(credential, chainId, verifySignature);
|
|
581
|
+
} catch {
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
const DEFAULT_CHECK_TIMEOUT_MS = 5e3;
|
|
586
|
+
function credentialIssuedTo(credential, address, chainId, appDid) {
|
|
587
|
+
const [, , , issuerChainId, issuerAddress] = credential.issuer.id.split(":");
|
|
588
|
+
return credential.credentialSubject.id === appDid && issuerChainId === String(chainId) && issuerAddress?.toLowerCase() === address.toLowerCase() && credential.issuer.ethereumAddress.toLowerCase() === address.toLowerCase();
|
|
589
|
+
}
|
|
590
|
+
function goneStatus(expirationDate) {
|
|
591
|
+
if (!expirationDate) return "revoked";
|
|
592
|
+
const expiresAt = Date.parse(expirationDate);
|
|
593
|
+
return !Number.isNaN(expiresAt) && expiresAt <= Date.now() ? "expired" : "revoked";
|
|
594
|
+
}
|
|
595
|
+
async function checkOverRest(options, baseUrl) {
|
|
596
|
+
const { address, chainId, appDid, expirationDate } = options;
|
|
597
|
+
const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, baseUrl);
|
|
598
|
+
const response = await fetch(url, {
|
|
599
|
+
method: "GET",
|
|
600
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS)
|
|
601
|
+
});
|
|
602
|
+
if (!response.ok && response.status !== 404) return { status: "unknown" };
|
|
603
|
+
const body = await response.json().catch(() => void 0);
|
|
604
|
+
if (!body) return { status: "unknown" };
|
|
605
|
+
if (!body.credential) return { status: goneStatus(expirationDate) };
|
|
606
|
+
return {
|
|
607
|
+
status: "active",
|
|
608
|
+
credential: body.credential
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
async function checkOverSwitchboard(options, source) {
|
|
612
|
+
const { address, chainId, appDid, expirationDate } = options;
|
|
613
|
+
const client = new SwitchboardClient(source);
|
|
614
|
+
const credential = await client.getCredential({
|
|
615
|
+
address,
|
|
616
|
+
chainId,
|
|
617
|
+
appDid
|
|
618
|
+
});
|
|
619
|
+
if (credential) return {
|
|
620
|
+
status: "active",
|
|
621
|
+
credential
|
|
622
|
+
};
|
|
623
|
+
const issued = await client.getIssuedCredentials({
|
|
624
|
+
address,
|
|
625
|
+
chainId,
|
|
626
|
+
appDid
|
|
627
|
+
});
|
|
628
|
+
if (issued.length === 0 && !expirationDate) return { status: "unknown" };
|
|
629
|
+
return { status: goneStatus(issued.map((row) => row.expirationDate).filter((date) => Boolean(date)).sort().at(-1) ?? expirationDate) };
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Asks Renown about a credential, keeping "no" apart from "no answer". Never
|
|
633
|
+
* throws. Used where a definite answer stops something, unlike
|
|
634
|
+
* {@link fetchDelegationCredential}, which reads both as undefined.
|
|
635
|
+
*/
|
|
636
|
+
async function checkDelegationCredential(options) {
|
|
637
|
+
const source = options.switchboardRequest ?? options.switchboardUrl;
|
|
638
|
+
try {
|
|
639
|
+
const check = source ? await checkOverSwitchboard(options, source) : await checkOverRest(options, options.baseUrl ?? "https://www.renown.id");
|
|
640
|
+
if (check.status !== "active" || !check.credential) return check;
|
|
641
|
+
const { address, chainId, appDid } = options;
|
|
642
|
+
const verified = credentialIssuedTo(check.credential, address, chainId, appDid) ? await finalizeCredential(check.credential, chainId, true) : void 0;
|
|
643
|
+
return verified ? {
|
|
644
|
+
status: "active",
|
|
645
|
+
credential: verified
|
|
646
|
+
} : { status: "unknown" };
|
|
647
|
+
} catch {
|
|
648
|
+
return { status: "unknown" };
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
async function verifyAuthCredential(jwt, options = {}) {
|
|
652
|
+
const verified = await verifyAuthBearerToken(jwt, { audience: options.audience });
|
|
653
|
+
if (!verified) return void 0;
|
|
654
|
+
const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
|
|
655
|
+
const appDid = verified.issuer;
|
|
656
|
+
const credential = await fetchDelegationCredential({
|
|
657
|
+
address,
|
|
658
|
+
chainId,
|
|
659
|
+
appDid,
|
|
660
|
+
baseUrl: options.renownUrl,
|
|
661
|
+
switchboardUrl: options.switchboardUrl,
|
|
662
|
+
switchboardRequest: options.switchboardRequest,
|
|
663
|
+
verifySignature: options.verifySignature
|
|
664
|
+
});
|
|
665
|
+
if (!credential) return void 0;
|
|
666
|
+
return {
|
|
667
|
+
address,
|
|
668
|
+
chainId,
|
|
669
|
+
networkId,
|
|
670
|
+
did: credential.issuer.id,
|
|
671
|
+
appDid,
|
|
672
|
+
credential
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
//#endregion
|
|
676
|
+
//#region src/delegation.ts
|
|
677
|
+
/** The tag of the `signatures` entry holding a statement, and of its binding. */
|
|
678
|
+
const DELEGATION_TAG = "dlg1";
|
|
679
|
+
/** Keeps a statement apart from the bearer tokens the same key signs. */
|
|
680
|
+
const DELEGATION_JWT_TYPE = "ph-delegation+jwt";
|
|
681
|
+
/** What a statement may name in this version. Nothing wider is accepted. */
|
|
682
|
+
const DELEGABLE_OPERATIONS = ["PUBLISH_WORKFLOW"];
|
|
683
|
+
const DEFAULT_LIFETIME_SECONDS = 2592e3;
|
|
684
|
+
/** How far the browser's clock at issuance may run ahead of the signing tuple. */
|
|
685
|
+
const ISSUED_AT_TOLERANCE_SECONDS = 300;
|
|
686
|
+
const BINDING_PREFIX = `${DELEGATION_TAG}-`;
|
|
687
|
+
/**
|
|
688
|
+
* Signs a statement naming `delegate`, with no wallet step: the session key
|
|
689
|
+
* signs it, and the statement carries the credential so it verifies offline.
|
|
690
|
+
*/
|
|
691
|
+
async function createDelegation(params) {
|
|
692
|
+
const { issuer, credential, delegate, environment, scope, lifetimeSeconds = DEFAULT_LIFETIME_SECONDS, now = Math.floor(Date.now() / 1e3) } = params;
|
|
693
|
+
const claims = {
|
|
694
|
+
iss: issuer.did,
|
|
695
|
+
aud: delegate,
|
|
696
|
+
sub: credential.issuer.id,
|
|
697
|
+
env: environment,
|
|
698
|
+
scp: scope,
|
|
699
|
+
iat: now,
|
|
700
|
+
exp: now + lifetimeSeconds,
|
|
701
|
+
jti: globalThis.crypto.randomUUID(),
|
|
702
|
+
prf: credential
|
|
703
|
+
};
|
|
704
|
+
const signingInput = [encodeSegment({
|
|
705
|
+
alg: "ES256",
|
|
706
|
+
typ: DELEGATION_JWT_TYPE
|
|
707
|
+
}), encodeSegment(claims)].join(".");
|
|
708
|
+
const signature = await issuer.signer(signingInput);
|
|
709
|
+
if (typeof signature !== "string") throw new Error("A delegation issuer must sign as base64url");
|
|
710
|
+
return `${signingInput}.${signature}`;
|
|
711
|
+
}
|
|
712
|
+
/** The statement's claims, unverified; undefined when it does not parse. */
|
|
713
|
+
function decodeDelegation(statement) {
|
|
714
|
+
const [, payload] = statement.split(".");
|
|
715
|
+
if (!payload) return void 0;
|
|
716
|
+
try {
|
|
717
|
+
const claims = JSON.parse(toString(fromString(payload, "base64url")));
|
|
718
|
+
return isClaims(claims) ? claims : void 0;
|
|
719
|
+
} catch {
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Whether `statement` lets `key` sign this action as `user`. Offline and pure:
|
|
725
|
+
* every replica reaches the same verdict at any time, so an old operation
|
|
726
|
+
* verifies forever. The credential's own dates are not read: link one is judged
|
|
727
|
+
* at issuance, and a credential outliving its seven days must not end a delegate.
|
|
728
|
+
*/
|
|
729
|
+
async function verifyDelegation(statement, params) {
|
|
730
|
+
const { user, key, signedAt, actionType } = params;
|
|
731
|
+
const parts = statement.split(".");
|
|
732
|
+
if (parts.length !== 3) return refuse("is not a compact JWS");
|
|
733
|
+
const claims = decodeDelegation(statement);
|
|
734
|
+
if (!claims) return refuse("has malformed claims");
|
|
735
|
+
const header = decodeHeader(parts[0]);
|
|
736
|
+
if (header?.alg !== "ES256" || header.typ !== "ph-delegation+jwt") return refuse("has the wrong header");
|
|
737
|
+
if (!await signedBy(claims.iss, parts)) return refuse("is not signed by its issuer");
|
|
738
|
+
if (!samePerson(claims.sub, user)) return refuse(`does not name ${user.address}`);
|
|
739
|
+
if (claims.aud !== key) return refuse(`names ${claims.aud}, not the signing key ${key}`);
|
|
740
|
+
if (!await chainsToPerson(claims, user)) return refuse("has no credential binding its issuer to the person");
|
|
741
|
+
const scopeProblem = scopeRefusal(claims.scp, actionType);
|
|
742
|
+
if (scopeProblem) return refuse(scopeProblem);
|
|
743
|
+
if (signedAt < claims.iat - ISSUED_AT_TOLERANCE_SECONDS || signedAt >= claims.exp) return refuse("does not cover the time the action was signed");
|
|
744
|
+
return {
|
|
745
|
+
ok: true,
|
|
746
|
+
claims
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
/** What `signer` carries of a delegation; undefined when it carries nothing. */
|
|
750
|
+
function delegationOf(signer) {
|
|
751
|
+
const signatures = signer.signatures;
|
|
752
|
+
const tuple = signatures?.at(-1);
|
|
753
|
+
if (!signatures || !tuple) return void 0;
|
|
754
|
+
const statements = signatures.slice(0, -1).filter((entry) => entry[0] === DELEGATION_TAG).map((entry) => entry[3]);
|
|
755
|
+
const binding = tuple[3]?.startsWith(BINDING_PREFIX) ? tuple[3] : void 0;
|
|
756
|
+
if (statements.length === 0 && binding === void 0) return void 0;
|
|
757
|
+
return {
|
|
758
|
+
...statements.length === 1 ? { statement: statements[0] } : {},
|
|
759
|
+
...binding !== void 0 ? { binding } : {},
|
|
760
|
+
signedAt: Number(tuple[0])
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
/** Why what `signer` carries does not stand as bound; undefined when it does. */
|
|
764
|
+
async function bindingRefusal(carried) {
|
|
765
|
+
if (carried.statement === void 0) return "the signing tuple names a statement the action does not carry";
|
|
766
|
+
if (carried.binding === void 0) return "the signing tuple does not cover the statement";
|
|
767
|
+
if (carried.binding !== await delegationBinding(carried.statement)) return "the signing tuple covers a different statement";
|
|
768
|
+
}
|
|
769
|
+
/** What the signing tuple's element [3] holds, so the signature covers the statement. */
|
|
770
|
+
async function delegationBinding(statement) {
|
|
771
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(statement));
|
|
772
|
+
return BINDING_PREFIX + toString(new Uint8Array(digest), "base64url");
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Signs `action` as the person, carrying the statement in an earlier entry of
|
|
776
|
+
* `signatures`. The reactor leaves an action already signed under a key as it
|
|
777
|
+
* is, so this goes through any client.
|
|
778
|
+
*/
|
|
779
|
+
async function signDelegatedAction(params) {
|
|
780
|
+
const { action, target, crypto, appName, user, statement } = params;
|
|
781
|
+
const identity = actionSignerIdentity({
|
|
782
|
+
user,
|
|
783
|
+
app: {
|
|
784
|
+
name: appName,
|
|
785
|
+
key: crypto.did
|
|
786
|
+
}
|
|
787
|
+
});
|
|
788
|
+
const tuple = await signActionV2({
|
|
789
|
+
action,
|
|
790
|
+
target,
|
|
791
|
+
signer: identity,
|
|
792
|
+
sign: (message) => crypto.sign(message),
|
|
793
|
+
previousStateHash: await delegationBinding(statement)
|
|
794
|
+
});
|
|
795
|
+
const issuer = decodeDelegation(statement)?.iss ?? "";
|
|
796
|
+
const entry = [
|
|
797
|
+
DELEGATION_TAG,
|
|
798
|
+
issuer,
|
|
799
|
+
"",
|
|
800
|
+
statement,
|
|
801
|
+
""
|
|
802
|
+
];
|
|
803
|
+
return {
|
|
804
|
+
...action,
|
|
805
|
+
context: {
|
|
806
|
+
...action.context,
|
|
807
|
+
signer: {
|
|
808
|
+
...identity,
|
|
809
|
+
signatures: [entry, tuple]
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
function refuse(reason) {
|
|
815
|
+
return {
|
|
816
|
+
ok: false,
|
|
817
|
+
reason: `the statement ${reason}`
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
function encodeSegment(value) {
|
|
821
|
+
return toString(fromString(JSON.stringify(value)), "base64url");
|
|
822
|
+
}
|
|
823
|
+
function decodeHeader(segment) {
|
|
824
|
+
try {
|
|
825
|
+
return JSON.parse(toString(fromString(segment, "base64url")));
|
|
826
|
+
} catch {
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function isClaims(value) {
|
|
831
|
+
return !!value && typeof value.iss === "string" && typeof value.aud === "string" && typeof value.sub === "string" && typeof value.env === "string" && typeof value.iat === "number" && typeof value.exp === "number" && typeof value.jti === "string" && typeof value.scp === "object" && value.scp !== null && typeof value.prf === "object" && value.prf !== null;
|
|
832
|
+
}
|
|
833
|
+
async function signedBy(issuer, parts) {
|
|
834
|
+
try {
|
|
835
|
+
const key = await importDidPublicKey(issuer);
|
|
836
|
+
return await globalThis.crypto.subtle.verify({
|
|
837
|
+
name: "ECDSA",
|
|
838
|
+
hash: "SHA-256"
|
|
839
|
+
}, key, new Uint8Array(fromString(parts[2], "base64url")), new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
|
|
840
|
+
} catch {
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
function samePerson(subject, user) {
|
|
845
|
+
try {
|
|
846
|
+
const person = parsePkhDid(subject);
|
|
847
|
+
return person.address.toLowerCase() === user.address.toLowerCase() && person.networkId === user.networkId && person.chainId === user.chainId;
|
|
848
|
+
} catch {
|
|
849
|
+
return false;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
/** Link one: the credential in `prf` binds the person to the statement's issuer. */
|
|
853
|
+
async function chainsToPerson(claims, user) {
|
|
854
|
+
const credential = claims.prf;
|
|
855
|
+
const address = user.address.toLowerCase();
|
|
856
|
+
try {
|
|
857
|
+
if (credential.credentialSubject.id !== claims.iss || credential.issuer.id !== claims.sub || credential.issuer.ethereumAddress.toLowerCase() !== address) return false;
|
|
858
|
+
return await verifyDelegationProof(credential, user.chainId);
|
|
859
|
+
} catch {
|
|
860
|
+
return false;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
function scopeRefusal(scope, actionType) {
|
|
864
|
+
if (!Array.isArray(scope.ops) || scope.ops.length === 0) return "names no operations";
|
|
865
|
+
const wider = scope.ops.find((op) => !DELEGABLE_OPERATIONS.includes(op));
|
|
866
|
+
if (wider !== void 0) return `names ${wider}, which cannot be delegated`;
|
|
867
|
+
if (!scope.ops.includes(actionType)) return `does not cover ${actionType}`;
|
|
868
|
+
}
|
|
869
|
+
//#endregion
|
|
870
|
+
//#region src/signer-trust.ts
|
|
871
|
+
const DEFAULT_MAX_ACCEPTED = 1e4;
|
|
872
|
+
const DEFAULT_REFUSAL_TTL_MS = 6e4;
|
|
873
|
+
/**
|
|
874
|
+
* Accepts a key the user's EIP-712 Renown credential delegates to, ignoring
|
|
875
|
+
* expiry and revocation. Verdicts are cached per (address, key); this node's
|
|
876
|
+
* own key is checked before the cache and never cached.
|
|
877
|
+
*
|
|
878
|
+
* A signer carrying a delegation is verified from what it carries, with no
|
|
879
|
+
* lookup and no cache: the verdict depends on the statement, not on (address,
|
|
880
|
+
* key). `options.delegationOnly` accepts every other signer.
|
|
881
|
+
*/
|
|
882
|
+
function createRenownTrustPolicy(options = {}) {
|
|
883
|
+
const maxAccepted = options.maxAccepted ?? DEFAULT_MAX_ACCEPTED;
|
|
884
|
+
const refusalTtlMs = options.refusalTtlMs ?? DEFAULT_REFUSAL_TTL_MS;
|
|
885
|
+
const client = options.switchboard ? new SwitchboardClient(options.switchboard) : void 0;
|
|
886
|
+
const renownUrl = options.renownUrl ?? "https://www.renown.id";
|
|
887
|
+
const accepted = /* @__PURE__ */ new Set();
|
|
888
|
+
const refusedUntil = /* @__PURE__ */ new Map();
|
|
889
|
+
const pending = /* @__PURE__ */ new Map();
|
|
890
|
+
const issued = (user, key) => client ? client.getIssuedCredentials({
|
|
891
|
+
address: user.address,
|
|
892
|
+
chainId: user.chainId,
|
|
893
|
+
appDid: key
|
|
894
|
+
}) : fetchIssuedCredentialRest(user, key, renownUrl);
|
|
895
|
+
async function lookup(user, key) {
|
|
896
|
+
for (const credential of await issued(user, key)) if (bindsTo(credential, user, key) && await verifyDelegationProof(credential, user.chainId)) return true;
|
|
897
|
+
return false;
|
|
898
|
+
}
|
|
899
|
+
function remember(entry, verdict) {
|
|
900
|
+
if (verdict) {
|
|
901
|
+
if (accepted.size >= maxAccepted) {
|
|
902
|
+
const oldest = accepted.values().next().value;
|
|
903
|
+
if (oldest !== void 0) accepted.delete(oldest);
|
|
904
|
+
}
|
|
905
|
+
accepted.add(entry);
|
|
906
|
+
refusedUntil.delete(entry);
|
|
907
|
+
} else refusedUntil.set(entry, Date.now() + refusalTtlMs);
|
|
908
|
+
}
|
|
909
|
+
return { authorizeSigner(signer, key, _documentId, context) {
|
|
910
|
+
const user = signer.user;
|
|
911
|
+
const self = ownIdentity(options);
|
|
912
|
+
if (self && isSelf(self, user, key)) return Promise.resolve(true);
|
|
913
|
+
const carried = delegationOf(signer);
|
|
914
|
+
if (carried) return authorizeDelegated(carried, user, key, self?.key, context);
|
|
915
|
+
if (options.delegationOnly) return Promise.resolve(true);
|
|
916
|
+
if (!user || !isLookupable(user, key)) return Promise.resolve(false);
|
|
917
|
+
const entry = `${user.networkId}|${user.chainId}|${user.address.toLowerCase()}|${key}`;
|
|
918
|
+
if (accepted.has(entry)) return Promise.resolve(true);
|
|
919
|
+
const until = refusedUntil.get(entry);
|
|
920
|
+
if (until !== void 0 && until > Date.now()) return Promise.resolve(false);
|
|
921
|
+
const inFlight = pending.get(entry);
|
|
922
|
+
if (inFlight) return inFlight;
|
|
923
|
+
const verdict = lookup(user, key).then((result) => {
|
|
924
|
+
pending.delete(entry);
|
|
925
|
+
remember(entry, result);
|
|
926
|
+
return result;
|
|
927
|
+
}, (error) => {
|
|
928
|
+
pending.delete(entry);
|
|
929
|
+
throw error;
|
|
930
|
+
});
|
|
931
|
+
pending.set(entry, verdict);
|
|
932
|
+
return verdict;
|
|
933
|
+
} };
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* The statement alone decides, so every replica agrees and no network is
|
|
937
|
+
* needed. The one exception is `env`, checked only at first write: peers
|
|
938
|
+
* receive these operations legitimately on load.
|
|
939
|
+
*/
|
|
940
|
+
async function authorizeDelegated(carried, user, key, ownKey, context) {
|
|
941
|
+
if (!user || !context || carried.statement === void 0) return false;
|
|
942
|
+
if (await bindingRefusal(carried) !== void 0) return false;
|
|
943
|
+
const verdict = await verifyDelegation(carried.statement, {
|
|
944
|
+
user,
|
|
945
|
+
key,
|
|
946
|
+
signedAt: carried.signedAt,
|
|
947
|
+
actionType: context.actionType
|
|
948
|
+
});
|
|
949
|
+
if (!verdict.ok) return false;
|
|
950
|
+
return context.path === "load" || verdict.claims.env === ownKey;
|
|
951
|
+
}
|
|
952
|
+
function ownIdentity(options) {
|
|
953
|
+
if (!options.ownSigner) return options.self;
|
|
954
|
+
const { app, user } = options.ownSigner;
|
|
955
|
+
return {
|
|
956
|
+
key: app?.key ?? "",
|
|
957
|
+
user: {
|
|
958
|
+
address: user?.address ?? "",
|
|
959
|
+
networkId: user?.networkId ?? "",
|
|
960
|
+
chainId: user?.chainId ?? 0
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
function isSelf(self, user, key) {
|
|
965
|
+
return self.key !== "" && key === self.key && (user?.address ?? "").toLowerCase() === self.user.address.toLowerCase() && (user?.networkId ?? "") === self.user.networkId && (user?.chainId ?? 0) === self.user.chainId;
|
|
966
|
+
}
|
|
967
|
+
function isLookupable(user, key) {
|
|
968
|
+
return key.startsWith("did:key:") && /^0x[0-9a-fA-F]{40}$/.test(user.address) && user.networkId !== "" && Number.isInteger(user.chainId) && user.chainId > 0;
|
|
969
|
+
}
|
|
970
|
+
function bindsTo(credential, user, key) {
|
|
971
|
+
const address = user.address.toLowerCase();
|
|
972
|
+
const issuer = credential.issuer.id.split(":");
|
|
973
|
+
if (issuer.length !== 5) return false;
|
|
974
|
+
const [scheme, method, networkId, chainId, issuerAddress] = issuer;
|
|
975
|
+
return credential.credentialSubject.id === key && scheme === "did" && method === "pkh" && networkId === user.networkId && chainId === String(user.chainId) && issuerAddress.toLowerCase() === address && credential.issuer.ethereumAddress.toLowerCase() === address;
|
|
976
|
+
}
|
|
977
|
+
async function fetchIssuedCredentialRest(user, key, renownUrl) {
|
|
978
|
+
const url = new URL("/api/auth/credential", renownUrl);
|
|
979
|
+
url.searchParams.set("address", user.address);
|
|
980
|
+
url.searchParams.set("chainId", String(user.chainId));
|
|
981
|
+
url.searchParams.set("connectId", key);
|
|
982
|
+
url.searchParams.set("appId", key);
|
|
983
|
+
const response = await fetch(url, { method: "GET" });
|
|
984
|
+
if (response.status === 404) return [];
|
|
985
|
+
if (!response.ok) throw new Error(`Renown credential lookup failed: ${response.status}`);
|
|
986
|
+
const { credential } = await response.json();
|
|
987
|
+
return credential ? [credential] : [];
|
|
988
|
+
}
|
|
989
|
+
//#endregion
|
|
990
|
+
export { verifyCredentialSignature as _, bindingRefusal as a, SwitchboardClient as b, delegationBinding as c, verifyDelegation as d, buildAndSignCredential as f, verifyAuthCredential as g, recoverCredentialSigner as h, DELEGATION_TAG as i, delegationOf as l, fetchDelegationCredential as m, DELEGABLE_OPERATIONS as n, createDelegation as o, checkDelegationCredential as p, DELEGATION_JWT_TYPE as r, decodeDelegation as s, createRenownTrustPolicy as t, signDelegatedAction as u, verifyDelegationProof as v, resolveSwitchboardEndpoint as x, MissingSwitchboardError as y };
|
|
991
|
+
|
|
992
|
+
//# sourceMappingURL=signer-trust-aVg9lYAn.js.map
|