diff --git a/CHANGELOG.md b/CHANGELOG.md index 18830c8..29e3811 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ Versions follow `package.json`. A tag `v` publishes the image `ghcr.io/nicolasdb/solid-backoffice:` (`.github/workflows/ci.yml`); an instance pins it in `instance-template/.env`. +## Unreleased + +- **A WebID on your own domain works with every profile step** (#26, + solid-kit ADR 002 amendment of 2026-11-26). Such a profile is a static + file no app can write, so "Use this inbox", the name, "May act for you" + and joining ended in a NetworkError. Each step now writes the profile + only when its server says it may (`WAC-Allow` / `Allow`), else the + extended profile it links in your pod, else a new `profile/about.ttl` + (public read, you edit), and You shows the two lines to add to your + profile, with a copy button. +- **Profiles are read with their extended profile**: the documents linked + with `rdfs:seeAlso` or `foaf:isPrimaryTopicOf`, one level, only inside a + `pim:storage` the profile declares. A collective checking a request, the + members table and the agents found for a member count a membership or a + delegation written only there. You shows the extended profile under the + profile, with its address. + ## 0.3.1 — 2026-11-24 - **Sign-up: the passphrase toggle is an eye inside the field** (#23). The diff --git a/CLAUDE.md b/CLAUDE.md index 6dcf0d3..18b5fc6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,13 @@ one changes, change the other. Never point it at the real provider. `getAccess` is a write's base (always fresh); `readAccess` is for showing (the `.acl`'s location from memory, the document through `read.ts`). - `src/lib/collective.ts` — ADR 006, member side: config, profile and roster - parsing, the membership state table, `as:Join` / `as:Announce`. + parsing, the membership state table, `as:Join` / `as:Announce`. A + profile is read with the extended documents it links (`rdfs:seeAlso` / + `foaf:isPrimaryTopicOf`, one level, only inside a `pim:storage` it + declares), and `updateOwnProfile` writes the WebID document only when its + GET answers as writable, else the linked extended document, else a new + `profile/about.ttl` (solid-kit ADR 002 amendment, solid-backoffice#26; + `docs/explanation/membership.md`). - `src/lib/admin.ts` — ADR 006, collective side: read the inbox, check each requester's profile, accept / refuse / remove (order pinned in `src/lib/admin.test.ts`), members from both sides. `src/lib/activity.ts` @@ -94,7 +100,9 @@ one changes, change the other. Never point it at the real provider. to, joining); one collective opens inside it as `src/member.ts` (sharing, leaving, its members and agent) or `src/admin.ts` (the one you run). `src/you.ts` is You (name, inbox, may act for you, your agents on our - provider, and `profile/card` read only with the steps' lines marked). `src/steps.ts` holds the pieces they + provider, and `profile/card` read only with the steps' lines marked, + the extended profile below it, and the two lines to add when the profile + cannot be written and does not link it). `src/steps.ts` holds the pieces they share. No role, progress or tab state is stored. - `src/places.ts` — Pods (slice C, the tab once called Places): your pod as a file explorer, built as an iceberg (list → `···` menu → access diff --git a/docs/explanation/membership.md b/docs/explanation/membership.md index d716e02..5535617 100644 --- a/docs/explanation/membership.md +++ b/docs/explanation/membership.md @@ -32,6 +32,37 @@ What depends on it (agents) is offered when the provider says it offers it (`/.well-known/css/provider.json`, solid-kit ADR 010), and otherwise shown with why not. +## A profile no app can write + +"Your profile" is usually `profile/card` in your pod, which the steps on +You write. A WebID on your own domain +(`https://id.openfab.be/profile/card#me`, solid-kit +[ADR 002](https://github.com/nicolasdb/solid-kit/blob/main/docs/adr/002-portability-tiers.md), +tier 1, amendment of 2026-11-26) is a static file: no app can write it, and +before this every step that wrote it ended in a NetworkError. + +So a profile is read as **the WebID document plus the extended documents it +links** with `rdfs:seeAlso` or `foaf:isPrimaryTopicOf` (either one), one +level only, and only when they are inside a `pim:storage` the WebID +document itself declares: anyone can link anything, only you write in your +pod. A linked document outside it is ignored; one that fails to load is +skipped. This is how the collective checks a request (`org:memberOf`) and +how a member's agents are found (`acl:delegates`): one function per +decision in `src/lib/collective.ts` (`declaresMembership`, +`declaredDelegates`), so another authorization backend can replace it. + +Writing follows the same rule. A step writes your WebID document only if +the server says you may (`WAC-Allow`, else `Allow`, on its GET; a static +file says neither). Otherwise it writes the extended document your profile +links in your pod. With none, it creates `profile/about.ttl` (readable by +anyone, written by you only: what it holds is there to be checked by +others), writes there, and You shows the two lines to add to your WebID +document by hand, with a copy button. Until they are added, only you see +what the steps saved there: a collective reading your request finds no +`org:memberOf` and says so. The name the steps saved there is the one +shown, over the card's. A line the card itself holds (added by hand) cannot +be removed by an app: the step refuses and says where to remove it. + ## Newcomers Most newcomers have no Solid account and already know the collective that diff --git a/docs/how-to/set-up-a-collective.md b/docs/how-to/set-up-a-collective.md index eef5b34..4619827 100644 --- a/docs/how-to/set-up-a-collective.md +++ b/docs/how-to/set-up-a-collective.md @@ -21,7 +21,11 @@ members share; it switches sharing on in `config.ttl` once the agent exists collective's address and in every member's `org:memberOf`. 2. **Create the inbox** from You → "Create my inbox". It makes `inbox/`, lets any signed-in account Append there, then names it `ldp:inbox` in the - profile, in that order. `config.ttl` points at the same `inbox/`, so the + profile, in that order (for a WebID on the collective's own domain, a + file apps cannot write, these profile lines go to `profile/about.ttl` in + the pod instead, and You gives the two lines that link it: + [a profile no app can write](../explanation/membership.md#a-profile-no-app-can-write)). + `config.ttl` points at the same `inbox/`, so the account and the collective share one. 3. **Upload `config.ttl`** at the pod root, from the [template](../../templates/collective/config.ttl): replace every @@ -51,7 +55,7 @@ members share; it switches sharing on in `config.ttl` once the agent exists compare it with what step 3 wrote. 7. **Let it act for the collective**: on You, the step "May act for you", offers the agent in one click. That writes `acl:delegates` in the - account's profile, which is how the agent's skill checks it acts for this + account's profile (or its `profile/about.ttl`, as in step 2), which is how the agent's skill checks it acts for this collective. Creating the agent does not do it. 8. **Switch sharing on** in `config.ttl`: uncomment `sc:feature sc:Sharing`, `sc:agent` and, if you suggest a folder, `sc:suggestedFolder`. `sc:agent` diff --git a/docs/manual-tests.md b/docs/manual-tests.md index b9ca2f7..da2b855 100644 --- a/docs/manual-tests.md +++ b/docs/manual-tests.md @@ -659,7 +659,8 @@ both themes. only, the lines `foaf:name`, `ldp:inbox`, `acl:delegates` and each `org:memberOf` marked ("Your name", "Joined HyperScope"…). Change your name: the marked line changes with it. "Open in Pods" opens the same - file in Pods. + file in Pods. A profile that links an extended profile in your pod + shows it below, with its address ([extended profile](#extended-profile--a-webid-on-your-own-domain)). ## E · A member's agents read what the member reads @@ -744,6 +745,43 @@ subdomains: the address is `https://openfab.pod.mapsofmaking.org/`. 12. **A member.** The newcomer follows the link, asks to join, is accepted, shares a folder: J1 to J4 on this pod. +## Extended profile · a WebID on your own domain + +Not yet run (solid-backoffice#26, solid-kit ADR 002 amendment of +2026-11-26). Signed in as a tier-1 WebID, such as +`https://id.openfab.be/profile/card#me` (a static file declaring +`pim:storage `). Do it twice: once with +the profile linking `profile/about.ttl` (`rdfs:seeAlso` and +`foaf:isPrimaryTopicOf`), once on an account whose profile links nothing +and whose pod has no `profile/about.ttl` yet. + +1. **You, read.** "Source · …/profile/card" says the file cannot be + written by apps; a linked `profile/about.ttl` is shown below it with + its address and "Open in Pods", its lines marked like the profile's. +2. **The inbox step.** Without an inbox: "Create my inbox" (or "Use this + inbox"). No NetworkError, no "Failed to fetch". In Pods, + `profile/about.ttl` now holds `ldp:inbox`; the WebID document is + unchanged. +3. **No extended profile yet.** On the second account, the same step + creates `profile/about.ttl`. Its access: anyone can read, only you edit + (Pods → "Who can access it"); in a private window it opens. You shows + "Link your extended profile" with the two lines; "Copy the two lines" + copies them. Add them to the WebID document where it is hosted, reload: + the step is gone and the extended profile is shown as linked. +4. **Name and may act for you.** Change the name; add an agent. Both land + in `profile/about.ttl`, marked in the source; the new name is the one + shown, even though the card keeps its own. Remove an agent the card + itself names (a line added by hand): refused, saying to remove it where + the file is hosted; nothing is written. Leave a collective the card + names: the same. +5. **Membership, read by the collective.** Join a collective. Signed in as + its account, the request shows "Profile says they belong to …" (read + from `about.ttl`). Before the two lines are added, it says the profile + does not, and the join's message says why. +6. **Tier 0 unchanged.** As a WebID in its own pod (`…/profile/card#me` + on the provider), every step still writes `profile/card`, and no + `profile/about.ttl` appears. + ## H · Mermaid in the Markdown preview 1. **The plan.** In Pods, open `hyperscope_ndb/tasks/now.md`: the diff --git a/docs/slices.md b/docs/slices.md index 3083ef2..ebf50b5 100644 --- a/docs/slices.md +++ b/docs/slices.md @@ -4,7 +4,20 @@ Each slice is usable on its own and is tested by a real person before the next one starts. The order follows who is waiting: new members first, then the admin who accepts them, then everyone's daily work. -## Where we are (17 Nov 2026) +## Where we are (27 Nov 2026) + +**A WebID on your own domain, writers and readers** (solid-backoffice#26, +solid-kit ADR 002 amendment of 2026-11-26). Profiles are read with the +extended documents they link inside their own `pim:storage`; every profile +step writes the WebID document only when it answers as writable, else the +linked extended profile, else a new `profile/about.ttl`, and You gives the +two lines to link it. A line held in the static card itself is refused on +removal, never "removed" silently. Run live: not yet +([manual tests](manual-tests.md#extended-profile--a-webid-on-your-own-domain)). +Next: the two "Bring your domain" paths (#27, #28); whether the inbox step +should also give the `ldp:inbox` line for the card. + +## Where we were (17 Nov 2026) **Creating a collective, reviewed on OpenFab (Maps of Making); docs only, no code.** Followed as written, the how-to produced a collective whose agent diff --git a/src/admin.ts b/src/admin.ts index 76711d6..70ead32 100644 --- a/src/admin.ts +++ b/src/admin.ts @@ -25,7 +25,7 @@ import { type MemberView, type Person, } from "./lib/admin"; -import type { Collective } from "./lib/collective"; +import { declaresMembership, type Collective } from "./lib/collective"; import { describePodError } from "./lib/pod"; import { announce } from "./ui/a11y"; import { esc, toast } from "./ui/patterns"; @@ -136,8 +136,8 @@ function renderRequest(request: Request, i: number, collective: Collective): str const name = esc(collective.name); const facts = profile ? `
    - ${check(profile.memberOf.includes(collective.group), - profile.memberOf.includes(collective.group) ? `Profile says they belong to ${name}` : `Profile does not say they belong to ${name}`)} + ${check(declaresMembership(profile, collective.group), + declaresMembership(profile, collective.group) ? `Profile says they belong to ${name}` : `Profile does not say they belong to ${name}`)} ${check(!!profile.inbox, profile.inbox ? "Has an inbox for the answer" : "No inbox: the answer cannot be sent; tell them another way")} ${check(profile.delegates.length > 0, `Agents: ${profile.delegates.length ? profile.delegates.map((d) => `${esc(d)}`).join(", ") : "none"}`)}
` diff --git a/src/collectives.ts b/src/collectives.ts index d42f09c..26b3617 100644 --- a/src/collectives.ts +++ b/src/collectives.ts @@ -112,7 +112,7 @@ export function bindCollectives(app: HTMLElement, data: Loaded, ctx: ViewContext // Profile first: if the message then fails, the screen shows the // request as pending and offers to send it again. The other order // would leave the collective holding a request the profile denies. - await updateOwnProfile(webId, profileEdits.join(collective.group)); + const written = await updateOwnProfile(webId, profileEdits.join(collective.group)); // Already listed: declaring completes the handshake, and a request // would ask the collective for something it has already done. if (view.state !== "left") { @@ -120,7 +120,15 @@ export function bindCollectives(app: HTMLElement, data: Loaded, ctx: ViewContext } // The profile now carries the link; the invitation has done its job. setInvite(null); - announce(`Request sent to ${collective.name}.`); + // Written to an extended profile your profile does not link yet: the + // collective cannot see it until the two lines on You are added. + if (written?.linkToAdd) { + const msg = `Request sent to ${collective.name}. It sees your membership once your profile links your extended profile: You shows the two lines to add.`; + toast(msg); + announce(msg); + } else { + announce(`Request sent to ${collective.name}.`); + } }, rerender); }); } diff --git a/src/lib/admin.ts b/src/lib/admin.ts index 2164c03..91207e7 100644 --- a/src/lib/admin.ts +++ b/src/lib/admin.ts @@ -24,9 +24,11 @@ import { readTurtle } from "./read"; import { NS } from "./vocab"; import { buildAnswer, buildRemove } from "./activity"; import { - parseProfile, - profileDocOf, + declaredDelegates, + declaresMembership, + readProfile, sendToInbox, + type ProfileReadError, type Collective, type MemberDeclaration, type MembershipState, @@ -195,13 +197,17 @@ export interface Person { problem: string | null; } +/** + * Their profile and the extended documents it links inside its own + * pim:storage (solid-kit ADR 002 amendment, point 3): a membership declared + * only in their `profile/about.ttl` counts; one in a document elsewhere does not. + */ export async function readPerson(webId: string): Promise { try { - const doc = profileDocOf(webId); - const res = await readTurtle(doc); - if (!res.ok) return { webId, profile: null, problem: `Their profile could not be read (${res.status}).` }; - return { webId, profile: parseProfile(await res.text(), doc, webId), problem: null }; + return { webId, profile: await readProfile(webId), problem: null }; } catch (err) { + const status = (err as ProfileReadError).status; + if (status !== undefined) return { webId, profile: null, problem: `Their profile could not be read (${status}).` }; return { webId, profile: null, problem: err instanceof Error ? err.message : String(err) }; } } @@ -217,7 +223,7 @@ export function requestFlags(message: InboxMessage, person: Person, collective: } if (!person.profile) { flags.push("Their profile could not be read, so the request cannot be checked."); - } else if (!person.profile.memberOf.includes(collective.group)) { + } else if (!declaresMembership(person.profile, collective.group)) { flags.push(`Their profile does not say they belong to ${collective.name}.`); } return flags; @@ -372,7 +378,8 @@ function memberFolders(collective: Collective): string[] { * acts for its human, in the pod and in the collective's graph. */ export function readersOf(person: Person): string[] { - return [person.webId, ...(person.profile?.delegates ?? []).filter((d) => d !== person.webId && isValidWebId(d))]; + const delegates = person.profile ? declaredDelegates(person.profile) : []; + return [person.webId, ...delegates.filter((d) => d !== person.webId && isValidWebId(d))]; } /** @@ -478,7 +485,7 @@ export interface MemberView extends Person { export function memberState(person: Person, group: string): MembershipState { if (!person.profile) return "unknown"; - return person.profile.memberOf.includes(group) ? "member" : "left"; + return declaresMembership(person.profile, group) ? "member" : "left"; } /** diff --git a/src/lib/agents.ts b/src/lib/agents.ts index 671fb3d..e90a52a 100644 --- a/src/lib/agents.ts +++ b/src/lib/agents.ts @@ -565,7 +565,7 @@ export async function deleteAgent(session: AccountSession, owner: string, podUrl await step("rules", async () => { for (const r of agent.reach) await setFolderAccess(r.url, owner, podUrl, agent.webId, []); }); - if (agent.delegate) await step("delegates", () => updateOwnProfile(owner, profileEdits.removeDelegate(agent.webId))); + if (agent.delegate) await step("delegates", async () => void (await updateOwnProfile(owner, profileEdits.removeDelegate(agent.webId)))); await step("unlink", async () => { const res = await account(session, agent.link.resource, { method: "DELETE" }); if (res.status === 401) throw ended(); diff --git a/src/lib/collective.ts b/src/lib/collective.ts index 6f8f34a..555981e 100644 --- a/src/lib/collective.ts +++ b/src/lib/collective.ts @@ -30,6 +30,7 @@ import { } from "@inrupt/solid-client"; import { authFetch } from "./auth"; import { readTurtle } from "./read"; +import { setPublicAccess } from "./acl"; import { NS } from "./vocab"; export { NS }; @@ -40,6 +41,9 @@ const FOAF_MEMBER = NS.foaf + "member"; const MEMBER_OF = NS.org + "memberOf"; const DELEGATES = NS.acl + "delegates"; const INBOX = NS.ldp + "inbox"; +const SEE_ALSO = NS.rdfs + "seeAlso"; +const PRIMARY_TOPIC_OF = NS.foaf + "isPrimaryTopicOf"; +const STORAGE = NS.pim + "storage"; /** * What a collective's `config.ttl` declares. @@ -237,18 +241,198 @@ export interface MemberDeclaration { memberOf: string[]; delegates: string[]; inbox: string | null; + /** + * Your own profile only: the extended profile the steps write to + * (`profile/about.ttl`) when your profile is a file apps cannot write and + * does not link it yet. What it holds is counted here, for you, but nobody + * else finds it until the two lines (`linkLines`) are in your profile. + */ + unlinked?: string; } export function parseProfile(turtle: string, profileDocUrl: string, webId: string): MemberDeclaration { - const quads = parse(turtle, profileDocUrl); + return declarationOf(parse(turtle, profileDocUrl), webId); +} + +/** What the quads say about `webId`; only triples whose subject is the WebID count. */ +function declarationOf(quads: Quad[], webId: string): MemberDeclaration { + const unique = (values: string[]) => [...new Set(values)]; return { name: objectsOf(quads, webId, FOAF_NAME)[0] ?? null, - memberOf: objectsOf(quads, webId, MEMBER_OF), - delegates: objectsOf(quads, webId, DELEGATES), + memberOf: unique(objectsOf(quads, webId, MEMBER_OF)), + delegates: unique(objectsOf(quads, webId, DELEGATES)), inbox: objectsOf(quads, webId, INBOX)[0] ?? null, }; } +/* + * ── The extended profile (solid-kit ADR 002, amendment of 2026-11-26) ────── + * + * A tier-1 WebID (https://id.openfab.be/profile/card#me) is a static file on + * the owner's own domain: no app can write it. It links an extended profile + * in the pod, `profile/about.ttl`, with rdfs:seeAlso AND + * foaf:isPrimaryTopicOf; either one is followed. What happened before this: + * every step that wrote the profile ended in a NetworkError on + * pod.syntonie.be (solid-backoffice#26), and the lines were added by hand. + * + * TRUST: a linked document is read only when it is inside a pim:storage the + * WebID profile itself declares (prefix match). Anyone can link anything; only + * the owner writes in their storage. One level only: links inside the + * extended documents are not followed. + */ + +/** One document of a profile, as read. */ +export interface ProfileDocument { + url: string; + text: string; +} + +/** A profile and the extended documents it links, read for showing or deciding. */ +export interface ProfileDocuments { + profile: ProfileDocument; + /** Linked documents inside a declared storage that could be read. One that fails is skipped. */ + extended: ProfileDocument[]; + /** Linked documents outside every declared storage: never read. */ + ignored: string[]; + /** The storages the profile declares, each ending in "/". */ + storages: string[]; + /** Whether the profile's GET answered as writable (`WAC-Allow` / `Allow`). */ + writable: boolean; +} + +/** A profile that could not be read, with its HTTP status when there was one. */ +export interface ProfileReadError extends Error { + status?: number; +} + +/** + * Whether a GET's headers say this app may write the document: `WAC-Allow`'s + * `user` holds write or append; without a `WAC-Allow`, an `Allow` listing + * PATCH or PUT. A static file answers neither. `WAC-Allow` decides when it is + * there: CSS lists PATCH in `Allow` whatever the requester may do. + */ +export function answersWritable(headers: Headers): boolean { + const wac = headers.get("wac-allow"); + if (wac !== null) { + const user = /user\s*=\s*"([^"]*)"/i.exec(wac)?.[1] ?? ""; + return /\b(write|append)\b/i.test(user); + } + return /\b(PATCH|PUT)\b/i.test(headers.get("allow") ?? ""); +} + +function storagesIn(quads: Quad[], webId: string): string[] { + return [...new Set(objectsOf(quads, webId, STORAGE).map((s) => (s.endsWith("/") ? s : s + "/")))]; +} + +/** + * The documents a profile links with rdfs:seeAlso or foaf:isPrimaryTopicOf, + * split by whether they are inside one of `storages` (the only ones read). + */ +export function linkedDocuments( + quads: Quad[], + webId: string, + profileDocUrl: string, + storages: string[] +): { inside: string[]; outside: string[] } { + const docs = new Set(); + for (const iri of [...objectsOf(quads, webId, SEE_ALSO), ...objectsOf(quads, webId, PRIMARY_TOPIC_OF)]) { + try { + const doc = profileDocOf(iri); + if (doc !== profileDocUrl && /^https?:/.test(doc)) docs.add(doc); + } catch { + // Not an IRI a document can be read from (a blank node, a literal). + } + } + const inside = [...docs].filter((d) => storages.some((s) => d.startsWith(s))); + return { inside, outside: [...docs].filter((d) => !inside.includes(d)) }; +} + +/** A document's text through read.ts, or `null` when it cannot be read or parsed. */ +async function readOptional(url: string): Promise { + try { + const res = await readTurtle(url); + if (!res.ok) return null; + const text = await res.text(); + parse(text, url); + return { url, text }; + } catch { + return null; + } +} + +/** + * Reads a WebID's profile and the extended documents it links (one level), + * through read.ts (ADR 007: revalidated, never stale). A profile with no + * links costs one request, as before. Throws a ProfileReadError when the + * profile itself cannot be read. + */ +export async function readProfileDocuments(webId: string): Promise { + const url = profileDocOf(webId); + const res = await readTurtle(url); + if (!res.ok) { + const err = new Error(`Could not read the profile at ${url} (${res.status}).`) as ProfileReadError; + err.status = res.status; + throw err; + } + const text = await res.text(); + const quads = parse(text, url); + const storages = storagesIn(quads, webId); + const { inside, outside } = linkedDocuments(quads, webId, url, storages); + const extended = (await Promise.all(inside.map(readOptional))).filter((d): d is ProfileDocument => d !== null); + return { profile: { url, text }, extended, ignored: outside, storages, writable: answersWritable(res.headers) }; +} + +/** + * The union of what the documents declare about `webId`, the profile first + * (`docs[0]`), except the name: an extended document's wins. A static card + * keeps the name it was written with (OpenFab's says "OpenFab"), and the name + * step writes the extended profile, so the card's would hide every change. + */ +export function declarationOfDocuments(docs: ProfileDocument[], webId: string): MemberDeclaration { + const parsed = docs.map((d) => parse(d.text, d.url)); + const merged = declarationOf(parsed.flat(), webId); + const extendedName = parsed.slice(1).map((q) => objectsOf(q, webId, FOAF_NAME)[0]).find((n) => n !== undefined); + return extendedName === undefined ? merged : { ...merged, name: extendedName }; +} + +/** The merged declaration of anyone's profile: the profile and its extended documents. */ +export async function readProfile(webId: string): Promise { + const docs = await readProfileDocuments(webId); + return declarationOfDocuments([docs.profile, ...docs.extended], webId); +} + +/* + * Decisions. One function each, so another authorization backend (UMA/ODRL) + * can replace it without touching how profiles are read (ADR 002 amendment, + * point 3). They take the merged declaration from `readProfile`. + */ + +/** Whether a profile declares membership of `group` (`org:memberOf`). */ +export function declaresMembership(profile: MemberDeclaration, group: string): boolean { + return profile.memberOf.includes(group); +} + +/** The agents a profile declares may act for it (`acl:delegates`). */ +export function declaredDelegates(profile: MemberDeclaration): string[] { + return profile.delegates; +} + +/** Where the extended profile goes when the profile links none: `profile/about.ttl` in the first storage. */ +export function extendedProfileUrl(storage: string): string { + return new URL("profile/about.ttl", storage).href; +} + +/** + * The two lines a static profile needs to link its extended profile, absolute + * IRIs only (a redirect changes the base a reader parses against). + */ +export function linkLines(webId: string, extendedUrl: string): string { + return [ + `<${webId}> <${SEE_ALSO}> <${extendedUrl}> .`, + `<${webId}> <${PRIMARY_TOPIC_OF}> <${extendedUrl}> .`, + ].join("\n"); +} + /** The WebIDs a roster lists as `foaf:member` of the group. */ export function parseRoster(turtle: string, rosterUrl: string, group: string): string[] { return objectsOf(parse(turtle, rosterUrl), group, FOAF_MEMBER); @@ -287,51 +471,181 @@ export async function sendToInbox(inbox: string, turtle: string): Promise { + const docUrl = profileDocOf(webId); + let res: Response; + try { + res = await authFetch(docUrl, { headers: { Accept: "text/turtle" }, cache: "no-store" }); + } catch { + throw unreachable(docUrl, ", your profile, to know where to write"); + } + if (!res.ok) throw new Error(`Could not read your profile (${res.status}), so nothing was written.`); + if (answersWritable(res.headers)) return { url: docUrl, create: false, linked: true, card: null }; + + const quads = parse(await res.text(), docUrl); + const storages = storagesIn(quads, webId); + if (!storages.length) { + throw new Error( + `Your profile at ${docUrl} is a file apps cannot write, and it declares no pim:storage, ` + + "so there is no pod to write in. Add a pim:storage line to it. Nothing was written." + ); + } + const linked = linkedDocuments(quads, webId, docUrl, storages).inside[0]; + const url = linked ?? extendedProfileUrl(storages[0]); + let head: Response; + try { + head = await authFetch(url, { method: "HEAD", cache: "no-store" }); + } catch { + throw unreachable(url, ", your extended profile"); + } + if (!head.ok && head.status !== 404) throw new Error(`Could not reach your extended profile at ${url} (${head.status}). Nothing was written.`); + return { url, create: head.status === 404, linked: Boolean(linked), card: quads }; +} + /** - * Edits the signed-in user's own profile. solid-client sends only the changed - * triples as a PATCH, so a concurrent edit to some other triple in the same - * document survives — which is why this is not a read-modify-PUT. + * Creates the extended profile: an almost empty document about the WebID, + * then its own rules (public Read, you Read/Write/Control: what it holds is + * there to be checked by others). In that order: a resource's `.acl` is + * found from the resource. Already there (412) counts as created. + */ +async function createExtendedProfile(url: string, webId: string): Promise { + const body = `<> <${NS.foaf}primaryTopic> <${webId}> .\n`; + let res: Response; + try { + res = await authFetch(url, { method: "PUT", headers: { "Content-Type": "text/turtle", "If-None-Match": "*" }, body }); + } catch { + throw unreachable(url, " to create your extended profile"); + } + if (!res.ok && res.status !== 412) throw new Error(`Could not create your extended profile at ${url} (${res.status}).`); + await setPublicAccess(url, webId, ["read"]); +} + +/** + * Edits the signed-in user's own profile, in the document + * `profileWriteTarget` picks. solid-client sends only the changed triples as + * a PATCH, so a concurrent edit to some other triple in the same document + * survives — which is why this is not a read-modify-PUT. */ export async function updateOwnProfile( webId: string, edit: (thing: ReturnType) => ReturnType -): Promise { - const docUrl = profileDocOf(webId); - const dataset = await getSolidDataset(docUrl, { fetch: authFetch }); - const thing = getThing(dataset, webId) ?? createThing({ url: webId }); - await saveSolidDatasetAt(docUrl, setThing(dataset, edit(thing)), { fetch: authFetch }); +): Promise { + const target = await profileWriteTarget(webId); + // Removing a line the static card holds would PATCH the extended profile + // with nothing to remove, say "done", and the line would be back on the + // next read. Refuse instead, naming where it can be removed. + const removes = (edit as ProfileEdit).removes; + if ( + removes && + target.card?.some((q) => q.subject.value === webId && q.predicate.value === removes.predicate && q.object.value === removes.value) + ) { + throw new Error( + `This line is in your profile itself, ${profileDocOf(webId)}, a file apps cannot write: ` + + `remove <${removes.value}> there, where the file is hosted. Nothing was written.` + ); + } + if (target.create) await createExtendedProfile(target.url, webId); + try { + const dataset = await getSolidDataset(target.url, { fetch: authFetch }); + const thing = getThing(dataset, webId) ?? createThing({ url: webId }); + await saveSolidDatasetAt(target.url, setThing(dataset, edit(thing)), { fetch: authFetch }); + } catch (err) { + // fetch rejects with a TypeError on CORS or a lost network: say where. + if (err instanceof TypeError) throw unreachable(target.url, ""); + throw err; + } + return { document: target.url, linkToAdd: target.linked ? null : linkLines(webId, target.url) }; +} + +/** Your profile's documents, plus the extended profile the steps wrote but the profile does not link yet. */ +export interface OwnProfileDocuments extends ProfileDocuments { + unlinked: ProfileDocument | null; +} + +/** + * Your own profile as the steps see it: the merged read, plus, when your + * profile cannot be written and links no extended document, the + * `profile/about.ttl` the steps write to (so a name just saved there does + * not look undone). Others never read that one until it is linked. + */ +export async function readOwnProfileDocuments(webId: string): Promise { + const docs = await readProfileDocuments(webId); + const unlinked = + !docs.writable && docs.extended.length === 0 && docs.storages.length > 0 + ? await readOptional(extendedProfileUrl(docs.storages[0])) + : null; + return { ...docs, unlinked }; } export async function readOwnProfile(webId: string): Promise { - const docUrl = profileDocOf(webId); - const res = await readTurtle(docUrl); - if (!res.ok) throw new Error(`Could not read your profile (${res.status}).`); - return parseProfile(await res.text(), docUrl, webId); + let docs: OwnProfileDocuments; + try { + docs = await readOwnProfileDocuments(webId); + } catch (err) { + const status = (err as ProfileReadError).status; + if (status !== undefined) throw new Error(`Could not read your profile (${status}).`); + throw err; + } + const declaration = declarationOfDocuments([docs.profile, ...docs.extended, ...(docs.unlinked ? [docs.unlinked] : [])], webId); + return docs.unlinked ? { ...declaration, unlinked: docs.unlinked.url } : declaration; } /** - * Anyone's `foaf:name`, from the document their WebID points into: a card, or - * an agent's own document (`profile/claude#me`). `null` when there is none or - * it cannot be read; the caller falls back to the address. + * Anyone's `foaf:name`, from the document their WebID points into (a card, + * or an agent's own document, `profile/claude#me`) and the extended + * documents it links. `null` when there is none or it cannot be read; the + * caller falls back to the address. */ export async function readName(webId: string): Promise { try { - const docUrl = profileDocOf(webId); - const res = await readTurtle(docUrl); - return res.ok ? parseProfile(await res.text(), docUrl, webId).name : null; + return (await readProfile(webId)).name; } catch { return null; } } +type Thing = ReturnType; + +/** An edit of your profile; one that removes a line says which, so a line held by a static card is refused, not ignored. */ +export type ProfileEdit = ((t: Thing) => Thing) & { removes?: { predicate: string; value: string } }; + +function removing(predicate: string, value: string, edit: (t: Thing) => Thing): ProfileEdit { + return Object.assign(edit, { removes: { predicate, value } }); +} + export const profileEdits = { setName: (name: string) => (t: ReturnType) => setStringNoLocale(t, FOAF_NAME, name), addDelegate: (agent: string) => (t: ReturnType) => getUrlAll(t, DELEGATES).includes(agent) ? t : addUrl(t, DELEGATES, agent), - removeDelegate: (agent: string) => (t: ReturnType) => removeUrl(t, DELEGATES, agent), + removeDelegate: (agent: string) => removing(DELEGATES, agent, (t: Thing) => removeUrl(t, DELEGATES, agent)), join: (group: string) => (t: ReturnType) => getUrlAll(t, MEMBER_OF).includes(group) ? t : addUrl(t, MEMBER_OF, group), - leave: (group: string) => (t: ReturnType) => removeUrl(t, MEMBER_OF, group), + leave: (group: string) => removing(MEMBER_OF, group, (t: Thing) => removeUrl(t, MEMBER_OF, group)), setInbox: (inbox: string) => (t: ReturnType) => setUrl(t, INBOX, inbox), }; diff --git a/src/lib/profile.test.ts b/src/lib/profile.test.ts new file mode 100644 index 0000000..9418f2e --- /dev/null +++ b/src/lib/profile.test.ts @@ -0,0 +1,236 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * The extended profile (solid-kit ADR 002, amendment of 2026-11-26; + * solid-backoffice#26). A tier-1 WebID is a static file on its owner's domain + * that no app can write: the steps write to `profile/about.ttl` in the pod + * instead, and readers that decide something follow the profile's links only + * into the pod the profile itself names. + * + * The server is faked at ./auth, by method and URL. solid-client's own read + * and PATCH are replaced, so the test sees which document a step writes; the + * `.acl` goes through acl.ts unchanged. + */ +type Reply = { status: number; body?: string; headers?: Record }; +let routes: Record Reply)> = {}; +let calls: string[] = []; +let saved: { url: string; dataset: unknown }[] = []; +let unreachable = false; + +vi.mock("./auth", () => ({ + authFetch: async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + calls.push(`${method} ${url}`); + if (unreachable) throw new TypeError("Failed to fetch"); + const route = routes[`${method} ${url}`] ?? (method === "GET" ? routes[url] : undefined); + const reply = typeof route === "function" ? route() : route ?? { status: 404 }; + if (method === "PUT") puts.set(url, String(init?.body ?? "")); + return new Response(method === "HEAD" || reply.status === 204 ? null : reply.body ?? "", { + status: reply.status, + headers: { "content-type": "text/turtle", ...reply.headers }, + }); + }, +})); +const puts = new Map(); + +vi.mock("@inrupt/solid-client", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getSolidDataset: async (url: string) => { + calls.push(`read ${url}`); + return actual.createSolidDataset(); + }, + saveSolidDatasetAt: async (url: string, dataset: unknown) => { + calls.push(`save ${url}`); + saved.push({ url, dataset }); + return dataset; + }, + }; +}); + +const collective = await import("./collective"); +const { forgetReads } = await import("./read"); +const { forgetAclLocations } = await import("./acl"); +const admin = await import("./admin"); +const solid = await import("@inrupt/solid-client"); +const { answersWritable, updateOwnProfile, profileEdits, readProfile, readOwnProfile, readName, declaresMembership, linkLines, NS } = collective; + +/** OpenFab's shape: a WebID on its own domain, the pod on the provider. */ +const WEBID = "https://id.openfab.example/profile/card#me"; +const CARD = "https://id.openfab.example/profile/card"; +const POD = "https://openfab.pod.example/"; +const ABOUT = POD + "profile/about.ttl"; +const GROUP = "https://pod.example/maakbib/config.ttl#maakbib"; + +const card = (extra = "") => ` +@prefix foaf: . +@prefix pim: . +@prefix rdfs: . +<#me> a foaf:Organization ; + foaf:name "OpenFab" ; + pim:storage <${POD}> ${extra}. +`; +const linked = `; rdfs:seeAlso <${ABOUT}> ; foaf:isPrimaryTopicOf <${ABOUT}> `; +const STATIC = {}; // a static file: no WAC-Allow, no Allow +const CSS_OWNER = { "wac-allow": 'user="read write append control",public="read"', allow: "OPTIONS, HEAD, GET, PATCH, PUT" }; + +beforeEach(() => { + routes = {}; + calls = []; + saved = []; + puts.clear(); + unreachable = false; + forgetReads(); + forgetAclLocations(); +}); + +describe("answersWritable", () => { + it("reads WAC-Allow's user modes first, then Allow; a static file has neither", () => { + expect(answersWritable(new Headers(CSS_OWNER))).toBe(true); + expect(answersWritable(new Headers({ "wac-allow": 'user="read append"' }))).toBe(true); + // CSS lists PATCH in Allow whatever you may do: WAC-Allow decides. + expect(answersWritable(new Headers({ "wac-allow": 'user="read",public="read"', allow: "GET, PATCH, PUT" }))).toBe(false); + expect(answersWritable(new Headers({ allow: "GET, HEAD, PATCH" }))).toBe(true); + expect(answersWritable(new Headers({ allow: "GET, HEAD" }))).toBe(false); + expect(answersWritable(new Headers())).toBe(false); + }); +}); + +describe("writing your profile", () => { + it("writes the profile itself when it answers as writable (tier 0: nothing changes)", async () => { + routes[CARD] = { status: 200, body: card(), headers: CSS_OWNER }; + const result = await updateOwnProfile(WEBID, profileEdits.setName("OpenFab asbl")); + expect(result).toEqual({ document: CARD, linkToAdd: null }); + expect(calls).toEqual([`GET ${CARD}`, `read ${CARD}`, `save ${CARD}`]); + const thing = solid.getThing(saved[0].dataset as never, WEBID)!; + expect(solid.getStringNoLocale(thing, NS.foaf + "name")).toBe("OpenFab asbl"); + }); + + it("writes the linked about.ttl in your storage when the profile is a static file", async () => { + routes[CARD] = { status: 200, body: card(linked), headers: STATIC }; + routes[`HEAD ${ABOUT}`] = { status: 200 }; + const result = await updateOwnProfile(WEBID, profileEdits.setInbox(POD + "inbox/")); + expect(result).toEqual({ document: ABOUT, linkToAdd: null }); + expect(calls).toEqual([`GET ${CARD}`, `HEAD ${ABOUT}`, `read ${ABOUT}`, `save ${ABOUT}`]); + expect(calls.filter((c) => c.startsWith("PUT") || c.startsWith("PATCH"))).toEqual([]); + const thing = solid.getThing(saved[0].dataset as never, WEBID)!; + expect(solid.getUrl(thing, NS.ldp + "inbox")).toBe(POD + "inbox/"); + }); + + it("with no extended profile, creates about.ttl and its rules, writes there, and gives the two lines to add", async () => { + let created = false; + routes[CARD] = { status: 200, body: card(), headers: STATIC }; + routes[`HEAD ${ABOUT}`] = () => + created ? { status: 200, headers: { link: `<${ABOUT}.acl>; rel="acl"` } } : { status: 404 }; + routes[`PUT ${ABOUT}`] = () => ((created = true), { status: 201 }); + routes[`PUT ${ABOUT}.acl`] = { status: 201 }; + + const result = await updateOwnProfile(WEBID, profileEdits.setInbox(POD + "inbox/")); + + // The document first (its .acl is found from it), then its rules, then the edit. + expect(calls).toEqual([ + `GET ${CARD}`, + `HEAD ${ABOUT}`, + `PUT ${ABOUT}`, + `HEAD ${ABOUT}`, + `GET ${ABOUT}.acl`, + `PUT ${ABOUT}.acl`, + `read ${ABOUT}`, + `save ${ABOUT}`, + ]); + expect(puts.get(ABOUT)).toContain(`<${WEBID}>`); + const acl = puts.get(ABOUT + ".acl")!; + expect(acl).toContain(`acl:agent <${WEBID}>`); + expect(acl).toContain("acl:mode acl:Read, acl:Write, acl:Control."); + expect(acl).toMatch(/acl:agentClass foaf:Agent;\s+acl:accessTo <\.\/about\.ttl>;\s+acl:mode acl:Read\./); + expect(result.document).toBe(ABOUT); + expect(result.linkToAdd).toBe(linkLines(WEBID, ABOUT)); + expect(result.linkToAdd!.split("\n")).toEqual([ + `<${WEBID}> <${ABOUT}> .`, + `<${WEBID}> <${ABOUT}> .`, + ]); + }); + + it("refuses to remove a line the static card holds itself, instead of saying it is done", async () => { + const agent = POD + "profile/claude#me"; + routes[CARD] = { status: 200, body: card(`${linked}; <${NS.acl}delegates> <${agent}> `), headers: STATIC }; + routes[`HEAD ${ABOUT}`] = { status: 200 }; + await expect(updateOwnProfile(WEBID, profileEdits.removeDelegate(agent))).rejects.toThrow(/where the file is hosted/); + await expect(updateOwnProfile(WEBID, profileEdits.leave(GROUP))).resolves.toEqual({ document: ABOUT, linkToAdd: null }); + expect(calls.filter((c) => c.startsWith("save"))).toEqual([`save ${ABOUT}`]); + }); + + it("refuses, naming the missing line, when a static profile declares no storage", async () => { + routes[CARD] = { status: 200, body: `<#me> "OpenFab".`, headers: STATIC }; + await expect(updateOwnProfile(WEBID, profileEdits.setName("x"))).rejects.toThrow(/pim:storage/); + expect(calls).toEqual([`GET ${CARD}`]); + }); + + it("never shows the browser's Failed to fetch", async () => { + unreachable = true; + const err = await updateOwnProfile(WEBID, profileEdits.setName("x")).catch((e: Error) => e); + expect((err as Error).message).toContain(CARD); + expect((err as Error).message).not.toMatch(/Failed to fetch|NetworkError/); + }); +}); + +describe("reading a profile and its extended profile", () => { + it("a membership found only in about.ttl counts", async () => { + routes[CARD] = { status: 200, body: card(linked), headers: { etag: '"c"' } }; + routes[ABOUT] = { status: 200, body: `<${WEBID}> <${NS.org}memberOf> <${GROUP}> .`, headers: { etag: '"a"' } }; + const person = await admin.readPerson(WEBID); + expect(person.profile!.name).toBe("OpenFab"); + expect(declaresMembership(person.profile!, GROUP)).toBe(true); + expect(admin.memberState(person, GROUP)).toBe("member"); + const message = { url: "x", type: "Join", rawType: null, actor: WEBID, object: GROUP, target: null, summary: null, published: null, problem: null }; + const flags = admin.requestFlags(message as never, person, { group: GROUP, name: "Maakbib" } as never); + expect(flags).toEqual([]); + }); + + it("ignores a linked document outside the profile's storage, without reading it", async () => { + const elsewhere = "https://elsewhere.example/claims.ttl"; + routes[CARD] = { status: 200, body: card(`; rdfs:seeAlso <${elsewhere}> `) }; + routes[elsewhere] = { status: 200, body: `<${WEBID}> <${NS.org}memberOf> <${GROUP}> .` }; + const profile = await readProfile(WEBID); + expect(profile.memberOf).toEqual([]); + expect(calls).toEqual([`GET ${CARD}`]); + }); + + it("skips a linked document that fails to load, and follows one level only", async () => { + const deeper = POD + "profile/deeper.ttl"; + routes[CARD] = { status: 200, body: card(`; rdfs:seeAlso <${POD}profile/broken.ttl>, <${ABOUT}> `) }; + routes[POD + "profile/broken.ttl"] = { status: 500 }; + routes[ABOUT] = { status: 200, body: `<${WEBID}> <${deeper}> ; <${NS.acl}delegates> <${POD}profile/claude#me> .` }; + routes[deeper] = { status: 200, body: `<${WEBID}> <${NS.org}memberOf> <${GROUP}> .` }; + const profile = await readProfile(WEBID); + expect(profile.delegates).toEqual([POD + "profile/claude#me"]); + expect(profile.memberOf).toEqual([]); + expect(calls).not.toContain(`GET ${deeper}`); + expect(await readName(WEBID)).toBe("OpenFab"); + }); + + it("shows the name the step saved in about.ttl, not the one the static card was written with", async () => { + routes[CARD] = { status: 200, body: card(linked), headers: STATIC }; + routes[ABOUT] = { status: 200, body: `<${WEBID}> <${NS.foaf}name> "OpenFab asbl" .` }; + expect((await readOwnProfile(WEBID)).name).toBe("OpenFab asbl"); + expect((await admin.readPerson(WEBID)).profile!.name).toBe("OpenFab asbl"); + }); + + it("a profile with no links costs one request, as before", async () => { + routes[CARD] = { status: 200, body: card(), headers: CSS_OWNER }; + await readOwnProfile(WEBID); + expect(calls).toEqual([`GET ${CARD}`]); + }); + + it("shows you what the steps wrote to an about.ttl your profile does not link yet, and says so", async () => { + routes[CARD] = { status: 200, body: card(), headers: STATIC }; + routes[ABOUT] = { status: 200, body: `<${WEBID}> <${NS.ldp}inbox> <${POD}inbox/> .` }; + const profile = await readOwnProfile(WEBID); + expect(profile.inbox).toBe(POD + "inbox/"); + expect(profile.unlinked).toBe(ABOUT); + // Others do not read it: it is not linked. + forgetReads(); + expect((await admin.readPerson(WEBID)).profile!.inbox).toBeNull(); + }); +}); diff --git a/src/lib/vocab.ts b/src/lib/vocab.ts index 5537adb..c727241 100644 --- a/src/lib/vocab.ts +++ b/src/lib/vocab.ts @@ -8,6 +8,8 @@ export const NS = { xsd: "http://www.w3.org/2001/XMLSchema#", rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#", schema: "http://schema.org/", + rdfs: "http://www.w3.org/2000/01/rdf-schema#", + pim: "http://www.w3.org/ns/pim/space#", /** * The collectives' vocabulary (solid-kit ADR 006 §7, amended 2026-11-17; * the terms are solid-kit `docs/vocab/vocab.ttl`). Everything this app diff --git a/src/onboarding.test.ts b/src/onboarding.test.ts index b818f8f..7862f3e 100644 --- a/src/onboarding.test.ts +++ b/src/onboarding.test.ts @@ -320,6 +320,19 @@ describe("slice A — the member's side of the handshake", () => { vi.mocked(authFetch).mockReset(); }); + it("gives the two lines to add when the steps wrote to an extended profile the profile does not link", async () => { + const about = "https://pod.example/neil/profile/about.ttl"; + Object.assign(profile, { unlinked: about }); + const app = await render("#/you"); + const row = [...app.querySelectorAll("details.you-row")].find((d) => d.textContent!.includes("Link your extended profile"))!; + expect(row.hasAttribute("open")).toBe(true); + const copy = row.querySelector("[data-copy]")!.dataset.copy!; + expect(copy.split("\n")).toEqual([ + `<${WEBID}> <${about}> .`, + `<${WEBID}> <${about}> .`, + ]); + }); + it("says why the source could not be read, and keeps the steps", async () => { vi.mocked(authFetch).mockResolvedValue(new Response("", { status: 403 })); const app = await render("#/you"); diff --git a/src/onboarding.ts b/src/onboarding.ts index 5fa6268..fd08a87 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -19,6 +19,7 @@ import { findRunCollective, isListed, loadCollective, + declaresMembership, membershipState, readOwnProfile, type Collective, @@ -149,7 +150,7 @@ export async function load(webId: string, podUrl: string): Promise { ]); return { collective, - state: membershipState(profile.memberOf.includes(collective.group), listed), + state: membershipState(declaresMembership(profile, collective.group), listed), folderUrl, chosen: Boolean(picked), published, diff --git a/src/you.ts b/src/you.ts index 558cef0..217d454 100644 --- a/src/you.ts +++ b/src/you.ts @@ -7,30 +7,67 @@ * holds. Editing it by hand is Pods' job (its editor saves with If-Match); * a broken card can break sign-in, so not here. * + * A WebID on your own domain (solid-kit ADR 002, tier 1) is a static file no + * app can write: the steps then write to your extended profile in the pod + * (`profile/about.ttl`, `updateOwnProfile`), and the source shows it below + * the profile, with its address. When the profile does not link it yet, a + * step gives the two lines to add by hand. + * * Every write here is on the signed-in user's own pod. */ import { isValidWebId } from "./lib/acl"; import { createInbox } from "./lib/newcomer"; -import { NS, profileDocOf, profileEdits, updateOwnProfile, type Collective, type MemberDeclaration } from "./lib/collective"; -import { readTurtle } from "./lib/read"; +import { + NS, + linkLines, + profileDocOf, + profileEdits, + readOwnProfileDocuments, + updateOwnProfile, + type Collective, + type MemberDeclaration, + type ProfileReadError, +} from "./lib/collective"; import { describePodError } from "./lib/pod"; import { announce } from "./ui/a11y"; import { esc, toast } from "./ui/patterns"; import { bindButton, bindForm } from "./bind"; import { routeHref } from "./router"; -import { copyable } from "./steps"; +import { bindCopy, copyable } from "./steps"; import type { Loaded, ViewContext } from "./onboarding"; import { agentsSlot, agentSuggestionsFromAccount, mountAgents } from "./agents-view"; -/** Your profile document as the pod holds it, or why it could not be read. */ -export type Source = { text: string } | { error: string }; +/** An extended profile document shown under the profile; `linked: false` when the profile does not link it yet. */ +export interface ExtendedSource { + url: string; + text: string; + linked: boolean; +} + +/** + * Your profile document as the server holds it, the extended documents it + * links inside your storage, and the links it has outside it (never read); + * or why it could not be read. + */ +export type Source = + | { text: string; writable: boolean; extended: ExtendedSource[]; ignored: string[] } + | { error: string }; export async function readSource(webId: string): Promise { try { - const res = await readTurtle(profileDocOf(webId)); - if (!res.ok) return { error: `Could not read your profile (${res.status}).` }; - return { text: await res.text() }; + const docs = await readOwnProfileDocuments(webId); + return { + text: docs.profile.text, + writable: docs.writable, + extended: [ + ...docs.extended.map((d) => ({ ...d, linked: true })), + ...(docs.unlinked ? [{ ...docs.unlinked, linked: false }] : []), + ], + ignored: docs.ignored, + }; } catch (err) { + const status = (err as ProfileReadError).status; + if (status !== undefined) return { error: `Could not read your profile (${status}).` }; return { error: describePodError(err) }; } } @@ -101,16 +138,39 @@ export function renderYouView(data: Loaded, webId: string, podUrl: string, sourc ]); const doc = profileDocOf(webId); const inPod = doc.startsWith(podUrl) ? doc.slice(podUrl.length) : null; + const pre = (text: string, label: string) => + `
${sourceLines(text, names)
+      .map(({ line, mark }) =>
+        mark
+          ? `${esc(mark)}${esc(line)}`
+          : `${esc(line) || " "}`
+      )
+      .join("")}
`; + const extended = (e: ExtendedSource) => { + const path = e.url.startsWith(podUrl) ? e.url.slice(podUrl.length) : null; + return ` +
+

