gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit40627a8940627a89ident#33: the time zone section's spacing moves into timezone.hlmre40627a89/lib/apps.hl

16.4 KB

  1. // lib/apps.hl — APPS AND THE LOGIN BUTTON (piece 2 of 6, ticket #25; CONCEPT.md "Apps",
  2. // "One id per app", "Flow 1: login button"; the invite's login flow, ident#22). Statics only, the server realm.
  3. // Every write to the apps, connections, requests and grants tables is here. The checks (app form, origins,
  4. // return URL), keys and the row a page shows: lib/apps-helpers.hl.
  5. //
  6. // appsTable pk @id index @owner, !apiKey
  7. // { owner (account @id), name, origins ('a b c': the origins it runs
  8. // on, space separated), apiKey, secretHash = sha256(secret), created, updated }
  9. // connectionsTable pk @id index !pair, @app
  10. // { pair = '<app @id>:<identity @id>', app, identity, created } — `created` is
  11. // when the identity registered in that app (the per-app page).
  12. // What an app holds is the identity's ONE SHORT ID (ident#23, lib/identities.hl
  13. // `shortId`), the same in every app. Rows made before ident#23 still carry
  14. // `appIdentity` (the old per-app id, 32 hex) until the app has migrated:
  15. // POST /api/migrate-ids answers old → short and, with finish, drops them.
  16. // requestsTable pk @id index !rid a login button press waiting for the choice:
  17. // { rid, app (app @id), returnUrl, expires, invite (invite @id, ident#22; absent for a plain login) }
  18. // grantsTable pk @id index !hash a one-time code on its way back to the app:
  19. // { hash = sha256(code), app, identity, expires }
  20. //
  21. // Any signed-in account registers apps. An app has a PUBLIC API key (`pk_…`, it may sit
  22. // in a page) and a SECRET (`sk_…`, the app's server only). The secret is shown ONCE, when
  23. // it is made (register / new secret); only its sha256 is stored.
  24. // Public app ids are the records' mpackdb UUIDs (`@id`), as for accounts and identities;
  25. // the files live in storage/mpackdb/ (lib/util.hl `dir`).
  26. import { MPackDB } from 'hl:mpackdb'
  27. import { now } from 'hl:time'
  28. import { randomBytes, sha256 } from 'hl:crypto'
  29. import { dir, envNumber, countOf, first, merged, isId, oldestFirst } from './util.hl'
  30. import { checkAppInput, newKey, newSecret, appRowOf, checkReturn } from './apps-helpers.hl'
  31. import { ownIdentity, identitiesTable, identityByShortId } from './identities.hl'
  32. import { checkProfileFields, profileValues } from './identities-helpers.hl'
  33. import { dropInvitesOf, openableInvite, inviteById, acceptInvite } from './invites.hl'
  34. static appsTable = new MPackDB(file = dir + '/apps.db', primaryKey = '@id', indexes = ['@owner' '!apiKey'])
  35. static connectionsTable = new MPackDB(file = dir + '/connections.db', primaryKey = '@id', indexes = ['!pair' '@app'])
  36. static requestsTable = new MPackDB(file = dir + '/requests.db', primaryKey = '@id', indexes = ['!rid'])
  37. static grantsTable = new MPackDB(file = dir + '/grants.db', primaryKey = '@id', indexes = ['!hash'])
  38. static grantTtl = envNumber('IDENT_GRANT_TTL_MS', 60000) // a one-time code: 60 s
  39. static requestTtl = 1800000 // a login button press: 30 min
  40. // an account's apps (mission SI): each app may mail invitations (lib/invites.hl mailLimit) and any address can make an account, so the
  41. // number of apps bounds what one account can make ident mail. The gate sets a lower one.
  42. static maxApps = envNumber('IDENT_MAX_APPS', 20)
  43. // ---- apps -----------------------------------------------------------------------------
  44. // the account's apps, oldest first (stored `created`, never key order)
  45. static appRows = (accountId) => {
  46. out = []
  47. if (!isId(accountId)) { return out }
  48. for (r of oldestFirst(appsTable.find('owner', accountId))) { out.push(appRowOf(r)) }
  49. return out
  50. }
  51. // the app record `id` (public) if the account owns it, else null
  52. static ownApp = (accountId, id) => {
  53. if (!isId(id)) { return null }
  54. r = appsTable.fetch(id)
  55. if (r == null || r.owner != accountId) { return null }
  56. return r
  57. }
  58. static appByKey = (key) => {
  59. if (key == null || hlTypeName(key) != 'String' || key == '') { return null }
  60. return first(appsTable.find('apiKey', key))
  61. }
  62. // ident#G48: gitoria answers on a repo address (<repo>.gitoria.worldapi.org) with the same API key as on its main address, so its
  63. // registration must hold the wildcard origin as well. The registration made in September has the main address only; this adds the
  64. // wildcard once, at load, to the app named gitoria.worldapi.org and to no other app (and only when the main address is its origin).
  65. static gitoriaName = 'gitoria.worldapi.org'
  66. static gitoriaMain = 'https://gitoria.worldapi.org'
  67. static gitoriaWildcard = 'https://*.gitoria.worldapi.org'
  68. static addGitoriaWildcard = () => {
  69. let n = 0
  70. rows = appsTable.find(null, null)
  71. if (countOf(rows) > 0) {
  72. for (r of rows) {
  73. if (r.name != gitoriaName) { continue }
  74. os = r.origins == '' ? [] : r.origins.split(' ')
  75. if (os.includes(gitoriaMain) && !os.includes(gitoriaWildcard)) {
  76. os.push(gitoriaWildcard)
  77. appsTable.update(r.id, merged(r, { origins = os.join(' ') }))
  78. n = n + 1
  79. }
  80. }
  81. }
  82. return n
  83. }
  84. static gitoriaWildcardAdded = addGitoriaWildcard()
  85. // THE APP'S SERVER, key + secret: answers the app record or null (unknown key or wrong secret: one answer, 401)
  86. static appOfSecret = (key, secret) => {
  87. a = appByKey(key)
  88. if (a == null || hlTypeName(secret) != 'String' || sha256(secret) != a.secretHash) { return null }
  89. return a
  90. }
  91. // answers { error, field } or { app (row), secret } — the secret leaves ident only here
  92. static createApp = (accountId, input) => {
  93. c = checkAppInput(input)
  94. if (c.error != null) { return c }
  95. if (countOf(appsTable.find('owner', accountId)) >= maxApps) { return { error = 'an account can have at most ' + maxApps + ' apps' field = '' } }
  96. let secret = newSecret()
  97. id = appsTable.put({ owner = accountId name = c.name origins = c.origins.join(' ') apiKey = newKey() secretHash = sha256(secret) created = now() updated = now() })
  98. return { app = appRowOf(appsTable.fetch(id)) secret = secret }
  99. }
  100. static updateApp = (accountId, id, input) => {
  101. r = ownApp(accountId, id)
  102. if (r == null) { return { error = 'no such app' field = 'id' } }
  103. c = checkAppInput(input)
  104. if (c.error != null) { return c }
  105. appsTable.update(r.id, merged(r, { name = c.name origins = c.origins.join(' ') updated = now() }))
  106. return { app = appRowOf(appsTable.fetch(r.id)) }
  107. }
  108. // a NEW SECRET: the old one stops working at once; the API key stays
  109. static regenerateSecret = (accountId, id) => {
  110. r = ownApp(accountId, id)
  111. if (r == null) { return { error = 'no such app' } }
  112. let secret = newSecret()
  113. appsTable.update(r.id, merged(r, { secretHash = sha256(secret) updated = now() }))
  114. return { app = appRowOf(appsTable.fetch(r.id)) secret = secret }
  115. }
  116. // DELETING AN APP removes its connections (the per-app ids) and its invites with it; a pending login
  117. // request or code for it dies because its app is gone
  118. static deleteApp = (accountId, id) => {
  119. r = ownApp(accountId, id)
  120. if (r == null) { return { error = 'no such app' } }
  121. conns = connectionsTable.find('app', id)
  122. if (countOf(conns) > 0) { for (c of conns) { connectionsTable.delete(c.id) } }
  123. dropInvitesOf(id)
  124. appsTable.delete(r.id)
  125. return { deleted = id }
  126. }
  127. // ---- the login button ---------------------------------------------------------------
  128. // the login button's GET /login?key=&return= : answers { error } or { rid }
  129. static openRequest = (key, returnUrl) => {
  130. a = appByKey(key)
  131. if (a == null) { return { error = key == null || key == '' ? 'the key parameter (the app’s API key) is missing' : 'no app has this API key' } }
  132. r = checkReturn(returnUrl, a)
  133. if (r.error != null) { return r }
  134. let rid = randomBytes(16)
  135. requestsTable.put({ rid = rid app = a.id returnUrl = returnUrl expires = now() + requestTtl })
  136. return { rid = rid }
  137. }
  138. // { rid, app (row), origin, returnUrl } or null (unknown, expired, or its app is gone)
  139. static requestOf = (rid) => {
  140. if (rid == null || hlTypeName(rid) != 'String' || rid == '') { return null }
  141. r = first(requestsTable.find('rid', rid))
  142. if (r == null) { return null }
  143. if (r.expires < now()) {
  144. requestsTable.delete(r.id)
  145. return null
  146. }
  147. a = isId(r.app) ? appsTable.fetch(r.app) : null
  148. if (a == null) { return null }
  149. c = checkReturn(r.returnUrl, a)
  150. if (c.error != null) { return null } // the origin was removed from the app since
  151. return { rid = r.rid app = appRowOf(a) origin = c.origin returnUrl = r.returnUrl invite = r.invite == null ? '' : r.invite }
  152. }
  153. // The identity's connection to the app, made on the first login
  154. static connectionOf = (appId, identityId) => {
  155. let pair = appId + ':' + identityId
  156. c = first(connectionsTable.find('pair', pair))
  157. if (c != null) { return c }
  158. id = connectionsTable.put({ pair = pair app = appId identity = identityId created = now() })
  159. return connectionsTable.fetch(id)
  160. }
  161. // "SIGN OUT" OF AN APP (ticket #2): forgets this identity's connection to it (its
  162. // notification settings for the app). The identity's short id does not change: a later
  163. // login makes a fresh connection and the app gets the same id. Notifications already sent
  164. // through the old connection stay (as for a deleted app).
  165. static disconnectConnection = (accountId, id) => {
  166. if (!isId(id)) { return { error = 'no such app connection' } }
  167. c = connectionsTable.fetch(id)
  168. if (c == null) { return { error = 'no such app connection' } }
  169. ident = ownIdentity(accountId, c.identity)
  170. if (ident == null) { return { error = 'no such app connection' } }
  171. connectionsTable.delete(c.id)
  172. return { disconnected = id }
  173. }
  174. // A ONE-TIME CODE for app `appId` and identity `identityId` (public ids): 48 hex, single
  175. // use, grantTtl (60 s), this app only. The login button AND the selector (lib/selector.hl)
  176. // hand out these codes; the app's server trades one with `exchange` below.
  177. static issueCode = (appId, identityId) => {
  178. connectionOf(appId, identityId)
  179. code = randomBytes(24)
  180. grantsTable.put({ hash = sha256(code) app = appId identity = identityId expires = now() + grantTtl })
  181. return code
  182. }
  183. // THE CHOICE: the account picks one of its identities for the request. Answers { error }
  184. // or { url } — the app's return URL with a fresh one-time `ident_code`.
  185. static grantLogin = (accountId, rid, identityId) => {
  186. rq = requestOf(rid)
  187. if (rq == null) { return { error = 'this login request is unknown or expired — go back to the app and start again' } }
  188. ident = ownIdentity(accountId, identityId)
  189. if (ident == null) { return { error = 'no such identity' } }
  190. code = issueCode(rq.app.id, identityId)
  191. r = first(requestsTable.find('rid', rid))
  192. if (r != null) { requestsTable.delete(r.id) }
  193. sep = rq.returnUrl.includes('?') ? '&' : '?'
  194. return { url = rq.returnUrl + sep + 'ident_code=' + code }
  195. }
  196. // THE EXCHANGE (the app's server): answers { status, error } or { identity }. The app
  197. // authenticates with key + secret (401); a code works once, for its own app, for 60 s (400).
  198. // A code shown to the wrong app is spent: it has leaked.
  199. // ident#11: with `fields` (a list of profile field names the app wants) the answer also carries `profile`, one key per field
  200. // (null when the person has not filled it in); a bad field name is a 400 and the code is NOT spent. Without `fields` nothing changes.
  201. static exchange = (key, secret, code, fields) => {
  202. a = appByKey(key)
  203. if (a == null || sha256(secret) != a.secretHash) { return { status = 401 error = 'unknown API key or wrong secret' } }
  204. let asked = []
  205. if (fields != null) {
  206. pf = checkProfileFields(fields)
  207. if (pf.error != null) { return { status = 400 error = pf.error } }
  208. asked = pf.fields
  209. }
  210. g = first(grantsTable.find('hash', sha256(code)))
  211. if (g == null) { return { status = 400 error = 'unknown or already used code' } }
  212. grantsTable.delete(g.id)
  213. if (g.app != a.id) { return { status = 400 error = 'this code was not issued to this app' } }
  214. if (g.expires < now()) { return { status = 400 error = 'the code expired' } }
  215. c = first(connectionsTable.find('pair', a.id + ':' + g.identity))
  216. ident = isId(g.identity) ? identitiesTable.fetch(g.identity) : null
  217. if (c == null || ident == null) { return { status = 400 error = 'the identity is no longer connected to this app' } }
  218. // ident#26: the "Used in" list's last use — one write per login, none per request
  219. connectionsTable.update(c.id, merged(c, { lastLogin = now() }))
  220. if (fields != null) { return { identity = ident.shortId profile = profileValues(ident, asked) } }
  221. return { identity = ident.shortId }
  222. }
  223. // THE PROFILE, asked later (ident#11): the app's server (key + secret, checked by the route) asks again for an identity (short id)
  224. // that signed in to this app before. Answers { status, error } or { identity, profile }. An identity that does not exist and one that
  225. // never signed in to this app get the same answer, so an app cannot probe for identities.
  226. static profileOf = (a, given, fields) => {
  227. pf = checkProfileFields(fields)
  228. if (pf.error != null) { return { status = 400 error = pf.error } }
  229. ident = identityByShortId(given)
  230. c = ident == null ? null : first(connectionsTable.find('pair', a.id + ':' + ident.id))
  231. if (c == null) { return { status = 404 error = 'no such identity in this app' } }
  232. return { identity = ident.shortId profile = profileValues(ident, pf.fields) }
  233. }
  234. // ---- AN INVITE'S LOGIN (ident#22; the invite records: lib/invites.hl) -------------------------------
  235. // GET /invite/<token>: answers { status, title, error } (an error page) or { rid } — a login
  236. // request of the app that carries the invite, so the login flow does the rest.
  237. static openInvite = (token) => {
  238. o = openableInvite(token)
  239. if (o.error != null) { return o }
  240. rec = o.invite
  241. let rid = randomBytes(16)
  242. requestsTable.put({ rid = rid app = rec.app returnUrl = rec.returnUrl invite = rec.id expires = now() + requestTtl })
  243. return { rid = rid }
  244. }
  245. // THE CHOICE for an invite's request: the identity accepts it. Answers { error } or { url }
  246. // (the app's return URL with ident_code and invite). An identity that already accepted this
  247. // invite may pass again without taking another use.
  248. static grantInvite = (accountId, rid, identityId) => {
  249. rq = requestOf(rid)
  250. if (rq == null) { return { error = 'this login request is unknown or expired — open the invitation link again' } }
  251. rec = inviteById(rq.invite)
  252. if (rec == null || rec.app != rq.app.id) { return { error = 'this invitation no longer exists' } }
  253. if (ownIdentity(accountId, identityId) == null) { return { error = 'no such identity' } }
  254. conn = connectionOf(rq.app.id, identityId)
  255. a = acceptInvite(rec, identityId, conn)
  256. if (a.error != null) { return a }
  257. code = issueCode(rq.app.id, identityId)
  258. r = first(requestsTable.find('rid', rid))
  259. if (r != null) { requestsTable.delete(r.id) }
  260. sep = rq.returnUrl.includes('?') ? '&' : '?'
  261. return { url = rq.returnUrl + sep + 'ident_code=' + code + '&invite=' + rec.id }
  262. }
  263. // the face chooseIdentity (components/home.hl): a request that carries an invite accepts the invite, any
  264. // other is a plain login. Answers { error } or { url }.
  265. static grantRequest = (accountId, rid, identityId) => {
  266. rq = requestOf(rid)
  267. if (rq != null && rq.invite != '') { return grantInvite(accountId, rid, identityId) }
  268. return grantLogin(accountId, rid, identityId)
  269. }
  270. // ---- THE SHORT IDS (ident#23) ---------------------------------------------------------------------
  271. // WHAT THE APP MEANT BY AN ID: a notification or a lookup may name an identity by
  272. // its short id, or — until the app has migrated — by its old per-app id. Answers the
  273. // connection (of app `appId`) or null.
  274. static connectionByAnyId = (appId, given) => {
  275. ident = identityByShortId(given)
  276. if (ident != null) { return first(connectionsTable.find('pair', appId + ':' + ident.id)) }
  277. if (given == null || hlTypeName(given) != 'String') { return null }
  278. rows = connectionsTable.find('app', appId)
  279. if (countOf(rows) > 0) {
  280. for (c of rows) { if (c.appIdentity != null && c.appIdentity == given) { return c } }
  281. }
  282. return null
  283. }
  284. // THE MIGRATION, for the app's server: answers { ids } — every old per-app id
  285. // → the identity's short id (an identity that was deleted has none and is left out).
  286. // With `finish` the old ids are dropped afterwards: the app has stored the short ids.
  287. static migrateIds = (a, finish) => {
  288. let ids = {}
  289. let n = 0
  290. rows = connectionsTable.find('app', a.id)
  291. if (countOf(rows) > 0) {
  292. for (c of rows) {
  293. if (c.appIdentity == null) { continue }
  294. let ident = isId(c.identity) ? identitiesTable.fetch(c.identity) : null
  295. if (ident != null) { ids[c.appIdentity] = ident.shortId n = n + 1 }
  296. if (finish) {
  297. let rec = {}
  298. for (k of c.keys()) { if (k != 'appIdentity') { rec[k] = c[k] } }
  299. connectionsTable.update(c.id, rec)
  300. }
  301. }
  302. }
  303. return { ids = ids count = n finished = finish }
  304. }

Branches

Latest commits

  • 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
  • edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre