UNPKG

@atproto/did

Version:

DID resolution and verification library

70 lines 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DID_WEB_PREFIX = void 0; exports.isDidWeb = isDidWeb; exports.asDidWeb = asDidWeb; exports.assertDidWeb = assertDidWeb; exports.didWebToUrl = didWebToUrl; exports.urlToDidWeb = urlToDidWeb; const did_error_js_1 = require("../did-error.js"); const did_js_1 = require("../did.js"); exports.DID_WEB_PREFIX = `did:web:`; /** * This function checks if the input is a valid Web DID, as per DID spec. */ function isDidWeb(input) { // Optimization: make cheap checks first if (typeof input !== 'string') return false; if (!input.startsWith(exports.DID_WEB_PREFIX)) return false; if (input.charAt(exports.DID_WEB_PREFIX.length) === ':') return false; try { didWebToUrl(input); return true; } catch { return false; } } function asDidWeb(input) { assertDidWeb(input); return input; } function assertDidWeb(input) { if (typeof input !== 'string') { throw new did_error_js_1.InvalidDidError(typeof input, `DID must be a string`); } if (!input.startsWith(exports.DID_WEB_PREFIX)) { throw new did_error_js_1.InvalidDidError(input, `Invalid did:web prefix`); } if (input.charAt(exports.DID_WEB_PREFIX.length) === ':') { throw new did_error_js_1.InvalidDidError(input, 'did:web MSID must not start with a colon'); } void didWebToUrl(input); } function didWebToUrl(did) { // Make sure every char is valid (per DID spec) (0, did_js_1.assertDidMsid)(did, exports.DID_WEB_PREFIX.length); const hostIdx = exports.DID_WEB_PREFIX.length; const pathIdx = did.indexOf(':', hostIdx); const host = pathIdx === -1 ? did.slice(hostIdx) : did.slice(hostIdx, pathIdx); const path = pathIdx === -1 ? '' : did.slice(pathIdx); try { const url = new URL(`https://${host.replaceAll('%3A', ':')}${path.replaceAll(':', '/')}`); if (url.hostname === 'localhost') { url.protocol = 'http:'; } return url; } catch (cause) { throw new did_error_js_1.InvalidDidError(did, 'Invalid Web DID', cause); } } function urlToDidWeb(url) { const port = url.port ? `%3A${url.port}` : ''; const path = url.pathname === '/' ? '' : url.pathname.replaceAll('/', ':'); return `did:web:${url.hostname}${port}${path}`; } //# sourceMappingURL=web.js.map