-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathelysia-resolver.ts
More file actions
200 lines (171 loc) · 5.97 KB
/
Copy pathelysia-resolver.ts
File metadata and controls
200 lines (171 loc) · 5.97 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
import { readFile } from 'node:fs/promises';
import { ed25519 } from '@noble/curves/ed25519.js';
import { Elysia } from 'elysia';
import { AbstractCrypto, resolveDID } from '../src';
import type { DIDDoc, SigningInput, SigningOutput, Verifier } from '../src/types';
class ElysiaVerifier extends AbstractCrypto implements Verifier {
constructor(
public readonly verificationMethod: {
id: string;
controller: string;
type: string;
publicKeyMultibase: string;
secretKeyMultibase: string;
}
) {
super({ verificationMethod });
}
async sign(input: SigningInput): Promise<SigningOutput> {
throw new Error('Not implemented');
}
async verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): Promise<boolean> {
try {
return ed25519.verify(signature, message, publicKey, { zip215: false });
} catch (error) {
console.error('Ed25519 verification error:', error);
return false;
}
}
}
const createElysiaVerifier = () => {
return new ElysiaVerifier({
id: 'did:example:123#key-1',
controller: 'did:example:123',
type: 'Ed25519VerificationKey2020',
publicKeyMultibase: `z123`,
secretKeyMultibase: `z123`,
});
};
const elysiaVerifier = createElysiaVerifier();
const WELL_KNOWN_ALLOW_LIST = ['did.jsonl'];
// Helper function to map DID resolution errors to HTTP status codes
const getStatusCodeFromError = (errorType?: string): number => {
switch (errorType) {
case 'invalidDid':
return 400;
case 'invalidDidUrl':
return 400;
case 'invalidOptions':
return 400;
case 'notFound':
return 404;
default:
return 500;
}
};
const getFile = async ({
params: { path, file },
isRemote = false,
didDocument,
}: {
params: { path: string; file: string };
isRemote?: boolean;
didDocument?: DIDDoc;
}) => {
try {
if (isRemote) {
let serviceEndpoint;
if (file === 'whois') {
const whoisService = didDocument?.service?.find((s: any) => s.id === '#whois');
if (whoisService?.serviceEndpoint) {
serviceEndpoint = whoisService.serviceEndpoint;
}
} else {
const filesService = didDocument?.service?.find((s: any) => s.id === '#files');
if (filesService?.serviceEndpoint) {
serviceEndpoint = filesService.serviceEndpoint;
}
}
if (!serviceEndpoint) {
const cleanDomain = path.replace('.well-known/', '');
serviceEndpoint = `https://${cleanDomain}`;
if (file === 'whois') {
serviceEndpoint = `${serviceEndpoint}/whois.vp`;
}
}
serviceEndpoint = serviceEndpoint.replace(/\/$/, '');
const url = file === 'whois' ? serviceEndpoint : `${serviceEndpoint}/${file}`;
const response = await fetch(url);
if (!response.ok) {
if (response.status === 404) {
throw new Error('Error 404: Not Found');
}
throw new Error(`Error ${response.status}: ${response.statusText}`);
}
return response.text();
}
if (file === 'whois') {
file = 'whois.vp';
}
const filePath = WELL_KNOWN_ALLOW_LIST.some((f) => f === file)
? `./src/routes/.well-known/${file}`
: path
? `./src/routes/${path}/${file}`
: `./src/routes/${file}`;
return await readFile(filePath, 'utf8');
} catch (e: unknown) {
console.error(e);
throw new Error(`Failed to resolve File: ${e instanceof Error ? e.message : String(e)}`);
}
};
const port = Number(process.env.PORT ?? 3010);
const app = new Elysia()
.get('/health', () => 'ok')
.get('/resolve/:id', async ({ params, query, set }) => {
try {
const id = params.id;
if (!id) {
set.status = 400;
return { error: 'No id provided' };
}
const [didPart, ...pathParts] = id.split('/');
if (pathParts.length === 0) {
const options = {
versionNumber: query?.versionNumber ? parseInt(query.versionNumber as string, 10) : undefined,
versionId: query?.versionId as string,
versionTime: query?.versionTime ? new Date(query.versionTime as string) : undefined,
verifier: elysiaVerifier,
};
console.log(`Resolving DID ${didPart}`);
const result = await resolveDID(didPart, options);
// Check for error in resolution metadata and set appropriate status code
if (result.didResolutionMetadata?.error) {
set.status = getStatusCodeFromError(result.didResolutionMetadata.error);
}
return result;
}
const resolution = await resolveDID(didPart, { verifier: elysiaVerifier });
// Only bail when there is no usable document. A valid earlier version can
// be returned alongside a warning-level error, so still serve files in that case.
if (resolution.didResolutionMetadata?.error && !resolution.didDocument) {
set.status = getStatusCodeFromError(resolution.didResolutionMetadata.error);
return {
error: 'Resolution failed',
details: resolution.didResolutionMetadata.error,
};
}
const did = resolution.didDocument?.id ?? '';
const doc = (resolution.didDocument as DIDDoc | null) ?? undefined;
const controlled = Boolean((resolution.didResolutionMetadata as { controlled?: boolean }).controlled);
const didParts = did.split(':');
const domain = didParts[didParts.length - 1];
const fileIdentifier = didParts[didParts.length - 2];
const fileContent = await getFile({
params: {
path: !controlled ? domain : fileIdentifier,
file: pathParts.join('/'),
},
isRemote: !controlled,
didDocument: doc,
});
return fileContent;
} catch (error: unknown) {
set.status = 500;
return {
error: 'Resolution failed',
details: error instanceof Error ? error.message : String(error),
};
}
})
.listen(port);
console.log(`Elysia resolver is running at http://localhost:${app.server?.port ?? port}`);