ident
All repositories: gitoria
17.9 KB
// lib/api.hl — THE FUNCTION ROUTES (project.hl `routes`): the login button's GET /login, the app's server calls// (exchange, migrate-ids, kinds, notify, invites), the selector's two CORS calls, the code request, the invite// link, the code page, the offline probe. THIN WRAPPERS: check the method, the body (lib/api-helpers.hl strictBody)// and the app's key + secret, call the topic function, answer. Shapes: README "How apps use ident",// "How apps send notifications", "Invites". Statics only.import { Response } from 'hl:http1'import { reply, fail, withProfile, redirect, strictBody, errorPage, field, inviteCaller, baseOf, hexId, refuse, corsHeaders, answer, caller, hardenPage, framedBy } from './api-helpers.hl'import { openRequest, exchange, profileOf, migrateIds, appOfSecret, openInvite, requestOf, grantRequest } from './apps.hl'import { selectorList, codeOfPick } from './selector.hl'import { createInvite, listInvites, revokeInvite, ownInvite, inviteRow } from './invites.hl'import { registerKinds, sendNotification } from './notify.hl'import { startLogin, pendingOf } from './login.hl'import { accountOfSession } from './accounts.hl'import { sendCode, sendInvite } from './mail.hl'import { deliverUrgent } from './delivery.hl'// ---- THE LOGIN BUTTON: GET /login?key=<api key>&return=<url> ---------------------------// An unknown key or a return URL outside the app's origins → an error page, NEVER a// redirect. Otherwise the request is parked under a random id (a page component cannot// read the query, hybriel #18) and the browser goes to /signin/<rid>.static appLogin = (route, req) => {if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }q = req.query != null ? req.query : {}r = openRequest(q.key, q['return'])if (r.error != null) { return errorPage(400, 'Bad login request', r.error) }return redirect('/signin/' + r.rid)}// ---- POST /api/migrate-ids { key, secret, finish? } → { ids: { <old per-app id>: <short id> } } (ident#23)// the APP'S SERVER moves its stored users to the identities' short ids in one step; with// `finish: true` the old per-app ids are dropped afterwards (they are gone for good).static apiMigrateIds = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } finish = { type = 'Boolean' required = false } })if (b.error != null) { return fail(400, b.error) }a = appOfSecret(b.body.key.trim(), b.body.secret.trim())if (a == null) { return fail(401, 'unknown API key or wrong secret') }return reply(200, migrateIds(a, b.body.finish == true))}// ---- POST /api/exchange { key, secret, code, fields? } → { identity, <asked fields>? } ------// the APP'S SERVER trades the ident_code from its return URL for the identity's short id. Only// when it sends `fields` (ident#11: nickname, firstname, lastname) it also gets one// key per asked field (flat, next to `identity`), null when empty. Without `fields` the answer is { identity } as ever.static apiExchange = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } code = { type = 'String' required = true } fields = { type = 'List' required = false } })if (b.error != null) { return fail(400, b.error) }for (k of ['key' 'secret' 'code']) {if (b.body[k].trim() == '') { return fail(400, 'missing field: ' + k) }}r = exchange(b.body.key.trim(), b.body.secret.trim(), b.body.code.trim(), b.body.fields)if (r.error != null) { return fail(r.status, r.error) }if (r.profile != null) { return reply(200, withProfile(r.identity, r.profile)) }return reply(200, { identity = r.identity })}// ---- POST /api/profile { key, secret, identity, fields } → { identity, profile } (ident#11) ------// the APP'S SERVER asks again for the profile fields of an identity (short id) that signed in to// this app before. 401 wrong key or secret, 404 no such identity in this app, 400 a bad field name.static apiProfile = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } identity = { type = 'String' required = true } fields = { type = 'List' required = true } })if (b.error != null) { return fail(400, b.error) }a = appOfSecret(b.body.key.trim(), b.body.secret.trim())if (a == null) { return fail(401, 'unknown API key or wrong secret') }r = profileOf(a, b.body.identity.trim(), b.body.fields)if (r.error != null) { return fail(r.status, r.error) }return reply(200, withProfile(r.identity, r.profile))}// ---- THE SELECTOR's two calls (lib/selector.hl): the ident user is the cookie's ---------// (hl:web hands a function route the cookie's session as req.session, hybriel#11)static apiSelectorIdentities = (route, req) => { return selectorIdentities(req, &req.session) }static apiSelectorChoose = (route, req) => { return selectorChoose(req, &req.session) }// GET /api/selector/identities?key=static selectorIdentities = (req, &session) => {c = caller(req)if (c.error != null) { return refuse(c.status, c.error) }if (req.method != 'GET') { return answer(c.origin, 405, { error = 'GET only' }) }me = accountOfSession(&session)if (me == null) { return answer(c.origin, 200, { signedIn = false identities = [] }) }return answer(c.origin, 200, { signedIn = true identities = selectorList(c.app, me.id) })}// POST /api/selector/choose?key= { identity } (+ its OPTIONS preflight)static selectorChoose = (req, &session) => {c = caller(req)if (c.error != null) { return refuse(c.status, c.error) }if (req.method == 'OPTIONS') {h = corsHeaders(c.origin)h['Access-Control-Allow-Methods'] = 'POST'h['Access-Control-Allow-Headers'] = 'Content-Type'h['Access-Control-Max-Age'] = '600'return new Response('', { status = 204 headers = h })}if (req.method != 'POST') { return answer(c.origin, 405, { error = 'POST only' }) }b = strictBody(req, { identity = { type = 'String' required = true } })if (b.error != null) { return answer(c.origin, 400, { error = b.error }) }me = accountOfSession(&session)if (me == null) { return answer(c.origin, 401, { error = 'you are not signed in to ident' }) }let code = codeOfPick(c.app, me.id, b.body.identity)if (code != null) { return answer(c.origin, 200, { code = code }) }return answer(c.origin, 400, { error = 'no such identity' })}// ---- POST /api/code { email } → { email }: THE ONE WAY TO GET A LOGIN CODE MAILED --------// (the sign-in form of `/` and `/signin/<rid>` fetches it). Limits: per address (3 / 10 min)// and per client IP (lib/login-helpers.hl ipBucket: 10 / 10 min, 30 / 24 h) → 429 with the reason.// THE CLIENT IP is the X-Client-IP header and nothing else: nginx on Byrodin sets it and// overwrites any the client sent (/CONTAINERS/web/nginx/conf.d/cloudflare-client-ip.conf).// CF-Connecting-IP / X-Forwarded-For / X-Real-IP are NEVER read (a client could forge them).// Without the header (dev, no nginx) every request shares ONE bucket ('direct'):// (hl:web's req.remoteAddress, hybriel#25, would be nginx's address behind the proxy.)// A function route, not a face: a face gets no request (no headers), and the per-IP limit needs the IP.static apiCode = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { email = { type = 'String' required = true } })if (b.error != null) { return fail(400, b.error) }r = startLogin(b.body.email, req.headers['x-client-ip'])if (r.error != null) { return fail(r.limited == true ? 429 : 400, r.error) }sendCode(r.email, r.code)return reply(200, { email = r.email })}// ---- NOTIFICATIONS (piece 4, lib/notify.hl; README "How apps send notifications") -------// The APP'S SERVER, with its key + secret. Strict JSON bodies. ident stores the notification and its channels, the// user reads it in the inbox (/inbox); delivery (the daily mail, urgent at once): lib/delivery.hl (piece 5, ident#7).// POST /api/kinds { key, secret, kinds: [{ name, push, email }] } → { kinds }// POST /api/notify { key, secret, identity, name, text, icon?, link?, urgent? } → { id }static apiKinds = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } kinds = { type = 'List' required = true } })if (b.error != null) { return fail(400, b.error) }a = appOfSecret(b.body.key, b.body.secret)if (a == null) { return fail(401, 'unknown API key or wrong secret') }r = registerKinds(a, b.body.kinds)if (r.error != null) { return fail(r.status, r.error) }return reply(200, { kinds = r.kinds })}static apiNotify = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } identity = { type = 'String' required = true } name = { type = 'String' required = true } text = { type = 'String' required = true } icon = { type = 'String' required = false } link = { type = 'String' required = false } urgent = { type = 'Boolean' required = false } })if (b.error != null) { return fail(400, b.error) }r = sendNotification(b.body)if (r.error != null) { return fail(r.status, r.error) }// an URGENT one goes out at once (lib/delivery.hl); a normal one waits for the daily maildeliverUrgent(r.id)return reply(200, { id = r.id })}// ---- INVITES (ident#22, lib/invites.hl; README "Invites") ----------------------------------------// The APP'S SERVER, key + secret, strict JSON bodies:// POST /api/invites { key, secret, project, role, return, uses?, days?, email? } → { id, url, state, … }// POST /api/invites/list { key, secret, project? } → { invites: [...] }// POST /api/invites/get { key, secret, id } → { invite }// POST /api/invites/revoke { key, secret, id } → { invite }// and the PERSON: GET /invite/<token> → the login flow (or an error page: used, expired, withdrawn).static apiInvites = (route, req) => {c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') project = field(true, 'String') role = field(true, 'String') 'return' = field(true, 'String') uses = field(false, 'Number') days = field(false, 'Number') email = field(false, 'String') })if (c.res != null) { return c.res }r = createInvite(c.app, c.body, baseOf(req))if (r.error != null) { return fail(r.status, r.error) }let mailed = falseif (r.mail != null) {sendInvite(r.mail.to, r.url, c.app.name, r.invite.project, r.invite.role, r.mail.days)mailed = true}return reply(200, { id = r.invite.id url = r.url state = r.invite.state project = r.invite.project role = r.invite.role uses = r.invite.uses expires = r.invite.expires mailed = mailed })}static apiInvitesList = (route, req) => {c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') project = field(false, 'String') })if (c.res != null) { return c.res }return reply(200, { invites = listInvites(c.app, c.body.project) })}static apiInvitesGet = (route, req) => {c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })if (c.res != null) { return c.res }r = ownInvite(c.app, c.body.id)if (r == null) { return fail(404, 'no such invite') }return reply(200, { invite = inviteRow(r) })}static apiInvitesRevoke = (route, req) => {c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })if (c.res != null) { return c.res }r = revokeInvite(c.app, c.body.id)if (r.error != null) { return fail(r.status, r.error) }return reply(200, { invite = r.invite })}static inviteLink = (route, req) => {if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }r = openInvite(route.params.token)if (r.error != null) { return errorPage(r.status, r.title, r.error) }return redirect('/signin/' + r.rid)}// ---- THE CODE PAGE: GET /code and /signin/<rid>/code (ident#20, mission 008 (old 032)) ------------// Creator: "just make a /code where it checks a pending code". The page asks the SESSION// (lib/login.hl pendingOf) whether a code it asked for is still waiting — unused, unexpired,// not killed by wrong tries. Yes → Home renders its code step with that address (a reload// shows it again). No, or already signed in → 302 back to the email form (`/` or// `/signin/<rid>`), so a stale /code is never a dead end.// A FUNCTION route because a component route cannot answer a redirect: it takes the// cookie's session (req.session, hybriel#11) and renders `pageComponent` (Home) through the framework's own page// render (`srv.page`, the same call a component route makes) with `step = 'code'`; project.hl hands in// its server (by reference) and Home.// Its signature since hybriel #105 (mission 048): page(match, session, host, headers) — the// old page(match, req, session) still compiles but renders with req as the session (empty page).static codePage = (route, req, &srv, pageComponent) => {let rid = route.params.rid// a rid is 32 hex (lib/apps.hl); anything else goes to `/` (it lands in a Location header)if (rid != null && !hexId(rid)) { return redirect('/') }home = rid != null ? '/signin/' + rid : '/'if (req.method != 'GET') { return redirect(home) }let s = req.sessionif (s == null || accountOfSession(&s) != null || pendingOf(&s) == null) { return redirect(home) }m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = rid step = 'code' pending = pendingOf(&s) } path = route.path }return hardenPage(srv.page(m, s, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)))}// ---- THE SELECTOR'S SIGN-IN FRAME (ident#31): GET /embed/signin?key=<api key>&return=<url> ----------------------------// Shown inside the identity selector's panel on an app's page. The same checks as the login button (a known key, a return URL on// one of the app's origins; else an error page, never a redirect), the request is parked the same way, and the page may be framed// ONLY by the app's registered origins (`frame-ancestors` from them; every other page of ident stays unframeable).// A function route like codePage: it renders `pageComponent` (Embed) through the framework's page render and sets the headers.static embedSignin = (route, req, &srv, pageComponent) => {if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }q = req.query != null ? req.query : {}r = openRequest(q.key, q['return'])if (r.error != null) { return errorPage(400, 'Bad login request', r.error) }rq = requestOf(r.rid)m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = r.rid } path = route.path }// a visitor with no session yet gets one here, as a component route would give it (a function route is handed none): the frame's// faces (the code check) need it, and the cookie is ident's ownlet s = req.sessionlet fresh = s == nullif (fresh) { s = srv.sessions.mint() }res = framedBy(srv.page(m, s, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)), rq.app.origins)if (fresh) { res.headers['Set-Cookie'] = srv.sessions.cookieHeader(s.id) }return res}// GET /embed/go?rid=<request id>&identity=<identity id>: the frame's identity link (target="_top"). The signed-in browser's identity// gets the app's one-time code and the top window goes to `<return>?ident_code=<code>` (the login button's flow, step 4).static embedGo = (route, req) => {if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }q = req.query != null ? req.query : {}if (q.rid == null || !hexId(q.rid) || q.identity == null || hlTypeName(q.identity) != 'String') { return errorPage(400, 'Bad login request', 'This link is incomplete. Go back to the app and sign in again.') }me = accountOfSession(&req.session)if (me == null) { return errorPage(401, 'Not signed in', 'You are not signed in to ident. Go back to the app and sign in again.') }r = grantRequest(me.id, q.rid, q.identity)if (r.error != null) { return errorPage(400, 'Login request failed', r.error) }return redirect(r.url)}// GET /signin/<rid>/welcome: a NEW address, signed in in the frame, lands here in the top window: Home with the default identity's// name form open (the same form as after the first login on /signin/<rid>), then the identity choice, then back to the app.static welcomePage = (route, req, &srv, pageComponent) => {let rid = route.params.ridif (rid == null || !hexId(rid)) { return redirect('/') }if (req.method != 'GET' || accountOfSession(&req.session) == null || requestOf(rid) == null) { return redirect('/signin/' + rid) }m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = rid step = 'welcome' } path = req.path }return hardenPage(srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)))}// THE 404 PAGE (any path no route answers): the same page render as every ident page (shell, viewport, theme), status 404static notFoundPage = (route, req, &srv, pageComponent) => {m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))res.status = 404return hardenPage(res)}static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }// GET /api/online → 204: the shell's network probe (components/main.hl). Never cached, carries nothing.static apiOnline = (route, req) => { return new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' 'X-Content-Type-Options' = 'nosniff' } }) }
Branches
Latest commits
- 436206fcident#47: deploy.sh runs the sign-in gate on the deploy's own port slot, like the sessionwrites and docs gates (the default 8700 can be taken by another process)mre
- a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
- d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
- ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
- 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre
- c0edca26ident#28 A28G: write & at every call that hands a session to an &-parameter; gate tests/sessionwrites.mjs pins that sign-in, pending address, embed sign-in and selector land in the session filesmre
- 80965c08ident#28: README says the deploy goes through the standbymre
- 2f41670cident#28: ident-standby service on port 45012 (no background round in the standby) and deploy.sh hands over through standby-swap.shmre
- a544b261ident#28: README names the new vendored Hybrielmre
- 716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre
- 889e00fbident#28: Hybriel master ac1ed9da (sessions reload a newer file, a replayed reconnect carries the server session); a startup fault exits 1 (on Error)mre
- f5a55f8aident#11: apps can ask for nickname, firstname and lastname (fields list on /api/exchange, new POST /api/profile); empty fields come back null; gate checks, READMEmre
- d8be66ebident: report and log line for the widget cache and frame height changemre
- 2068f61aident#31: browsers revalidate the widget scripts on every load; the sign-in frame is exactly as tall as the current step (the frame page reports its height, selector.js accepts it from ident only)mre
- a22d2daaident#31: the sign-in frame is no taller than the tallest step needs (plain CSS height per width), gate check for itmre
- a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemre
- 5c481bfdident#31: sign in to ident inside the selector's panel (email, code, identity in an iframe; a new address goes to ident in the same tab and comes back)mre
- 061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre
- 45f7e4daident: the user menu's Sign out waits for the server before it reloads (the apps gate failed because the session could still be signed in)mre
- f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mre