fedipod 1.47.0 → 1.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/architecture.md +1 -1
- package/gateway.md +1 -1
- package/lib/server/embed.mjs +1 -1
- package/lib/session/README.md +2 -135
- package/lib/surface/surface.mjs +4 -3
- package/package.json +5 -3
- package/scripts/check-netlify-bundles.mjs +0 -4
- package/scripts/check-pod-calls.mjs +5 -108
- package/scripts/check-sizes.mjs +6 -3
- package/scripts/dependents.mjs +76 -0
- package/scripts/stage-site.mjs +10 -8
- package/scripts/start.mjs +2 -2
- package/scripts/test-dependents.mjs +37 -0
- package/web/app/dist/boot.js +59 -57
- package/web/app/dist/boot.js.map +4 -4
- package/web/app/dist/sw.js +1 -1
- package/web/app/dist/sw.js.map +2 -2
- package/web/app/forum-support.mjs +2 -2
- package/web/app/oidc-session.mjs +2 -2
- package/lib/session/demo.html +0 -94
- package/lib/session/fedi-account.mjs +0 -417
- package/lib/session/fedi-login.mjs +0 -123
- package/lib/session/oidc-session.mjs +0 -233
- package/lib/session/package.json +0 -49
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// null. The counterpart of netlify/forum-support.mjs, which decides whether
|
|
5
5
|
// the Gateway behind this page keeps forums: the two go together.
|
|
6
6
|
//
|
|
7
|
-
// with forums import * as setup from '
|
|
7
|
+
// with forums import * as setup from 'fedipod-bb/setup'; export default setup;
|
|
8
8
|
// without forums export default null;
|
|
9
9
|
|
|
10
|
-
import * as setup from '
|
|
10
|
+
import * as setup from 'fedipod-bb/setup';
|
|
11
11
|
export default setup;
|
package/web/app/oidc-session.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// oidc-session.mjs — FediPod's Solid-OIDC session: the solid-oidc-session
|
|
2
|
-
// library (
|
|
2
|
+
// library (fediverse-session) bound to this app's database and client name. The
|
|
3
3
|
// page and the service worker both import this file, so both read one session.
|
|
4
|
-
import { solidOidcSession } from '
|
|
4
|
+
import { solidOidcSession } from 'fediverse-session/oidc-session.mjs';
|
|
5
5
|
|
|
6
6
|
export const { beginLogin, completeLogin, getSession, signOut } = solidOidcSession({ dbName: 'fedipod-oidc', clientName: 'FediPod' });
|
package/lib/session/demo.html
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
<!doctype html>
|
|
2
|
-
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="utf-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
-
<title>Act as a Fediverse account</title>
|
|
7
|
-
<link rel="stylesheet" href="../../web/admin/tokens.css">
|
|
8
|
-
<style>
|
|
9
|
-
body { font-family: var(--font, Arial, Helvetica, sans-serif); background: var(--bg); color: var(--fg); margin: 0; padding: .75rem 1rem 2rem; }
|
|
10
|
-
main { max-width: 44rem; margin: 0 auto; }
|
|
11
|
-
h1 { margin-top: .5rem; }
|
|
12
|
-
form { display: flex; gap: .75rem; flex-wrap: wrap; align-items: end; margin: 1.25rem 0; }
|
|
13
|
-
label { display: flex; flex-direction: column; gap: .35rem; flex: 1 1 18rem; }
|
|
14
|
-
input { font: inherit; padding: .6rem .8rem; background: var(--field-bg); color: var(--field-text); border: 1px solid var(--field-border); border-radius: .4rem; }
|
|
15
|
-
button { font: inherit; padding: .6rem 1.2rem; background: var(--btn); color: var(--btn-text); border: 1px solid var(--btn-edge); border-radius: .4rem; cursor: pointer; }
|
|
16
|
-
button:hover { background: var(--btn-hover); }
|
|
17
|
-
a { color: var(--link); }
|
|
18
|
-
.kinds { padding-left: 1.4rem; margin: .75rem 0 1.25rem; } .kinds li { margin: .4rem 0; }
|
|
19
|
-
:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
|
20
|
-
.skip { position: absolute; left: -999px; } .skip:focus { left: 1rem; top: 1rem; }
|
|
21
|
-
#status, #profile { padding: 1rem 1.2rem; border: 1px solid var(--line); border-radius: .4rem; background: var(--surface); margin: 1rem 0; }
|
|
22
|
-
#status { min-height: 1.5em; }
|
|
23
|
-
#status[data-kind="error"] { border-color: var(--err); }
|
|
24
|
-
#status[hidden] { display: none; }
|
|
25
|
-
#profile { display: grid; grid-template-columns: auto 1fr; gap: .5rem 1.2rem; align-items: start; }
|
|
26
|
-
#profile img { width: 5rem; height: 5rem; border-radius: .6rem; object-fit: cover; background: var(--raised); }
|
|
27
|
-
#profile dl { margin: 0; display: grid; grid-template-columns: max-content 1fr; gap: .3rem 1rem; }
|
|
28
|
-
#profile dt { font-weight: bold; } #profile dd { margin: 0; overflow-wrap: anywhere; }
|
|
29
|
-
section[hidden] { display: none; }
|
|
30
|
-
</style>
|
|
31
|
-
</head>
|
|
32
|
-
<body>
|
|
33
|
-
<a href="#main" class="skip">Skip to content</a>
|
|
34
|
-
<main id="main">
|
|
35
|
-
<h1>Act as a Fediverse account</h1>
|
|
36
|
-
<p>Type an address and you are sent to wherever that account signs in, then come back here signed in as it. Any of these works:</p>
|
|
37
|
-
<ul class="kinds">
|
|
38
|
-
<li><strong>A FediPod handle</strong> — <code>@jeff@fedipod.net</code> — signs in at your Solid pod</li>
|
|
39
|
-
<li><strong>Other Fediverse handle</strong> — <code>@you@mastodon.social</code> — signs in at your server</li>
|
|
40
|
-
<li><strong>A WebID</strong> — <code>https://you.solidcommunity.net/profile/card#me</code> — signs in at your Solid pod</li>
|
|
41
|
-
</ul>
|
|
42
|
-
<p>This demo is created with the <a href="https://github.com/jeff-zucker/FediPod/tree/main/lib/session">fediverse-session</a> library. Once signed in, the demo shows you your profile. The library itself returns an account session with methods to post, reply, like, etc.</p>
|
|
43
|
-
<form id="form">
|
|
44
|
-
<label>Your address
|
|
45
|
-
<input id="address" name="address" type="text" autocomplete="username" placeholder="@you@your.server" required>
|
|
46
|
-
</label>
|
|
47
|
-
<button type="submit" id="go">Sign in</button>
|
|
48
|
-
<button type="button" id="out" hidden>Sign out</button>
|
|
49
|
-
</form>
|
|
50
|
-
<p id="status" role="status" aria-live="polite">Not signed in.</p>
|
|
51
|
-
<section id="acting" hidden aria-labelledby="profile-h">
|
|
52
|
-
<h2 id="profile-h">Profile</h2>
|
|
53
|
-
<div id="profile"></div>
|
|
54
|
-
</section>
|
|
55
|
-
</main>
|
|
56
|
-
<script type="module">
|
|
57
|
-
import { fediAccount } from './fedi-account.mjs';
|
|
58
|
-
const accounts = fediAccount({ dbName: 'fedi-account-demo', clientName: 'Fediverse account demo' });
|
|
59
|
-
const $ = (id) => document.getElementById(id);
|
|
60
|
-
const say = (text, kind = '') => { $('status').hidden = false; $('status').textContent = text; $('status').dataset.kind = kind; $('status').setAttribute('role', kind === 'error' ? 'alert' : 'status'); };
|
|
61
|
-
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
62
|
-
const link = (u) => (u ? `<a href="${esc(u)}">${esc(u)}</a>` : '—');
|
|
63
|
-
const showProfile = async (me) => {
|
|
64
|
-
try {
|
|
65
|
-
const p = await me.profile();
|
|
66
|
-
$('profile').innerHTML = `${p.avatar ? `<img src="${esc(p.avatar)}" alt="">` : '<span></span>'}
|
|
67
|
-
<dl>
|
|
68
|
-
<dt>Name</dt><dd>${esc(p.name || '—')}</dd>
|
|
69
|
-
<dt>Handle</dt><dd>${esc(p.handle || '—')}</dd>
|
|
70
|
-
<dt>Kind</dt><dd>${me.kind === 'pod' ? 'a FediPod account on a Solid pod' : 'a Mastodon account'}</dd>
|
|
71
|
-
<dt>Bio</dt><dd>${p.bio || '—'}</dd>
|
|
72
|
-
<dt>Counts</dt><dd>${p.posts ?? '?'} posts, ${p.followers ?? '?'} followers, ${p.following ?? '?'} following</dd>
|
|
73
|
-
<dt>Profile page</dt><dd>${link(p.url)}</dd>
|
|
74
|
-
<dt>Actor</dt><dd>${link(p.actor)}</dd>
|
|
75
|
-
${p.webId ? `<dt>WebID</dt><dd>${link(p.webId)}</dd>` : ''}
|
|
76
|
-
</dl>`;
|
|
77
|
-
} catch (e) { $('profile').textContent = `The profile could not be read: ${e.message}`; }
|
|
78
|
-
};
|
|
79
|
-
const show = async () => {
|
|
80
|
-
const me = await accounts.current();
|
|
81
|
-
$('out').hidden = !me; $('acting').hidden = !me; $('status').hidden = !!me;
|
|
82
|
-
if (!me) { say('Not signed in.'); $('profile').innerHTML = ''; return; }
|
|
83
|
-
await showProfile(me);
|
|
84
|
-
};
|
|
85
|
-
try { await accounts.resume(); } catch (e) { say(e.message, 'error'); }
|
|
86
|
-
await show();
|
|
87
|
-
$('form').addEventListener('submit', async (e) => {
|
|
88
|
-
e.preventDefault(); say('Finding that account…');
|
|
89
|
-
try { await accounts.login($('address').value); } catch (err) { say(err.message, 'error'); }
|
|
90
|
-
});
|
|
91
|
-
$('out').addEventListener('click', async () => { await accounts.signOut(); await show(); });
|
|
92
|
-
</script>
|
|
93
|
-
</body>
|
|
94
|
-
</html>
|
|
@@ -1,417 +0,0 @@
|
|
|
1
|
-
// fedi-account.mjs — type a Fediverse handle or a WebID, and get back an
|
|
2
|
-
// account you can act with: post, read its timeline, follow, reply,
|
|
3
|
-
// favourite, boost. The library works out whether the account lives on a
|
|
4
|
-
// Mastodon-family server or on a Solid pod through FediPod, and speaks to
|
|
5
|
-
// whichever it is. The app never has to know which it got.
|
|
6
|
-
//
|
|
7
|
-
// import { fediAccount } from './fedi-account.mjs';
|
|
8
|
-
// const accounts = fediAccount({ dbName: 'my-app', clientName: 'My app' });
|
|
9
|
-
//
|
|
10
|
-
// await accounts.resume(); // on every page load
|
|
11
|
-
// await accounts.login('@kwame@mastodon.social'); // or '@mei@fedipod.net', or a WebID
|
|
12
|
-
// const me = await accounts.current(); // null, or the account below
|
|
13
|
-
//
|
|
14
|
-
// me.handle, me.kind ('mastodon' | 'pod'), me.notice (a sentence to show, or null)
|
|
15
|
-
// await me.post({ text }); await me.timeline({ limit: 20 })
|
|
16
|
-
// await me.reply(postUrlOrId, text); await me.follow('@aisha@her.server')
|
|
17
|
-
// await me.favourite(postUrlOrId); await me.boost(postUrlOrId)
|
|
18
|
-
// await me.outbox({ limit: 20 }); // this account's own posts, newest first
|
|
19
|
-
// await me.outbox({ rdf: true }); // the same, plus the real RDF graph on .rdf
|
|
20
|
-
// await me.signOut()
|
|
21
|
-
//
|
|
22
|
-
// A Mastodon account is used through its server's API with a token the
|
|
23
|
-
// person granted this app; the token stays in this browser. A pod account
|
|
24
|
-
// is used through its FediPod outbox door with the person's pod sign-in:
|
|
25
|
-
// what is posted there is carried out by the account's own agent. When that
|
|
26
|
-
// agent is a browser at fedipod.net, the account carries a notice saying so.
|
|
27
|
-
//
|
|
28
|
-
// No imports but the two files beside it, no Node built-ins, nothing named
|
|
29
|
-
// after the application that uses it.
|
|
30
|
-
import { fediLogin, parseAddress } from './fedi-login.mjs';
|
|
31
|
-
|
|
32
|
-
const AS = 'https://www.w3.org/ns/activitystreams';
|
|
33
|
-
const PUBLIC = `${AS}#Public`;
|
|
34
|
-
const AS_OUTBOX = `${AS}#outbox`;
|
|
35
|
-
const FOAF_ACCOUNT = 'http://xmlns.com/foaf/0.1/account';
|
|
36
|
-
const DEFAULT_SCOPES = 'read write follow';
|
|
37
|
-
const PENDING_TTL_MS = 10 * 60_000;
|
|
38
|
-
|
|
39
|
-
export const BROWSER_ACCOUNT_NOTICE = 'Because you have a browser-based account, your posts and interactions will only go out to the Fediverse when your browser is opened to your account.';
|
|
40
|
-
|
|
41
|
-
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
42
|
-
const toHtml = (text) => `<p>${esc(text).replace(/\r?\n/g, '<br>')}</p>`;
|
|
43
|
-
const memoryStorage = () => { const m = new Map(); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k) }; };
|
|
44
|
-
|
|
45
|
-
export function fediAccount({
|
|
46
|
-
dbName = 'fediverse-account', clientName = 'Fediverse app', redirectUri = null, scopes = DEFAULT_SCOPES,
|
|
47
|
-
website = null, fetch: f = globalThis.fetch?.bind(globalThis), storage = globalThis.localStorage || memoryStorage(),
|
|
48
|
-
} = {}) {
|
|
49
|
-
const pod = fediLogin({ dbName, clientName, redirectUri, fetch: f });
|
|
50
|
-
const here = () => (globalThis.location ? location.origin + location.pathname : null);
|
|
51
|
-
const key = (k) => `${dbName}:${k}`;
|
|
52
|
-
const read = (k) => { try { return JSON.parse(storage.getItem(key(k)) || 'null'); } catch { return null; } };
|
|
53
|
-
const write = (k, v) => storage.setItem(key(k), JSON.stringify(v));
|
|
54
|
-
const drop = (k) => storage.removeItem(key(k));
|
|
55
|
-
const json = (url, init = {}) => f(url, { ...init, headers: { accept: 'application/json', ...(init.headers || {}) } })
|
|
56
|
-
.then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
57
|
-
const said = async (res, host) => {
|
|
58
|
-
const body = await res.json().catch(() => ({}));
|
|
59
|
-
if (!res.ok) throw new Error(body.error_description || body.error || `${host} answered ${res.status}`);
|
|
60
|
-
return body;
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
// A collection, or a page of one, may be named by its address or given
|
|
64
|
-
// whole in place (ActivityPub allows either); the whole one is used as it
|
|
65
|
-
// is, an address is fetched.
|
|
66
|
-
const idOf = (v) => (typeof v === 'string' ? v : v?.id || null);
|
|
67
|
-
const asDoc = async (v) => (v && typeof v === 'object'
|
|
68
|
-
? (v.type ? v : await asDoc(v.id))
|
|
69
|
-
: (typeof v === 'string' ? await json(v, { headers: { accept: 'application/activity+json' } }) : null));
|
|
70
|
-
|
|
71
|
-
// Only loaded when `outbox({ rdf: true })` is actually called, so nobody
|
|
72
|
-
// pays for a JSON-LD parser just by importing this file. Not in
|
|
73
|
-
// `dependencies` — the app supplies "jsonld" if it wants this flag to work.
|
|
74
|
-
const loadJsonLd = async () => {
|
|
75
|
-
try { return (await import('jsonld')).default; }
|
|
76
|
-
catch { throw new Error('outbox({ rdf: true }) needs the "jsonld" package available to the app — it is not bundled with this library'); }
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
// The account's real outbox, read from the pod: the head collection names
|
|
80
|
-
// `first`, each page names `orderedItems` and (while there is more) `next`.
|
|
81
|
-
// Walked only far enough to cover `limit`, and run through jsonld.toRDF so
|
|
82
|
-
// the result is a genuine RDF/JS quad array, not this library's own shape.
|
|
83
|
-
const fetchOutboxRdf = async (actorUrl, limit) => {
|
|
84
|
-
if (!actorUrl) return null;
|
|
85
|
-
const jsonld = await loadJsonLd();
|
|
86
|
-
const actorDoc = await json(actorUrl, { headers: { accept: 'application/activity+json' } });
|
|
87
|
-
const head = await asDoc(actorDoc?.outbox);
|
|
88
|
-
let page = head?.first ?? null;
|
|
89
|
-
const quads = []; const seen = new Set(); let collected = 0;
|
|
90
|
-
while (page && collected < limit && !seen.has(idOf(page) || page)) {
|
|
91
|
-
seen.add(idOf(page) || page);
|
|
92
|
-
const doc = await asDoc(page);
|
|
93
|
-
if (!doc) break;
|
|
94
|
-
quads.push(...(await jsonld.toRDF(doc)));
|
|
95
|
-
collected += (doc.orderedItems || []).length;
|
|
96
|
-
page = doc.next ?? null;
|
|
97
|
-
}
|
|
98
|
-
return quads;
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
// ---- finding out what an address is ----
|
|
102
|
-
|
|
103
|
-
// Does this host speak the Mastodon API? Any server of that family says so
|
|
104
|
-
// here; a pod, a Gateway and a plain web host do not.
|
|
105
|
-
const speaksMastodon = async (host) => {
|
|
106
|
-
const inst = await json(`https://${host}/api/v1/instance`);
|
|
107
|
-
return !!(inst && (inst.uri || inst.domain || inst.title));
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
const webfinger = async (name, host) => {
|
|
111
|
-
const jrd = await json(`https://${host}/.well-known/webfinger?resource=${encodeURIComponent(`acct:${name}@${host}`)}`,
|
|
112
|
-
{ headers: { accept: 'application/jrd+json, application/json' } });
|
|
113
|
-
if (!jrd) throw new Error(`${host} does not know @${name}@${host}`);
|
|
114
|
-
const self = (jrd.links || []).find((l) => l.rel === 'self' && /activity\+json|ld\+json/u.test(l.type || ''));
|
|
115
|
-
return { actor: self?.href || null, aliases: (jrd.aliases || []).filter((u) => typeof u === 'string') };
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
// Where a pod account keeps its records: the actor on the pod itself is
|
|
119
|
-
// `<root>ap/actor`, and the aliases name it even when the address is at a
|
|
120
|
-
// Gateway.
|
|
121
|
-
const rootOf = (actor, aliases) => {
|
|
122
|
-
const onPod = [...aliases, actor].find((u) => typeof u === 'string' && /\/ap\/actor$/u.test(u) && (!actor || new URL(u).origin !== new URL(actor).origin))
|
|
123
|
-
|| [...aliases, actor].find((u) => typeof u === 'string' && /\/ap\/actor$/u.test(u));
|
|
124
|
-
return onPod ? onPod.replace(/ap\/actor$/u, '') : null;
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
/** What an address is, without signing in: { kind: 'mastodon' | 'pod', host, handle, actor, … }. */
|
|
128
|
-
async function describe(address) {
|
|
129
|
-
const a = parseAddress(address);
|
|
130
|
-
if (!a) throw new Error('an address looks like @you@your.server, or is your WebID');
|
|
131
|
-
if (a.url) {
|
|
132
|
-
// A WebID: the account it names leads to the handle, and the handle to
|
|
133
|
-
// everything else.
|
|
134
|
-
const card = await json(a.url, { headers: { accept: 'application/ld+json' } });
|
|
135
|
-
const nodes = Array.isArray(card) ? card : (card?.['@graph'] || (card ? [card] : []));
|
|
136
|
-
const me = nodes.find((n) => n?.['@id'] === a.url) || {};
|
|
137
|
-
const actorId = [].concat(me[FOAF_ACCOUNT] || []).map((v) => v?.['@id'] || v).find((v) => typeof v === 'string');
|
|
138
|
-
if (!actorId) throw new Error(`${a.host} names no Fediverse account on that WebID`);
|
|
139
|
-
const actor = await json(actorId, { headers: { accept: 'application/activity+json' } });
|
|
140
|
-
if (!actor?.preferredUsername) throw new Error(`the account ${actorId} could not be read`);
|
|
141
|
-
return describe(`@${actor.preferredUsername}@${new URL(actorId).host}`);
|
|
142
|
-
}
|
|
143
|
-
const { actor, aliases } = await webfinger(a.name, a.host);
|
|
144
|
-
const actorHost = actor ? new URL(actor).host : a.host;
|
|
145
|
-
for (const host of [...new Set([actorHost, a.host])]) {
|
|
146
|
-
if (await speaksMastodon(host)) return { kind: 'mastodon', host, handle: a.at, actor };
|
|
147
|
-
}
|
|
148
|
-
const where = await pod.resolve(a.at);
|
|
149
|
-
return { kind: 'pod', host: a.host, handle: a.at, actor: actor || where.actor, issuer: where.issuer, root: rootOf(actor || where.actor, aliases) };
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// ---- signing in ----
|
|
153
|
-
|
|
154
|
-
const appFor = async (host, ru) => {
|
|
155
|
-
const apps = read('masto:apps') || {};
|
|
156
|
-
const known = apps[host];
|
|
157
|
-
if (known?.redirectUri === ru && known.clientId) return known;
|
|
158
|
-
const res = await f(`https://${host}/api/v1/apps`, {
|
|
159
|
-
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
160
|
-
body: JSON.stringify({ client_name: clientName, redirect_uris: ru, scopes, ...(website ? { website } : {}) }),
|
|
161
|
-
});
|
|
162
|
-
const body = await said(res, host);
|
|
163
|
-
if (!body.client_id) throw new Error(`${host} registered no client`);
|
|
164
|
-
const app = { host, redirectUri: ru, clientId: body.client_id, clientSecret: body.client_secret || null };
|
|
165
|
-
write('masto:apps', { ...apps, [host]: app });
|
|
166
|
-
return app;
|
|
167
|
-
};
|
|
168
|
-
|
|
169
|
-
/** Everything `login` does short of leaving the page: what the address is and the page to send the person to. */
|
|
170
|
-
async function startLogin(address, { returnTo = globalThis.location?.href || null, redirectUri: ru = redirectUri || here() } = {}) {
|
|
171
|
-
const what = await describe(address);
|
|
172
|
-
if (what.kind === 'pod') {
|
|
173
|
-
const s = await pod.startLogin(what.handle, { returnTo, redirectUri: ru });
|
|
174
|
-
write('pod:pending', { handle: what.handle, actor: what.actor, root: what.root, at: Date.now() });
|
|
175
|
-
return { ...what, authorizationUrl: s.authorizationUrl, returnTo };
|
|
176
|
-
}
|
|
177
|
-
const app = await appFor(what.host, ru);
|
|
178
|
-
const bytes = crypto.getRandomValues(new Uint8Array(24));
|
|
179
|
-
const state = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
180
|
-
write('masto:pending', { state, host: what.host, redirectUri: ru, returnTo, at: Date.now() });
|
|
181
|
-
const u = new URL(`https://${what.host}/oauth/authorize`);
|
|
182
|
-
for (const [k, v] of Object.entries({ client_id: app.clientId, redirect_uri: ru, response_type: 'code', scope: scopes, state })) u.searchParams.set(k, v);
|
|
183
|
-
return { ...what, authorizationUrl: u.href, returnTo };
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** Send the person to wherever this account signs in. They come back to this
|
|
187
|
-
* page (unless `redirectUri` says otherwise) and `resume` returns them to
|
|
188
|
-
* where they were (unless `returnTo` says otherwise). */
|
|
189
|
-
async function login(address, opts) {
|
|
190
|
-
const s = await startLogin(address, opts);
|
|
191
|
-
location.href = s.authorizationUrl;
|
|
192
|
-
return s;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** Call on every page load. Finishes a sign-in the person is coming back
|
|
196
|
-
* from, of either kind, and returns them to where they were. Returns the
|
|
197
|
-
* account, or null when nobody is coming back. */
|
|
198
|
-
async function resume({ currentUrl = globalThis.location?.href, go = (u) => location.replace(u) } = {}) {
|
|
199
|
-
const u = new URL(currentUrl);
|
|
200
|
-
const code = u.searchParams.get('code'); const state = u.searchParams.get('state');
|
|
201
|
-
const pend = read('masto:pending');
|
|
202
|
-
if (code && state && pend?.state === state) {
|
|
203
|
-
drop('masto:pending');
|
|
204
|
-
if (Date.now() - pend.at > PENDING_TTL_MS) throw new Error('that sign-in has expired — start again');
|
|
205
|
-
const app = await appFor(pend.host, pend.redirectUri);
|
|
206
|
-
const tok = await said(await f(`https://${pend.host}/oauth/token`, {
|
|
207
|
-
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
208
|
-
body: JSON.stringify({ grant_type: 'authorization_code', code, redirect_uri: pend.redirectUri, client_id: app.clientId, ...(app.clientSecret ? { client_secret: app.clientSecret } : {}), scope: scopes }),
|
|
209
|
-
}), pend.host);
|
|
210
|
-
if (!tok.access_token) throw new Error(`${pend.host} returned no token`);
|
|
211
|
-
const me = await said(await f(`https://${pend.host}/api/v1/accounts/verify_credentials`, { headers: { authorization: `Bearer ${tok.access_token}` } }), pend.host);
|
|
212
|
-
write('masto:account', { host: pend.host, token: tok.access_token, handle: `@${me.username}@${pend.host}`, name: me.display_name || me.username, actor: me.url || me.uri || null });
|
|
213
|
-
drop('pod:facts');
|
|
214
|
-
if (pend.returnTo && pend.returnTo !== currentUrl) go(pend.returnTo);
|
|
215
|
-
return current();
|
|
216
|
-
}
|
|
217
|
-
const session = await pod.resume({ currentUrl, go: () => {} });
|
|
218
|
-
if (!session) return null;
|
|
219
|
-
const p = read('pod:pending') || {};
|
|
220
|
-
drop('pod:pending');
|
|
221
|
-
const facts = await podFacts(session, p);
|
|
222
|
-
write('pod:facts', facts);
|
|
223
|
-
drop('masto:account');
|
|
224
|
-
if (session.returnTo && session.returnTo !== currentUrl) go(session.returnTo);
|
|
225
|
-
return current();
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// What a pod account needs, found once at sign-in: its door, its records,
|
|
229
|
-
// its followers collection, and whether its agent is a browser.
|
|
230
|
-
const podFacts = async (session, p) => {
|
|
231
|
-
const card = await json(session.webId, { headers: { accept: 'application/ld+json' } });
|
|
232
|
-
const nodes = Array.isArray(card) ? card : (card?.['@graph'] || (card ? [card] : []));
|
|
233
|
-
const me = nodes.find((n) => n?.['@id'] === session.webId) || {};
|
|
234
|
-
const pick = (node, k) => [].concat(node?.[k] || []).map((v) => v?.['@id'] || v).find((v) => typeof v === 'string') || null;
|
|
235
|
-
let actor = p.actor || pick(me, FOAF_ACCOUNT);
|
|
236
|
-
let door = pick(me, AS_OUTBOX);
|
|
237
|
-
const doc = actor ? await json(actor, { headers: { accept: 'application/activity+json' } }) : null;
|
|
238
|
-
if (!door && doc?.outbox) door = idOf(doc.outbox);
|
|
239
|
-
let root = p.root || null;
|
|
240
|
-
if (!root && doc?.preferredUsername && actor) {
|
|
241
|
-
const { aliases } = await webfinger(doc.preferredUsername, new URL(actor).host).catch(() => ({ aliases: [] }));
|
|
242
|
-
root = rootOf(actor, aliases);
|
|
243
|
-
}
|
|
244
|
-
const handle = p.handle || (doc?.preferredUsername && actor ? `@${doc.preferredUsername}@${new URL(actor).host}` : null);
|
|
245
|
-
// A browser-made account keeps its signing key on the pod sealed under
|
|
246
|
-
// the password; a device keeps its key with itself. The shape says which.
|
|
247
|
-
let browserBased = false;
|
|
248
|
-
if (root) {
|
|
249
|
-
const keys = await session.fetch(`${root}ap-state/keys.json`, { headers: { accept: 'application/json' } }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
250
|
-
const envelope = keys && (keys.v === 1 && typeof keys.ct === 'string' && typeof keys.salt === 'string'
|
|
251
|
-
|| Object.values(keys).some((k) => k && k.v === 1 && typeof k.ct === 'string' && typeof k.salt === 'string'));
|
|
252
|
-
browserBased = !!envelope;
|
|
253
|
-
}
|
|
254
|
-
return { handle, actor, name: doc?.name || null, door, root, followers: doc?.followers || null, webId: session.webId, browserBased };
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
// ---- the account ----
|
|
258
|
-
|
|
259
|
-
const mastodonAccount = (a) => {
|
|
260
|
-
const base = `https://${a.host}`;
|
|
261
|
-
const auth = { authorization: `Bearer ${a.token}` };
|
|
262
|
-
const call = (path, init = {}) => f(`${base}${path}`, { ...init, headers: { ...auth, ...(init.headers || {}) } });
|
|
263
|
-
const post = (path, body) => call(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}) }).then((r) => said(r, a.host));
|
|
264
|
-
// A post named by its address is found on this server by a search that
|
|
265
|
-
// fetches it if need be; one named by an id here is used as it is.
|
|
266
|
-
const idOf = async (target) => {
|
|
267
|
-
if (!/^https?:\/\//u.test(String(target))) return String(target);
|
|
268
|
-
const u = new URL(`${base}/api/v2/search`);
|
|
269
|
-
u.searchParams.set('q', target); u.searchParams.set('resolve', 'true'); u.searchParams.set('type', 'statuses'); u.searchParams.set('limit', '1');
|
|
270
|
-
const body = await call(u.href).then((r) => said(r, a.host));
|
|
271
|
-
const id = body.statuses?.[0]?.id;
|
|
272
|
-
if (!id) throw new Error(`${a.host} could not find that post`);
|
|
273
|
-
return id;
|
|
274
|
-
};
|
|
275
|
-
const item = (s) => ({
|
|
276
|
-
id: s.id, url: s.url || s.uri || null, published: s.created_at,
|
|
277
|
-
author: { id: s.account?.url || null, handle: s.account?.acct ? `@${s.account.acct}${s.account.acct.includes('@') ? '' : '@' + a.host}` : null, name: s.account?.display_name || s.account?.username || null },
|
|
278
|
-
html: s.content || '', inReplyTo: s.in_reply_to_id || null,
|
|
279
|
-
...(s.reblog ? { boostOf: item(s.reblog) } : {}),
|
|
280
|
-
});
|
|
281
|
-
return {
|
|
282
|
-
kind: 'mastodon', handle: a.handle, name: a.name, actor: a.actor, notice: null,
|
|
283
|
-
fetch: call,
|
|
284
|
-
async profile() {
|
|
285
|
-
const me = await call('/api/v1/accounts/verify_credentials').then((r) => said(r, a.host));
|
|
286
|
-
return { handle: a.handle, name: me.display_name || me.username || null, url: me.url || null, avatar: me.avatar || null, bio: me.note || '',
|
|
287
|
-
followers: me.followers_count ?? null, following: me.following_count ?? null, posts: me.statuses_count ?? null, actor: a.actor, webId: null };
|
|
288
|
-
},
|
|
289
|
-
async post({ text, inReplyTo = null, visibility = 'public' }) {
|
|
290
|
-
const made = await post('/api/v1/statuses', { status: text, visibility, ...(inReplyTo ? { in_reply_to_id: await idOf(inReplyTo) } : {}) });
|
|
291
|
-
return { id: made.id, url: made.url || made.uri || null, sent: true };
|
|
292
|
-
},
|
|
293
|
-
reply(target, text) { return this.post({ text, inReplyTo: target }); },
|
|
294
|
-
async timeline({ limit = 20 } = {}) {
|
|
295
|
-
const list = await call(`/api/v1/timelines/home?limit=${Math.min(40, limit)}`).then((r) => said(r, a.host));
|
|
296
|
-
return (Array.isArray(list) ? list : []).map(item);
|
|
297
|
-
},
|
|
298
|
-
// This account's own posts, newest first — Mastodon's equivalent of an
|
|
299
|
-
// outbox. A Mastodon server IS an ActivityPub server, so its actor and
|
|
300
|
-
// outbox are real AS2/JSON-LD too, same as a pod's; `rdf: true` reads
|
|
301
|
-
// that, not the REST API above. It comes back empty on an instance that
|
|
302
|
-
// requires a signed request just to read the public actor document
|
|
303
|
-
// (some do — mastodon.social among them); `fetchOutboxRdf`'s plain GET
|
|
304
|
-
// then gets 401 and the loop below finds nothing to walk.
|
|
305
|
-
async outbox({ limit = 20, rdf = false } = {}) {
|
|
306
|
-
const me = await call('/api/v1/accounts/verify_credentials').then((r) => said(r, a.host));
|
|
307
|
-
const list = await call(`/api/v1/accounts/${me.id}/statuses?limit=${Math.min(40, limit)}`).then((r) => said(r, a.host));
|
|
308
|
-
const items = (Array.isArray(list) ? list : []).map(item);
|
|
309
|
-
if (rdf) items.rdf = await fetchOutboxRdf(a.actor, limit);
|
|
310
|
-
return items;
|
|
311
|
-
},
|
|
312
|
-
async follow(handle) {
|
|
313
|
-
const who = parseAddress(handle);
|
|
314
|
-
if (!who?.at) throw new Error('a handle looks like @you@your.server');
|
|
315
|
-
const acct = await call(`/api/v1/accounts/lookup?acct=${encodeURIComponent(who.at.slice(1))}`).then((r) => said(r, a.host));
|
|
316
|
-
if (!acct.id) throw new Error(`${a.host} could not find ${who.at}`);
|
|
317
|
-
await post(`/api/v1/accounts/${acct.id}/follow`);
|
|
318
|
-
return { followed: who.at, sent: true };
|
|
319
|
-
},
|
|
320
|
-
async favourite(target) { await post(`/api/v1/statuses/${await idOf(target)}/favourite`); return { sent: true }; },
|
|
321
|
-
async boost(target) { await post(`/api/v1/statuses/${await idOf(target)}/reblog`); return { sent: true }; },
|
|
322
|
-
async signOut() {
|
|
323
|
-
const apps = read('masto:apps') || {};
|
|
324
|
-
const app = apps[a.host];
|
|
325
|
-
if (app) {
|
|
326
|
-
try { await f(`${base}/oauth/revoke`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ client_id: app.clientId, client_secret: app.clientSecret, token: a.token }) }); } catch { /* told if we could */ }
|
|
327
|
-
}
|
|
328
|
-
drop('masto:account');
|
|
329
|
-
},
|
|
330
|
-
};
|
|
331
|
-
};
|
|
332
|
-
|
|
333
|
-
const podAccount = (session, facts) => {
|
|
334
|
-
const knock = async (activity) => {
|
|
335
|
-
if (!facts.door) throw new Error('this account names no outbox to post through');
|
|
336
|
-
const res = await session.fetch(facts.door, { method: 'POST', headers: { 'content-type': 'application/activity+json' }, body: JSON.stringify({ '@context': AS, ...activity }) });
|
|
337
|
-
if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`the outbox refused it (HTTP ${res.status})${body ? `: ${body.slice(0, 200)}` : ''}`); }
|
|
338
|
-
return { id: res.headers.get('location') || null, sent: res.status === 201, queued: res.status === 202 };
|
|
339
|
-
};
|
|
340
|
-
const audience = (visibility) => {
|
|
341
|
-
if (visibility === 'unlisted') return { to: facts.followers ? [facts.followers] : [], cc: [PUBLIC] };
|
|
342
|
-
if (visibility === 'private' || visibility === 'followers') return { to: facts.followers ? [facts.followers] : [], cc: [] };
|
|
343
|
-
return { to: [PUBLIC], cc: facts.followers ? [facts.followers] : [] };
|
|
344
|
-
};
|
|
345
|
-
const state = (name) => (facts.root ? session.fetch(`${facts.root}ap-state/${name}`, { headers: { accept: 'application/json' } }).then((r) => (r.ok ? r.json() : null)).catch(() => null) : Promise.resolve(null));
|
|
346
|
-
return {
|
|
347
|
-
kind: 'pod', handle: facts.handle, name: facts.name, actor: facts.actor, webId: facts.webId,
|
|
348
|
-
notice: facts.browserBased ? BROWSER_ACCOUNT_NOTICE : null,
|
|
349
|
-
fetch: session.fetch,
|
|
350
|
-
async profile() {
|
|
351
|
-
const doc = facts.actor ? await json(facts.actor, { headers: { accept: 'application/activity+json' } }) : null;
|
|
352
|
-
const count = async (v) => (await asDoc(v))?.totalItems ?? null;
|
|
353
|
-
return { handle: facts.handle, name: doc?.name || null, url: doc?.url || null, avatar: doc?.icon?.url || (typeof doc?.icon === 'string' ? doc.icon : null), bio: doc?.summary || '',
|
|
354
|
-
followers: await count(doc?.followers), following: await count(doc?.following), posts: await count(doc?.outbox), actor: facts.actor, webId: facts.webId };
|
|
355
|
-
},
|
|
356
|
-
async post({ text, inReplyTo = null, visibility = 'public' }) {
|
|
357
|
-
const made = await knock({ type: 'Note', content: toHtml(text), source: { content: text, mediaType: 'text/plain' }, ...(inReplyTo ? { inReplyTo } : {}), ...audience(visibility) });
|
|
358
|
-
return { id: made.id, url: made.id, sent: made.sent, queued: made.queued };
|
|
359
|
-
},
|
|
360
|
-
reply(target, text) { return this.post({ text, inReplyTo: target }); },
|
|
361
|
-
async timeline({ limit = 20 } = {}) {
|
|
362
|
-
const rows = await state('statuses.json');
|
|
363
|
-
const actors = (await state('actors.json')) || {};
|
|
364
|
-
const who = (id) => { const d = actors[id]?.doc || actors[id] || {}; return { id, handle: d.preferredUsername ? `@${d.preferredUsername}@${new URL(id).host}` : null, name: d.name || null }; };
|
|
365
|
-
return (Array.isArray(rows) ? rows : [])
|
|
366
|
-
.filter((s) => s.kind !== 'remote' && s.kind !== 'mention' && !s.direct && s.visibility !== 'direct')
|
|
367
|
-
.sort((x, y) => String(y.published || '').localeCompare(String(x.published || '')))
|
|
368
|
-
.slice(0, limit)
|
|
369
|
-
.map((s) => ({ id: s.noteId, url: s.noteId, published: s.published || null, author: who(s.actor), html: s.content || '', inReplyTo: s.inReplyTo || null }));
|
|
370
|
-
},
|
|
371
|
-
// This account's own posts, newest first, read from the same local
|
|
372
|
-
// record `timeline` uses (fast, no network call). With `rdf: true`,
|
|
373
|
-
// also fetches the real outbox from the pod and parses it into RDF/JS
|
|
374
|
-
// quads on the returned array's `.rdf` — a second, live document, not
|
|
375
|
-
// derived from the local record, so it needs `jsonld` (see loadJsonLd).
|
|
376
|
-
async outbox({ limit = 20, rdf = false } = {}) {
|
|
377
|
-
const rows = await state('statuses.json');
|
|
378
|
-
const actors = (await state('actors.json')) || {};
|
|
379
|
-
const who = (id) => { const d = actors[id]?.doc || actors[id] || {}; return { id, handle: d.preferredUsername ? `@${d.preferredUsername}@${new URL(id).host}` : null, name: d.name || null }; };
|
|
380
|
-
const items = (Array.isArray(rows) ? rows : [])
|
|
381
|
-
.filter((s) => s.kind === 'post')
|
|
382
|
-
.sort((x, y) => String(y.published || '').localeCompare(String(x.published || '')))
|
|
383
|
-
.slice(0, limit)
|
|
384
|
-
.map((s) => ({ id: s.noteId, url: s.noteId, published: s.published || null, author: who(s.actor), html: s.content || '', inReplyTo: s.inReplyTo || null }));
|
|
385
|
-
if (rdf) items.rdf = await fetchOutboxRdf(facts.actor, limit);
|
|
386
|
-
return items;
|
|
387
|
-
},
|
|
388
|
-
async follow(handle) {
|
|
389
|
-
const who = parseAddress(handle);
|
|
390
|
-
if (!who?.at) throw new Error('a handle looks like @you@your.server');
|
|
391
|
-
const made = await knock({ type: 'Follow', object: who.at });
|
|
392
|
-
return { followed: who.at, sent: made.sent, queued: made.queued };
|
|
393
|
-
},
|
|
394
|
-
async favourite(target) { return knock({ type: 'Like', object: target }); },
|
|
395
|
-
async boost(target) { return knock({ type: 'Announce', object: target, ...audience('public') }); },
|
|
396
|
-
async signOut() { await session.signOut(); drop('pod:facts'); },
|
|
397
|
-
};
|
|
398
|
-
};
|
|
399
|
-
|
|
400
|
-
/** The signed-in account, or null. */
|
|
401
|
-
async function current() {
|
|
402
|
-
const m = read('masto:account');
|
|
403
|
-
if (m) return mastodonAccount(m);
|
|
404
|
-
const session = await pod.getSession();
|
|
405
|
-
if (!session) return null;
|
|
406
|
-
let facts = read('pod:facts');
|
|
407
|
-
if (!facts || facts.webId !== session.webId) { facts = await podFacts(session, {}); write('pod:facts', facts); }
|
|
408
|
-
return podAccount(session, facts);
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
async function signOut() { const me = await current(); if (me) await me.signOut(); }
|
|
412
|
-
|
|
413
|
-
// For a test that hands in a pod session of its own.
|
|
414
|
-
const _podAccount = async (session, pending = {}) => podAccount(session, await podFacts(session, pending));
|
|
415
|
-
|
|
416
|
-
return { describe, startLogin, login, resume, current, signOut, _podAccount };
|
|
417
|
-
}
|