Devmachinist /Docs
Sign in Start
All docs

App sign-in (auth API)

Every API you build in the API tab can have its own sign-in. The people who sign in to your app are kept in that API's own users table. They are not Devmachinist accounts, and they never see the builder.

This page covers every route under /_api/<apiId>/auth/ plus the extras that build on sign-in: roles, the default admin, the admin endpoints, memberships, the free-read meter and page-view tracking. For the data routes themselves see the data API; for the generated JavaScript client see the client.

Before you start #

Turn sign-in on in API → Auth → Enable authentication. The same panel has:

  • Email & password sign-in (on by default).
  • Robot check on sign-in and sign-up (a proof-of-work check, see below).
  • Who can upload files (see App file storage).
  • Session length in days (default 7, 1 to 365).
  • External providers (Google, Microsoft Entra ID, Azure AD B2C, GitHub, generic OIDC).
  • Roles besides user and admin, and the access rules for each model.

Everything below lives under one base URL per API:

http
https://devmachinist.com/_api/<apiId>

API ids are short lowercase strings such as mhz0k4w0x7q2rd. The same /_api path also works on a published site's own address, so a page can call /_api/<apiId>/… on its own origin. The runtime is open to any origin (CORS *, allowed headers Content-Type, Authorization, X-API-Key, X-PB-Device) and never uses cookies: you prove who you are with a token.

Most apps never call these routes by hand. The generated src/api/<slug>-auth.jsx already wraps the app in <AuthProvider> and gives you <LoginForm />, <Auth>, useAuth() and <AccountSettings />. Read on when you need the raw HTTP, a native client or a script.

Tokens #

Register, login, an OAuth callback and a password change all hand back a token. It is a JWT signed with HS256 using a secret that belongs to that API alone (the builder never sends the secret to a browser). Its payload is:

json
{ "sub": "mhz1a9c2b4k7mn", "email": "ada@example.com", "name": "Ada", "v": 1, "iat": 1794643200, "exp": 1795248000 }

sub is the account id. v is the account's token version (left out while it is 0): it goes up each time the password changes. exp is the issue time plus the API's session length (7 days unless you changed it). A token is never extended: sign in again to get a new one.

Send it on every request that needs a signed-in person:

http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtaHoxYTljMmI0azdtbiIs...

The generated client keeps the token in localStorage under pb_auth_<apiId> and adds the header for you, from both the auth client and the data client (src/api/<slug>.js), which read the same key.

A token stops working when it expires, when the account's password changes (the change hands back a new token, so the person who changed it stays signed in while every other device is signed out), or when the account is deleted. Signing out (POST /auth/logout) only means the client forgets the token. Roles are read from the users table on every request, so promoting or demoting someone applies at once.

Rate limits #

RoutesLimit per IP
register, login, PATCH /auth/me, DELETE /auth/me, POST /auth/password30 per 10 minutes
everything under /_api300 per minute

Over the limit you get 429 with a Retry-After header:

json
{ "ok": false, "error": "Too many requests — try again in 412s" }

Errors from the auth routes are plain JSON with an error string, for example { "error": "Invalid email or password" }.

What sign-in offers #

GET /auth/providers says which methods the API has turned on. No token needed.

bash
curl https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/providers
json
{
  "enabled": true,
  "password": true,
  "providers": [{ "id": "mhz2p0q1r7s3tv", "type": "google", "label": "Google" }]
}

With sign-in off the answer is { "enabled": false }. The API index, GET /_api/<apiId>, carries the same object as auth.

Register #

POST /auth/register creates an account with role user and signs it in.

Body fieldNotes
emailRequired. Trimmed and lower-cased.
passwordRequired, at least 6 characters.
nameOptional.
robotRequired when the robot check is on (see below).
bash
curl -X POST https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/register \
  -H 'Content-Type: application/json' \
  -d '{"email":"ada@example.com","password":"correct-horse","name":"Ada"}'
