LifeCare.ID® Developer Docs Public

Recipes ✅

Task-oriented guides, copy, adapt, ship. Each is self-contained and links to the deeper reference. For full runnable apps, see the quickstarts.


Add LifeCare.ID® as a login option to an app that already has auth

Goal: offer LifeCare.ID® as one more login option in an app that already has its own users and sessions (the quickstart-app builds a new app from scratch, this drops sign-in into an existing one). Two small routes, no new framework.

Read this first, why you can't just add it as a generic OIDC provider (yet). LifeCare.ID® is OpenID-style today, not fully OIDC-compliant, so a stock provider config will not work. Three concrete differences to code around:

  1. No discovery document. There is no /.well-known/openid-configuration, so you set the two endpoints (/authorize, /token) by hand rather than from an issuer URL.
  2. The token endpoint takes JSON, not form-encoded. Most OIDC/OAuth libraries POST application/x-www-form-urlencoded to the token endpoint; ours expects application/json and will reject the default.
  3. Identity is a did, not an id_token. The token response carries the user's did directly (no id_token JWT, no /userinfo). You map that did to a user in your own store.

So wire it as the small custom flow below, not a library provider. (Native OIDC discovery, one-line config for any relying party, is on the roadmap.)

You need a client_id / client_secret and a registered redirect_uri, register one yourself in the sandbox; an operator provisions it for production.

Node / Express (the common case)

The whole flow is the standard authorization-code + PKCE handshake; only the token exchange and the identity mapping differ from a textbook OIDC provider.

import crypto from "node:crypto";

const BASE = process.env.LIFECAREID_BASE;                 // e.g. https://your-node.example/id
const CLIENT_ID = process.env.LIFECAREID_CLIENT_ID;
const CLIENT_SECRET = process.env.LIFECAREID_CLIENT_SECRET;
const REDIRECT_URI = process.env.LIFECAREID_REDIRECT_URI; // must be registered, exact match

const b64url = (b) => b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

// 1) Start sign-in: PKCE + redirect to /authorize.
app.get("/auth/lifecareid", (req, res) => {
  const verifier = b64url(crypto.randomBytes(32));
  const state = b64url(crypto.randomBytes(16));
  req.session.lc = { verifier, state };                   // bind to the user's session
  const q = new URLSearchParams({
    response_type: "code", client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, state,
    code_challenge: b64url(crypto.createHash("sha256").update(verifier).digest()),
    code_challenge_method: "S256",                         // plain is rejected
  });
  res.redirect(`${BASE}/authorize?${q}`);
});

// 2) Callback: exchange the code (server-side) and map the did to your user.
app.get("/auth/lifecareid/callback", async (req, res) => {
  const { code, state } = req.query;
  const saved = req.session.lc;
  if (!code || !saved || state !== saved.state) return res.status(400).send("bad callback");

  const r = await fetch(`${BASE}/token`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },      // JSON, not form-encoded
    body: JSON.stringify({
      grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI,
      client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code_verifier: saved.verifier,
    }),
  });
  if (!r.ok) return res.status(502).send("token exchange failed");
  const { did, access_token } = await r.json();           // identity is `did`; no id_token

  const user = await findOrCreateUserByLifecareDid(did);  // your existing user store
  req.session.userId = user.id;                           // your existing session
  req.session.lcSession = access_token;                   // optional: keep for the consent panel
  delete req.session.lc;
  res.redirect("/");
});

did (e.g. did:web:your-node.example:u:9f2a1c4d…) is the stable, portable user identifier, use it as the external id you link accounts on. Keep the returned access_token (lcs_…) only if you want to render the consent panel as that user later; it is a session token, not a data-access token.

NextAuth / Auth.js (v5)

A custom provider works if you override the token request (to send JSON) and synthesize the profile from the did (there is no userinfo endpoint). The request-override API shifts between Auth.js versions, adapt to yours:

const LifeCareID = {
  id: "lifecareid", name: "LifeCare.ID®", type: "oauth" as const,
  clientId: process.env.LIFECAREID_CLIENT_ID,
  clientSecret: process.env.LIFECAREID_CLIENT_SECRET,
  checks: ["pkce", "state"] as const,                      // Auth.js adds code_challenge + state
  authorization: { url: `${BASE}/authorize`, params: { response_type: "code" } },
  token: {
    url: `${BASE}/token`,
    async request({ params, checks, provider }) {
      const res = await fetch(provider.token.url, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          grant_type: "authorization_code", code: params.code,
          redirect_uri: provider.callbackUrl, client_id: provider.clientId,
          client_secret: provider.clientSecret, code_verifier: checks.code_verifier,
        }),
      });
      return { tokens: await res.json() };                 // { access_token, did, ... }
    },
  },
  userinfo: { async request({ tokens }) { return { sub: tokens.did }; } },
  profile(p) { return { id: p.sub }; },                    // map did -> your user
};

Passport / openid-client and other libraries

These assume discovery and a form-encoded, id_token-bearing token endpoint, so they fight the three differences above rather than help. Until native OIDC lands, prefer the two-route flow (it is what the runnable quickstart-app does, end to end), or, if you want a Passport Strategy, wrap those two routes rather than subclassing passport-oauth2.

Full handshake reference, error codes, and the security checklist: Authentication.


Add a "verify your node" badge

Goal: let your users check, in their own browser, what the node they talk to says it is running and whose key signed that statement.

Easiest, link the hosted verifier. Point users at the public page with the node pre-filled; it fetches the node's attestation and verifies it client-side:

<a href="https://lifecare.id/verify?node=https://your-node.example">Verify your node ↗</a>

Inline, verify it yourself with the zero-dependency library (same algorithm as the hosted page):

npm install @lifecareid/verify-attestation
import { fetchAndVerify } from "@lifecareid/verify-attestation";

const { verdict, attestation } = await fetchAndVerify("https://your-node.example", {
  registryUrl: "https://lifecare.id/v1/node-keys", // the keys LifeCare.ID® lists per node
});
badge.textContent =
  verdict === "verified-key-known"
    ? `✓ Verified, key known · running ${attestation.code_commit}`
    : verdict === "signature-valid-key-unknown"
      ? "Signature valid, key unknown"
      : "✗ Not verified";

"Verified, key known" means the claim recomputes, its signature is valid, and the key that signed it is the one the node's operator declared to LifeCare.ID®. A valid signature by an unlisted key may come from a different machine, so show it as a warning, never as the verified state. All of it is the software floor, not yet hardware-rooted. See Security & compliance.


Goal: give users a "Powered by LifeCare.ID®" data-rights screen, see grants, the access ledger, grant/revoke, without building consent UI yourself.

The panel API acts as the signed-in user: authenticate with the user's session token (lcs_… from the federation handshake) and you never pass a subject_did, it comes from the session, so a panel can only ever read or mutate its own user.

const headers = { Authorization: `Bearer ${sessionToken}` };

// what's granted + identity
const summary = await fetch(`${BASE}/v1/panel/summary`, { headers }).then(r => r.json());

// the access/consent feed (paginated, filterable by category)
const feed = await fetch(`${BASE}/v1/panel/feed?limit=20`, { headers }).then(r => r.json());

// revoke a grant (ownership-checked server-side)
await fetch(`${BASE}/v1/panel/revoke`, {
  method: "POST", headers: { ...headers, "Content-Type": "application/json" },
  body: JSON.stringify({ consent_id }),
});

Render those three calls and you have a complete data-rights panel. Full field reference: Embedding the consent panel.


Become a CGM data source

Goal: serve a user's CGM data to authorized requesters, directly, never through LifeCare.ID®, under their consent.

On each incoming request, introspect the presented lc_… token, as yourself (your own client credentials: introspection answers 401 to an anonymous caller, per RFC 7662 section 2.1), and enforce the claims before serving. Record the access before you answer, and introspect on every request so a revoked token stops at the next one:

import base64, json, urllib.request

def post(base, path, body, client_id, client_secret):
    basic = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    req = urllib.request.Request(f"{base}{path}", method="POST",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json",
                 "Authorization": f"Basic {basic}",    # your credential, not the caller's token
                 "User-Agent": "yoursource/1.0"})      # name your client: the edge refuses Python's default
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read() or b"{}")

MY_RESOURCE = "https://yoursource.example/cgm"     # the identifier your metadata publishes
ACCEPTED_CLIENTS = {"sbx_…"}                       # the clients whose tokens you serve

def refusal(info, requested_owner):
    """The status to refuse with, or None to serve."""
    if not info.get("active"):                         return 401  # invalid, expired or revoked
    if info.get("token_type") != "access":             return 403  # not a data-access token
    aud = info.get("aud")                              # present on a token from the authorization code flow
    if aud is not None and MY_RESOURCE not in ([aud] if isinstance(aud, str) else aud):
        return 401                                     # issued for another resource
    if info.get("requester") not in ACCEPTED_CLIENTS:  return 403  # wrong grantee
    if info.get("scope") != "cgm":                     return 403  # wrong scope
    if info.get("resource_owner") != requested_owner:  return 403  # not this user's data
    return None

# on every request, nothing cached:
info = post(BASE, "/v1/token/introspect", {"token": presented_token}, CLIENT_ID, CLIENT_SECRET)
status = refusal(info, requested_owner)
if status: return status                               # with the WWW-Authenticate challenge on a 401
post(BASE, "/v1/access/record", {"subject_did": requested_owner, "scope": "cgm",
     "purpose": info.get("purpose"), "accessor": "yoursource:cgm",
     "consent_id": info.get("consent_id")}, CLIENT_ID, CLIENT_SECRET)   # if this fails, serve nothing (503)
serve_cgm_directly(requested_owner)                    # data never touches LifeCare.ID®

resource_owner is the data owner the token authorizes, one introspection call gives you everything to authorize the request. Then record the access so it appears in the user's ledger. Full guide, including discovery (the metadata and the challenge a client follows): Data sources & connectors (developer access); the library's server half does all of it: Person-managed authorization. Runnable version: the kit's server example.


Handle revocation gracefully

Goal: treat revocation as a normal, expected state, not an error to retry-storm. Consent can be withdrawn at any instant; dependent tokens die in < 500 ms.

  1. On 403 / active: false, stop using the data. It's a valid outcome, not a bug. Don't retry the same token, re-request authorization only if the user acts.
const intro = await introspect(token);
if (!intro.active) {
  stopUsingData();          // clear caches, halt syncs for this grant
  return;                   // do NOT retry-storm
}
  1. Don't cache active results. Introspect on every request. A cached active lets a revoked token keep reading. For an agent, a 401 invalid_token within the token's life is the person's stop: drop the token and do not ask again by yourself.

  2. Use the revocation registry as a coarse, cacheable secondary check. Poll it and drop any token whose consent_id is listed:

const reg = await fetch(`${BASE}/v1/revocation/${userId}`).then(r => r.json());
if (reg.revoked_consents.includes(intro.consent_id)) stopUsingData();
  1. Degrade, don't fail loudly. Show the user that access ended and offer to reconnect, revocation is a feature of the system working, not an outage.

See Authorization & tokens → Revocation.