gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain0f6d1592Merge branch 'f18b-shell-session' into mainIdentmain/lib/access.hl

11.5 KB

  1. // lib/access.hl — IDENTITY ACCESS (ident#27): ONE KEY per identity (`idt_` + 48 hex) for all the apps it has access to, given from
  2. // the account's own session, no logging out and in. Every write to the keys and access tables is here; the Access page
  3. // (components/access.hl) and the app's check (lib/api.hl apiIntrospect) call these. Statics only, the server realm.
  4. //
  5. // keysTable pk @id index !hash, @identity { identity (identity @id), hash = sha256(key), tail (last 3 chars), label, created, lastUse, revoked }
  6. // the key is shown ONCE, when it is made; only the hash is stored. One live key per identity (a rotation revokes the old one at once).
  7. // accessTable pk @id index !pair, @identity, @app one row per cell of the matrix:
  8. // { pair = '<identity @id>:<app @id>', identity, app, level ('write' | 'read'), created, createdBy (account @id),
  9. // lastUse, calls (all time), days ({ '<day number>': calls }, the last 30 days) }
  10. //
  11. // An app asks ident whether a key is valid (POST /api/introspect, with its own key + secret): ident reads the tables at that moment, so a
  12. // revoke is dead for the app at once; the app's own cache (the proposal's 30 s) is the only delay. Every answer that says active records the use.
  13. import { MPackDB } from 'hl:mpackdb'
  14. import { now, timestamp } from 'hl:time'
  15. import { randomBytes, sha256 } from 'hl:crypto'
  16. import { dir, countOf, first, merged, isId, str, oldestFirst } from './util.hl'
  17. import { identityRecords, identityRecord, ownIdentity, createAgent, isAgent, identitiesTable } from './identities.hl'
  18. import { appsTable, appRows, ownApp, connectionsTable } from './apps.hl'
  19. import { labelOf } from './identities-helpers.hl'
  20. import { dayText, agoText, whole } from './usedin-helpers.hl'
  21. static keysTable = new MPackDB(file = dir + '/accesskeys.db', primaryKey = '@id', indexes = ['!hash' '@identity'])
  22. static accessTable = new MPackDB(file = dir + '/access.db', primaryKey = '@id', indexes = ['!pair' '@identity' '@app'])
  23. static dayMs = 86400000
  24. static hexChars = '0123456789abcdef'
  25. // `idt_` + 48 hex; anything else is refused without a lookup
  26. static isKeyShape = (t) => {
  27. if (t == null || hlTypeName(t) != 'String' || t.length != 52 || !t.startsWith('idt_')) { return false }
  28. let i = 4
  29. while (i < 52) {
  30. if (!hexChars.includes(t[i])) { return false }
  31. i = i + 1
  32. }
  33. return true
  34. }
  35. // the identity's live key row, or null
  36. static liveKeyOf = (identityId) => {
  37. rows = keysTable.find('identity', identityId)
  38. if (countOf(rows) > 0) { for (k of rows) { if (k.revoked == null) { return k } } }
  39. return null
  40. }
  41. // a NEW KEY for the identity: answers the key string (shown once)
  42. static issueKey = (identityId, label) => {
  43. key = 'idt_' + randomBytes(24)
  44. keysTable.put({ identity = identityId hash = sha256(key) tail = key.slice(49, 52) label = label created = now() })
  45. return key
  46. }
  47. // ---- reading: the matrix, the cell, the give-access list -------------------------------------------------------
  48. static grantOf = (identityId, appId) => { return first(accessTable.find('pair', identityId + ':' + appId)) }
  49. static grantsOf = (identityId) => { return accessTable.find('identity', identityId) }
  50. static whoText = (r, n) => { return labelOf(r, n) }
  51. // the Access page: { apps: [{ id, name }], rows: [{ id, shortId, label, sub, isAgent, cells: [{ app, appName, state, level }] }], never: [...], hasNever }
  52. // state: 'key' (an agent key works there), 'login' (the identity logged in there as a person), 'none'
  53. static matrix = (accountId) => {
  54. t = now()
  55. apps = appRows(accountId)
  56. let rows = []
  57. let never = []
  58. let n = 1
  59. for (r of identityRecords(accountId)) {
  60. let cells = []
  61. let grants = 0
  62. for (a of apps) {
  63. g = grantOf(r.id, a.id)
  64. conn = first(connectionsTable.find('pair', a.id + ':' + r.id))
  65. let state = 'none'
  66. let level = ''
  67. if (g != null) { state = 'key' level = g.level grants = grants + 1 }
  68. else if (conn != null) { state = 'login' }
  69. cells.push({ app = a.id appName = a.name state = state level = level cls = 'cell ' + state value = r.id + ':' + a.id tip = labelOf(r, n) + ' in ' + a.name + ': ' + (state == 'key' ? 'agent key works' : (state == 'login' ? 'logs in there' : 'no access')) glyph = state == 'key' ? '●' : (state == 'login' ? '◐' : '○') })
  70. if (g != null && g.lastUse == null) { never.push({ identity = r.id app = a.id value = r.id + ':' + a.id text = labelOf(r, n) + ' · ' + a.name line = 'given ' + agoText(g.created, t) + ', no call yet' }) }
  71. }
  72. let sub = 'you'
  73. if (isAgent(r)) { sub = grants > 0 ? 'agent' : 'no access' }
  74. rows.push({ id = r.id href = '/identity/' + r.id shortId = str(r.shortId) label = labelOf(r, n) sub = sub isAgent = isAgent(r) cells = cells })
  75. n = n + 1
  76. }
  77. return { apps = apps rows = rows never = never hasNever = never.length > 0 }
  78. }
  79. // calls in the last 30 days of a grant
  80. static calls30 = (g) => {
  81. let sum = 0
  82. if (g.days == null) { return 0 }
  83. today = whole(now() / dayMs)
  84. for (k of g.days.keys()) { if (toNumber(k) > today - 30) { sum = sum + g.days[k] } }
  85. return sum
  86. }
  87. // the cell's sheet: { text, since, last, level, hasGrant, hasKey } for the account's identity and app, or null
  88. static cellOf = (accountId, identityId, appId) => {
  89. r = ownIdentity(accountId, identityId)
  90. a = ownApp(accountId, appId)
  91. if (r == null || a == null) { return null }
  92. g = grantOf(r.id, a.id)
  93. t = now()
  94. if (g == null) {
  95. conn = first(connectionsTable.find('pair', a.id + ':' + r.id))
  96. return { identity = r.id app = a.id who = labelOf(r, 1) appName = a.name hasGrant = false noGrant = true login = conn != null noLogin = conn == null since = '' last = '' level = '' isAgent = isAgent(r) }
  97. }
  98. ts = timestamp(g.created)
  99. let last = 'never used'
  100. if (g.lastUse != null) { last = agoText(g.lastUse, t) + ' · ' + calls30(g) + ' calls in 30 days' }
  101. return { identity = r.id app = a.id who = labelOf(r, 1) appName = a.name hasGrant = true noGrant = false login = false noLogin = true since = ts.slice(0, 10) + ' ' + ts.slice(11, 16) + ' · by you' last = last level = g.level == 'write' ? 'read + write' : 'read only' levelRaw = g.level isAgent = isAgent(r) }
  102. }
  103. // step 1 of giving access: the account's identities, agents first
  104. static pickList = (accountId) => {
  105. agents = []
  106. people = []
  107. let n = 1
  108. for (r of identityRecords(accountId)) {
  109. g = countOf(grantsOf(r.id))
  110. let sub = 'you'
  111. if (isAgent(r)) { sub = g > 0 ? 'agent · in ' + g + (g == 1 ? ' app' : ' apps') : 'agent · no access yet' }
  112. row = { id = r.id label = labelOf(r, n) sub = sub initial = labelOf(r, n).slice(0, 1).toUpperCase() isAgent = isAgent(r) hasKey = liveKeyOf(r.id) != null }
  113. if (isAgent(r)) { agents.push(row) } else { people.push(row) }
  114. n = n + 1
  115. }
  116. out = []
  117. for (x of agents) { out.push(x) }
  118. for (x of people) { out.push(x) }
  119. return out
  120. }
  121. // ---- writing ---------------------------------------------------------------------------------------------------
  122. // GIVE ACCESS: input { identity (id) | newName, apps [app ids], level, label }. Makes the agent identity when `newName` is given. The first
  123. // access of an identity makes its ONE key (answered as `key`, shown once); later ones add grants to the existing key (`key` null).
  124. // Answers { error } or { identity, who, key, apps (names), level }
  125. static giveAccess = (accountId, input) => {
  126. if (input == null || hlTypeName(input) != 'Hybrid') { return { error = 'no input' } }
  127. lv = input.level == 'read' ? 'read' : 'write'
  128. if (input.apps == null || hlTypeName(input.apps) != 'Hybrid' || input.apps.length == null || input.apps.length == 0) { return { error = 'tick at least one app' } }
  129. if (input.apps.length > 100) { return { error = 'too many apps' } }
  130. chosen = []
  131. for (id of input.apps) {
  132. a = ownApp(accountId, id)
  133. if (a == null) { return { error = 'no such app' } }
  134. chosen.push(a)
  135. }
  136. let identityId = input.identity
  137. if (input.newName != null && ('' + input.newName).trim() != '') {
  138. c = createAgent(accountId, '' + input.newName)
  139. if (c.error != null) { return c }
  140. identityId = c.identity
  141. }
  142. r = ownIdentity(accountId, identityId)
  143. if (r == null) { return { error = 'no such identity' } }
  144. names = []
  145. for (a of chosen) {
  146. g = grantOf(r.id, a.id)
  147. if (g == null) { accessTable.put({ pair = r.id + ':' + a.id identity = r.id app = a.id level = lv created = now() createdBy = accountId calls = 0 }) }
  148. else { accessTable.update(g.id, merged(g, { level = lv })) }
  149. names.push(a.name)
  150. }
  151. let key = null
  152. if (liveKeyOf(r.id) == null) {
  153. lab = input.label == null || ('' + input.label).trim() == '' ? labelOf(r, 1) : ('' + input.label).trim()
  154. if (lab.length > 60) { return { error = 'the key label is longer than 60 characters' } }
  155. key = issueKey(r.id, lab)
  156. }
  157. return { identity = r.id who = labelOf(r, 1) key = key apps = names level = lv }
  158. }
  159. // REVOKE one cell: the identity has no access to the app at once. Answers { error } or { revoked }
  160. static revokeAccess = (accountId, identityId, appId) => {
  161. r = ownIdentity(accountId, identityId)
  162. a = ownApp(accountId, appId)
  163. if (r == null || a == null) { return { error = 'no such cell' } }
  164. g = grantOf(r.id, a.id)
  165. if (g == null) { return { error = 'no access to revoke' } }
  166. accessTable.delete(g.id)
  167. return { revoked = g.id }
  168. }
  169. // the cell's level: 'read' or 'write'
  170. static setLevel = (accountId, identityId, appId, level) => {
  171. r = ownIdentity(accountId, identityId)
  172. a = ownApp(accountId, appId)
  173. if (r == null || a == null) { return { error = 'no such cell' } }
  174. g = grantOf(r.id, a.id)
  175. if (g == null) { return { error = 'no access to change' } }
  176. if (level != 'read' && level != 'write') { return { error = 'level must be read or write' } }
  177. accessTable.update(g.id, merged(g, { level = level }))
  178. return { level = level }
  179. }
  180. // ROTATE: a new key for the identity, the old one is dead at once. Answers { error } or { identity, who, key, apps }
  181. static rotateKey = (accountId, identityId) => {
  182. r = ownIdentity(accountId, identityId)
  183. if (r == null) { return { error = 'no such identity' } }
  184. grants = grantsOf(r.id)
  185. if (countOf(grants) == 0) { return { error = 'this identity has no access yet — give it access first' } }
  186. old = liveKeyOf(r.id)
  187. let label = labelOf(r, 1)
  188. if (old != null) {
  189. label = old.label
  190. keysTable.update(old.id, merged(old, { revoked = now() }))
  191. }
  192. let key = issueKey(r.id, label)
  193. names = []
  194. for (g of grants) { a = isId(g.app) ? appsTable.fetch(g.app) : null if (a != null) { names.push(a.name) } }
  195. return { identity = r.id who = labelOf(r, 1) key = key apps = names level = '' }
  196. }
  197. // ---- THE APP'S QUESTION: is this key valid, for whom, with which rights? -------------------------------------------
  198. // `a` is the asking app (its key + secret were checked by the route). Answers { active = false } or { active = true, identity (short id),
  199. // name, access }. A key counts only for an app the identity was given access to, and only while the identity exists. Records the use.
  200. static introspect = (a, token) => {
  201. if (!isKeyShape(token)) { return { active = false } }
  202. k = first(keysTable.find('hash', sha256(token)))
  203. if (k == null || k.revoked != null) { return { active = false } }
  204. r = identityRecord(k.identity)
  205. if (r == null) { return { active = false } }
  206. g = grantOf(r.id, a.id)
  207. if (g == null) { return { active = false } }
  208. t = now()
  209. let days = g.days == null ? {} : g.days
  210. today = '' + whole(t / dayMs)
  211. kept = {}
  212. for (d of days.keys()) { if (toNumber(d) > whole(t / dayMs) - 30) { kept[d] = days[d] } }
  213. kept[today] = (kept[today] == null ? 0 : kept[today]) + 1
  214. accessTable.update(g.id, merged(g, { lastUse = t calls = (g.calls == null ? 0 : g.calls) + 1 days = kept }))
  215. keysTable.update(k.id, merged(k, { lastUse = t }))
  216. return { active = true identity = r.shortId name = labelOf(r, 1) access = g.level }
  217. }

Branches

Latest commits

  • 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
  • 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
  • 5d1b3fedMerge branch 'v61-day61' into mainIdent
  • 83faeb15|||PR ident: vendor Hybriel day61mre
  • b2572b34Merge branch 'v59-day59' into mainIdent
  • 67cf016d|||PR ident: vendor Hybriel day59mre
  • 600c043dMerge branch 'v58-day58' into mainIdent
  • 365f8c80|||PR ident: vendor Hybriel day58mre
  • 585126e5Merge branch 'f16-setf' into mainIdent
  • 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
  • a1419d9cMerge branch 'f15-navigate' into mainIdent
  • 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
  • e36f4516Merge branch 'f14-online' into mainIdent
  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre