ident
All repositories: gitoria
11.5 KB
// lib/access.hl — IDENTITY ACCESS (ident#27): ONE KEY per identity (`idt_` + 48 hex) for all the apps it has access to, given from// the account's own session, no logging out and in. Every write to the keys and access tables is here; the Access page// (components/access.hl) and the app's check (lib/api.hl apiIntrospect) call these. Statics only, the server realm.//// keysTable pk @id index !hash, @identity { identity (identity @id), hash = sha256(key), tail (last 3 chars), label, created, lastUse, revoked }// 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).// accessTable pk @id index !pair, @identity, @app one row per cell of the matrix:// { pair = '<identity @id>:<app @id>', identity, app, level ('write' | 'read'), created, createdBy (account @id),// lastUse, calls (all time), days ({ '<day number>': calls }, the last 30 days) }//// 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// 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.import { MPackDB } from 'hl:mpackdb'import { now, timestamp } from 'hl:time'import { randomBytes, sha256 } from 'hl:crypto'import { dir, countOf, first, merged, isId, str, oldestFirst } from './util.hl'import { identityRecords, identityRecord, ownIdentity, createAgent, isAgent, identitiesTable } from './identities.hl'import { appsTable, appRows, ownApp, connectionsTable } from './apps.hl'import { labelOf } from './identities-helpers.hl'import { dayText, agoText, whole } from './usedin-helpers.hl'static keysTable = new MPackDB(file = dir + '/accesskeys.db', primaryKey = '@id', indexes = ['!hash' '@identity'])static accessTable = new MPackDB(file = dir + '/access.db', primaryKey = '@id', indexes = ['!pair' '@identity' '@app'])static dayMs = 86400000static hexChars = '0123456789abcdef'// `idt_` + 48 hex; anything else is refused without a lookupstatic isKeyShape = (t) => {if (t == null || hlTypeName(t) != 'String' || t.length != 52 || !t.startsWith('idt_')) { return false }let i = 4while (i < 52) {if (!hexChars.includes(t[i])) { return false }i = i + 1}return true}// the identity's live key row, or nullstatic liveKeyOf = (identityId) => {rows = keysTable.find('identity', identityId)if (countOf(rows) > 0) { for (k of rows) { if (k.revoked == null) { return k } } }return null}// a NEW KEY for the identity: answers the key string (shown once)static issueKey = (identityId, label) => {key = 'idt_' + randomBytes(24)keysTable.put({ identity = identityId hash = sha256(key) tail = key.slice(49, 52) label = label created = now() })return key}// ---- reading: the matrix, the cell, the give-access list -------------------------------------------------------static grantOf = (identityId, appId) => { return first(accessTable.find('pair', identityId + ':' + appId)) }static grantsOf = (identityId) => { return accessTable.find('identity', identityId) }static whoText = (r, n) => { return labelOf(r, n) }// the Access page: { apps: [{ id, name }], rows: [{ id, shortId, label, sub, isAgent, cells: [{ app, appName, state, level }] }], never: [...], hasNever }// state: 'key' (an agent key works there), 'login' (the identity logged in there as a person), 'none'static matrix = (accountId) => {t = now()apps = appRows(accountId)let rows = []let never = []let n = 1for (r of identityRecords(accountId)) {let cells = []let grants = 0for (a of apps) {g = grantOf(r.id, a.id)conn = first(connectionsTable.find('pair', a.id + ':' + r.id))let state = 'none'let level = ''if (g != null) { state = 'key' level = g.level grants = grants + 1 }else if (conn != null) { state = 'login' }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' ? '◐' : '○') })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' }) }}let sub = 'you'if (isAgent(r)) { sub = grants > 0 ? 'agent' : 'no access' }rows.push({ id = r.id href = '/identity/' + r.id shortId = str(r.shortId) label = labelOf(r, n) sub = sub isAgent = isAgent(r) cells = cells })n = n + 1}return { apps = apps rows = rows never = never hasNever = never.length > 0 }}// calls in the last 30 days of a grantstatic calls30 = (g) => {let sum = 0if (g.days == null) { return 0 }today = whole(now() / dayMs)for (k of g.days.keys()) { if (toNumber(k) > today - 30) { sum = sum + g.days[k] } }return sum}// the cell's sheet: { text, since, last, level, hasGrant, hasKey } for the account's identity and app, or nullstatic cellOf = (accountId, identityId, appId) => {r = ownIdentity(accountId, identityId)a = ownApp(accountId, appId)if (r == null || a == null) { return null }g = grantOf(r.id, a.id)t = now()if (g == null) {conn = first(connectionsTable.find('pair', a.id + ':' + r.id))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) }}ts = timestamp(g.created)let last = 'never used'if (g.lastUse != null) { last = agoText(g.lastUse, t) + ' · ' + calls30(g) + ' calls in 30 days' }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) }}// step 1 of giving access: the account's identities, agents firststatic pickList = (accountId) => {agents = []people = []let n = 1for (r of identityRecords(accountId)) {g = countOf(grantsOf(r.id))let sub = 'you'if (isAgent(r)) { sub = g > 0 ? 'agent · in ' + g + (g == 1 ? ' app' : ' apps') : 'agent · no access yet' }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 }if (isAgent(r)) { agents.push(row) } else { people.push(row) }n = n + 1}out = []for (x of agents) { out.push(x) }for (x of people) { out.push(x) }return out}// ---- writing ---------------------------------------------------------------------------------------------------// GIVE ACCESS: input { identity (id) | newName, apps [app ids], level, label }. Makes the agent identity when `newName` is given. The first// access of an identity makes its ONE key (answered as `key`, shown once); later ones add grants to the existing key (`key` null).// Answers { error } or { identity, who, key, apps (names), level }static giveAccess = (accountId, input) => {if (input == null || hlTypeName(input) != 'Hybrid') { return { error = 'no input' } }lv = input.level == 'read' ? 'read' : 'write'if (input.apps == null || hlTypeName(input.apps) != 'Hybrid' || input.apps.length == null || input.apps.length == 0) { return { error = 'tick at least one app' } }if (input.apps.length > 100) { return { error = 'too many apps' } }chosen = []for (id of input.apps) {a = ownApp(accountId, id)if (a == null) { return { error = 'no such app' } }chosen.push(a)}let identityId = input.identityif (input.newName != null && ('' + input.newName).trim() != '') {c = createAgent(accountId, '' + input.newName)if (c.error != null) { return c }identityId = c.identity}r = ownIdentity(accountId, identityId)if (r == null) { return { error = 'no such identity' } }names = []for (a of chosen) {g = grantOf(r.id, a.id)if (g == null) { accessTable.put({ pair = r.id + ':' + a.id identity = r.id app = a.id level = lv created = now() createdBy = accountId calls = 0 }) }else { accessTable.update(g.id, merged(g, { level = lv })) }names.push(a.name)}let key = nullif (liveKeyOf(r.id) == null) {lab = input.label == null || ('' + input.label).trim() == '' ? labelOf(r, 1) : ('' + input.label).trim()if (lab.length > 60) { return { error = 'the key label is longer than 60 characters' } }key = issueKey(r.id, lab)}return { identity = r.id who = labelOf(r, 1) key = key apps = names level = lv }}// REVOKE one cell: the identity has no access to the app at once. Answers { error } or { revoked }static revokeAccess = (accountId, identityId, appId) => {r = ownIdentity(accountId, identityId)a = ownApp(accountId, appId)if (r == null || a == null) { return { error = 'no such cell' } }g = grantOf(r.id, a.id)if (g == null) { return { error = 'no access to revoke' } }accessTable.delete(g.id)return { revoked = g.id }}// the cell's level: 'read' or 'write'static setLevel = (accountId, identityId, appId, level) => {r = ownIdentity(accountId, identityId)a = ownApp(accountId, appId)if (r == null || a == null) { return { error = 'no such cell' } }g = grantOf(r.id, a.id)if (g == null) { return { error = 'no access to change' } }if (level != 'read' && level != 'write') { return { error = 'level must be read or write' } }accessTable.update(g.id, merged(g, { level = level }))return { level = level }}// ROTATE: a new key for the identity, the old one is dead at once. Answers { error } or { identity, who, key, apps }static rotateKey = (accountId, identityId) => {r = ownIdentity(accountId, identityId)if (r == null) { return { error = 'no such identity' } }grants = grantsOf(r.id)if (countOf(grants) == 0) { return { error = 'this identity has no access yet — give it access first' } }old = liveKeyOf(r.id)let label = labelOf(r, 1)if (old != null) {label = old.labelkeysTable.update(old.id, merged(old, { revoked = now() }))}let key = issueKey(r.id, label)names = []for (g of grants) { a = isId(g.app) ? appsTable.fetch(g.app) : null if (a != null) { names.push(a.name) } }return { identity = r.id who = labelOf(r, 1) key = key apps = names level = '' }}// ---- THE APP'S QUESTION: is this key valid, for whom, with which rights? -------------------------------------------// `a` is the asking app (its key + secret were checked by the route). Answers { active = false } or { active = true, identity (short id),// name, access }. A key counts only for an app the identity was given access to, and only while the identity exists. Records the use.static introspect = (a, token) => {if (!isKeyShape(token)) { return { active = false } }k = first(keysTable.find('hash', sha256(token)))if (k == null || k.revoked != null) { return { active = false } }r = identityRecord(k.identity)if (r == null) { return { active = false } }g = grantOf(r.id, a.id)if (g == null) { return { active = false } }t = now()let days = g.days == null ? {} : g.daystoday = '' + whole(t / dayMs)kept = {}for (d of days.keys()) { if (toNumber(d) > whole(t / dayMs) - 30) { kept[d] = days[d] } }kept[today] = (kept[today] == null ? 0 : kept[today]) + 1accessTable.update(g.id, merged(g, { lastUse = t calls = (g.calls == null ? 0 : g.calls) + 1 days = kept }))keysTable.update(k.id, merged(k, { lastUse = t }))return { active = true identity = r.shortId name = labelOf(r, 1) access = g.level }}
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