ident
All repositories: gitoria
20.0 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 Home from '../components/home.hl'import Embed from '../components/embed.hl'import NotFound from '../components/notfound.hl'import { reply, fail, withProfile, redirect, strictBody, errorPage, field, inviteCaller, baseOf, hexId, refuse, corsHeaders, answer, caller, hardenPage, framedBy } from './api-helpers.hl'import { introspect } from './access.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'static pageServer = { server = null }// the login button's error page: the error component rendered with a status (needs the server, like the routes above)static errorAnswer = (route, req, status, title, message) => { return errorPage(route, req, &pageServer.server, status, title, message) }static codeRoute = (route, req) => { return codePage(route, req, &pageServer.server, Home) }static signinCodeRoute = (route, req) => { return codePage(route, req, &pageServer.server, Home) }static welcomeRoute = (route, req) => { return welcomePage(route, req, &pageServer.server, Home) }static embedSigninRoute = (route, req) => { return embedSignin(route, req, &pageServer.server, Embed) }static notFoundRoute = (route, req) => { return notFoundPage(route, req, &pageServer.server, NotFound) }// ---- 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 errorAnswer(route, req, 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 errorAnswer(route, req, 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))}// ---- POST /api/introspect { key, secret, token } → { active, identity?, name?, access? } (ident#27) -----------------// the APP'S SERVER asks whether an identity key (`idt_…`, from a conductor's request) is valid for THIS app, and for which identity// (short id), under which name and with which rights (`read` | `write`). 401 wrong key or secret; an unknown, revoked or not-granted key is// 200 { active: false }. ident records the last use. Nothing is cached here: a revoke is dead at the next question.static apiIntrospect = (route, req) => {if (req.method != 'POST') { return fail(405, 'POST only') }b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } token = { type = 'String' 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') }return reply(200, introspect(a, b.body.token.trim()))}// ---- 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 errorAnswer(route, req, 405, 'Method not allowed', 'Use a GET request.') }r = openInvite(route.params.token)if (r.error != null) { return errorAnswer(route, req, 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) }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 errorAnswer(route, req, 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 errorAnswer(route, req, 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.sessionfresh = 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 errorAnswer(route, req, 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 errorAnswer(route, req, 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 errorAnswer(route, req, 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 errorAnswer(route, req, 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
- e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
- c7eef14aMerge branch 'nv1-navigate' into mainIdent
- 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
- 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
- 23971fb7ident#49: media queries in the language's @media formmre
- 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
- aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
- ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
- dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
- d277633cident#27: README: identity access and the introspect endpointmre