gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb96796bdb96796bdtests: wait for hydration before real clicks after a navigation (H2)mreb96796bd/lib/apps.hl

13.7 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 { dropInvitesOf, openableInvite, inviteById, acceptInvite } from './invites.hl'
  33. static appsTable = new MPackDB(file = dir + '/apps.db', primaryKey = '@id', indexes = ['@owner' '!apiKey'])
  34. static connectionsTable = new MPackDB(file = dir + '/connections.db', primaryKey = '@id', indexes = ['!pair' '@app'])
  35. static requestsTable = new MPackDB(file = dir + '/requests.db', primaryKey = '@id', indexes = ['!rid'])
  36. static grantsTable = new MPackDB(file = dir + '/grants.db', primaryKey = '@id', indexes = ['!hash'])
  37. static grantTtl = envNumber('IDENT_GRANT_TTL_MS', 60000) // a one-time code: 60 s
  38. static requestTtl = 1800000 // a login button press: 30 min
  39. // ---- apps -----------------------------------------------------------------------------
  40. // the account's apps, oldest first (stored `created`, never key order)
  41. static appRows = (accountId) => {
  42. out = []
  43. if (!isId(accountId)) { return out }
  44. for (r of oldestFirst(appsTable.find('owner', accountId))) { out.push(appRowOf(r)) }
  45. return out
  46. }
  47. // the app record `id` (public) if the account owns it, else null
  48. static ownApp = (accountId, id) => {
  49. if (!isId(id)) { return null }
  50. r = appsTable.fetch(id)
  51. if (r == null || r.owner != accountId) { return null }
  52. return r
  53. }
  54. static appByKey = (key) => {
  55. if (key == null || hlTypeName(key) != 'String' || key == '') { return null }
  56. return first(appsTable.find('apiKey', key))
  57. }
  58. // THE APP'S SERVER, key + secret: answers the app record or null (unknown key or wrong secret: one answer, 401)
  59. static appOfSecret = (key, secret) => {
  60. a = appByKey(key)
  61. if (a == null || hlTypeName(secret) != 'String' || sha256(secret) != a.secretHash) { return null }
  62. return a
  63. }
  64. // answers { error, field } or { app (row), secret } — the secret leaves ident only here
  65. static createApp = (accountId, input) => {
  66. c = checkAppInput(input)
  67. if (c.error != null) { return c }
  68. let secret = newSecret()
  69. id = appsTable.put({ owner = accountId name = c.name origins = c.origins.join(' ') apiKey = newKey() secretHash = sha256(secret) created = now() updated = now() })
  70. return { app = appRowOf(appsTable.fetch(id)) secret = secret }
  71. }
  72. static updateApp = (accountId, id, input) => {
  73. r = ownApp(accountId, id)
  74. if (r == null) { return { error = 'no such app' field = 'id' } }
  75. c = checkAppInput(input)
  76. if (c.error != null) { return c }
  77. appsTable.update(r.id, merged(r, { name = c.name origins = c.origins.join(' ') updated = now() }))
  78. return { app = appRowOf(appsTable.fetch(r.id)) }
  79. }
  80. // a NEW SECRET: the old one stops working at once; the API key stays
  81. static regenerateSecret = (accountId, id) => {
  82. r = ownApp(accountId, id)
  83. if (r == null) { return { error = 'no such app' } }
  84. let secret = newSecret()
  85. appsTable.update(r.id, merged(r, { secretHash = sha256(secret) updated = now() }))
  86. return { app = appRowOf(appsTable.fetch(r.id)) secret = secret }
  87. }
  88. // DELETING AN APP removes its connections (the per-app ids) and its invites with it; a pending login
  89. // request or code for it dies because its app is gone
  90. static deleteApp = (accountId, id) => {
  91. r = ownApp(accountId, id)
  92. if (r == null) { return { error = 'no such app' } }
  93. conns = connectionsTable.find('app', id)
  94. if (countOf(conns) > 0) { for (c of conns) { connectionsTable.delete(c.id) } }
  95. dropInvitesOf(id)
  96. appsTable.delete(r.id)
  97. return { deleted = id }
  98. }
  99. // ---- the login button ---------------------------------------------------------------
  100. // the login button's GET /login?key=&return= : answers { error } or { rid }
  101. static openRequest = (key, returnUrl) => {
  102. a = appByKey(key)
  103. if (a == null) { return { error = key == null || key == '' ? 'the key parameter (the app’s API key) is missing' : 'no app has this API key' } }
  104. r = checkReturn(returnUrl, a)
  105. if (r.error != null) { return r }
  106. let rid = randomBytes(16)
  107. requestsTable.put({ rid = rid app = a.id returnUrl = returnUrl expires = now() + requestTtl })
  108. return { rid = rid }
  109. }
  110. // { rid, app (row), origin, returnUrl } or null (unknown, expired, or its app is gone)
  111. static requestOf = (rid) => {
  112. if (rid == null || hlTypeName(rid) != 'String' || rid == '') { return null }
  113. r = first(requestsTable.find('rid', rid))
  114. if (r == null) { return null }
  115. if (r.expires < now()) {
  116. requestsTable.delete(r.id)
  117. return null
  118. }
  119. a = isId(r.app) ? appsTable.fetch(r.app) : null
  120. if (a == null) { return null }
  121. c = checkReturn(r.returnUrl, a)
  122. if (c.error != null) { return null } // the origin was removed from the app since
  123. return { rid = r.rid app = appRowOf(a) origin = c.origin returnUrl = r.returnUrl invite = r.invite == null ? '' : r.invite }
  124. }
  125. // The identity's connection to the app, made on the first login
  126. static connectionOf = (appId, identityId) => {
  127. let pair = appId + ':' + identityId
  128. c = first(connectionsTable.find('pair', pair))
  129. if (c != null) { return c }
  130. id = connectionsTable.put({ pair = pair app = appId identity = identityId created = now() })
  131. return connectionsTable.fetch(id)
  132. }
  133. // "SIGN OUT" OF AN APP (ticket #2): forgets this identity's connection to it (its
  134. // notification settings for the app). The identity's short id does not change: a later
  135. // login makes a fresh connection and the app gets the same id. Notifications already sent
  136. // through the old connection stay (as for a deleted app).
  137. static disconnectConnection = (accountId, id) => {
  138. if (!isId(id)) { return { error = 'no such app connection' } }
  139. c = connectionsTable.fetch(id)
  140. if (c == null) { return { error = 'no such app connection' } }
  141. ident = ownIdentity(accountId, c.identity)
  142. if (ident == null) { return { error = 'no such app connection' } }
  143. connectionsTable.delete(c.id)
  144. return { disconnected = id }
  145. }
  146. // A ONE-TIME CODE for app `appId` and identity `identityId` (public ids): 48 hex, single
  147. // use, grantTtl (60 s), this app only. The login button AND the selector (lib/selector.hl)
  148. // hand out these codes; the app's server trades one with `exchange` below.
  149. static issueCode = (appId, identityId) => {
  150. connectionOf(appId, identityId)
  151. code = randomBytes(24)
  152. grantsTable.put({ hash = sha256(code) app = appId identity = identityId expires = now() + grantTtl })
  153. return code
  154. }
  155. // THE CHOICE: the account picks one of its identities for the request. Answers { error }
  156. // or { url } — the app's return URL with a fresh one-time `ident_code`.
  157. static grantLogin = (accountId, rid, identityId) => {
  158. rq = requestOf(rid)
  159. if (rq == null) { return { error = 'this login request is unknown or expired — go back to the app and start again' } }
  160. ident = ownIdentity(accountId, identityId)
  161. if (ident == null) { return { error = 'no such identity' } }
  162. code = issueCode(rq.app.id, identityId)
  163. r = first(requestsTable.find('rid', rid))
  164. if (r != null) { requestsTable.delete(r.id) }
  165. sep = rq.returnUrl.includes('?') ? '&' : '?'
  166. return { url = rq.returnUrl + sep + 'ident_code=' + code }
  167. }
  168. // THE EXCHANGE (the app's server): answers { status, error } or { identity }. The app
  169. // authenticates with key + secret (401); a code works once, for its own app, for 60 s (400).
  170. // A code shown to the wrong app is spent: it has leaked.
  171. static exchange = (key, secret, code) => {
  172. a = appByKey(key)
  173. if (a == null || sha256(secret) != a.secretHash) { return { status = 401 error = 'unknown API key or wrong secret' } }
  174. g = first(grantsTable.find('hash', sha256(code)))
  175. if (g == null) { return { status = 400 error = 'unknown or already used code' } }
  176. grantsTable.delete(g.id)
  177. if (g.app != a.id) { return { status = 400 error = 'this code was not issued to this app' } }
  178. if (g.expires < now()) { return { status = 400 error = 'the code expired' } }
  179. c = first(connectionsTable.find('pair', a.id + ':' + g.identity))
  180. ident = isId(g.identity) ? identitiesTable.fetch(g.identity) : null
  181. if (c == null || ident == null) { return { status = 400 error = 'the identity is no longer connected to this app' } }
  182. // ident#26: the "Used in" list's last use — one write per login, none per request
  183. connectionsTable.update(c.id, merged(c, { lastLogin = now() }))
  184. return { identity = ident.shortId }
  185. }
  186. // ---- AN INVITE'S LOGIN (ident#22; the invite records: lib/invites.hl) -------------------------------
  187. // GET /invite/<token>: answers { status, title, error } (an error page) or { rid } — a login
  188. // request of the app that carries the invite, so the login flow does the rest.
  189. static openInvite = (token) => {
  190. o = openableInvite(token)
  191. if (o.error != null) { return o }
  192. rec = o.invite
  193. let rid = randomBytes(16)
  194. requestsTable.put({ rid = rid app = rec.app returnUrl = rec.returnUrl invite = rec.id expires = now() + requestTtl })
  195. return { rid = rid }
  196. }
  197. // THE CHOICE for an invite's request: the identity accepts it. Answers { error } or { url }
  198. // (the app's return URL with ident_code and invite). An identity that already accepted this
  199. // invite may pass again without taking another use.
  200. static grantInvite = (accountId, rid, identityId) => {
  201. rq = requestOf(rid)
  202. if (rq == null) { return { error = 'this login request is unknown or expired — open the invitation link again' } }
  203. rec = inviteById(rq.invite)
  204. if (rec == null || rec.app != rq.app.id) { return { error = 'this invitation no longer exists' } }
  205. if (ownIdentity(accountId, identityId) == null) { return { error = 'no such identity' } }
  206. conn = connectionOf(rq.app.id, identityId)
  207. a = acceptInvite(rec, identityId, conn)
  208. if (a.error != null) { return a }
  209. code = issueCode(rq.app.id, identityId)
  210. r = first(requestsTable.find('rid', rid))
  211. if (r != null) { requestsTable.delete(r.id) }
  212. sep = rq.returnUrl.includes('?') ? '&' : '?'
  213. return { url = rq.returnUrl + sep + 'ident_code=' + code + '&invite=' + rec.id }
  214. }
  215. // the face chooseIdentity (components/home.hl): a request that carries an invite accepts the invite, any
  216. // other is a plain login. Answers { error } or { url }.
  217. static grantRequest = (accountId, rid, identityId) => {
  218. rq = requestOf(rid)
  219. if (rq != null && rq.invite != '') { return grantInvite(accountId, rid, identityId) }
  220. return grantLogin(accountId, rid, identityId)
  221. }
  222. // ---- THE SHORT IDS (ident#23) ---------------------------------------------------------------------
  223. // WHAT THE APP MEANT BY AN ID: a notification or a lookup may name an identity by
  224. // its short id, or — until the app has migrated — by its old per-app id. Answers the
  225. // connection (of app `appId`) or null.
  226. static connectionByAnyId = (appId, given) => {
  227. ident = identityByShortId(given)
  228. if (ident != null) { return first(connectionsTable.find('pair', appId + ':' + ident.id)) }
  229. if (given == null || hlTypeName(given) != 'String') { return null }
  230. rows = connectionsTable.find('app', appId)
  231. if (countOf(rows) > 0) {
  232. for (c of rows) { if (c.appIdentity != null && c.appIdentity == given) { return c } }
  233. }
  234. return null
  235. }
  236. // THE MIGRATION, for the app's server: answers { ids } — every old per-app id
  237. // → the identity's short id (an identity that was deleted has none and is left out).
  238. // With `finish` the old ids are dropped afterwards: the app has stored the short ids.
  239. static migrateIds = (a, finish) => {
  240. let ids = {}
  241. let n = 0
  242. rows = connectionsTable.find('app', a.id)
  243. if (countOf(rows) > 0) {
  244. for (c of rows) {
  245. if (c.appIdentity == null) { continue }
  246. let ident = isId(c.identity) ? identitiesTable.fetch(c.identity) : null
  247. if (ident != null) { ids[c.appIdentity] = ident.shortId n = n + 1 }
  248. if (finish) {
  249. let rec = {}
  250. for (k of c.keys()) { if (k != 'appIdentity') { rec[k] = c[k] } }
  251. connectionsTable.update(c.id, rec)
  252. }
  253. }
  254. }
  255. return { ids = ids count = n finished = finish }
  256. }

Branches

Latest commits

  • b96796bdtests: wait for hydration before real clicks after a navigation (H2)mre
  • 9722964fre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • c9b196c9tests/iplimit: wait for the welcome form itself after B's first login (identities list renders before it); mission 017 reportmre
  • 72e0f587ident#26: identity page with "Used in" (app, since, last use, Notif. chip, empty state); lastLogin recorded at exchange; gates + lisbeth E2E; mission 016 reportmre
  • 94576fbcident#26 WIP: identity page /identity/:iid with "Used in" (app, since, last use, Notif. chip), lastLogin recorded at exchange, "Used in…" link on the identities list; apps gate 4b, e2e-usedin.mjsmre
  • 349cb502tests/invites: wait for hydration on the code page before entering the code (native GET submit raced the welcome form); mission 015 reportmre
  • d1bf4720tests: no hard-coded ports — every gate's ports and fixture origins come from <GATE>_PORT / _CHROME env (defaults unchanged; Bob/fixture origins follow, selector cookie name too)mre
  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 147744bftests/migration: the fixture app origin follows MIGRATION_GATE_TESTAPP_PORT (oldstore-009 OLD_TESTAPP)mre
  • 48cd36bctests/migration: ports from env (MIGRATION_GATE_PORT, MIGRATION_GATE_TESTAPP_PORT); 8395/8396 were taken by a foreign servermre
  • 3d9b2fd8docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 19b7e3c3deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre
  • 9cc8eddftests: notify and iplimit gate Chrome ports from env (NOTIFY_GATE_CHROME, IPLIMIT_GATE_CHROME_A/B)mre
  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre