2bda4ce2307dc0b026ba3975e65d0f56a936b940
3 const { mf2
} = require('microformats-parser');
4 const { parse: parseLinkHeader
} = require('@squeep/web-linking');
5 const { Iconv
} = require('iconv');
6 const { version: packageVersion
, name: packageName
} = require('../package.json');
7 const { randomBytes
, createHash
} = require('crypto');
8 const { promisify
} = require('util');
9 const randomBytesAsync
= promisify(randomBytes
);
10 const { Address4
, Address6
} = require('ip-address');
11 const dns
= require('dns');
12 const common
= require('./common');
13 const Enum
= require('./enum');
14 const { ValidationError
} = require('./errors');
15 const { fileScope
} = require('@squeep/log-helper');
17 const _fileScope
= fileScope(__filename
);
19 const noDotPathRE
= /(\/\.\/|\/\.\.\/)/;
20 const v6HostRE
= /\[[0-9a-f:]+\]/;
21 const loopback4
= new Address4('127.0.0.0/8');
22 const scopeSplitRE
= / +/;
23 const utf8CharsetRE
= /utf-*8/i;
27 * @param {Console} logger
28 * @param {Object} options
29 * @param {Number=} options.timeout
30 * @param {Object=} options.userAgent
31 * @param {String=} options.userAgent.product
32 * @param {String=} options.userAgent.version
33 * @param {String=} options.userAgent.implementation
35 constructor(logger
, options
= {}) {
37 this.options
= options
;
39 this._defaultAccept
= options
?.defaultAccept
|| 'text/html, text/*;q=0.9, application/xhtml+xml;q=0.8, application/xml;q=0.8, */*;q=0.1';
40 this._jsonAccept
= options
?.jsonAccept
|| [Enum
.ContentType
.ApplicationJson
, Enum
.ContentType
.Any
+ ';q=0.1'].join(', ');
43 this.got
= this._init
; // Do the dynamic import on first attempt to use client.
48 * Do a little dance to support this ESM client.
50 async
_init(...args
) {
52 // For some reason eslint is confused about import being supported here.
53 // eslint-disable-next-line
54 this.Got
= await
import('got');
55 this.got
= this.Got
.got
.extend({
57 [Enum
.Header
.UserAgent
]: Communication
._userAgentString(this.options
.userAgent
),
58 [Enum
.Header
.Accept
]: this._defaultAccept
,
61 request: this.options
.timeout
|| 120000,
65 this._onRetry
.bind(this),
71 return this.got(...args
);
77 * Take notes on transient retries.
79 * @param {*} retryCount
81 _onRetry(error
, retryCount
) {
82 const _scope
= _fileScope('_onRetry');
83 this.logger
.debug(_scope
, 'retry', { retryCount
, error
});
88 * Encode hashed verifier data for PKCE.
89 * @param {BinaryLike} verifier
92 static _challengeFromVerifier(verifier
) {
93 const hash
= createHash('sha256');
94 hash
.update(verifier
);
95 return hash
.digest('base64url');
101 * @property {String} codeChallengeMethod
102 * @property {String} codeVerifier
103 * @property {String} codeChallenge
106 * Create a code verifier and its challenge.
107 * @param {Number} length of verifier string, between 43 and 128
108 * @returns {Promise<PKCEData>}
110 static async
generatePKCE(length
= 128) {
111 if (length
< 43 || length
> 128) {
112 throw new RangeError('InvalidLength');
115 const bufferLength
= Math
.floor(length
* 3 / 4);
116 const randomBuffer
= await
randomBytesAsync(bufferLength
);
117 const verifier
= randomBuffer
.toString('base64url');
119 const challenge
= Communication
._challengeFromVerifier(verifier
);
122 codeChallengeMethod: 'S256',
123 codeVerifier: verifier
,
124 codeChallenge: challenge
,
130 * Check a challenge with a verifier.
131 * @param {String} codeChallenge
132 * @param {String} codeVerifier
133 * @param {String} codeChallengeMethod
136 static verifyChallenge(codeChallenge
, codeVerifier
, codeChallengeMethod
) {
137 switch (codeChallengeMethod
) {
140 const challenge
= Communication
._challengeFromVerifier(codeVerifier
);
141 return challenge
=== codeChallenge
;
145 throw new Error('unsupported challenge method');
151 * Assemble a suitable User-Agent value.
152 * @param {Object} userAgentConfig
153 * @param {String=} userAgentConfig.product
154 * @param {String=} userAgentConfig.version
155 * @param {String=} userAgentConfig.implementation
158 static _userAgentString(userAgentConfig
) {
159 // eslint-disable-next-line security/detect-object-injection
160 const _conf
= (field
, def
) => (userAgentConfig
&& field
in userAgentConfig
) ? userAgentConfig
[field
] : def
;
161 const product
= _conf('product', packageName
).split('/').pop();
162 const version
= _conf('version', packageVersion
);
163 let implementation
= _conf('implementation', Enum
.Specification
);
164 if (implementation
) {
165 implementation
= ` (${implementation})`;
167 return `${product}/${version}${implementation}`;
172 * Isolate the base of a url.
173 * mf2 parser needs this so that relative links can be made absolute.
174 * @param {URL} urlObj
177 static _baseUrlString(urlObj
) {
178 const baseUrl
= new URL(urlObj
);
179 const lastSlashIdx
= baseUrl
.pathname
.lastIndexOf('/');
180 if (lastSlashIdx
> 0) {
181 baseUrl
.pathname
= baseUrl
.pathname
.slice(0, lastSlashIdx
+ 1);
188 * Convert a Content-Type string to normalized components.
190 * N.B. this ill-named non-parsing implementation will not work
191 * if a parameter value for some reason includes a ; or = within
193 * @param {String} contentTypeHeader
194 * @returns {Object} contentType
195 * @returns {String} contentType.mediaType
196 * @returns {Object} contentType.params
198 static _parseContentType(contentTypeHeader
, defaultContentType
= Enum
.ContentType
.ApplicationOctetStream
) {
199 const [ mediaType
, ...params
] = (contentTypeHeader
|| '').split(/ *; */
);
201 mediaType: mediaType
.toLowerCase() || defaultContentType
,
202 params: params
.reduce((obj
, param
) => {
203 const [field
, value
] = param
.split('=');
204 const isQuoted
= value
?.startsWith('"') && value
?.endsWith('"');
205 obj
[field
.toLowerCase()] = isQuoted
? value
.slice(1, value
.length
- 1) : value
;
213 * Parse and add any header link relations from response to microformat data.
214 * @param {Object} microformat
215 * @param {Object} response
216 * @param {Object} response.headers
218 _mergeLinkHeader(microformat
, response
) {
219 const _scope
= _fileScope('_mergeLinkHeader');
221 // Establish that microformat has expected structure
222 ['rels', 'rel-urls'].forEach((p
) => {
223 if (!(p
in microformat
)) {
224 microformat
[p
] = {}; // eslint-disable-line security/detect-object-injection
227 if (!('items' in microformat
)) {
228 microformat
.items
= [];
231 const linkHeader
= response
.headers
[Enum
.Header
.Link
.toLowerCase()];
235 links
.push(...parseLinkHeader(linkHeader
));
237 this.logger
.error(_scope
, 'failed to parse link header', { error: e
, linkHeader
});
242 // Push header link rels into microformat form.
243 // Inserted at front of lists, as headers take precedence.
244 links
.forEach((link
) => {
245 link
.attributes
.forEach((attr
) => {
246 if (attr
.name
=== 'rel') {
247 if (!(attr
.value
in microformat
.rels
)) {
248 microformat
.rels
[attr
.value
] = [];
250 microformat
.rels
[attr
.value
].unshift(link
.target
);
252 if (!(link
.target
in microformat
['rel-urls'])) {
253 microformat
['rel-urls'][link
.target
] = {
258 microformat
['rel-urls'][link
.target
].rels
.unshift(attr
.value
);
266 * Retrieve and parse microformat data from url.
267 * N.B. this absorbs any errors!
268 * @param {URL} urlObj
269 * @returns {Promise<Object>}
271 async
fetchMicroformat(urlObj
) {
272 const _scope
= _fileScope('fetchMicroformat');
273 const logInfoData
= {
275 microformat: undefined,
280 const fetchMicroformatConfig
= {
283 responseType: 'buffer',
285 response
= await
this.got(fetchMicroformatConfig
);
287 this.logger
.error(_scope
, 'microformat request failed', { error: e
, ...logInfoData
});
290 logInfoData
.response
= common
.gotResponseLogData(response
);
292 // Normalize to utf8.
294 const contentType
= Communication
._parseContentType(response
.headers
[Enum
.Header
.ContentType
.toLowerCase()]);
295 // If a charset was specified, and it's not utf8ish, attempt to transliterate it to utf8.
296 const nonUTF8Charset
= !utf8CharsetRE
.test(contentType
.params
.charset
) && contentType
.params
.charset
;
297 if (nonUTF8Charset
) {
299 const iconv
= new Iconv(nonUTF8Charset
, 'utf-8//translit//ignore');
300 body
= iconv
.convert(response
.body
).toString('utf8');
302 // istanbul ignore next
303 this.logger
.error(_scope
, 'iconv conversion error', { error: e
, ...logInfoData
});
304 // Try to carry on, maybe the encoding will work anyhow...
307 body
= response
.body
.toString('utf8');
310 let microformat
= {};
312 microformat
= mf2(body
, {
313 baseUrl: Communication
._baseUrlString(urlObj
),
316 this.logger
.error(_scope
, 'failed to parse microformat data', { error: e
, ...logInfoData
});
317 // Try to carry on, maybe there are link headers...
320 this._mergeLinkHeader(microformat
, response
);
322 logInfoData
.microformat
= microformat
;
324 this.logger
.debug(_scope
, 'parsed microformat data', logInfoData
);
330 * Retrieve and parse JSON.
331 * N.B. this absorbs any errors!
332 * @param {URL} urlObj
333 * @returns {Promise<Object>}
335 async
fetchJSON(urlObj
) {
336 const _scope
= _fileScope('fetchJSON');
337 const logInfoData
= {
343 const fetchJSONConfig
= {
347 [Enum
.Header
.Accept
]: this._jsonAccept
,
349 responseType: 'json',
351 response
= await
this.got(fetchJSONConfig
);
353 this.logger
.error(_scope
, 'json request failed', { error: e
, ...logInfoData
});
357 return response
.body
;
362 * Validate a url has a specific schema.
363 * @param {URL} urlObj
364 * @param {String[]} validSchemes
366 static _urlValidScheme(urlObj
, validSchemes
= ['http:', 'https:']) {
367 if (!validSchemes
.includes(urlObj
.protocol
)) {
368 throw new ValidationError(`unsupported url scheme '${urlObj.protocol}'`);
374 * Validate a url does not include some components.
375 * @param {URL} urlObj
376 * @param {String[]} disallowed
378 static _urlPartsDisallowed(urlObj
, disallowed
) {
379 disallowed
.forEach((part
) => {
380 if (urlObj
[part
]) { // eslint-disable-line security/detect-object-injection
381 throw new ValidationError(`url cannot contain ${common.properURLComponentName(part)}`);
388 * Validate a url does not have relative path.
389 * @param {String} url
391 static _urlPathNoDots(url
) {
392 if (noDotPathRE
.test(url
)) {
393 throw new ValidationError('relative path segment not valid');
399 * Validate a url does not have a hostname which is an ip address.
400 * N.B. Sets isLoopback on urlObj
401 * @param {URL} urlObj
402 * @param {Boolean} allowLoopback
403 * @param {Boolean} resolveHostname
404 * @returns {Promise<void>}
406 static async
_urlNamedHost(urlObj
, allowLoopback
, resolveHostname
) {
408 if (v6HostRE
.test(urlObj
.hostname
)) {
410 * We do not need to worry about the Address6() failing to parse,
411 * as if it looks like an ipv6 addr but is not valid, the URL()
412 * call would already have failed.
414 address
= new Address6(urlObj
.hostname
.slice(1, urlObj
.hostname
.length
- 1));
415 /* succeeded parsing as ipv6, reject unless loopback */
416 urlObj
.isLoopback
= address
.isLoopback();
419 address
= new Address4(urlObj
.hostname
);
420 /* succeeded parsing as ipv4, reject unless loopback */
421 urlObj
.isLoopback
= address
.isInSubnet(loopback4
);
423 /* did not parse as ip, carry on */
427 if (resolveHostname
&& !urlObj
.isLoopback
) {
429 * Resolve hostname to check for localhost.
430 * This is more complicated due to SSRF mitigation:
431 * If the hostname does not end with a ., we also resolve that,
432 * and complain if the two resolutions do not match, assuming
433 * malicious intent for the server to resolve a local record.
435 const hostnames
= [urlObj
.hostname
];
436 if (!urlObj
.hostname
.endsWith('.')) {
437 hostnames
.push(urlObj
.hostname
+ '.');
439 const settledResolutions
= await Promise
.allSettled(hostnames
.map((hostname
) => dns
.promises
.lookup(hostname
, {
443 // If any resolution failed, bail.
444 if (settledResolutions
445 .map((resolution
) => resolution
.status
)
446 .includes('rejected')) {
447 throw new ValidationError('could not resolve hostname');
450 // extract each resolution value, array of {address,family}
451 const resolutions
= settledResolutions
.map((resolution
) => resolution
.value
);
453 // If there were two resolutions, ensure they returned identical results.
454 if (resolutions
.length
> 1) {
455 // create set of addresses for each resolution
456 const addressSets
= resolutions
.map((addrs
) => {
457 return new Set((addrs
|| []).map((a
) => a
.address
));
459 const differences
= common
.setSymmetricDifference(...addressSets
);
460 if (differences
.size
) {
461 throw new ValidationError('inconsistent hostname resolution');
464 const resolvedHost
= resolutions
[0] || [];
466 // Persist the loopback state
467 urlObj
.isLoopback
= resolvedHost
.reduce((acc
, resolved
) => {
469 switch (resolved
.family
) {
471 addr
= new Address4(resolved
.address
);
472 return acc
|| addr
.isInSubnet(loopback4
);
474 addr
= new Address6(resolved
.address
);
475 return acc
|| addr
.isLoopback();
483 && (!urlObj
.isLoopback
|| !allowLoopback
)) {
484 throw new ValidationError('hostname cannot be IP');
490 * Ensure a url meets the requirements to be a profile uri.
491 * @param {String} url
492 * @param {Object} validationOptions
493 * @param {Boolean=} validationOptions.allowLoopback default is false, following spec
494 * @param {Boolean=} validationOptions.resolveHostname default is false, following spec
495 * @returns {Promise<URL>}
497 async
validateProfile(url
, validationOptions
) {
498 const _scope
= _fileScope('validateProfile');
499 const errorScope
= 'invalid profile url';
501 const options
= Object
.assign({
502 allowLoopback: false,
503 resolveHostname: false,
504 }, validationOptions
);
508 profile
= new URL(url
);
510 this.logger
.debug(_scope
, 'failed to parse url', { error: e
, url
});
511 throw new ValidationError(`${errorScope}: unparsable`);
513 profile
.isLoopback
= false;
516 Communication
._urlValidScheme(profile
);
517 Communication
._urlPartsDisallowed(profile
, ['hash', 'username', 'password', 'port']);
518 Communication
._urlPathNoDots(url
);
519 await Communication
._urlNamedHost(profile
, options
.allowLoopback
, options
.resolveHostname
);
521 this.logger
.debug(_scope
, 'profile url not valid', { url
, error: e
});
522 throw new ValidationError(`${errorScope}: ${e.message}`);
530 * Ensure a url meets the requirements to be a client identifier.
531 * Sets 'isLoopback' on returned URL object to true if hostname is - or resolves to - a loopback ip.
532 * @param {String} url
533 * @param {Object} validationOptions
534 * @param {Boolean=} validationOptions.allowLoopback default is true, following spec
535 * @param {Boolean=} validationOptions.resolveHostname default is true, following spec
536 * @returns {Promise<URL>}
538 async
validateClientIdentifier(url
, validationOptions
) {
539 const _scope
= _fileScope('validateClientIdentifier');
540 const errorScope
= 'invalid client identifier url';
542 const options
= Object
.assign({
544 resolveHostname: true,
545 }, validationOptions
);
549 clientId
= new URL(url
);
551 this.logger
.debug(_scope
, 'failed to parse url', { error: e
, url
});
552 throw new ValidationError('invalid client identifier url: unparsable');
554 clientId
.isLoopback
= false;
557 Communication
._urlValidScheme(clientId
);
558 Communication
._urlPartsDisallowed(clientId
, ['hash', 'username', 'password']);
559 Communication
._urlPathNoDots(url
);
560 await Communication
._urlNamedHost(clientId
, options
.allowLoopback
, options
.resolveHostname
);
562 this.logger
.debug(_scope
, 'client identifier url not valid', { url
, error: e
});
563 throw new ValidationError(`${errorScope}: ${e.message}`);
571 * @typedef {Object} ClientIdentifierData
572 * @property {Object} rels - keyed by relation to array of uris
573 * @property {HAppData[]} items
576 * Retrieve and parse client identifier endpoint data.
577 * N.B. Assumes urlObj has passed validateClientIdentifier.
578 * @param {URL} urlObj
579 * @returns {Promise<ClientIdentifierData|undefined>} mf2 data filtered for h-app items, or undefined if url could not be fetched
581 async
fetchClientIdentifier(urlObj
) {
582 const _scope
= _fileScope('fetchClientIdentifier');
584 // Loopback address will eschew client fetch, return empty data.
585 const isLoopbackResult
= {
590 // Set by validation method in case of loopback ip hostname
591 if (urlObj
.isLoopback
) {
592 return isLoopbackResult
;
595 const mfData
= await
this.fetchMicroformat(urlObj
);
600 // Only return h-app items with matching url field.
602 rels: mfData
.rels
|| {},
603 items: (mfData
.items
|| []).filter((item
) => {
604 let urlMatched
= false;
605 const itemType
= item
.type
|| [];
606 if ((itemType
.includes('h-app') || itemType
.includes('h-x-app'))
607 && (item
?.properties
?.url
)) {
608 item
.properties
.url
.forEach((url
) => {
610 const hUrl
= new URL(url
);
611 if (hUrl
.href
=== urlObj
.href
) {
624 * @typedef {Object} Metadata
625 * @property {String} issuer
626 * @property {String} authorizationEndpoint
627 * @property {String} tokenEndpoint
628 * @property {String} ticketEndpoint
629 * @property {String} introspectionEndpoint
630 * @property {String} introspectionEndpointAuthMethodsSupported
631 * @property {String} revocationEndpoint
632 * @property {String} revocationEndpointAuthMethodsSupported
633 * @property {String} scopesSupported
634 * @property {String} responseTypesSupported
635 * @property {String} grantTypesSupported
636 * @property {String} serviceDocumentation
637 * @property {String} codeChallengeMethodsSupported
638 * @property {String} authorizationResponseIssParameterSupported
639 * @property {String} userinfoEndpoint
642 * @typedef ProfileData
643 * @property {String} name
644 * @property {String} photo
645 * @property {String} url
646 * @property {String} email
647 * @property {String} authorizationEndpoint - deprecated, backwards compatibility for 20201126 spec
648 * @property {String} tokenEndpoint - deprecated, backwards compatibility for 20201126 spec
649 * @property {String} indieauthMetadata authorization server metadata endpoint
650 * @property {Metadata} metadata - authorization server metadata for profile
653 * Fetch the relevant microformat data from profile url h-card information,
654 * and authorization server metadata.
655 * N.B. Assumes urlObj has passed validateProfile
656 * @param {URL} urlObj
657 * @returns {Promise<ProfileData>} mf2 data filtered for select fields from h-card
659 async
fetchProfile(urlObj
) {
660 const _scope
= _fileScope('fetchProfile');
662 const mfData
= await
this.fetchMicroformat(urlObj
);
671 // Locate h-card mf2 items with url field matching profile url,
672 // and populate profile fields with first-encountered card values.
673 if (mfData
&& 'items' in mfData
) {
674 const hCards
= mfData
.items
.filter((item
) =>
675 item
?.type
?.includes('h-card') &&
676 item
.properties
&& item
.properties
.url
&& item
.properties
.url
.includes(urlObj
.href
));
677 hCards
.forEach((hCard
) => {
678 Object
.keys(profile
).forEach((key
) => {
679 if (!profile
[key
] && key
in hCard
.properties
) { // eslint-disable-line security/detect-object-injection
680 profile
[key
] = hCard
.properties
[key
][0]; // eslint-disable-line security/detect-object-injection
686 // Populate legacy mf2 fields from relation links.
687 // These will be overwritten if they also exist in server metadata.
689 authorizationEndpoint: 'authorization_endpoint', // backwards compatibility
690 tokenEndpoint: 'token_endpoint', // backwards compatibility
691 ticketEndpoint: 'ticket_endpoint', // backwards compatibility
692 }).forEach(([p
, r
]) => {
693 if (mfData
&& r
in mfData
.rels
) {
694 profile
.metadata
[p
] = profile
[p
] = mfData
.rels
[r
][0]; // eslint-disable-line security/detect-object-injection
698 // Set metadata field.
699 if (mfData
&& 'indieauth-metadata' in mfData
.rels
) {
700 profile
.indieauthMetadata
= mfData
.rels
['indieauth-metadata'][0];
703 // Attempt to populate metadata from authorization server.
704 if (profile
.indieauthMetadata
) {
707 mdURL
= new URL(profile
.indieauthMetadata
);
708 } catch (e
) /* istanbul ignore next */ {
709 this.logger
.error(_scope
, 'invalid authorization server metadata url', { profile
});
711 /* istanbul ignore else */
713 profile
.metadata
= await
this.fetchMetadata(mdURL
);
715 // Populate legacy profile fields.
716 ['authorizationEndpoint', 'tokenEndpoint', 'ticketEndpoint'].forEach((f
) => {
717 if (f
in profile
.metadata
) {
718 profile
[f
] = profile
.metadata
[f
]; // eslint-disable-line security/detect-object-injection
729 * Fetch the server metadata from an authorization server's metadata endpoint.
730 * @param {URL} metadataUrl
731 * @returns {Promise<Metadata>}
733 async
fetchMetadata(metadataUrl
) {
734 const metadataResponse
= await
this.fetchJSON(metadataUrl
);
736 if (metadataResponse
) {
737 // Map snake_case fields to camelCase.
740 authorizationEndpoint: 'authorization_endpoint',
741 tokenEndpoint: 'token_endpoint',
742 ticketEndpoint: 'ticket_endpoint',
743 introspectionEndpoint: 'introspection_endpoint',
744 introspectionEndpointAuthMethodsSupported: 'introspection_endpoint_auth_methods_supported',
745 revocationEndpoint: 'revocation_endpoint',
746 revocationEndpointAuthMethodsSupported: 'revocation_endpoint_auth_methods_supported',
747 scopesSupported: 'scopes_supported',
748 responseTypesSupported: 'response_types_supported',
749 grantTypesSupported: 'grant_types_supported',
750 serviceDocumentation: 'service_documentation',
751 codeChallengeMethodsSupported: 'code_challenge_methods_supported',
752 authorizationResponseIssParameterSupported: 'authorization_response_iss_parameter_supported',
753 userinfoEndpoint: 'userinfo_endpoint',
754 }).forEach(([c
, s
]) => {
755 if (s
in metadataResponse
) {
756 metadata
[c
] = metadataResponse
[s
]; // eslint-disable-line security/detect-object-injection
766 * POST to the auth endpoint, to redeem a code for a profile or token.
767 * N.B. this absorbs any errors!
768 * @param {URL} urlObj
769 * @param {String} code
770 * @param {String} codeVerifier
771 * @param {String} clientId
772 * @param {String} redirectURI
773 * @returns {Promise<Object>}
775 async
redeemCode(urlObj
, code
, codeVerifier
, clientId
, redirectURI
) {
776 const _scope
= _fileScope('redeemCode');
778 const postRedeemCodeConfig
= {
782 [Enum
.Header
.Accept
]: this._jsonAccept
,
785 'grant_type': 'authorization_code',
787 'client_id': clientId
,
788 'redirect_uri': redirectURI
,
789 'code_verifier': codeVerifier
,
791 responseType: 'json',
795 const response
= await
this.got(postRedeemCodeConfig
);
796 return response
.body
;
798 this.logger
.error(_scope
, 'redeem code request failed', { error: e
, url: urlObj
.href
});
805 * Deprecated method name alias.
807 * @param {URL} urlObj
808 * @param {String} code
809 * @param {Strin} codeVerifier
810 * @param {String} clientId
811 * @param {String} redirectURI
812 * @returns {Promise<Object>}
814 async
redeemProfileCode(urlObj
, code
, codeVerifier
, clientId
, redirectURI
) {
815 return this.redeemCode(urlObj
, code
, codeVerifier
, clientId
, redirectURI
);
820 * Verify a token with an IdP endpoint, using the Authorization header supplied.
821 * @param {URL} introspectionUrlObj
822 * @param {String} authorizationHeader
823 * @param {String} token
824 * @returns {Promise<Object>}
826 async
introspectToken(introspectionUrlObj
, authorizationHeader
, token
) {
827 const _scope
= _fileScope('introspectToken');
829 const postIntrospectConfig
= {
830 url: introspectionUrlObj
,
833 [Enum
.Header
.Authorization
]: authorizationHeader
,
834 [Enum
.Header
.Accept
]: this._jsonAccept
,
839 responseType: 'json',
843 const response
= await
this.got(postIntrospectConfig
);
855 if (![true, false].includes(active
)) {
856 throw new RangeError('missing required response field "active"');
862 ...(clientId
&& { clientId
}),
863 ...(scope
&& { scope: scope
.split(scopeSplitRE
) }),
864 ...(exp
&& { exp: Number(exp
) }),
865 ...(iat
&& { iat: Number(iat
) }),
868 this.logger
.error(_scope
, 'failed to parse json', { error: e
, response: common
.gotResponseLogData(response
) });
872 this.logger
.error(_scope
, 'introspect token request failed', { error: e
, url: introspectionUrlObj
.href
});
879 * Attempt to deliver a ticket to an endpoint.
880 * N.B. does not absorb errors
881 * @param {URL} ticketEndpointUrlObj
882 * @param {URL} resourceUrlObj
883 * @param {URL} subjectUrlObj
884 * @param {URL=} issuerUrlObj
885 * @param {String} ticket
886 * @returns {Promise<Response>}
888 async
deliverTicket(ticketEndpointUrlObj
, resourceUrlObj
, subjectUrlObj
, ticket
, issuerUrlObj
) {
889 const _scope
= _fileScope('deliverTicket');
892 const ticketConfig
= {
894 url: ticketEndpointUrlObj
,
897 resource: resourceUrlObj
.href
,
898 subject: subjectUrlObj
.href
,
899 ...( issuerUrlObj
&& { iss: issuerUrlObj
.href
}),
902 const result
= await
this.got(ticketConfig
);
903 this.logger
.debug(_scope
, 'success', { ...common
.gotResponseLogData(result
) });
906 this.logger
.error(_scope
, 'ticket delivery request failed', { error: e
, url: ticketEndpointUrlObj
.href
});
913 * Attempt to fetch some link relations from a url.
914 * @param {URL} urlObj
915 * @returns {Promise<Object>}
917 async
_fetchMetadataOrTokenEndpoint(urlObj
) {
918 const _scope
= _fileScope('_fetchMetadataOrTokenEndpoint');
920 let metadataUrl
, tokenUrl
;
922 const mfData
= await
this.fetchMicroformat(urlObj
);
923 const metadataRel
= mfData
?.rels
?.['indieauth-metadata']?.[0];
926 metadataUrl
= new URL(metadataRel
);
928 this.logger
.debug(_scope
, 'invalid metadata rel url', { url: urlObj
.href
, metadataRel
});
932 // no metadata rel, try old-style token endpoint
933 const tokenRel
= mfData
?.rels
?.['token_endpoint']?.[0];
936 tokenUrl
= new URL(tokenRel
);
938 this.logger
.debug(_scope
, 'invalid token rel url', { url: urlObj
.href
, tokenRel
});
943 return { metadataUrl
, tokenUrl
};
948 * Attempt to redeem a ticket for a token.
949 * N.B. does not absorb errors
950 * @property {String} ticket
951 * @property {URL} resourceUrlObj
952 * @property {URL=} issuerUrlObj
953 * @returns {Promise<Object>} response body
955 async
redeemTicket(ticket
, resourceUrlObj
, issuerUrlObj
) {
956 const _scope
= _fileScope('redeemTicket');
958 let metadataUrl
, tokenUrl
;
959 // Attempt to determine metadata or token endpoint from issuer MF data
961 ({ metadataUrl
, tokenUrl
} = await
this._fetchMetadataOrTokenEndpoint(issuerUrlObj
));
964 // Fallback to resource MF data
965 if (!metadataUrl
&& !tokenUrl
) {
966 ({ metadataUrl
, tokenUrl
} = await
this._fetchMetadataOrTokenEndpoint(resourceUrlObj
));
970 const metadata
= await
this.fetchMetadata(metadataUrl
);
972 tokenUrl
= new URL(metadata
?.tokenEndpoint
);
974 this.logger
.debug(_scope
, 'invalid token endpoint url from metadata', { resourceUrl: resourceUrlObj
.href
, issuerUrl: issuerUrlObj
.href
, tokenEndpoint: metadata
?.tokenEndpoint
});
979 throw new ValidationError('could not determine endpoint for ticket redemption');
982 const postRedeemTicketConfig
= {
986 [Enum
.Header
.Accept
]: this._jsonAccept
,
989 'grant_type': 'ticket',
992 responseType: 'json',
996 const response
= await
this.got(postRedeemTicketConfig
);
997 return response
.body
;
999 this.logger
.error(_scope
, 'ticket redemption failed', { error: e
, resource: resourceUrlObj
.href
, issuer: issuerUrlObj
?.href
});
1005 module
.exports
= Communication
;