Skip to main content

Who Signed In, in Your Code

On every request, the platform hands the application the identity of who signed in, signed. The SDK — TypeScript, Python or Java — checks it and returns the person. In another language, the check is the same and is described below.

TypeScript and Node​

Installing the SDK​

The @nnumbers/zero package is not in any registry: npm install @nnumbers/zero fails, because the name does not resolve. The SDK is distributed as a file, from the website — download it, check the checksum and install from the file:

curl -fsSLO https://zero.nnumbers.com.br/downloads/zero-sdk-typescript.tgz
curl -fsSLO https://zero.nnumbers.com.br/downloads/SHA256SUMS
shasum -a 256 -c SHA256SUMS --ignore-missing # on Linux, sha256sum -c

npm install ./zero-sdk-typescript.tgz

npm install records the dependency in package.json pointing to the file — "@nnumbers/zero": "file:./zero-sdk-typescript.tgz" —, and that is the path the build reads later. So commit the .tgz to the application's repository.

The platform does not inject the SDK

Zero does not put @nnumbers/zero into your application: there is no preinstalled package, no variable pointing to it and no import that works without the declared dependency. The build clones the project source's repository and builds from its Dockerfile — what is not committed does not exist in there. A file: pointing outside the repository works on your machine and fails in the build with ENOENT.

Reading who signed in​

import { NNumbers, UnauthenticatedError } from '@nnumbers/zero/app'

const nn = NNumbers.init() // reads the NNUMBERS_* variables

app.get('/api/me', async (req, res) => {
res.json({ user: await nn.auth.user(req) }) // the person, or null
})

app.get('/dashboard', async (req, res) => {
try {
const user = await nn.auth.requireUser(req, req.url)
res.send(`Hello, ${user.name ?? user.username}`)
} catch (e) {
if (e instanceof UnauthenticatedError) return res.redirect(e.loginPath)
throw e
}
})
APIWhat it does
NNumbers.init()the application context: appId, org, auth and querymesh
nn.auth.user(req)who signed in, or null
nn.auth.requireUser(req, returnTo)like user, but without a person it throws UnauthenticatedError with the loginPath that returns to returnTo
nn.auth.loginPath(returnTo)the sign-in path; a destination outside the application becomes /
nn.auth.logoutPaththe sign-out path (POST); it ends the session only in this application
nn.auth.sessionPaththe path of the session state, for the browser
ErrorCodeWhen
AppConfigurationErrorORGANIZATION_IAM_NOT_ENABLEDthe application runs without the capability on, or outside Zero
UnauthenticatedErrorUSER_SESSION_REQUIREDthe route requires someone and no one signed in
IdentityAssertionErrorIDENTITY_ASSERTION_INVALIDan identity arrived that does not check out — it never becomes a person

user accepts the Node request, a fetch Request or a headers object. There is a complete example, without a framework, in examples/organization-iam in the SDK repository. Its interface uses the components below, rendered on the server: the sign-in button, the UserMenu, the panel with name and email, "Testar QueryMesh" (test QueryMesh) and "Sair" (sign out).

In the Interface, with React​

The components and hooks of @nnumbers/zero/react work with React 18 or 19. They read the session the platform keeps and lead to the sign-in and sign-out paths:

import { NNumbersProvider, Authenticated, Unauthenticated, LoginButton, UserMenu, useUser, useOrganization } from '@nnumbers/zero/react'

export function App() {
return (
<NNumbersProvider>
<header>
<UserMenu />
</header>
<Authenticated fallback={<LoginButton>Sign in with your organization</LoginButton>}>
<Dashboard />
</Authenticated>
<Unauthenticated>
<p>Sign in with your organization account.</p>
</Unauthenticated>
</NNumbersProvider>
)
}

function Dashboard() {
const user = useUser() // who signed in; null if no one; undefined while loading
const org = useOrganization() // { id, slug }
return <p>Hello, {user?.name} — {org?.slug}</p>
}
APIWhat it does
<NNumbersProvider>reads the session once and hands it to the components below; initialSession avoids the fetch (server-side rendering, tests)
useAuth(){ user, organization, loading, error, refresh(), loginPath(returnTo?), logoutPath }
useUser()who signed in; null if no one; undefined while loading
useOrganization()the organization that owns the application
<Authenticated fallback?>the content for who signed in, the fallback for who did not, and nothing while loading
<Unauthenticated>the content for who did not sign in; nothing for who did, nor while loading
<LoginButton returnTo?>a link to the organization sign-in, which returns to the current page (or to returnTo)
<LogoutButton>a POST form for signing out — the platform refuses a sign-out that does not come from the application itself
<UserMenu>the name of who signed in and the sign-out
readSession()the same read, without React

The interface shows who signed in; what the person may do is decided by the server, with nn.auth.user(req).

What the Application Does Not Receive​

The IAM token, the refresh token and secrets do not reach the application, neither the server nor the browser. The SDK has no function to get the person's access token. That token is also valid on the Zero API with the person's access, so it stays in the platform. To query the organization's QueryMesh, the platform queries on behalf of the person.

The IAM groups do not reach it either: who gets in is decided by the platform before the application, and the identity has no groups, roles, realm_access nor resource_access. See who gets in.

In Another Language​

Python and Java have an SDK, with the same server runtime as TypeScript; installation is in SDKs. In any other language, check the identity by hand.

Python (Flask, FastAPI, Django)​

from nnumbers_zero.app import NNumbers, UnauthenticatedError

nn = NNumbers.init() # reads NNUMBERS_* from the environment

@app.get("/dashboard")
def dashboard():
try:
user = nn.auth.require_user(request, request.full_path)
except UnauthenticatedError as error:
return redirect(error.login_path)
return f"Hello, {user.name or user.username}"
  • nn.auth.user(req) accepts the Flask, FastAPI/Starlette and Django request, and also the WSGI environ.
  • For FastAPI, there are user_async and query_async.
  • QueryMesh is nn.querymesh.query(request, sql, max_rows=…).

Java (Spring Boot, Jakarta Servlet)​

AppContext nn = NNumbers.init(); // reads NNUMBERS_* from the environment

@GetMapping("/api/me")
Session me(HttpServletRequest request) {
return new Session(nn.auth().user(request::getHeader).orElse(null), nn.org());
}
  • The headers come in through a method reference (request::getHeader), which works for Spring MVC, WebFlux and Servlet with no framework dependency.
  • QueryMesh is nn.querymesh().query(request::getHeader, sql, options).

In both cases, the rule is the same as in TypeScript:

  • the SDK checks the ES256 signature against the broker's JWKS, the issuer, the audience (this application), the organization and the validity;
  • with no header, nobody signed in;
  • with an invalid header, the result is an error, never a person;
  • there is no access_token/accessToken().

Checking by hand​

The identity arrives in the X-NNumbers-Identity header: a compact JWS, algorithm ES256, typ nn-identity+jwt. Check it always, on every request — a header whose signature was not checked proves nothing:

  1. The signature, with the public keys at the address in NNUMBERS_IDENTITY_JWKS. Keep the keys for a few minutes and fetch them again when an unknown kid arrives.
  2. iss equal to NNUMBERS_IDENTITY_ISSUER.
  3. aud equal to NNUMBERS_APP_ID — an identity handed to another application is not valid here.
  4. org equal to NNUMBERS_ORG_ID.
  5. nbf and exp: the identity is valid for 5 minutes, with up to 60 s of clock tolerance.

Without the header, the request is anonymous. With the header and any check failing, refuse it — never treat it as a person.

ClaimWhat it is
subthe person's identifier in the organization's IAM
org, org_slugthe organization
iamthe address of the organization's IAM
sidthe session reference
name, email, email_verified, preferred_usernamewhen the account has them
iat, nbf, exp, jtithe validity and the identifier of this identity

The runtime protocol describes the reserved paths, the broker and the QueryMesh query in another language.

The Platform Variables​

With the capability on, the deployment injects:

VariableWhat it is
NNUMBERS_APP_IDthis application's id (svc_…)
NNUMBERS_ORG_ID, NNUMBERS_ORG_SLUGthe project's organization
NNUMBERS_IDENTITY_ISSUERthe identity issuer
NNUMBERS_IDENTITY_JWKSthe address of the public keys — reachable only from inside the platform
NNUMBERS_BROKER_URLwhere the application asks for a query to the organization's QueryMesh — reachable only from inside the platform

The NNUMBERS_ prefix belongs to the platform: the service configuration does not accept a variable with it.

Next Steps​