| 6 | const pki = forge.pki |
| 7 | |
| 8 | export function generate (options, callback) { |
| 9 | if (!options.agent) { |
| 10 | return callback(new Error('No agent uri found')) |
| 11 | } |
| 12 | if (!options.spkac) { |
| 13 | return callback(new Error('No public key found'), null) |
| 14 | } |
| 15 | if (!certificate.verifySpkac(Buffer.from(options.spkac))) { |
| 16 | return callback(new Error('Invalid SPKAC')) |
| 17 | } |
| 18 | options.duration = options.duration || 10 |
| 19 | const cert = pki.createCertificate() |
| 20 | cert.serialNumber = (Date.now()).toString(16) |
| 21 | const publicKey = certificate.exportPublicKey(options.spkac).toString() |
| 22 | cert.publicKey = pki.publicKeyFromPem(publicKey) |
| 23 | cert.validity.notBefore = new Date() |
| 24 | cert.validity.notAfter = new Date() |
| 25 | cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + options.duration) |
| 26 | const commonName = options.commonName || new URL(options.agent).hostname |
| 27 | const attrsSubject = [ |
| 28 | { name: 'commonName', value: commonName }, |
| 29 | { name: 'organizationName', value: options.organizationName || 'WebID' } |
| 30 | ] |
| 31 | const attrsIssuer = [ |
| 32 | { name: 'commonName', value: commonName }, |
| 33 | { name: 'organizationName', value: options.organizationName || 'WebID' } |
| 34 | ] |
| 35 | if (options.issuer) { |
| 36 | if (options.issuer.commonName) { |
| 37 | attrsIssuer[0].value = options.issuer.commonName |
| 38 | } |
| 39 | if (options.issuer.organizationName) { |
| 40 | attrsIssuer[1].value = options.issuer.organizationName |
| 41 | } |
| 42 | } |
| 43 | cert.setSubject(attrsSubject) |
| 44 | cert.setIssuer(attrsIssuer) |
| 45 | cert.setExtensions([ |
| 46 | { name: 'basicConstraints', cA: false, critical: true }, |
| 47 | { name: 'subjectAltName', altNames: [{ type: 6, value: options.agent }] }, |
| 48 | { name: 'subjectKeyIdentifier' } |
| 49 | ]) |
| 50 | const keys = pki.rsa.generateKeyPair(1024) |
| 51 | cert.sign(keys.privateKey, forge.md.sha256.create()) |
| 52 | return callback(null, cert) |
| 53 | } |