Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/acl/accessControlSubjects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { LiveStore, sym } from 'rdflib'
import { ns } from '../util/ns'

export type AccessControlSubjectKind = 'agent' | 'agentGroup' | 'agentClass' | 'origin'

export type AccessControlSubject = {
kind: AccessControlSubjectKind
subjectValue: string
}

const ACCESS_CONTROL_SUBJECT_GROUPS = {
agentClass: [ns.foaf('Agent'), ns.acl('AuthenticatedAgent'), ns.rdf('Resource'), ns.owl('Thing')],
agent: [ns.vcard('WebID'), ns.vcard('Individual'), ns.foaf('Person'), ns.foaf('Agent')],
group: [ns.vcard('Group')],
origin: [ns.solid('AppProvider'), ns.solid('AppProviderClass')]
} as const

function hasKnownTypes (types: Record<string, unknown>): boolean {
return Object.keys(types).length > 0
}

function isHttpUrl (value: string): boolean {
return value.startsWith('http://') || value.startsWith('https://')
}

function isBareOriginUrl (value: string): boolean {
try {
const parsed = new URL(value)
return parsed.pathname === '/' && !parsed.hash
Comment thread
SharonStrats marked this conversation as resolved.
} catch (_error) {
return false
}
}

function normalizeOriginUrl (value: string): string {
try {
const parsed = new URL(value)
if (parsed.pathname === '/' && !parsed.hash) {
return `${parsed.protocol}//${parsed.host}`
}
} catch (_error) {
// Return the original value below when parsing fails.
}

return value
}

export async function classifyAccessControlSubject (store: LiveStore, principle: string): Promise<AccessControlSubject | undefined> {
const subject = sym(principle)
let types = store.findTypeURIs(subject)

if (isBareOriginUrl(principle)) {
return { kind: 'origin', subjectValue: normalizeOriginUrl(principle) }
}

if (!hasKnownTypes(types) && isHttpUrl(principle)) {
try {
await store.fetcher.load(subject.doc())
} catch (error) {
console.error(`Failed to load access target ${principle}`, error)
}

types = store.findTypeURIs(subject)
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.origin.some(term => term.uri in types)) {
return { kind: 'origin', subjectValue: principle }
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.agent.some(term => term.uri in types)) {
const preferredURI = store.any(subject, ns.foaf('preferredURI'))
return {
kind: 'agent',
subjectValue: preferredURI?.value ?? principle
}
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.group.some(term => term.uri in types)) {
return { kind: 'agentGroup', subjectValue: principle }
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.agentClass.some(term => subject.sameTerm(term))) {
return { kind: 'agentClass', subjectValue: principle }
}

return undefined
}
6 changes: 6 additions & 0 deletions src/acl/aclLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { applyPlan as applyAuthorizationPlan, findEffectiveACL, planGrant as pla
import { graph, NamedNode, Namespace, serialize, sym } from 'rdflib'
import type { AclLogic } from '../types'
import { ns as namespace } from '../util/ns'
import * as accessControlSubjects from './accessControlSubjects'

// Helpers available from @dokieli/web-access-control:
// - Discovery: findEffectiveACL, parentContainer
Expand Down Expand Up @@ -70,6 +71,10 @@ export function createAclLogic(store): AclLogic {
async function applyPlan(plan: PatchPlan): Promise<Response> {
return applyAuthorizationPlan(plan, { fetch: getFetch() })
}

async function classifyAccessControlSubject(principle: string) {
return accessControlSubjects.classifyAccessControlSubject(store, principle)
}
/**
* Simple Access Control
*
Expand Down Expand Up @@ -206,6 +211,7 @@ export function createAclLogic(store): AclLogic {
planRevoke,
planPublicRead,
applyPlan,
classifyAccessControlSubject,
setACLUserPublic,
genACLText
}
Expand Down
89 changes: 89 additions & 0 deletions src/directory/catalogDirectory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { type DirectoryEntry } from '../types'
import { graph, type LiveStore, NamedNode, parse } from 'rdflib'
import { ns } from '../util/ns'
import * as debug from '../util/debug'
import { isHttpUri } from './directoryHelpers'

const CATALOG_VOCAB = 'http://example.org#'

export function createCatalogDirectoryDiscovery () {
const catalogEntriesCache = new Map<string, Promise<DirectoryEntry[]>>()

async function discoverCatalogEntries (
catalogUrl: string,
onEntry: (entry: DirectoryEntry) => void | Promise<void>
): Promise<void> {
const entries = await fetchCatalogEntries(catalogUrl)
for (const entry of entries) {
await onEntry(entry)
}
}

async function fetchCatalogEntries (catalogUrl: string): Promise<DirectoryEntry[]> {
const cached = catalogEntriesCache.get(catalogUrl)
if (cached) {
return cached
}

const promise = (async () => {
if (typeof fetch !== 'function') {
return []
}

try {
const response = await fetch(catalogUrl, {
headers: { accept: 'text/turtle' }
})

if (!response.ok) {
debug.warn(`[Directory] Failed to fetch ${catalogUrl}: ${response.status}`)
return []
}

const turtle = await response.text()
const catalogStore = graph() as LiveStore
parse(turtle, catalogStore, catalogUrl, 'text/turtle')

const personType = new NamedNode(`${CATALOG_VOCAB}Person`)
const webIdPredicate = new NamedNode(`${CATALOG_VOCAB}webid`)
const namePredicate = new NamedNode(`${CATALOG_VOCAB}name`)
const catalogPeople = new Map<string, DirectoryEntry>()

const statements = catalogStore.statementsMatching(undefined, ns.rdf('type'), personType)
for (const statement of statements) {
const subject = statement.subject
const webIdNode = catalogStore.any(subject, webIdPredicate)
if (webIdNode && webIdNode.termType === 'NamedNode') {
const webId = webIdNode.value
const personName = catalogStore.anyValue(subject, namePredicate)
if (isHttpUri(webId) && personName) {
catalogPeople.set(webId, {
kind: 'person',
uri: webId,
label: personName,
subjectType: 'agent',
relationshipLabel: 'People',
sources: ['catalog']
})
}
}
}

return Array.from(catalogPeople.values())
} catch (error) {
debug.warn('[Directory] Error fetching directory catalog:', error)
return []
}
})().catch(error => {
catalogEntriesCache.delete(catalogUrl)
throw error
})

catalogEntriesCache.set(catalogUrl, promise)
Comment thread
SharonStrats marked this conversation as resolved.
return promise
}

return {
discoverCatalogEntries
}
}
148 changes: 148 additions & 0 deletions src/directory/contactsDirectory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { type DirectoryEntry, type DirectorySource, type TypeIndexLogic } from '../types'
import { type LiveStore, NamedNode } from 'rdflib'
import { ns } from '../util/ns'
import { isHttpUri, labelForNode, loadDocumentSilently, uniqueNamedNodes } from './directoryHelpers'

const CONTACT_CARD_CONCURRENCY = 8

export function createContactsDirectoryDiscovery (
store: LiveStore,
typeIndexLogic: TypeIndexLogic
) {
const personalAddressBooksCache = new Map<string, Promise<NamedNode[]>>()
const contactWebIdCache = new Map<string, Promise<string | null>>()

async function loadPersonalAddressBooks (user: NamedNode): Promise<NamedNode[]> {
const cached = personalAddressBooksCache.get(user.value)
if (cached) {
return cached
}

const promise = (async () => {
const scopes = await typeIndexLogic.loadTypeIndexesFor(user)
let scopedApps = [] as Awaited<ReturnType<TypeIndexLogic['getScopedAppsFromIndex']>>

for (const scope of scopes) {
const apps = await typeIndexLogic.getScopedAppsFromIndex(scope, ns.vcard('AddressBook'))
scopedApps = scopedApps.concat(apps)
}

return uniqueNamedNodes(scopedApps.map(app => app.instance))
})().catch(error => {
personalAddressBooksCache.delete(user.value)
throw error
})

personalAddressBooksCache.set(user.value, promise)
return promise
}

async function webIdForAddressBookContact (contact: NamedNode): Promise<string | null> {
const cached = contactWebIdCache.get(contact.value)
if (cached) {
return cached
}

const promise = (async () => {
if (!await loadDocumentSilently(store, contact)) {
return null
}

const urlNodes = store.each(contact, ns.vcard('url'), null, contact.doc()) as NamedNode[]
for (const urlNode of urlNodes) {
const valueNode = store.any(urlNode, ns.vcard('value'), null, contact.doc())
const webId = valueNode?.value || ''
if (isHttpUri(webId)) {
return webId
}
Comment thread
SharonStrats marked this conversation as resolved.
}

return null
})().catch(error => {
contactWebIdCache.delete(contact.value)
throw error
})

contactWebIdCache.set(contact.value, promise)
return promise
}

async function discoverAddressBookContacts (
user: NamedNode,
onEntry: (entry: DirectoryEntry) => void | Promise<void>
): Promise<void> {
const books = await loadPersonalAddressBooks(user)

for (const book of books) {
if (await loadDocumentSilently(store, book)) {
const nameEmailIndex = store.any(book, ns.vcard('nameEmailIndex'), null, book.doc()) as NamedNode | null
if (nameEmailIndex) {
if (await loadDocumentSilently(store, nameEmailIndex)) {
const contacts = store.each(undefined, ns.vcard('inAddressBook'), book, nameEmailIndex) as NamedNode[]
for (let index = 0; index < contacts.length; index += CONTACT_CARD_CONCURRENCY) {
const batch = contacts.slice(index, index + CONTACT_CARD_CONCURRENCY)
const entries = await Promise.all(batch.map(async contact => {
const webId = await webIdForAddressBookContact(contact)
if (!webId) {
return null
}

return {
kind: 'person' as const,
uri: webId,
label: store.anyValue(contact, ns.vcard('fn'), null, nameEmailIndex) || labelForNode(store, contact),
subjectType: 'agent' as const,
relationshipLabel: 'Contact' as const,
sources: ['contacts'] as DirectorySource[]
}
}))

for (const entry of entries.filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))) {
await onEntry(entry)
}
}
}
}
}
}
}

async function discoverAddressBookGroups (
user: NamedNode,
onEntry: (entry: DirectoryEntry) => void | Promise<void>
): Promise<void> {
const books = await loadPersonalAddressBooks(user)

for (const book of books) {
if (await loadDocumentSilently(store, book)) {
const groupIndex = store.any(book, ns.vcard('groupIndex'), null, book.doc()) as NamedNode | null
if (groupIndex) {
if (await loadDocumentSilently(store, groupIndex)) {
const groups = uniqueNamedNodes([
...(store.each(book, ns.vcard('includesGroup'), null, groupIndex) as NamedNode[]),
...(store.each(book, ns.vcard('includesGroup'), null, book.doc()) as NamedNode[])
])

for (const group of groups) {
await loadDocumentSilently(store, group)

await onEntry({
kind: 'group',
uri: group.value,
label: labelForNode(store, group),
subjectType: 'agentGroup',
relationshipLabel: 'Group',
sources: ['groups']
})
}
}
}
}
}
}

return {
discoverAddressBookContacts,
discoverAddressBookGroups
}
}
Loading
Loading