Account #
On this page
The Account package gives your application's end users their own accounts, which are not Turn Zero accounts. You do not build identity infrastructure yourself. It covers account creation, sign-in, sign-out, sessions that last across visits, and access recovery. When your manifest declares the accounts service, the platform creates one end-user realm, the list of an environment's end users, for each environment your application has. An application with one environment has one realm, production's, and your testers sign in there, also during a local run. With a development environment added, a sign-in to the development realm never reaches production's users.
To use it, add {"kind": "accounts"} to the manifest's services and submit the manifest with submit_manifest. Your backend then uses the package's client, described in The client, to tell which user sent each request. Tell which user sent a request shows how.
To send a person back to the page they came from after signing in, see Choose where sign-in returns.
At a glance:
- Install: run
turnzero library take --entry account(turnzero.cmdin Windows PowerShell) at the project's root. Use the library shows the dependency and manifest entries the command writes. Then put the copy in a deploy. - Manifest: add
{"kind": "accounts"}toservices. - Settings your server reads:
TURNZERO_CLOUD_API,TURNZERO_CLOUD_APP_TOKEN, and, in a deployed copy,TURNZERO_CLOUD_REALM_KEYS. - Import:
import { makeVerifyClient } from '@turnzero/account'; - The client:
makeVerifyClient({ baseUrl, credential, realmKeys }), built once from the three settings, withrealmKeysleft out where its setting is unset or the route needs the user's email address (Construction and options). - The check:
client.verifySession(session, { sessionHeader })returns{ user }for a live session,{ anonymous: true }, or{ refused }(Methods and results). Tell which user sent a request has the whole server.
Use it when #
Use Account when your application must recognize a person across sessions, protect personal data, or tie records to one end user.
Do not add it only to remember a local preference or an anonymous device. Those needs do not justify an identity service.
What it provides #
- Account creation and sign-in.
- Sessions: creation, persistence, and sign-out.
- Access recovery.
- Verification of an end-user session from your application's backend, through the client described in The client.
- The end-user identity that other packages depend on.
- A test double,
createAccountDoubleat@turnzero/account/testing, which signs users in and out in memory behind the unchanged client. Test with the double shows it in use.
The package stores no per-account settings. Keep your application's preferences in the Database package. Manage end users covers the realm's settings, its passkeys and their notices, and its end-user actions.
Availability #
Version 0.23.3 is the package's current version, and this page describes it. Until the library's next publish, read_library can return an earlier version without every change described here. Use the version it returns. The entry includes the testing subpath. It also contains the compiled makeVerifyClient as @turnzero/account, the product statement and detailed contract, and the integration guide.
Related feature packages #
Verifying an end user explains how a backend verifies a session. Manage end users explains the realm's configuration and its end-user actions.
The client #
The package is published in the library as the npm package @turnzero/account, not on the npm registry; Use the library installs it with one line. Import makeVerifyClient from @turnzero/account. Install @types/node if your application type-checks against the client's declarations, because they import Node's built-in modules. Tell which user sent a request shows the client in a complete server, from an incoming request to the user's id. Verifying an end user explains the session token the client checks.
Construction and options #
The function makeVerifyClient(options) returns a client. Build it once and keep it, because each client has a cache of its own.
Pass realmKeys where the route needs only the user's id. Leave it out where the route needs the user's email address, sign-in methods, or standing, because a session verified with keys has none of them.
Leave it out too for a route that needs both the id and the email address on every request, because the verification route's response includes both. Each verification then has no per-request charge, and the client reuses a verdict for up to cacheSeconds.
| Option | Default | Meaning |
|---|---|---|
baseUrl |
Required | The platform's origin, from the setting TURNZERO_CLOUD_API. |
credential |
Required | The application's platform credential, from TURNZERO_CLOUD_APP_TOKEN, sent as the bearer on each verification. |
realmKeys |
None | The realm's public keys: the TURNZERO_CLOUD_REALM_KEYS string, or an array of { kid, publicKey }. A malformed value throws at construction. |
realm |
The realm of realmKeys |
The environment's realm, the one every token is checked against. |
cacheSeconds |
60 | The longest a verdict is reused; 0 turns reuse off. |
transport |
The global fetch |
The fetch-shaped function the client sends its requests through, such as the test double's transport. |
keyFetch |
The platform's key-set route | How the client reads the realm's current keys, when a token refers to a key the client does not have or its keys are an hour old. |
ownerAccount |
None | Your Turn Zero account's id, for verifyOwner. Read it through your own connection's read_account, as Methods and results explains. |
now |
Date.now |
The clock, in milliseconds, for tests. |
The two ways to build it:
- Local verification. For the user's id alone, build it with
realmKeysfromTURNZERO_CLOUD_REALM_KEYS, which every deploy, promote, and platform redeploy sets, and pass each request'sx-turnzero-cloud-sessionheader assessionHeader. The client checks the token in your process, and the router's header tells it whether the session ended. When the client accepts a session locally, the user it returns has emptyaddressesandroutes, because the token has neither. Tell which user sent a request shows a second client, built without keys, that reads the verified email. - The verification route. For the user's addresses, sign-in methods, or standing, build it without
realmKeys. It sends the session toPOST /accounts/v0/verifyunder the credential, and each verification has no per-request charge. In a local run of an application with one environment, the route accepts the development credential for production's realm. It checks a session a tester already has, and does not open a new one.
Methods and results #
Verify a session #
The verifySession(session, { sessionHeader }) method takes the session token the request sent. That is the value of the cookie __Host-turnzero_cloud_realm, or the token after Authorization: Bearer from a native app. A native app gets that token as the access_token of the realm's token endpoint, whose members Sign in from a native app lists. The client reads no header and no cookie itself.
Pass the request's x-turnzero-cloud-session header as sessionHeader; it contains the serving router's session verdict. Only a client configured with realm or realmKeys reads it. A client with neither ignores it and uses the verification route. An invalid header refuses the session immediately, even after a cached success. The router's session header describes both forms. verifySession returns a promise of one of three verdicts:
| Verdict | When |
|---|---|
{ user, verifiedAt, cacheUntil, sessionExpires } |
The session is live. Its user has id, realm, addresses, routes, and standing, active or suspended. |
{ anonymous: true } |
No session was passed. The client makes no request. |
{ refused, detail } |
The session was refused, and refused gives the reason. |
Each address is { email, verified }. A user who signed in only with a work account has, on the verification route, the address the company's tenant asserts, with source: "tenant". The optional xms_edov token claim indicates whether the email domain's owner has been verified. The address is verified: true only where that claim is true and no other account already has the address verified. Otherwise it is verified: false. Read verified before relying on the address.
Verify the application's owner #
verifyOwner is for a script or tool holding a Turn Zero token minted under your account. A web page never collects that credential.
The verifyOwner(bearer) method checks your application's owning account through read_account, returning { owner: { id } } on a match or { anonymous: true } without a bearer. Refusals are owner_not_configured without ownerAccount, or not_owner when the returned account differs. It also returns read_account's refusal name, such as authentication_required for a bad bearer, or http_<status> when the answer names none. It reads no session token. It needs no accounts service declared in the manifest, because it uses neither the verification route nor the realm's keys.
The check calls GET /api/v1/read_account at TURNZERO_CLOUD_API with Authorization: Bearer <token> and compares the answer's account.id with ownerAccount. See read_account for the exact request. It does not check which application a token was minted for.
To set ownerAccount, read account.id from read_account through your own Turn Zero connection. The platform supplies no environment variable for that id. Put it in a plain manifest setting, for example "OWNER_ACCOUNT": {"value": "<your account id>"} inside settings. The id is not secret. Your code reads process.env.OWNER_ACCOUNT and passes it as ownerAccount when building the client.
For verifyOwner, use a token minted for this application alone. An account-scoped token also works, but reaches every application in your account. A web page never collects either token.
Never pass it TURNZERO_CLOUD_APP_TOKEN: read_account identifies that credential as belonging to the application's owning account, so every caller would pass. A route for your own script or AI tool can use this check with OWNER_ACCOUNT. A route for your web page checks its session's verified email address instead, as Let only you reach an admin route shows.
Do not invent a shared admin key or password to get around an owner check.
Failures #
A refused verdict's refused is one of these:
- the verification route's reasons:
session_expired;session_ended, where no session matches the value or the token's key is gone;session_revoked, after a sign-out, a revocation, orrevoke_app_sign_in_keys;user_suspended; andsession_other_realm, a session of another realm; - on local verification, the token check's reason, one of
malformed,realm_mismatch,key_unknown,key_revoked,signature_invalid, andexpired, or the router header's, such asuser_revoked; http_<status>, where the route returns an error with no name, such as an outage's 503, andmalformed_answer, where it returns no user.
The client caches a verdict until the earliest of cacheSeconds, the route's cache_until, and the session's expiry. It caches a named refusal for ten seconds or until cache_until, and never caches an http_<status> refusal.
The client throws only at construction: if baseUrl is missing, or if realmKeys is malformed, names a different realm from realm, or supplies keys with no realm. A transport rejection, such as an unreachable network, also reaches the caller. The client sets no request timeout and does not retry.
Test with the double #
The test double replaces the accounts service behind the real client. Create it with await createAccountDouble() from @turnzero/account/testing. Build the client over the double's transport, realmKeys, and keyFetch, or call double.client() for the same client. The double's signIn(user) returns the user's session and the router's header for it. Its signOut, suspendUser, and revokeUser change the session's standing. Its headerFor(session) gives the router's header for the session's current standing. Set cacheSeconds: 0 where a test verifies one session twice, because the client reuses a verdict for up to a minute.
To test a route of your own, write it to take the client, and pass it account.client() in the test. The sample's last lines test a route that returns the user's id, with a signed-in session and with none. A test runs this sample over the double.
import assert from 'node:assert/strict';
import { makeVerifyClient } from '@turnzero/account';
import { createAccountDouble } from '@turnzero/account/testing';
const account = await createAccountDouble();
const client = makeVerifyClient({
baseUrl: account.baseUrl,
credential: account.credential,
realmKeys: account.realmKeys,
transport: account.transport,
keyFetch: account.keyFetch,
now: account.now,
cacheSeconds: 0,
});
const { session, header } = account.signIn({ id: 'user-1' });
const verdict = await client.verifySession(session, { sessionHeader: header });
assert.equal(verdict.user.id, 'user-1');
// After a sign-out, the router's header for the session says it ended.
account.signOut(session);
const ended = await client.verifySession(session, { sessionHeader: account.headerFor(session) });
assert.equal(ended.refused, 'session_revoked');
// Testing a route: the route takes the client, so the test hands it the double's.
async function me(request, accounts) {
const verdict = await accounts.verifySession(request.session, { sessionHeader: request.header });
return 'user' in verdict ? { status: 200, id: verdict.user.id } : { status: 401 };
}
const routeClient = account.client({ cacheSeconds: 0 });
const user2 = account.signIn({ id: 'user-2' });
assert.deepEqual(await me(user2, routeClient), { status: 200, id: 'user-2' });
assert.deepEqual(await me({}, routeClient), { status: 401 });
Run the tests with npm test or a bare node --test, not node --test with a folder (Test your application locally).
A server that builds its own client with no transport calls the global fetch. Replace that global with account.fetch in your test, and the server's calls reach the double.
A native app's request needs nothing new. Send the session as Authorization: Bearer <session>, as The account double and a native app's bearer says. The double has no token endpoint, no refresh, and no session list.
The double's signIn(user) also takes the user's addresses. A client built without realmKeys, such as account.client({ realmKeys: undefined }), returns them as given, including an address marked source: 'tenant'.
The client returns the refusals listed in Failures as { refused, detail }, and throws nothing. In a test, a refused session most often means the test signed no user in with signIn, used another realm, or passed a header that is not header or headerFor(session). Never sign a token yourself. These refusals come from the double itself:
| Refusal | Cause | Remedy |
|---|---|---|
authentication_required, not_owner |
The bearer differs from the double's credential, or the bearer passed to verifyOwner was not granted as 'owner'. |
Use double.client(), and pass grantBearer('owner') to verifyOwner. |
invalid_request, its detail starting The request holds a NUL character |
An accounts call's address contained a NUL character (U+0000), or its JSON body contained a NUL character or an unpaired UTF-16 surrogate. The double refuses it before it reads the credential, as the platform does. | Send the text without the character. |
TypeError from createAccountDouble |
The credential given is not a valid credential form. |
Leave the default credential. |
http_503 and the other http_ codes |
refuseNext scripted a bare status. |
Assert the code. |
is not a refusal the accounts service returns, no user <id> is signed in, no session exists |
A script or a state change named something the double does not have. | Use a refusal the double has, and sign the user in first. |
Calling the verification route directly #
If your backend does not use the package, it can call the verification route itself. The verification route explains when a backend needs it. This section gives the request and the response. For a complete server that calls this route with fetch and no package, see Without the Account package.
Send POST /accounts/v0/verify to the platform's origin, the value of TURNZERO_CLOUD_API, with these headers:
Authorization: Bearerfollowed by the application's platform credential, fromTURNZERO_CLOUD_APP_TOKEN.Content-Type: application/json.x-turnzero-cloud-environment,productionordevelopment, only under a credential that belongs to no environment, such as an account-wide credential or a minted token. The body memberenvironmentcan name it instead.
The body is a JSON object whose session member is the session token the request sent. That is the value of the cookie __Host-turnzero_cloud_realm, or the token after Bearer from a native app. Under an account-wide credential, the body can also name the application.
{ "session": "turnzero_cloud_usr_1.<payload>.<signature>" }
A live session returns status 200 and a JSON object with these members:
contract_version:1.user: the end user, withid, the opaque identifier,realm,addresses,routes, andstanding,active. Each address is{ email, verified }, and a work-account address also hassource: "tenant".routeslists the sign-in methods the user has.verified_at: when the route checked the session.cache_until: 60 seconds after the check, or the session's expiry where that comes first. Reuse the answer no later than this.session_expires: the session's expiry.
A refusal returns a JSON object with contract_version, error, and detail. A refusal of the session itself also has cache_until, ten seconds ahead: hold the refusal until then.
| Refusal | Status | Meaning |
|---|---|---|
invalid_request |
400 | The body has no session, or its value does not begin turnzero_cloud_usr_, or the body contains a NUL character or an unpaired surrogate. |
authentication_required |
401 | No credential was presented, or it matches none. |
session_ended |
401 | No session matches the value, the token fails under the realm's keys, or the user no longer exists. |
session_revoked |
401 | The session was signed out or revoked, or revoke_app_sign_in_keys revoked the key that signed the token. |
session_expired |
401 | The session is past its life. |
user_suspended |
403 | The end user is suspended. |
session_other_realm |
403 | The session belongs to another realm, whether it is live, signed out, or expired. |
end_user_credential_not_admitted |
403 | The bearer is an end user's session. It belongs in the body. |
transfer_grant_not_admitted, secret_grant_not_admitted, egress_key_not_admitted |
403 | The bearer is a transfer grant, a secret grant, or an egress key. |
environment_required |
400 | A credential that belongs to no environment named none, or named a value other than production or development. |
environment_mismatch |
403 | The header and the body name different environments, or one other than the platform credential's own. |
environment_not_created |
409 | A credential that belongs to no environment named development on an application with one environment. |
session_other_account |
403 | The realm belongs to another account than the credential's. |
token_scope_refused |
403 | application names another application than the one the credential is bounded to. |
realm_not_declared |
404 | The application declares no accounts service. |
Before an accounts call runs, the platform checks its credential. That check can return 403 account_suspended or insufficient_scope, 429 rate_capped, or 503 store_unavailable. An unexpected failure returns 500 internal. The refusals page explains each name.