gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita77d1b22a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemrea77d1b22/lib/api.hl

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

Branches

Latest commits

  • 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
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre