gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit716860b0716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre716860b0/lib/api.hl

17.9 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (project.hl `routes`): the login button's GET /login, the app's server calls
  2. // (exchange, migrate-ids, kinds, notify, invites), the selector's two CORS calls, the code request, the invite
  3. // link, the code page, the offline probe. THIN WRAPPERS: check the method, the body (lib/api-helpers.hl strictBody)
  4. // and the app's key + secret, call the topic function, answer. Shapes: README "How apps use ident",
  5. // "How apps send notifications", "Invites". Statics only.
  6. import { Response } from 'hl:http1'
  7. import { reply, fail, withProfile, redirect, strictBody, errorPage, field, inviteCaller, baseOf, hexId, refuse, corsHeaders, answer, caller, hardenPage, framedBy } from './api-helpers.hl'
  8. import { openRequest, exchange, profileOf, migrateIds, appOfSecret, openInvite, requestOf, grantRequest } from './apps.hl'
  9. import { selectorList, codeOfPick } from './selector.hl'
  10. import { createInvite, listInvites, revokeInvite, ownInvite, inviteRow } from './invites.hl'
  11. import { registerKinds, sendNotification } from './notify.hl'
  12. import { startLogin, pendingOf } from './login.hl'
  13. import { accountOfSession } from './accounts.hl'
  14. import { sendCode, sendInvite } from './mail.hl'
  15. import { deliverUrgent } from './delivery.hl'
  16. // ---- THE LOGIN BUTTON: GET /login?key=<api key>&return=<url> ---------------------------
  17. // An unknown key or a return URL outside the app's origins → an error page, NEVER a
  18. // redirect. Otherwise the request is parked under a random id (a page component cannot
  19. // read the query, hybriel #18) and the browser goes to /signin/<rid>.
  20. static appLogin = (route, req) => {
  21. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  22. q = req.query != null ? req.query : {}
  23. r = openRequest(q.key, q['return'])
  24. if (r.error != null) { return errorPage(400, 'Bad login request', r.error) }
  25. return redirect('/signin/' + r.rid)
  26. }
  27. // ---- POST /api/migrate-ids { key, secret, finish? } → { ids: { <old per-app id>: <short id> } } (ident#23)
  28. // the APP'S SERVER moves its stored users to the identities' short ids in one step; with
  29. // `finish: true` the old per-app ids are dropped afterwards (they are gone for good).
  30. static apiMigrateIds = (route, req) => {
  31. if (req.method != 'POST') { return fail(405, 'POST only') }
  32. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } finish = { type = 'Boolean' required = false } })
  33. if (b.error != null) { return fail(400, b.error) }
  34. a = appOfSecret(b.body.key.trim(), b.body.secret.trim())
  35. if (a == null) { return fail(401, 'unknown API key or wrong secret') }
  36. return reply(200, migrateIds(a, b.body.finish == true))
  37. }
  38. // ---- POST /api/exchange { key, secret, code, fields? } → { identity, <asked fields>? } ------
  39. // the APP'S SERVER trades the ident_code from its return URL for the identity's short id. Only
  40. // when it sends `fields` (ident#11: nickname, firstname, lastname) it also gets one
  41. // key per asked field (flat, next to `identity`), null when empty. Without `fields` the answer is { identity } as ever.
  42. static apiExchange = (route, req) => {
  43. if (req.method != 'POST') { return fail(405, 'POST only') }
  44. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } code = { type = 'String' required = true } fields = { type = 'List' required = false } })
  45. if (b.error != null) { return fail(400, b.error) }
  46. for (k of ['key' 'secret' 'code']) {
  47. if (b.body[k].trim() == '') { return fail(400, 'missing field: ' + k) }
  48. }
  49. r = exchange(b.body.key.trim(), b.body.secret.trim(), b.body.code.trim(), b.body.fields)
  50. if (r.error != null) { return fail(r.status, r.error) }
  51. if (r.profile != null) { return reply(200, withProfile(r.identity, r.profile)) }
  52. return reply(200, { identity = r.identity })
  53. }
  54. // ---- POST /api/profile { key, secret, identity, fields } → { identity, profile } (ident#11) ------
  55. // the APP'S SERVER asks again for the profile fields of an identity (short id) that signed in to
  56. // this app before. 401 wrong key or secret, 404 no such identity in this app, 400 a bad field name.
  57. static apiProfile = (route, req) => {
  58. if (req.method != 'POST') { return fail(405, 'POST only') }
  59. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } identity = { type = 'String' required = true } fields = { type = 'List' required = true } })
  60. if (b.error != null) { return fail(400, b.error) }
  61. a = appOfSecret(b.body.key.trim(), b.body.secret.trim())
  62. if (a == null) { return fail(401, 'unknown API key or wrong secret') }
  63. r = profileOf(a, b.body.identity.trim(), b.body.fields)
  64. if (r.error != null) { return fail(r.status, r.error) }
  65. return reply(200, withProfile(r.identity, r.profile))
  66. }
  67. // ---- THE SELECTOR's two calls (lib/selector.hl): the ident user is the cookie's ---------
  68. // (hl:web hands a function route the cookie's session as req.session, hybriel#11)
  69. static apiSelectorIdentities = (route, req) => { return selectorIdentities(req, req.session) }
  70. static apiSelectorChoose = (route, req) => { return selectorChoose(req, req.session) }
  71. // GET /api/selector/identities?key=
  72. static selectorIdentities = (req, &session) => {
  73. c = caller(req)
  74. if (c.error != null) { return refuse(c.status, c.error) }
  75. if (req.method != 'GET') { return answer(c.origin, 405, { error = 'GET only' }) }
  76. me = accountOfSession(session)
  77. if (me == null) { return answer(c.origin, 200, { signedIn = false identities = [] }) }
  78. return answer(c.origin, 200, { signedIn = true identities = selectorList(c.app, me.id) })
  79. }
  80. // POST /api/selector/choose?key= { identity } (+ its OPTIONS preflight)
  81. static selectorChoose = (req, &session) => {
  82. c = caller(req)
  83. if (c.error != null) { return refuse(c.status, c.error) }
  84. if (req.method == 'OPTIONS') {
  85. h = corsHeaders(c.origin)
  86. h['Access-Control-Allow-Methods'] = 'POST'
  87. h['Access-Control-Allow-Headers'] = 'Content-Type'
  88. h['Access-Control-Max-Age'] = '600'
  89. return new Response('', { status = 204 headers = h })
  90. }
  91. if (req.method != 'POST') { return answer(c.origin, 405, { error = 'POST only' }) }
  92. b = strictBody(req, { identity = { type = 'String' required = true } })
  93. if (b.error != null) { return answer(c.origin, 400, { error = b.error }) }
  94. me = accountOfSession(session)
  95. if (me == null) { return answer(c.origin, 401, { error = 'you are not signed in to ident' }) }
  96. let code = codeOfPick(c.app, me.id, b.body.identity)
  97. if (code != null) { return answer(c.origin, 200, { code = code }) }
  98. return answer(c.origin, 400, { error = 'no such identity' })
  99. }
  100. // ---- POST /api/code { email } → { email }: THE ONE WAY TO GET A LOGIN CODE MAILED --------
  101. // (the sign-in form of `/` and `/signin/<rid>` fetches it). Limits: per address (3 / 10 min)
  102. // and per client IP (lib/login-helpers.hl ipBucket: 10 / 10 min, 30 / 24 h) → 429 with the reason.
  103. // THE CLIENT IP is the X-Client-IP header and nothing else: nginx on Byrodin sets it and
  104. // overwrites any the client sent (/CONTAINERS/web/nginx/conf.d/cloudflare-client-ip.conf).
  105. // CF-Connecting-IP / X-Forwarded-For / X-Real-IP are NEVER read (a client could forge them).
  106. // Without the header (dev, no nginx) every request shares ONE bucket ('direct'):
  107. // (hl:web's req.remoteAddress, hybriel#25, would be nginx's address behind the proxy.)
  108. // A function route, not a face: a face gets no request (no headers), and the per-IP limit needs the IP.
  109. static apiCode = (route, req) => {
  110. if (req.method != 'POST') { return fail(405, 'POST only') }
  111. b = strictBody(req, { email = { type = 'String' required = true } })
  112. if (b.error != null) { return fail(400, b.error) }
  113. r = startLogin(b.body.email, req.headers['x-client-ip'])
  114. if (r.error != null) { return fail(r.limited == true ? 429 : 400, r.error) }
  115. sendCode(r.email, r.code)
  116. return reply(200, { email = r.email })
  117. }
  118. // ---- NOTIFICATIONS (piece 4, lib/notify.hl; README "How apps send notifications") -------
  119. // The APP'S SERVER, with its key + secret. Strict JSON bodies. ident stores the notification and its channels, the
  120. // user reads it in the inbox (/inbox); delivery (the daily mail, urgent at once): lib/delivery.hl (piece 5, ident#7).
  121. // POST /api/kinds { key, secret, kinds: [{ name, push, email }] } → { kinds }
  122. // POST /api/notify { key, secret, identity, name, text, icon?, link?, urgent? } → { id }
  123. static apiKinds = (route, req) => {
  124. if (req.method != 'POST') { return fail(405, 'POST only') }
  125. b = strictBody(req, { key = { type = 'String' required = true } secret = { type = 'String' required = true } kinds = { type = 'List' required = true } })
  126. if (b.error != null) { return fail(400, b.error) }
  127. a = appOfSecret(b.body.key, b.body.secret)
  128. if (a == null) { return fail(401, 'unknown API key or wrong secret') }
  129. r = registerKinds(a, b.body.kinds)
  130. if (r.error != null) { return fail(r.status, r.error) }
  131. return reply(200, { kinds = r.kinds })
  132. }
  133. static apiNotify = (route, req) => {
  134. if (req.method != 'POST') { return fail(405, 'POST only') }
  135. 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 } })
  136. if (b.error != null) { return fail(400, b.error) }
  137. r = sendNotification(b.body)
  138. if (r.error != null) { return fail(r.status, r.error) }
  139. // an URGENT one goes out at once (lib/delivery.hl); a normal one waits for the daily mail
  140. deliverUrgent(r.id)
  141. return reply(200, { id = r.id })
  142. }
  143. // ---- INVITES (ident#22, lib/invites.hl; README "Invites") ----------------------------------------
  144. // The APP'S SERVER, key + secret, strict JSON bodies:
  145. // POST /api/invites { key, secret, project, role, return, uses?, days?, email? } → { id, url, state, … }
  146. // POST /api/invites/list { key, secret, project? } → { invites: [...] }
  147. // POST /api/invites/get { key, secret, id } → { invite }
  148. // POST /api/invites/revoke { key, secret, id } → { invite }
  149. // and the PERSON: GET /invite/<token> → the login flow (or an error page: used, expired, withdrawn).
  150. static apiInvites = (route, req) => {
  151. 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') })
  152. if (c.res != null) { return c.res }
  153. r = createInvite(c.app, c.body, baseOf(req))
  154. if (r.error != null) { return fail(r.status, r.error) }
  155. let mailed = false
  156. if (r.mail != null) {
  157. sendInvite(r.mail.to, r.url, c.app.name, r.invite.project, r.invite.role, r.mail.days)
  158. mailed = true
  159. }
  160. 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 })
  161. }
  162. static apiInvitesList = (route, req) => {
  163. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') project = field(false, 'String') })
  164. if (c.res != null) { return c.res }
  165. return reply(200, { invites = listInvites(c.app, c.body.project) })
  166. }
  167. static apiInvitesGet = (route, req) => {
  168. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })
  169. if (c.res != null) { return c.res }
  170. r = ownInvite(c.app, c.body.id)
  171. if (r == null) { return fail(404, 'no such invite') }
  172. return reply(200, { invite = inviteRow(r) })
  173. }
  174. static apiInvitesRevoke = (route, req) => {
  175. c = inviteCaller(req, { key = field(true, 'String') secret = field(true, 'String') id = field(true, 'String') })
  176. if (c.res != null) { return c.res }
  177. r = revokeInvite(c.app, c.body.id)
  178. if (r.error != null) { return fail(r.status, r.error) }
  179. return reply(200, { invite = r.invite })
  180. }
  181. static inviteLink = (route, req) => {
  182. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  183. r = openInvite(route.params.token)
  184. if (r.error != null) { return errorPage(r.status, r.title, r.error) }
  185. return redirect('/signin/' + r.rid)
  186. }
  187. // ---- THE CODE PAGE: GET /code and /signin/<rid>/code (ident#20, mission 008 (old 032)) ------------
  188. // Creator: "just make a /code where it checks a pending code". The page asks the SESSION
  189. // (lib/login.hl pendingOf) whether a code it asked for is still waiting — unused, unexpired,
  190. // not killed by wrong tries. Yes → Home renders its code step with that address (a reload
  191. // shows it again). No, or already signed in → 302 back to the email form (`/` or
  192. // `/signin/<rid>`), so a stale /code is never a dead end.
  193. // A FUNCTION route because a component route cannot answer a redirect: it takes the
  194. // cookie's session (req.session, hybriel#11) and renders `pageComponent` (Home) through the framework's own page
  195. // render (`srv.page`, the same call a component route makes) with `step = 'code'`; project.hl hands in
  196. // its server (by reference) and Home.
  197. // Its signature since hybriel #105 (mission 048): page(match, session, host, headers) — the
  198. // old page(match, req, session) still compiles but renders with req as the session (empty page).
  199. static codePage = (route, req, &srv, pageComponent) => {
  200. let rid = route.params.rid
  201. // a rid is 32 hex (lib/apps.hl); anything else goes to `/` (it lands in a Location header)
  202. if (rid != null && !hexId(rid)) { return redirect('/') }
  203. home = rid != null ? '/signin/' + rid : '/'
  204. if (req.method != 'GET') { return redirect(home) }
  205. s = req.session
  206. if (s == null || accountOfSession(s) != null || pendingOf(s) == null) { return redirect(home) }
  207. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = rid step = 'code' pending = pendingOf(s) } path = route.path }
  208. return hardenPage(srv.page(m, s, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)))
  209. }
  210. // ---- THE SELECTOR'S SIGN-IN FRAME (ident#31): GET /embed/signin?key=<api key>&return=<url> ----------------------------
  211. // 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
  212. // 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
  213. // ONLY by the app's registered origins (`frame-ancestors` from them; every other page of ident stays unframeable).
  214. // A function route like codePage: it renders `pageComponent` (Embed) through the framework's page render and sets the headers.
  215. static embedSignin = (route, req, &srv, pageComponent) => {
  216. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  217. q = req.query != null ? req.query : {}
  218. r = openRequest(q.key, q['return'])
  219. if (r.error != null) { return errorPage(400, 'Bad login request', r.error) }
  220. rq = requestOf(r.rid)
  221. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = r.rid } path = route.path }
  222. // 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
  223. // faces (the code check) need it, and the cookie is ident's own
  224. let s = req.session
  225. let fresh = s == null
  226. if (fresh) { s = srv.sessions.mint() }
  227. res = framedBy(srv.page(m, s, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)), rq.app.origins)
  228. if (fresh) { res.headers['Set-Cookie'] = srv.sessions.cookieHeader(s.id) }
  229. return res
  230. }
  231. // GET /embed/go?rid=<request id>&identity=<identity id>: the frame's "Continue" link (target="_top"). The signed-in browser's identity
  232. // gets the app's one-time code and the top window goes to `<return>?ident_code=<code>` (the login button's flow, step 4).
  233. static embedGo = (route, req) => {
  234. if (req.method != 'GET') { return errorPage(405, 'Method not allowed', 'Use a GET request.') }
  235. q = req.query != null ? req.query : {}
  236. 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.') }
  237. me = accountOfSession(req.session)
  238. 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.') }
  239. r = grantRequest(me.id, q.rid, q.identity)
  240. if (r.error != null) { return errorPage(400, 'Login request failed', r.error) }
  241. return redirect(r.url)
  242. }
  243. // GET /signin/<rid>/welcome: a NEW address, signed in in the frame, lands here in the top window: Home with the default identity's
  244. // name form open (the same form as after the first login on /signin/<rid>), then the identity choice, then back to the app.
  245. static welcomePage = (route, req, &srv, pageComponent) => {
  246. let rid = route.params.rid
  247. if (rid == null || !hexId(rid)) { return redirect('/') }
  248. if (req.method != 'GET' || accountOfSession(req.session) == null || requestOf(rid) == null) { return redirect('/signin/' + rid) }
  249. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { rid = rid step = 'welcome' } path = req.path }
  250. return hardenPage(srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers)))
  251. }
  252. // THE 404 PAGE (any path no route answers): the same page render as every ident page (shell, viewport, theme), status 404
  253. static notFoundPage = (route, req, &srv, pageComponent) => {
  254. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }
  255. res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))
  256. res.status = 404
  257. return hardenPage(res)
  258. }
  259. static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }
  260. // GET /api/online → 204: the shell's network probe (components/main.hl). Never cached, carries nothing.
  261. static apiOnline = (route, req) => { return new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' 'X-Content-Type-Options' = 'nosniff' } }) }

Branches

Latest commits

  • 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
  • f2c43bbbtheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 6d4f996esessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 029eb5e5deploy: security gate (tests/security.mjs)mre
  • d3c065a8security audit (SI): uploadMax 0, Secure __Host- cookie behind https, headers on function routes/files, page CSP+referrer meta, app/identity caps, tests/security.mjs, reportmre
  • 5561a0cbreport I4-mobilemre
  • 4ca2ed20404 page in the shell (viewport, status 404, way home); phone: account actions live in the user menu so the open menu covers nothing; mobile gate; signoutall waits for a cold startmre
  • 9baad745tests: browser gate waits for the reloaded document (offline reload race under CPU throttle); HL_CPU_THROTTLE knobmre
  • b96796bdtests: wait for hydration before real clicks after a navigation (H2)mre
  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre