gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit23971fb723971fb7ident#49: media queries in the language's @media formmre23971fb7/lib/api.hl

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

Branches

Latest commits

  • 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
  • e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre
  • 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