You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
163 lines
4.8 KiB
163 lines
4.8 KiB
/// <reference types="node" />
|
|
// Add at the top of your file to ignore dom types
|
|
import * as didJwt from 'did-jwt';
|
|
import { ethers } from 'ethers';
|
|
import fetch from 'node-fetch';
|
|
|
|
interface DIDCreationResult {
|
|
did: string;
|
|
privateKey: string;
|
|
publicKey: string;
|
|
isValid: boolean;
|
|
jwt: string;
|
|
}
|
|
|
|
interface RegistrationResult {
|
|
success: boolean;
|
|
error?: string;
|
|
response?: any;
|
|
}
|
|
|
|
async function createAndValidateDID(adminDid: string): Promise<DIDCreationResult> {
|
|
if (!adminDid) {
|
|
throw new Error('Admin DID is required for registration');
|
|
}
|
|
|
|
console.log('Using admin DID:', adminDid);
|
|
|
|
// 1. Generate keypair
|
|
console.log('Generating new keypair...');
|
|
const wallet = ethers.Wallet.createRandom();
|
|
const did = `did:ethr:${wallet.address}`;
|
|
const privateKey = wallet.privateKey.slice(2);
|
|
const publicKey = wallet.publicKey;
|
|
|
|
// Create registration claim with admin as agent
|
|
const registerClaim = {
|
|
"@context": "https://schema.org",
|
|
"@type": "RegisterAction",
|
|
agent: { did: adminDid },
|
|
participant: { did: did },
|
|
object: "endorser.ch"
|
|
};
|
|
|
|
const vcPayload = {
|
|
iat: Math.floor(Date.now() / 1000),
|
|
exp: Math.floor(Date.now() / 1000) + 300,
|
|
sub: "RegisterAction",
|
|
vc: {
|
|
"@context": ["https://www.w3.org/2018/credentials/v1"],
|
|
type: ["VerifiableCredential"],
|
|
credentialSubject: registerClaim
|
|
}
|
|
};
|
|
|
|
console.log('\nGenerated DID Details:');
|
|
console.log('----------------------');
|
|
console.log('DID:', did);
|
|
console.log('Admin DID:', adminDid);
|
|
console.log('Address:', wallet.address);
|
|
console.log('Private Key:', wallet.privateKey);
|
|
console.log('Public Key:', wallet.publicKey);
|
|
|
|
console.log('\nDebug Details:');
|
|
console.log('-------------');
|
|
console.log('Private Key (hex):', privateKey); // Should be without 0x
|
|
console.log('Public Key (hex):', publicKey); // Should be with 0x
|
|
console.log('Header:', {
|
|
typ: "JWT",
|
|
alg: "ES256K"
|
|
});
|
|
console.log('Payload:', vcPayload);
|
|
|
|
// Create and sign JWT
|
|
console.log('\nCreating JWT...');
|
|
const signer = didJwt.SimpleSigner(privateKey);
|
|
const jwt = await didJwt.createJWT(vcPayload, {
|
|
issuer: did,
|
|
signer: signer
|
|
});
|
|
|
|
console.log('\nJWT Parts:');
|
|
const [header, payload, signature] = jwt.split('.');
|
|
console.log('Header (base64):', header);
|
|
console.log('Payload (base64):', payload);
|
|
console.log('Signature (base64):', signature);
|
|
|
|
return { did, privateKey, publicKey, isValid: true, jwt };
|
|
}
|
|
|
|
async function registerDID(jwt: string): Promise<RegistrationResult> {
|
|
try {
|
|
const response = await fetch('https://api.endorser.ch/api/v2/claim', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ jwtEncoded: jwt }),
|
|
});
|
|
|
|
console.log(`\nServer Response Status: ${response.status}`);
|
|
const responseText = await response.text();
|
|
console.log(`Server Response Body: ${responseText}`);
|
|
|
|
if (response.ok) {
|
|
return {
|
|
success: true,
|
|
response: JSON.parse(responseText)
|
|
};
|
|
} else {
|
|
try {
|
|
const errorJson = JSON.parse(responseText);
|
|
const errorMsg = errorJson.error?.message || 'Unknown error';
|
|
return {
|
|
success: false,
|
|
error: `Registration failed (${response.status}): ${errorMsg}`,
|
|
response: errorJson
|
|
};
|
|
} catch {
|
|
return {
|
|
success: false,
|
|
error: `Registration failed (${response.status}): ${responseText}`,
|
|
response: responseText
|
|
};
|
|
}
|
|
}
|
|
} catch (e) {
|
|
return {
|
|
success: false,
|
|
error: `Request failed: ${e}`
|
|
};
|
|
}
|
|
}
|
|
|
|
// Command line handling
|
|
const adminDid = 'did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F';
|
|
if (!adminDid) {
|
|
console.error('Usage: ts-node did_generator.ts <admin-did>');
|
|
console.error('Example: ts-node did_generator.ts did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F');
|
|
process.exit(1);
|
|
}
|
|
|
|
console.log('Starting DID Generation...\n');
|
|
createAndValidateDID(adminDid)
|
|
.then(async result => {
|
|
console.log('\nSuccessfully generated DID with admin authorization!');
|
|
console.log('Registration JWT:', result.jwt.substring(0, 50) + '...');
|
|
|
|
console.log('\nAttempting registration...');
|
|
const registrationResult = await registerDID(result.jwt);
|
|
if (registrationResult.success) {
|
|
console.log('Registration successful!');
|
|
console.log('Response:', JSON.stringify(registrationResult.response, null, 2));
|
|
} else {
|
|
console.log('Registration failed!');
|
|
console.log('Error:', registrationResult.error);
|
|
if (registrationResult.response) {
|
|
console.log('Full response:', JSON.stringify(registrationResult.response, null, 2));
|
|
}
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('\nError:', error);
|
|
});
|