-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdid-nostr.js
More file actions
205 lines (174 loc) · 5.42 KB
/
Copy pathdid-nostr.js
File metadata and controls
205 lines (174 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* DID:nostr Resolution
*
* Resolves did:nostr:<pubkey> to a Solid WebID by:
* 1. Fetching DID document from nostr.social
* 2. Extracting alsoKnownAs WebID
* 3. Verifying bidirectional link (WebID links back to did:nostr)
*/
// Default DID resolver endpoint
const DEFAULT_DID_RESOLVER = 'https://nostr.social/.well-known/did/nostr';
// Cache for resolved DIDs (pubkey -> webId or null)
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
/**
* Fetch with timeout
*/
async function fetchWithTimeout(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(id);
return response;
} catch (err) {
clearTimeout(id);
throw err;
}
}
/**
* Resolve did:nostr pubkey to WebID via DID document
* @param {string} pubkey - 64-char hex Nostr pubkey
* @param {string} resolverUrl - DID resolver base URL
* @returns {Promise<string|null>} WebID URL or null
*/
export async function resolveDidNostrToWebId(pubkey, resolverUrl = DEFAULT_DID_RESOLVER) {
if (!pubkey || pubkey.length !== 64) {
return null;
}
// Check cache
const cacheKey = pubkey.toLowerCase();
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.webId;
}
try {
// Fetch DID document
const didUrl = `${resolverUrl}/${pubkey}.json`;
const didRes = await fetchWithTimeout(didUrl, {
headers: { 'Accept': 'application/did+json, application/json' }
});
if (!didRes.ok) {
cache.set(cacheKey, { webId: null, timestamp: Date.now() });
return null;
}
const didDoc = await didRes.json();
// Extract WebID from alsoKnownAs (array) or profile.webid or profile.sameAs
let webId = null;
if (Array.isArray(didDoc.alsoKnownAs) && didDoc.alsoKnownAs.length > 0) {
// Find first HTTP(S) URL that looks like a WebID
webId = didDoc.alsoKnownAs.find(aka =>
typeof aka === 'string' && aka.startsWith('https://'));
}
// Fallback to profile fields
if (!webId && didDoc.profile) {
webId = didDoc.profile.webid || didDoc.profile.sameAs;
}
if (!webId) {
cache.set(cacheKey, { webId: null, timestamp: Date.now() });
return null;
}
// Verify bidirectional link - WebID must link back to did:nostr
const verified = await verifyWebIdBacklink(webId, pubkey);
if (verified) {
cache.set(cacheKey, { webId, timestamp: Date.now() });
return webId;
}
cache.set(cacheKey, { webId: null, timestamp: Date.now() });
return null;
} catch (err) {
// Network error or timeout - don't cache failures
console.error(`DID resolution error for ${pubkey}:`, err.message);
return null;
}
}
/**
* Verify WebID profile links back to did:nostr
* @param {string} webId - WebID URL
* @param {string} pubkey - Nostr pubkey
* @returns {Promise<boolean>}
*/
async function verifyWebIdBacklink(webId, pubkey) {
try {
const expectedDid = `did:nostr:${pubkey.toLowerCase()}`;
// Fetch WebID profile
const res = await fetchWithTimeout(webId, {
headers: { 'Accept': 'application/ld+json, application/json, text/html' }
});
if (!res.ok) {
return false;
}
const contentType = res.headers.get('content-type') || '';
const text = await res.text();
// Handle HTML with JSON-LD data island
if (contentType.includes('text/html')) {
const jsonLdMatch = text.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
if (jsonLdMatch) {
try {
const jsonLd = JSON.parse(jsonLdMatch[1]);
return checkSameAsLink(jsonLd, expectedDid);
} catch {
return false;
}
}
return false;
}
// Handle JSON-LD directly
if (contentType.includes('json')) {
try {
const jsonLd = JSON.parse(text);
return checkSameAsLink(jsonLd, expectedDid);
} catch {
return false;
}
}
return false;
} catch (err) {
console.error(`WebID backlink verification error for ${webId}:`, err.message);
return false;
}
}
/**
* Check if JSON-LD contains sameAs/owl:sameAs link to expected DID
* @param {object} jsonLd - Parsed JSON-LD
* @param {string} expectedDid - Expected did:nostr:pubkey
* @returns {boolean}
*/
function checkSameAsLink(jsonLd, expectedDid) {
// Check various sameAs fields
const sameAsFields = [
jsonLd['owl:sameAs'],
jsonLd['sameAs'],
jsonLd['schema:sameAs'],
jsonLd['http://www.w3.org/2002/07/owl#sameAs']
];
for (const field of sameAsFields) {
if (!field) continue;
// Handle string value
if (typeof field === 'string' && field.toLowerCase() === expectedDid) {
return true;
}
// Handle object with @id
if (field && typeof field === 'object' && field['@id']?.toLowerCase() === expectedDid) {
return true;
}
// Handle array
if (Array.isArray(field)) {
for (const item of field) {
if (typeof item === 'string' && item.toLowerCase() === expectedDid) {
return true;
}
if (item && typeof item === 'object' && item['@id']?.toLowerCase() === expectedDid) {
return true;
}
}
}
}
return false;
}
/**
* Clear the resolution cache (for testing)
*/
export function clearCache() {
cache.clear();
}