gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3ac859953ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre3ac85995/lib/api.hl

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

Branches

Latest commits

  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
  • c7eef14aMerge branch 'nv1-navigate' into mainIdent
  • 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
  • 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
  • 23971fb7ident#49: media queries in the language's @media formmre
  • 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
  • aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
  • ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
  • dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
  • d277633cident#27: README: identity access and the introspect endpointmre
  • 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