Skip to content
social-web-foundationPublic

About

Webfinger client library for Node.js

Resources

Code of conduct

Stars

44 stars

Watchers

11 watching

Forks

Latest commit

 

History

173 Commits

Folders and files

Repository files navigation

Webfinger

Webfinger client library for Node.js and browsers.

It supports RFC 7033.

Table of Contents

Security

This library does not provide protection against server-side request forgery (SSRF) out of the box. Its default transport is global fetch, which can connect to private or internal network addresses, including through redirects.

When discovering user-supplied addresses, use options.fetch to supply a transport that enforces your network policy, including checks on resolved IP addresses and redirect destinations. The example below shows how to supply an SSRF-protecting fetch implementation.

Install

For Node.js usage, requires Node.js 22.x, 24.x, or 26.x. For browser requirements and loading instructions, see Browser usage.

npm install webfinger

Dependencies

Unicode hostname decoding uses the browser-compatible punycode package's ES module entry point. The library is therefore not dependency-free. Account URI conversion is local and does not require a network lookup.

Usage

Import the named webfinger export and await discovery:

import { webfinger } from 'webfinger'

const jrd = await webfinger('user@example.com')
console.log(jrd.subject)
console.log(jrd.links)

See API for relation filtering, custom fetch functions, and JRD link selection. For user-supplied addresses, review Security.

Browser usage

The library uses native ES modules and the same promise-based webfinger() API in browsers. With a bundler, use the package import shown above. To load it through jsDelivr, use its ESM transformation endpoint with a pinned version so dependency imports are resolved:

<script type="module">
  import { webfinger } from 'https://cdn.jsdelivr.net/npm/webfinger@0.8.0/+esm'

  const jrd = await webfinger('user@example.com')
  console.log(jrd.subject)
  console.log(jrd.links)
</script>

Replace user@example.com with an account whose WebFinger endpoint allows requests from your site's origin. When serving the package's source files directly instead, provide an import map for bare package imports, including punycode/punycode.es6.js, or bundle the modules first.

Browsers must support ES modules, private class fields, fetch, URL, and URLSearchParams. Browser tests currently run in Chromium; Firefox and Safari have not been verified.

For cross-origin discovery, the remote WebFinger endpoint must return CORS headers allowing your site's origin, such as Access-Control-Allow-Origin. Without that permission, browser fetch cannot read the response and discovery rejects. Supplying options.fetch does not bypass browser CORS restrictions.

API

The webfinger() function returns a promise. Await the result; errors reject the promise. This replaces the previous callback API.

toAcctUri(address)

The named toAcctUri export synchronously converts an unescaped account address to an acct: URI string without making a network request. It works in Node.js and browsers.

The input must contain a nonempty username and hostname separated by @. The last @ is the separator; earlier @ characters belong to the username. The username is UTF-8 percent-encoded using encodeURIComponent(), and the hostname is converted to IDNA ASCII using the URL API.

Input Returned URI
user1@foo.example acct:user1@foo.example
josé@bücher.example acct:jos%C3%A9@xn--bcher-kva.example
some@name@foo.example acct:some%40name@foo.example
acct:user1@foo.example acct:acct%3Auser1@foo.example
https://foo.example/user@bar.example acct:https%3A%2F%2Ffoo.example%2Fuser@bar.example

All username text is treated literally, including URI prefixes and existing percent escapes. For example, user%40name@foo.example becomes acct:user%2540name@foo.example. Supply unescaped input; this function does not preserve or decode an existing acct: URI.

Empty strings, null, and other non-string inputs throw a TypeError. Missing separators, usernames, or hostnames throw an Error. Invalid hostnames that cannot be parsed by the URL constructor throw a TypeError.

fromAcctUri(uri)

The named fromAcctUri export synchronously converts an acct: URI to a readable account address string without making a network request. It works in Node.js and browsers.

The input must begin with the exact lowercase prefix acct: and contain a nonempty username and hostname separated by @. The last @ is the separator; earlier @ characters belong to the username. The username is percent-decoded using decodeURIComponent(), and Punycode hostname labels are converted to Unicode.

Input URI Returned address
acct:user1@foo.example user1@foo.example
acct:jos%C3%A9@xn--bcher-kva.example josé@bücher.example
acct:some%40name@foo.example some@name@foo.example
acct:user%2540name@foo.example user%40name@foo.example

Percent escapes in the username are decoded once. A literal + remains +. The hostname is not percent-decoded or parsed using the URL API; this function is a conversion helper rather than a complete account URI validator. Use toAcctUri() to encode an unescaped address in the other direction.

Empty strings, null, and other non-string inputs throw a TypeError. A missing or differently cased acct: prefix, or a missing separator, username, or hostname, throws an Error. Malformed percent escapes or invalid UTF-8 percent sequences in the username throw a URIError.

webfinger(address, options?)

Resolves to a JRD instance containing discovery data for address.

The address argument accepts an acct: URI, a bare account identifier such as user1@foo.example, or a URL with a hostname, such as an http: or https: URL.

By default, bare addresses and URI inputs are encoded before discovery. Both josé@bücher.example and acct:josé@bücher.example are looked up as acct:jos%C3%A9@xn--bcher-kva.example. Unicode URLs are serialized with percent-encoded paths and IDNA ASCII domains. To preserve an already encoded URI, pass options.encode: false; bare addresses are rejected in that mode. See options.encode for details.

The resource identifier is separately encoded for transport in the query string. For example, a % in an encoded acct: local part is sent as %25, so decoding the query yields the original encoded identifier. Empty strings, null, and other non-string inputs reject the promise with a TypeError.

Discovery requests https://<hostname>/.well-known/webfinger with the resource in the query string. The response must have status 200 and contain JSON. XRD conversion and host-meta/LRDD fallback are not supported.

The optional second argument is an object with encode, rel, and fetch properties. It defaults to {}. The previous positional rel argument and three-argument signature are no longer supported. Move the relation into options.rel and pass any custom fetch function in the same object.

options.encode

Controls encoding of the resource identifier. Defaults to true when the property is absent.

With encode: true:

  • Bare addresses with no URI scheme are converted using toAcctUri().
  • For acct: inputs, the prefix is retained, the local part is percent-encoded, and the domain is converted to IDNA ASCII. Local-part text is treated literally: existing % escapes are encoded again.
  • Other URI inputs are parsed and serialized using the URL API. For HTTP and HTTPS URLs, Unicode domains become IDNA ASCII and Unicode paths become UTF-8 percent escapes. Existing path escapes are preserved. Serialization also applies normal URL normalization, such as lowercasing the hostname.
Input with encoding enabled Resource identifier
josé@bücher.example acct:jos%C3%A9@xn--bcher-kva.example
acct:josé@bücher.example acct:jos%C3%A9@xn--bcher-kva.example
acct:jos%C3%A9@foo.example acct:jos%25C3%25A9@foo.example
http://bücher.example/profile/josé http://xn--bcher-kva.example/profile/jos%C3%A9

With encode: false, the input must be a URI. Its resource identifier is preserved exactly, including percent escapes; bare addresses reject the promise. Use this option for already encoded acct: URIs, or whenever you need to retain the original URI spelling.

In both modes, the identifier is encoded separately for query transport, and discovery uses HTTPS regardless of the resource's scheme. The native fetch transport handles IDNA conversion of the request hostname independently of this option.

If a bare username begins with scheme-like text such as acct: or https:, convert the complete address with toAcctUri() first, then pass the resulting URI to webfinger() with encode: false to avoid encoding its local part again.

options.rel

Supply a relation string or an array of relation strings to filter discovery results. An array sends repeated rel query parameters. Omitting rel, or passing undefined, null, an empty string, or an empty array, sends no relation filter.

const jrd = await webfinger('user1@foo.example', { rel: ['self', 'profile'] })

Servers may return additional links. Use the returned JRD's link() method or filter its links array to select the links you need.

options.fetch

Supply a custom fetch function for the discovery request. When the fetch property is absent, the module uses global fetch.

The function receives the discovery URL and a request-options object containing the Accept header. It should return a promise for a fetch-compatible response with a numeric status and an asynchronous json() method. The response must have status 200; its JSON is parsed into the returned JRD.

const jrd = await webfinger('user1@foo.example', { fetch: customFetch })

To also filter by relation, include rel in the same options object. Supply a callable function. Explicit values such as undefined or null do not select the default and cause the lookup to reject. If you pass an object method that depends on this, bind it to its instance first. Errors from the custom fetch function reject the lookup promise.

For example, after installing the optional guarded-fetch package in your application, you can supply its fetch-compatible function:

import { guardedFetch } from 'guarded-fetch'
import { webfinger } from 'webfinger'

const jrd = await webfinger('user@example.com', {
  fetch: guardedFetch
})
console.log(jrd.subject)

guarded-fetch checks destination IP addresses and redirects to help prevent SSRF. This is an integration example; guarded-fetch is not a dependency of this library. Its bare guardedFetch function does not limit response-body size; consult its documentation when choosing resource limits for your application.

The former httpsOnly and webfingerOnly options have no effect.

JRD

JRD represents a JSON Resource Descriptor returned by webfinger(). Obtain instances by awaiting webfinger(); the class is internal and is not exported for direct construction.

The class provides synchronous access to the document and its links. Reading its properties or selecting a link does not make a network request.

In general, malformed or mistyped response properties are ignored and filtered out. Missing or invalid top-level fields retain their defaults: subject is undefined, aliases and links are empty arrays, and properties is an empty object. A JSON response of null or another non-object value, including an array, produces an empty JRD.

Link titles and properties must be non-null, non-array objects. Invalid values are omitted, so reading those fields returns undefined; the rest of the link remains available. This handling applies to parsed response data. Network errors, non-200 responses, and invalid JSON syntax still reject the lookup promise.

Properties

All four properties are getter-only:

  • subject: the subject identifier from the document, or undefined when absent or mistyped.
  • aliases: a frozen array of alternative identifiers, defaulting to an empty array when absent or mistyped. Access an individual alias with jrd.aliases[i].
  • properties: a frozen object mapping property URI keys to string or null values, defaulting to an empty object when the field is absent or mistyped. Explicit null values within a valid properties object are preserved.
  • links: a frozen array of link objects in document order, defaulting to an empty array when absent or mistyped. Each link object and its titles and properties objects, when present and valid, are also frozen. Links retain server-supplied fields except metadata filtered out by validation.

The collections and standard link metadata are read-only. Attempting to change frozen contents or assign to these getter-only properties throws a TypeError in strict mode.

link(rel, type?)

Selects a link from the returned document by relation and, optionally, media type. This is local selection, independent of options.rel passed to webfinger() during discovery.

Returns the first link in document order whose rel exactly matches the requested relation and whose media type satisfies the optional filter:

  • Omit type or pass null to accept any media type, including a missing type.
  • Pass a nonempty string to require an exact type match.
  • Pass an array of strings to accept any listed type. Array order does not establish a preference; document order determines the first match.
  • Pass an empty array to match nothing.

Media type matching compares the complete string, including any parameters; it does not normalize media types.

The result is the same frozen link object exposed in links. Read its href property for the target URI. No match returns undefined. Callers needing multiple matches can filter the links array.

Example: finding an ActivityPub actor

With webfinger imported from this package, use the following expression inside an async function to find an account's ActivityPub actor URI:

(await webfinger('user1@foo.example')).link('self', ['application/activity+json', 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"'])?.href

This returns the first matching link's href, or undefined if no matching link has a target URI. Discovery errors still reject the promise.

Contributing

Questions, bug reports, and pull requests are welcome through the GitHub repository. Use the issue tracker for questions and bugs. Please follow the Code of Conduct and run lint and tests before submitting a pull request.

Testing

Use Node.js 22, 24, or 26 to run the tests with the built-in Node Test Runner. Nock intercepts HTTP and HTTPS requests; the tests call the real webfinger() function. No servers, certificates, network access, or elevated privileges are needed.

npm ci
npm run lint
npm test

Run the browser tests in headless Chromium with Playwright:

npx playwright install chromium
npm run test:browser

The browser tests import the library as a native ES module and exercise browser fetch with intercepted responses, including cross-origin discovery with CORS headers and repeated relation parameters. Installing Chromium requires network access; the tests themselves do not contact external services. CI runs both the Node.js and browser suites before publishing.

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

See LICENSE.md for the full license text.

About

Webfinger client library for Node.js

Resources

Code of conduct

Stars

44 stars

Watchers

11 watching

Forks

Releases

Packages

Used by

Contributors

Languages