gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8370b7488370b748ident#33: the app request box moves into home.hl's Stylemre8370b748/lib/api.hl

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

Branches

Latest commits

  • 8370b748ident#33: the app request box moves into home.hl's Stylemre
  • 40bf3b97ident#33: the 404 page's home link rule moves into notfound.hlmre
  • 40627a89ident#33: the time zone section's spacing moves into timezone.hlmre
  • d389db08ident#33: the identity page's rules and the Notif. chip move into identity.hl's Stylemre
  • ddda0b5bident#33: the identity row's parts move into identitylist.hl's Stylemre
  • 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
  • 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
  • f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
  • c512fb96Merge branch 'f4-homesplit' into mainIdent
  • 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
  • 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
  • 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