json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "mhz1a9c2b4k7mn",
    "email": "ada@example.com",
    "name": "Ada",
    "provider": "password",
    "role": "user",
    "member": false,
    "memberUntil": null,
    "metadata": null,
    "createdAt": "2026-11-13 09:12:44",
    "hasPassword": true
  }
}
StatusWhen
400Email or password missing, password shorter than 6 characters, or the robot check failed (the body then has "robot": true).
404Password auth is not enabled: sign-in is off, or email and password sign-in is off.
409Email already registered.

Sign in #

POST /auth/login takes email, password and, when the robot check is on, robot. It answers with the same { token, user } shape as register and records the sign-in time.

bash
curl -X POST https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"ada@example.com","password":"correct-horse"}'
js
const BASE = 'https://devmachinist.com/_api/mhz0k4w0x7q2rd'
const res = await fetch(BASE + '/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, password, robot }),
})
const data = await res.json()
if (!res.ok) throw new Error(data.error)
localStorage.setItem('pb_auth_mhz0k4w0x7q2rd', data.token)

A wrong email or password is 401 Invalid email or password. Accounts made through a provider have no password until they set one, so they can't use this route yet. Each failed sign-in makes the next robot check from that IP harder.

The robot check #

When Robot check on sign-in and sign-up is ticked (api.auth.robotCheck), register and login need a solved proof of work in body.robot. There is no third-party service: the browser does a little hashing, about a third of a second on a phone.

Get a challenge #

GET /auth/challenge?purpose=signup for register, purpose=login for login (anything else counts as login).

bash
curl 'https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/challenge?purpose=login'
json
{
  "required": true,
  "algorithm": "SHA-256",
  "challenge": "5c1f0e9b2d7a4c38e6f1b0a9d8c7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9",
  "salt": "8f2c4a9e1b7d3f6a0c5e2b8d.api_mhz0k4w0x7q2rd_login.1794643500000",
  "maxnumber": 60000,
  "signature": "a7d9c1e3f5b2a4c6e8d0f1a3b5c7e9d2f4a6c8e0b1d3f5a7c9e2b4d6f8a1c3e5"
}

When the check is off for this API (or turned off on the server) the answer is just { "required": false } and you send no robot field.

Solve it #

Find the whole number n from 0 to maxnumber for which the lower-case hex SHA-256 of salt + n (the salt string with the number appended) equals challenge. Then send robot as base64 of this JSON, with number as a JSON integer:

json
{ "algorithm": "SHA-256", "challenge": "5c1f…", "salt": "8f2c…", "number": 41873, "signature": "a7d9…" }

In Node:

js
import crypto from 'node:crypto'

const BASE = 'https://devmachinist.com/_api/mhz0k4w0x7q2rd'
async function robotFor(purpose) {
  const c = await (await fetch(`${BASE}/auth/challenge?purpose=${purpose}`)).json()
  if (!c.required) return undefined
  for (let n = 0; n <= c.maxnumber; n++) {
    if (crypto.createHash('sha256').update(c.salt + n).digest('hex') === c.challenge) {
      const { algorithm, challenge, salt, signature } = c
      return Buffer.from(JSON.stringify({ algorithm, challenge, salt, number: n, signature })).toString('base64')
    }
  }
  throw new Error('No solution found')
}

const robot = await robotFor('login')
await fetch(`${BASE}/auth/login`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: 'ada@example.com', password: 'correct-horse', robot }),
})

Rules #

  • A challenge is signed by the server, bound to this API and to its purpose (signup or login), and expires after 5 minutes.
  • A solution works once. A failed sign-in uses it up, so solve a fresh one before you try again.
  • maxnumber starts at 60,000. After 3 failures from an IP on this API within the hour it is 4 times larger, after 6 failures 16 times larger (capped at 2,000,000).
  • A bad or missing solution answers 400 with "robot": true and one of: Please confirm you’re not a robot, The robot check expired — tick the box again, The robot check failed — tick the box again, The robot check was already used — tick the box again.
  • Provider sign-in (OAuth) doesn't use the robot check.

In React #

<LoginForm /> already includes the check. If you build your own form, use the generated RobotCheck. It calls onChange(token) once solved, onChange('') when the API doesn't ask for it, and onChange(null) while unsolved. Change resetKey after a failed attempt.

jsx
import { useState } from 'react'
import { RobotCheck, useAuth } from '../api/shop-auth.jsx'

export default function QuickLogin() {
  const { login } = useAuth()
  const [robot, setRobot] = useState(null)
  const [tries, setTries] = useState(0)
  const [error, setError] = useState('')
  const submit = async (e) => {
    e.preventDefault()
    const f = new FormData(e.target)
    try { await login(f.get('email'), f.get('password'), robot || undefined) }
    catch (err) { setError(err.message); setTries(t => t + 1) }
  }
  return (
    <form onSubmit={submit} className="space-y-3">
      <input name="email" type="email" required />
      <input name="password" type="password" required />
      <RobotCheck purpose="login" onChange={setRobot} resetKey={tries} />
      {error && <p>{error}</p>}
      <button disabled={robot === null}>Sign in</button>
    </form>
  )
}

The signed-in account #

Read it #

GET /auth/me returns the account behind the token.

bash
curl https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/me \
  -H 'Authorization: Bearer eyJhbGciOi...'
json
{
  "id": "mhz1a9c2b4k7mn",
  "email": "ada@example.com",
  "name": "Ada",
  "provider": "password",
  "role": "user",
  "member": false,
  "memberUntil": null,
  "metadata": null,
  "createdAt": "2026-11-13 09:12:44",
  "hasPassword": true
}

A missing, expired or unknown token answers 401 Not authenticated. provider is password or the id of the provider the person last signed in with. member and memberUntil belong to memberships.

Change the name #

PATCH /auth/me with { "name": "…" }. Line breaks are removed and the name is cut to 120 characters. Answers the updated user.

bash
curl -X PATCH https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/me \
  -H 'Authorization: Bearer eyJhbGciOi...' -H 'Content-Type: application/json' \
  -d '{"name":"Ada Lovelace"}'

Change the password #

POST /auth/password with { "current": "…", "password": "…" }. The new password needs at least 8 characters. An account without a password yet (made through a provider) can set one without current. The answer is a fresh { token, user }; store the new token.

bash
curl -X POST https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/password \
  -H 'Authorization: Bearer eyJhbGciOi...' -H 'Content-Type: application/json' \
  -d '{"current":"correct-horse","password":"battery-staple-9"}'
StatusWhen
401Not signed in.
403Your current password isn’t right.
400The new password must be at least 8 characters.

Delete the account #

DELETE /auth/me with { "password": "…" }, or { "confirm": "delete" } for an account that has no password. Answers { "ok": true }. Only the sign-in is removed: rows the person created (orders, posts) stay with the site.

bash
curl -X DELETE https://devmachinist.com/_api/mhz0k4w0x7q2rd/auth/me \
  -H 'Authorization: Bearer eyJhbGciOi...' -H 'Content-Type: application/json' \
  -d '{"password":"battery-staple-9"}'

A wrong password is 403 Your password isn’t right; a missing word is 403 Type delete to confirm.

Sign out #

POST /auth/logout always answers { "ok": true } and changes nothing on the server. Drop the token on the client.

In React #

The generated hook covers all of the above:

jsx
import { useAuth, AccountSettings, Auth } from '../api/shop-auth.jsx'

function AccountPage() {
  const { user, logout } = useAuth()
  return (
    <Auth>
      <p>Signed in as {user?.email}</p>
      <AccountSettings />
      <button onClick={() => { logout(); window.location.hash = '#home' }}>Sign out</button>
    </Auth>
  )
}

useAuth() gives { user, loading, providers, login, register, logout, loginWithProvider, refresh, updateProfile, changePassword, deleteAccount }. Outside an <AuthProvider> it returns a signed-out stand-in instead of crashing.

There is no "forgot password" email for app accounts. The API's owner can set a new password for anyone in API → Auth → Users.

Sign in with a provider (OAuth) #

Add a provider in API → Auth → External providers and fill in its fields:

TypeFields
googleclientId, clientSecret
entra (Microsoft Entra ID)clientId, clientSecret, tenant (default common)
azureb2c (Azure AD B2C)clientId, clientSecret, tenant, policy
githubclientId, clientSecret
oidc (Okta, Auth0, Cognito, Keycloak…)clientId, clientSecret, issuer

Register this redirect URL with the provider:

http
https://devmachinist.com/_api/<apiId>/auth/callback/<providerId>

The flow:

  1. Send the browser to GET /auth/oauth/<provider>?redirect_uri=<your page>. <provider> is the provider's id or its type. The server answers with a redirect to the provider, carrying a signed state that expires after 10 minutes.
  2. The provider sends the person back to /auth/callback/<providerId>. The server exchanges the code, reads the profile and finds the account by provider id, then by email, or creates one with role user. It joins an existing account by email only when the provider says that email is verified; otherwise the sign-in is refused with An account with this email already exists…, and the person signs in the way they signed up.
  3. The server redirects to redirect_uri#access_token=<token>. Without redirect_uri it uses the site's own origin.

Because the token travels in that address, redirect_uri must be one of your own: the app's own address, the API owner's own published sites (their /@username/ path or subdomain, and their custom domains), an origin listed in API → Payments (allowed origins or store URL), the Android app (https://appassets.local), or localhost for development. Any other address answers 400 This sign-in can only return to the app’s own site…. The state is signed with its own key, so it can never be used as a sign-in token.

js
const BASE = 'https://devmachinist.com/_api/mhz0k4w0x7q2rd'
const back = window.location.href.split('#')[0]
window.location.href = `${BASE}/auth/oauth/google?redirect_uri=${encodeURIComponent(back)}`

The generated client reads #access_token= from the address when it loads, stores it under pb_auth_<apiId> and cleans the address. loginWithProvider(id) from useAuth() starts the flow, and <LoginForm /> shows a button per provider.

An unknown provider answers 404 Provider not configured, a bad or expired state 400 Invalid OAuth state, and a failed exchange 502 OAuth failed: … (plain text, since the browser is mid-redirect).

Roles #

Every account has exactly one role:

  • user: every account starts here.
  • admin: passes the admin rule, sees and changes every row under the owner rule, and can use the admin endpoints below.
  • Custom roles you add in API → Auth → Roles (for example editor or member): lowercase, 2 to 31 characters of letters, digits, - and _, starting with a letter, at most 20. They can't be user, admin or a rule word.

Set roles in API → Auth → Users, or from the app with PATCH /admin/users/:uid (below). Sign-up always gives user.

How rules use roles #

Each model has a rule for read (GET), create (POST; falls back to write when unset) and write (PUT, PATCH, DELETE). Rules apply only while sign-in is on.

RuleWho passes
publicAnyone, no token. The default.
authAny signed-in account.
ownerSigned in; lists show only the caller's rows, new rows are stamped with the caller's id, other rows answer 404. Admins see everything.
adminAccounts with role admin.
a custom role, such as editorAccounts with that role, and admins.
noneNobody through /_api; only the API's owner in the builder.

The owner field is ownerField if you set one, else the first field named user_id, userId, owner, owner_id, ownerId, author, created_by or createdBy. Failures answer 401 Authentication required, 403 Admins only or 403 Only editor accounts. More on rules, visibleWhen and filtering in the data API.

Roles in React #

jsx
import { Auth, hasRole, useAuth } from '../api/blog-auth.jsx'

<Auth role={['admin']} fallback={<p>You need an admin account.</p>}>
  <AdminPanel />
</Auth>

<Auth role={['editor']}>
  <DraftList />
</Auth>

hasRole(user, roles) and <Auth role> treat admin as admins only, a name in CUSTOM_ROLES (the API's custom roles, written into the client) as that role or an admin, and any other name, user included, as any signed-in account. Hiding something in React is only cosmetic; the rules on the server are what protect the data.

The default admin #

The store and blog templates, Shop template installs and AI builds whose rules use admin start with one admin account: your Devmachinist email, name Admin, role admin and a random password. The builder shows that password in API → Auth → Users until someone changes it; it is never sent through /_api. Change it before you share the site.

Admin endpoints #

These routes need a token whose account has role admin. Without a token they answer 401 Authentication required, with a non-admin token 403 Admins only.

List accounts #

GET /admin/users?q=&page=&limit= searches email and name. limit defaults to 25 (at most 100) and page starts at 1. members counts accounts with a membership right now.

bash
curl 'https://devmachinist.com/_api/mhz0k4w0x7q2rd/admin/users?q=ada&page=1' \
  -H 'Authorization: Bearer eyJhbGciOi...'
json
{
  "total": 1,
  "members": 0,
  "users": [{
    "id": "mhz1a9c2b4k7mn", "email": "ada@example.com", "name": "Ada", "provider": "password",
    "role": "user", "member": false, "memberStatus": null, "memberUntil": null,
    "createdAt": "2026-11-13 09:12:44", "lastLogin": "2026-11-13 10:02:17"
  }]
}

Change a role or grant a membership #

PATCH /admin/users/:uid with role and/or member. Answers { "ok": true }.

bash
curl -X PATCH https://devmachinist.com/_api/mhz0k4w0x7q2rd/admin/users/mhz1a9c2b4k7mn \
  -H 'Authorization: Bearer eyJhbGciOi...' -H 'Content-Type: application/json' \
  -d '{"role":"editor","member":true}'
  • role must be user, admin or one of the API's custom roles (400 Unknown role otherwise).
  • member: true gives a free ("comp") membership. member: false takes back a comp membership; a membership paid through Stripe can't be removed here (409).
  • You can't take away your own admin role (409). An unknown id is 404 User not found.

Delete an account #

DELETE /admin/users/:uid answers { "ok": true }. You can't delete yourself here (409).

Membership settings #

GET /admin/membership returns the plan and whether payments are set up:

json
{
  "enabled": true, "name": "Membership", "price": 5, "interval": "month", "freeReads": 3,
  "model": "Post", "field": "body", "perks": ["Every post in full"],
  "payments": { "enabled": true, "provider": "stripe", "currency": "usd", "mode": "live" }
}

PUT /admin/membership changes enabled, name (up to 60 characters), price (0.50 to 10,000), interval (month or year), freeReads (0 to 1000) and perks (up to 8, an array or one per line). It answers the saved settings the same way. The paywalled model and field aren't changed by this route.

Traffic report #

GET /admin/traffic?days=30 (1 to 365) summarises the page views sent with POST /track:

json
{
  "days": 30,
  "summary": { "views": 1840, "visitors": 612, "prev": { "views": 1502, "visitors": 540 }, "memberViews": 210 },
  "live": 3,
  "series": [{ "day": "2026-11-13", "views": 71, "visitors": 30 }],
  "pages": [{ "key": "#post/:id", "views": 920, "visitors": 401 }],
  "sources": [{ "key": "Direct", "views": 1100, "visitors": 380 }],
  "devices": [{ "key": "Mobile", "views": 1200, "visitors": 420 }],
  "people": { "users": 88, "newUsers": 12, "members": 9 },
  "meteredReads": [{ "item": "14", "n": 6 }]
}

live counts visitors in the last 5 minutes and meteredReads the most-read paywalled items this month by signed-in readers. The store's own admin routes (/admin/store, fulfillment, orders) are in payments.

Memberships #

A membership is a paid subscription to the app (the blog template uses it). People subscribe with Stripe Checkout on the store's own Stripe, set up in API → Payments (see payments). A membership counts while its status is active, trialing, past_due or comp, and a cancelled one counts until its period ends. Only Stripe (signed webhook events, or the subscription Stripe returns) and admin grants change it; the app itself can't.

Read the plan and your status #

GET /membership works with or without a token.

bash
curl https://devmachinist.com/_api/mhz0k4w0x7q2rd/membership -H 'Authorization: Bearer eyJhbGciOi...'
json
{
  "enabled": true, "payments": true, "name": "Membership", "price": 5, "interval": "month",
  "currency": "usd", "freeReads": 3, "perks": ["Every post in full"],
  "signedIn": true, "isAdmin": false,
  "member": true, "status": "active", "until": "2026-12-13T09:20:00.000Z", "cancelAt": null, "comp": false
}

Subscribe #

POST /membership/subscribe with { "returnUrl": "https://example.com/" } answers { "url": "https://checkout.stripe.com/…" }. Send the browser there. Stripe returns to <returnUrl>#account?subscribed=1, or <returnUrl>#subscribe when the person cancels. returnUrl must be an https address (http only on localhost) and, when the store lists allowed origins or a store URL in API → Payments, one of those origins; otherwise the store URL is used, and without one the call fails with 400.

StatusWhen
401Sign in to subscribe.
404Memberships aren’t open on this site.
409You’re already a member.
503Payments aren't set up yet.

Cancel or resume #

POST /membership/cancel cancels at the end of the paid period; { "resume": true } undoes that. It answers the new status:

json
{ "member": true, "status": "active", "until": "2026-12-13T09:20:00.000Z", "cancelAt": "2026-12-13T09:20:00.000Z", "comp": false }

Without a token it is 401 Sign in first; without a Stripe subscription 404 No subscription to change.

In React #

jsx
import { useMembership } from '../api/blog-auth.jsx'

function Subscribe() {
  const { info, isMember, loading, subscribe, cancel, resume } = useMembership()
  if (loading) return null
  if (isMember) return info.cancelAt
    ? <button onClick={resume}>Keep my membership</button>
    : <button onClick={cancel}>Cancel at period end</button>
  return <button onClick={subscribe}>Join for {info.price} {info.currency.toUpperCase()} a {info.interval}</button>
}

The free-read meter #

With memberships on, reads of the paywalled model (model, default Post) through GET /_api/<apiId>/<model> and GET /_api/<apiId>/<model>/<id> are metered. Admins and members get everything as stored. Everyone else:

  • Lists never carry the paywalled field (default body): it is null in every row, so lists are excerpts.
  • A single item costs one of freeReads reads per calendar month. Reading the same item again that month is free. An item with free: true or premium: false never costs a read.
  • When the reads are used up, the item comes back with the field set to null and "_locked": true.

Every single-item answer carries _meter:

json
{ "id": 14, "title": "Why tea", "body": null, "_locked": true, "_meter": { "free": 3, "used": 3, "left": 0, "signedIn": false } }

Signed-in readers are counted per account. Signed-out readers are counted per device, from the X-PB-Device header (a random id; the generated clients create one in localStorage under pb_device and send it on every call), or from IP and browser when there's no header. Signed-out devices on one network also share a cap of 5 times freeReads a month, so clearing storage doesn't reset the meter forever.

bash
curl https://devmachinist.com/_api/mhz0k4w0x7q2rd/post/14 -H 'X-PB-Device: k3j9x0q2lmhz4a1b'

Page views #

POST /track records one page view for the API's traffic report. No cookies are set and no IP is stored: a visitor is a hash of the IP, browser and day. Send p (the page, for example #post/14) and r (the referrer). Paths are cut to their first segment plus /:id, so #post/14 counts as #post/:id. With a token, views by members are counted as such. It always answers 204.

bash
curl -X POST https://devmachinist.com/_api/mhz0k4w0x7q2rd/track \
  -H 'Content-Type: application/json' -H 'User-Agent: Mozilla/5.0' \
  -d '{"p":"#post/14","r":"https://news.example.org/"}'

Requests whose user agent looks like a bot are ignored, and that includes curl, wget, python and headless browsers, so test with a browser-like user agent as above. In React, call usePageViews() once (for example in your layout): it sends a view on load and on every hash change.