Extended profile · ${esc(path ?? e.url)}

+ ${path !== null ? `Open in Pods` : ""} +
+

${ + e.linked + ? "Linked from your profile. Read with it, by you and by others." + : "Your profile does not link it yet: only you see these lines. Add the two lines of “Link your extended profile”." + }

+ ${pre(e.text, `Your extended profile, ${path ?? e.url}`)}`; + }; const src = "error" in source ? `` - : `
${sourceLines(source.text, names)
-          .map(({ line, mark }) =>
-            mark
-              ? `${esc(mark)}${esc(line)}`
-              : `${esc(line) || " "}`
-          )
-          .join("")}
`; + : [ + source.writable ? "" : `

A file apps cannot write: the steps write to your extended profile, below.

`, + pre(source.text, "Your profile document"), + ...source.extended.map(extended), + ...source.ignored.map( + (url) => `

Your profile also links ${esc(url)}, outside your pod: it is not read, so what it says counts for nothing here.

` + ), + ].join(""); return `
@@ -119,6 +179,7 @@ export function renderYouView(data: Loaded, webId: string, podUrl: string, sourc

${esc(profile.name ?? "You")}

+ ${profile.unlinked ? stepLink(webId, profile.unlinked) : ""} ${stepName(profile)} ${stepInbox(profile, unadvertisedInbox)} ${stepAgent(profile, run?.collective ?? null)} @@ -132,7 +193,7 @@ export function renderYouView(data: Loaded, webId: string, podUrl: string, sourc
${copyable(webId, "WebID copied.")} ${src} -

Your profile as your pod holds it, read just now: everything the steps beside it write, marked. Collectives read it; they never write it. Read only here; in Pods, its editor saves only if nobody changed it meanwhile.

+

Your profile as its server holds it, read just now, and the extended profile it links in your pod, if any: everything the steps beside it write, marked. Collectives read them; they never write them. Read only here; in Pods, its editor saves only if nobody changed it meanwhile.

An agent's own document is separate: profile/<name>, public, so servers can check who it is. Your profile only names it when it may act for you.

`; @@ -142,6 +203,7 @@ export function bindYou(app: HTMLElement, data: Loaded, ctx: ViewContext): void const { webId, podUrl, rerender } = ctx; const { unadvertisedInbox } = data; mountAgents(app, ctx); + bindCopy(app); bindForm(app, "#name-form", async (form) => { const name = (form.elements.namedItem("name") as HTMLInputElement).value.trim(); @@ -184,9 +246,32 @@ export function bindYou(app: HTMLElement, data: Loaded, ctx: ViewContext): void } } -/** Steps of You still to do: a name and an inbox (the agent is optional). */ +/** Steps of You still to do: a name, an inbox, and the link to an extended profile nobody finds yet (the agent is optional). */ export function youTodo(profile: MemberDeclaration): number { - return (profile.name ? 0 : 1) + (profile.inbox ? 0 : 1); + return (profile.name ? 0 : 1) + (profile.inbox ? 0 : 1) + (profile.unlinked ? 1 : 0); +} + +/** + * Your profile is a file apps cannot write and does not link the extended + * profile the steps wrote: the two lines to add to it by hand, to copy. Until + * then nobody else reads what the steps saved (ADR 002 amendment, point 2). + */ +function stepLink(webId: string, extended: string): string { + const lines = linkLines(webId, extended); + return youRow( + "Link your extended profile", + false, + "", + `

+ Your profile, ${esc(profileDocOf(webId))}, is a file apps + cannot write. What the steps here save goes to + ${esc(extended)} in your pod instead. Collectives and + agents find it only once your profile links it: add these two lines at + the end of your profile, where it is hosted. +

+
${esc(lines)}
+

${copyable(lines, "The two lines are copied.", "Copy the two lines")}

` + ); } function stepName(profile: MemberDeclaration): string {