JavaScript SDK
The JavaScript account client is in javascript/auth.mjs in mesgd-sdk. Use it to enroll an account, obtain a session, and manage public keys independently of the PKI layer. The examples use an existing account named alice; passwords and authenticator codes come from the application rather than literals in source.
Support status
| Capability | Current support |
|---|---|
| Account operations | Available: signup, confirmation, login, reset, keys, key updates, and logout |
| HTTPS | Available: built-in verified HTTPS transport, covered by the live auth runner |
| WSS | Pending SDK message client; use the browser WebSocket API for JSON messages |
Completeness position: 6 of 18. Verified HTTPS and tested peer-key operations; PKI imports Node filesystem code, and no registration helper is provided. The language matrix explains the ranking criteria and comparable tiers. WSS readiness is listed separately; no SDK currently provides a complete, validated encrypted messaging workflow against this server.
Setup and transport
Use auth.mjs from Node.js or serve it as an ES module in a browser. The auth module uses fetch and does not load the Node-specific PKI library. Browser account requests should use the mesgd origin unless the deployment supplies cross-origin handling.
httpsTransport uses browser or Node fetch, rejects redirects, and applies a timeout. Configure the runtime's CA trust for a private certificate rather than disabling certificate checks.
A custom transport must serialize JSON, attach Authorization: Bearer TOKEN only when a token is supplied, verify the certificate and hostname, reject redirects, and use a finite timeout. Its origin is an HTTPS URL, such as https://mesgd.example.com, rather than a WebSocket URL.
Log in, read keys, and log out
Pass the current authenticator code as a six-digit string, preserving leading zeroes. This example reads the account's published keys and ends the session on its successful path. Applications that retain a session can keep the bearer until logout or expiry instead.
import { AuthClient, httpsTransport } from './auth.mjs';
export async function readKeys(password, otp) {
const client = new AuthClient(httpsTransport('https://mesgd.example.com'));
const session = await client.login('alice', password, otp);
try {
return (await client.keys(session.access_token)).public_keys;
} finally {
await client.logout(session.access_token);
}
}
Calls return promises for decoded JSON objects. Rejected HTTP requests throw AuthError with a status property. PKI operations are asynchronous and the provided pki.mjs imports Node's filesystem module; it cannot be imported unchanged into a browser.
Enroll a new account
The following fragment uses an existing client or transport from the example above. Signup returns a pending enrollment. Display qr_png_base64 or otpauth_uri, let the person configure the authenticator, then collect a code to confirm it. These calls are separate application steps, with user interaction between them.
const enrollment = await client.signup('alice', 'alice@example.com', password);
// Display enrollment.qr_png_base64 or enrollment.otpauth_uri before collecting the code.
const session = await client.confirm('alice', enrollment.enrollment_token, enrollmentOtp);
const recoveryCodes = session.recovery_codes;
Confirmation returns the first session and eight recovery codes. Display the recovery codes for separate safekeeping. A code accepted for confirmation cannot be reused for login or a key update; wait for a new authenticator step before another operation that consumes a code.
Account operations
| Operation | Function or method | HTTP endpoint |
|---|---|---|
| Create a pending account | signup | POST /auth/signup |
| Confirm authenticator enrollment | confirm | POST /auth/signup/confirm |
| Log in | login | POST /auth/login |
| Reset a forgotten password | resetPassword | POST /auth/password/reset |
| Read account public keys | keys | GET /auth/keys |
| Replace account public keys | setKeys | PUT /auth/keys |
| End the current session | logout | POST /auth/logout |
A key update takes the session token, current password, a fresh authenticator code, and an array containing only public JWKs. An empty array clears the linked keys. A password reset takes the username, a saved recovery code, a new password, and a fresh authenticator code; success replaces the recovery codes and revokes existing sessions without returning a new session.
The shared authentication reference documents argument order, response fields, and transport behavior. Session refresh is available through the HTTP API but is not wrapped by these seven SDK operations.
Local signing and encryption
This example exercises the local PKI implementation without opening a network connection. It signs a short message, verifies it with the same identity, and encrypts and decrypts it locally. It demonstrates the primitives rather than a complete peer-to-peer exchange.
import { webcrypto } from 'node:crypto';
import { PKI } from './pki.mjs';
globalThis.crypto ??= webcrypto;
await PKI.generate('pki_keys.json');
const signature = await PKI.sign('hello');
if (!await PKI.verify('hello', signature)) throw new Error('signature rejected');
const ciphertext = await PKI.encrypt('hello');
if (await PKI.decrypt(ciphertext) !== 'hello') throw new Error('round trip failed');
const publicKeys = await PKI.pubJwk();
generate creates a new identity and writes its private keys. Use init with an existing file to retain an identity between runs rather than generating a replacement each time.
For a different recipient, use that recipient's public encryption key rather than the local identity's encryption key. Public-key export and interoperability coverage vary by implementation; see Keys and Languages. Private key files are not account credentials and must not be sent to PUT /auth/keys.
Message connections
The Node ping/pong sample imports root-level pki.mjs and mesgd.mjs; this checkout stores PKI under javascript/pki.mjs and has no mesgd.mjs wrapper. Use the browser JSON example below independently of that sample.
Account login does not establish a message connection. The current server accepts JSON WebSocket frames and can authenticate an upgrade with a login session or an issued grant token. Login sessions carry identity without path restrictions; grants limit routing to assigned patterns. See WebSocket and Routing.
The encrypted registration handshake in the ping/pong samples is not implemented by the current mesgd listener. Treat those samples as experimental cryptographic examples, with compatibility limits described in Samples.
Browser JSON WebSocket example
The browser already provides the WSS transport. This example uses a live login session from AuthClient.login and sends the JSON format accepted by the current server. It does not use the encrypted registration handshake. Keep the session active while opening the connection; the earlier example explicitly logs it out.
const socket = new WebSocket(
'wss://mesgd.example.com/kind=chat/room=lobby',
['json', session.access_token]
);
socket.addEventListener('open', () => {
socket.send(JSON.stringify({kind: 'chat', room: 'lobby', text: 'hello'}));
});
socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
// Pass message to the application's handler.
});
A login session does not restrict the route to the user's grant assignments. Use an issued grant token when routing needs those restrictions, following the credential rules in Routing.
Validation
From the mesgd-sdk repository root, run the account contract suite for this language:
python3 tests/test_auth.py --language javascript
This is an offline request-contract check. Missing toolchains are reported as skips. See Languages for live HTTPS and PKI test coverage.