Compare commits

...

10 commits

Author SHA1 Message Date
298fa4f42d Fixes to the rss/atom/json feeds 2023-10-03 09:19:23 +11:00
983d828f92 Some small refactoring and bug fixing 2023-10-03 09:19:04 +11:00
fa5ef0e282 Utilize the global actor object in 11ty templates 2023-09-28 12:23:25 +10:00
6f2e122dd6 Refactored to store actor info in a separate file
This makes it more easy to modify for future users
2023-09-28 11:15:25 +10:00
6647dabdc8 Added eleventy templates from death.id.au
Needed a little modification here and there to make it work with the activity pub data structure, but it's looking pretty good!
2023-09-27 17:06:56 +10:00
b76eb76e1a Utilize 11ty to build static pages and modify server to serve them 2023-09-27 14:13:10 +10:00
283220111f Adjusted admin follow to accept [@]user@domain.tld format 2023-09-27 09:50:06 +10:00
2701786de8 Some refactoring and removing the need to specify user
This is going to be single user anyway, so why use https://death.id.au/death.au when I can just be https://death.id.au
2023-09-27 09:49:32 +10:00
71f38cca62 use spread syntax in dedupe recipient Set 2023-09-21 17:12:34 +10:00
36d8ace51f Added dislikes, shares/boosts, replies and deleting posts
All admin/outbox stuff for now. Nothing inbox, yet
2023-09-21 17:04:27 +10:00
44 changed files with 1670 additions and 285 deletions

95
.eleventy.js Normal file
View file

@ -0,0 +1,95 @@
const ACTOR = require("./actor").default
module.exports = function(eleventyConfig) {
// I'm .gitignoring my content for now, so 11ty should not ignore that
eleventyConfig.setUseGitIgnore(false)
// Filters are in a separate function to try and keep this config less cluttered
addFilters(eleventyConfig)
// same with shortcodes
addShortcodes(eleventyConfig)
// and collections
addCollections(eleventyConfig)
// add the actor data, accessible globally
eleventyConfig.addGlobalData("ACTOR", ACTOR);
// TODO: assets?
// files to passthrough copy
eleventyConfig.addPassthroughCopy({"img":"assets/img"})
eleventyConfig.addPassthroughCopy({"js":"assets/js"})
eleventyConfig.addPassthroughCopy("css")
eleventyConfig.addPassthroughCopy("CNAME")
// plugins
eleventyConfig.addPlugin(require("@11ty/eleventy-plugin-rss"))
const { EleventyHtmlBasePlugin } = require("@11ty/eleventy")
eleventyConfig.addPlugin(EleventyHtmlBasePlugin)
// Return your Object options:
return {
dir: {
input: "_content",
output: "_site"
},
htmlTemplateEngine: "njk",
templateFormats: ["md","html","njk"]
}
}
function addCollections(eleventyConfig) {
eleventyConfig.addCollection("feed", function(collectionApi) {
return collectionApi.getAllSorted().reverse().filter(item => {
if(!item.data.published) return false
return item.filePathStem.startsWith('/posts/')
}).map(item => {
item.data.author = ACTOR
return item
}).sort((a, b) => new Date(b.published).getTime() - new Date(a.published).getTime())
})
}
function addShortcodes(eleventyConfig) {
eleventyConfig.addNunjucksShortcode("getVar", function(varString){ return this.ctx[varString] })
eleventyConfig.addShortcode('renderlayoutblock', function(name){ return (this.page.layoutblock || {})[name] || '' })
eleventyConfig.addPairedShortcode('layoutblock', function(content, name) {
if (!this.page.layoutblock) this.page.layoutblock = {}
this.page.layoutblock[name] = content
return ''
})
}
function addFilters(eleventyConfig) {
eleventyConfig.addFilter("formatDate", formatDateFilter)
eleventyConfig.addFilter("dateISOString", dateISOStringFilter)
eleventyConfig.addFilter("dateObj", (value) => new Date(value))
eleventyConfig.addFilter("log", (value) => { console.log(`[11ty] 📄LOG: `, value); return value })
eleventyConfig.addFilter("concat", (value, other) => value + '' + other)
eleventyConfig.addNunjucksAsyncFilter("await", (promise) => promise.then(res => callback(null, res)).catch(err => callback(err)))
}
// default date formatting
function formatDateFilter(value) {
try{
const date = new Date(value)
if(date) return date.toISOString().replace('T', ' ').slice(0, -5)
else throw 'Unrecognized data format'
}
catch(e) {
console.error(`Could not convert "${value}"`, e)
return value;
}
}
// dates as iso string
function dateISOStringFilter(value) {
try{
const date = new Date(value)
if(date) return date.toISOString()
else throw 'Unrecognized data format'
}
catch(e) {
console.error(`Could not convert "${value}"`, e)
return value;
}
}

5
.gitignore vendored
View file

@ -169,4 +169,7 @@ dist
.pnp.\*
# My custom ignores
_content
_content/_data/_inbox
_content/_data/_outbox
_content/posts
_site

1
CNAME Normal file
View file

@ -0,0 +1 @@
death.id.au

View file

@ -14,6 +14,10 @@ I may also experiment with pushing the content to a seperate git repository so I
- Bun has it's own built-in http server, so this project uses that rather than something like Express.
- It uses [`node-forge`](https://github.com/digitalbazaar/forge) for signing and verifying signed posts, as Bun does not yet implement the required `node:crypto` methods
- It uses [`gray-matter`](https://github.com/jonschlinkert/gray-matter) for writing and parsing YAML frontmatter in Markdown files
- It uses [11ty](https://www.11ty.dev/) to compile those Markdown files into a static website
Note: there is an error with 11ty in Bun, tracked [here](https://github.com/oven-sh/bun/issues/5560). Until there is a fix, there is a workaround:
`node_modules/graceful-fs/graceful-fs.js:299` — remove the `, this` from the end of the line
- The [RSS Plugin](https://www.11ty.dev/docs/plugins/rss/) for 11ty is also used to generate RSS feeds of the posts
## Development

View file

@ -0,0 +1 @@
[]

1
_content/_data/layout.js Normal file
View file

@ -0,0 +1 @@
module.exports = "layout-default.njk"

View file

@ -0,0 +1 @@
[]

View file

@ -0,0 +1,13 @@
---js
{
layout: "layout-main.njk",
ctx: function() { return this.ctx }
}
---
{% from "macro-entry.njk" import entryMacro %}
{{ entryMacro(ctx(), author, url, content) }}
{% layoutblock 'foot' %}
<script src="/assets/js/relative-time.js"></script>
{% endlayoutblock %}

View file

@ -0,0 +1,15 @@
---
title: Feed
layout: layout-main.njk
scripts_foot: '<script src="/assets/js/relative-time.js"></script>'
---
<div class="h-feed">
<h2 class="p-name">{{ title }}</h2>
{{ content | safe }}
</div>
{% include 'partial-pagination.njk' %}
{% layoutblock 'foot' %}
<script src="/assets/js/relative-time.js"></script>
{% endlayoutblock %}

View file

@ -0,0 +1,38 @@
---
title: Mon Repos (Death's Domain)
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/svg+xml" href="/assets/img/avatar-tt.svg">
<link rel="icon" type="image/png" href="/assets/img/avatar-tiny.png">
<link rel="authorization_endpoint" href="https://deathau-cellar-door.glitch.me/">
<link rel="token_endpoint" href="https://deathau-cellar-door.glitch.me/token">
{# <link rel="webmention" href="https://webmention.io/death.id.au/webmention" />
<link rel="pingback" href="https://webmention.io/death.id.au/xmlrpc" />
<link rel="microsub" href="https://aperture.p3k.io/microsub/807">
<link rel="micropub" href="https://micropub.death.id.au/.netlify/functions/micropub">
<link rel="micropub_media" href="https://micropub.death.id.au/.netlify/functions/media"> #}
<link rel="stylesheet" href="/css/styles.css">
<link rel="alternate" type="application/rss+xml" title="RSS Feed for {{ ACTOR.hostname }}" href="/rss.xml" />
<link rel="alternate" type="application/atom+xml" title="Atom Feed for {{ ACTOR.hostname}}" href="/atom.xml" />
<link rel="alternate" type="application/json" title="JSON Feed for {{ ACTOR.hostname }}" href="/feed.json" />
<script src="https://kit.fontawesome.com/ebe14e90c3.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon/build/global/luxon.min.js" crossorigin="anonymous"></script>
<title>{{ title }}</title>
{% renderlayoutblock 'head' %}
</head>
<body>
{% renderlayoutblock 'header' %}
<main>
{{ content | safe }}
</main>
</body>
{% renderlayoutblock 'footer' %}
{% renderlayoutblock 'foot' %}
</html>

View file

@ -0,0 +1,10 @@
{% macro authorMacro(author) %}
{# {{ author | getAuthorData | log }} #}
<a class="p-author h-card u-url" href="{{ author.canonical_uri if author.canonical_uri else author.url }}">
<img class="u-photo small-avatar" alt="{{ author.icon.name if author.icon.name else "Avatar for " + author.preferredUsername }}" src="{{ author.icon.url if author.icon.url else author.avatar }}"/>
<span class="display-name">
<span class="p-name">{{ author.name }}</span>
<span class="p-nickname">{{ author.preferredUsername }}</span>
</span>
</a>
{% endmacro %}

View file

@ -0,0 +1,9 @@
{% from "macro-author.njk" import authorMacro %}
{% macro cardHeadMacro(author, date, url) %}
<div class="card-head">
<a class="u-url permalink" rel="bookmark" href="{{ url }}" >
<time class="dt-published" datetime="{{ date | dateISOString }}">{{ date | formatDate }}</time>
</a>
{{ authorMacro(author) }}
</div>
{% endmacro %}

View file

@ -0,0 +1,14 @@
{% from "macro-card-head.njk" import cardHeadMacro %}
{% from "macro-summary.njk" import summaryMacro %}
{% macro entryMacro(item, author, url, content, summaryOnly=false) %}
<div class="h-entry type-{{ item.postType }}">
{{ cardHeadMacro(author, item.published, url) }}
<div class="card-body">
{{ summaryMacro(item, url) }}
{% if item.type == 'article' and summaryOnly %}
{% elseif content %}
<div class="e-content">{{ content | safe }}</div>
{% endif %}
</div>
</div>
{% endmacro %}

View file

@ -0,0 +1,83 @@
{% macro summaryMacro(item, url) %}
{% switch item.type %}
{% case "article" %} {# article summary: #}
<h2 class="p-name"><a class="u-url" rel="bookmark" title="{{ item.name if item.name else item.title }}" href="{{ url }}">
{{ item.name if item.name else item.title }}
</a></h2>
{% if item.summary %}
<p class="p-summary">{{ item.summary | safe }}</p>
{% endif %}
{% case "reply" %} {# reply summary: #}
<p class="p-summary"><i class="fa-solid fa-reply"></i> Reply to <a class="u-in-reply-to" href="{{ item["in-reply-to"] }}">{{ item["in-reply-to"] }}</a></p>
{% case "like" %} {# like summary: #}
<p class="p-summary">Favourited <i class="fa-solid fa-star"></i> <a class="u-like-of" href="{{ item['like-of'] }}">{{ item['like-of'] }}</a></p>
{% case "boost" %} {# boost summary: #}
<p class="p-summary"></p>Boosted <i class="fa-solid fa-retweet"></i> <a class="u-repost-of" href="{{ item["repost-of"] }}">{{ item["repost-of"] }}</a></p>
{% case "bookmark" %} {# bookmark summary: #}
<p class="p-summary">Bookmarked <i class="fa-solid fa-bookmark"></i> <a class="u-bookmark-of" href="{{ item["bookmark-of"] }}">{{ item["bookmark-of"] }}</a></p>
{% case "read" %} {# read summary: #}
<p class="p-summary">
{% if item["read-status"].toLowerCase() == "to-read" %}
<data class="p-x-read-status p-read-status" value="to-read">To Read: </data>
<i class="fa-solid fa-book"></i>
{% elseif item["read-status"].toLowerCase() == "reading" %}
<data class="p-x-read-status p-read-status" value="reading">Currently Reading: </data>
<i class="fa-solid fa-book-open"></i>
{% elseif item["read-status"].toLowerCase() == "finished" %}
<data class="p-x-read-status p-read-status" value="finished">Finished Reading: </data>
<i class="fa-solid fa-book-bookmark"></i>
{% endif %}
{% if item["read-of"].startsWith("http") %}
<a class="u-read-of" href="{{ item["read-of"] }}">{{ item["read-of"] }}</a>
{% else %}
<strong class="p-read-of">{{ item["read-of"] }}</strong>
{% endif %}
</p>
{% case "watch" %} {# watch summary: #}
<p class="p-summary">
{% if item["watch-status"].toLowerCase() == "to-watch" %}
<data class="p-x-watch-status p-watch-status" value="to-watch">To Watch: </data>
{% elseif item["watch-status"].toLowerCase() == "watching" %}
<data class="p-x-watch-status p-watch-status" value="watching">Currently Watching: </data>
{% elseif item["watch-status"].toLowerCase() == "watched" or item["watch-status"].toLowerCase() == "finished" %}
<data class="p-x-watch-status p-watch-status" value="finished">Finished watching: </data>
{% else %}
<data class="p-x-watch-status p-watch-status" value="finished">Watched: </data>
{% endif %}
<i class="fa-solid fa-clapperboard"></i>
{% if item["watch-of"].startsWith("http") %}
<a class="u-watch-of" href="{{ item["watch-of"] }}">{{ item["watch-of"] }}</a>
{% else %}
<strong class="p-watch-of">{{ item["watch-of"] }}</strong>
{% endif %}
</p>
{% case "rsvp" %} {# rsvp summary: #}
<p class="p-summary">
{% if item.rsvp.toLowerCase() == "yes" %}
<i class="fa-regular fa-calendar-check"></i>
<data class="p-rsvp" value="yes">Will attend</data>
{% elseif item.rsvp.toLowerCase() == "maybe" %}
<i class="fa-regular fa-calendar-minus"></i>
<data class="p-rsvp" value="maybe">Might attend</data>
{% elseif item.rsvp.toLowerCase() == "no" %}
<i class="fa-regular fa-calendar-xmark"></i>
<data class="p-rsvp" value="no">Won't attend</data>
{% elseif item.rsvp.toLowerCase() == "interested" %}
<i class="fa-regular fa-calendar-plus"></i>
<data class="p-rsvp" value="interested">Interested in</data>
{% endif %}
<a class="u-in-reply-to" href="{{ item["in-reply-to"] }}">{{ item["in-reply-to"] }}</a>
</p>
{% endswitch %}
{% endmacro %}

View file

@ -0,0 +1,15 @@
{% if pagination %}
<nav>
<ul class="pagination" role="list">
<li><a href="{{ pagination.href.first }}" rel="first" title="First Page">«</a></li>
<li><a href="{{ pagination.href.previous if pagination.href.previous else "#" }}" class="{{ '' if pagination.href.previous else 'disabled' }}" rel="prev" title="Previous Page"></a></li>
{%- for pageEntry in pagination.pages %}
<li><a href="{{ pagination.hrefs[ loop.index0 ] }}"{% if page.url == pagination.hrefs[ loop.index0 ] %} aria-current="page" class="active" title="Current Page" {% else %} title="Jump to Page {{ loop.index }}" {% endif %}>{{ loop.index }}</a></li>
{%- endfor %}
<li><a href="{{ pagination.href.next if pagination.href.next else "#" }}" class="{{ '' if pagination.href.next else 'disabled' }}" rel="next" title="Next Page"></a></li>
<li><a href="{{ pagination.href.last }}" rel="last" title="Last Page">»</a></li>
</ul>
</nav>
{% endif %}

View file

@ -0,0 +1,6 @@
<h2 class="p-name"><a class="u-url" rel="bookmark" title="{{ item.name if item.name else item.title }}" href="{{ url }}">
{{ item.name if item.name else item.title }}
</a></h2>
{% if item.summary %}
<p class="p-summary">{{ item.summary | safe }}</p>
{% endif %}

View file

36
_content/atom.njk Normal file
View file

@ -0,0 +1,36 @@
---json
{
"layout": null,
"permalink": "atom.xml",
"eleventyExcludeFromCollections": true,
"metadata": {
"subtitle": "A feed of all my posts on the fediverse",
"language": "en"
}
}
---
<?xml version="1.0" encoding="utf-8"?>
{% from "macro-summary.njk" import summaryMacro %}
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="{{ ACTOR.url }}">
<title>{{ ACTOR.name }}'s feed</title>
<subtitle>{{ metadata.subtitle }}</subtitle>
<link href="{{ permalink | absoluteUrl(ACTOR.url) }}" rel="self"/>
<updated>{{ collections.feed[0].date | dateToRfc3339 }}</updated>
<id>{{ ACTOR.id | absoluteUrl(ACTOR.url) }}</id>
<author>
<name>{{ ACTOR.name }}</name>
</author>
{%- for post in collections.feed %}
{%- set absolutePostUrl = post.url | absoluteUrl(ACTOR.url) %}
<entry>
<title>{{ post.data.title }}</title>
<link href="{{ absolutePostUrl }}"/>
<updated>{{ post.data.published | dateObj | dateToRfc3339 }}</updated>
<id>{{ absolutePostUrl }}</id>
<content xml:lang="{{ metadata.language }}" type="html">
{{ summaryMacro(post.data, post.url) | htmlToAbsoluteUrls(absolutePostUrl) }}
{{ post.templateContent | htmlToAbsoluteUrls(absolutePostUrl) }}
</content>
</entry>
{%- endfor %}
</feed>

76
_content/index.html Normal file
View file

@ -0,0 +1,76 @@
---
layout: layout-main.njk
eleventyExcludeFromCollections: true
---
<!-- Reference for representative h-card properties: https://microformats.org/wiki/h-card -->
<div class="h-card" rel="author">
<img class="u-featured" src="{{ ACTOR.image.url }}" alt="{{ ACTOR.image.name}}" />
<img class="u-photo" alt="{{ ACTOR.icon.name}}" src="{{ ACTOR.icon.url }}" />
<h1>
I'm <span class="p-name">{{ ACTOR.name }}</span>
{% if ACTOR.name != ACTOR.preferredUsername %}
(a.k.a <span class="p-nickname">{{ ACTOR.preferredUsername }}</span>)
{% endif %}
</h1>
<p class="p-note">
{% if ACTOR.summary %}
{{ ACTOR.summary }}
{% else %}
...and I am a human on the Internet.
{% endif %}
</p>
<p>
Go check out some <a href="/posts">stuff I wrote</a><br>
Or stay up-to-date by following me
<ul>
<li><button class="icon-button button-input"
data-instruction="Please enter your fediverse / mastodon handle (e.g. '@user@domain.social')"
data-placeholder="@user@domain.social"
data-success="Thanks for the follow!"
onsubmit="handleFollow(event.value)">
<img src="/assets/img/Fediverse_logo_proposal.svg" alt="Fediverse logo">
Follow @{{ ACTOR.preferredUsername }}@{{ ACTOR.hostname }}
</button></li>
<li><i class="fa fa-rss"></i> <a class="u-url" href="/rss.xml">RSS Feed</a></li>
<li><i class="fa fa-feed"></i> <a class="u-url" href="/atom.xml">Atom Feed</a></li>
<li><i class="fa fa-feed"></i> <a class="u-url" href="/feed.json">JSON Feed</a></li>
</ul>
</p>
<p>
...or elsewhere on the Internet:
<ul>
<li><i><img class="tiny-avatar" src="/assets/img/avatar-tt-trans.svg"></i> <a class="u-uid u-url" href="https://death.id.au">Mon Repos (you are here)</a><a class="u-url" href="acct:death.au@death.id.au"></a></li>
<li><i><img class="tiny-avatar" src="/assets/img/Obsidian.svg"></i> <a class="u-url" href="https://notes.death.id.au" rel="me">My published notes</a></li>
<li><i class="fa-brands fa-mastodon"></i> <a class="u-url" href="https://pkm.social/@death_au" rel="me">@death_au@pkm.social</a></li>
<li><i class="fa-brands fa-github"></i> <a class="u-url" href="https://github.com/deathau" rel="me">@deathau</a></li>
<li><i class="fa-brands fa-twitter"></i> <a class="u-url" href="https://twitter.com/death_au" rel="me">@death_au</a></li>
<li><i class="fa-brands fa-linkedin"></i> <a class="u-url" href="https://www.linkedin.com/in/gordon-pedersen/">Gordon Pedersen</a></li>
</ul>
</p>
</div>
{% layoutblock 'foot' %}
<script src="/assets/js/follow.js"></script>
<script src="/assets/js/button-input.js"></script>
<script>
window.addEventListener('unhandledrejection', function(event) {
alert(event.reason)
})
function handleFollow(handle) {
try{
follow(`@${ACTOR.preferredUsername}@${ACTOR.hostname}`, handle)
}
catch(e){
alert(e)
}
}
function tryFollow(user) {
try{
follow(user)
}
catch(e){
alert(e)
}
}
</script>
{% endlayoutblock %}

36
_content/json.njk Normal file
View file

@ -0,0 +1,36 @@
---json
{
"layout": null,
"permalink": "feed.json",
"eleventyExcludeFromCollections": true,
"metadata": {
"subtitle": "A feed of all my posts on the fediverse",
"language": "en"
}
}
---
{ {% from "macro-summary.njk" import summaryMacro %}
"version": "https://jsonfeed.org/version/1.1",
"title": "{{ ACTOR.name }}'s feed",
"language": "{{ metadata.language }}",
"home_page_url": "{{ ACTOR.url }}/",
"feed_url": "{{ permalink | absoluteUrl(ACTOR.url) }}",
"description": "{{ metadata.subtitle }}",
"author": {
"name": "{{ ACTOR.name }}",
"url": "{{ ACTOR.url }}/"
},
"items": [
{%- for post in collections.feed %}
{%- set absolutePostUrl = post.url | absoluteUrl(ACTOR.url) %}
{
"id": "{{ absolutePostUrl }}",
"url": "{{ absolutePostUrl }}",
"title": "{{ post.data.title }}",
"content_html": {{ summaryMacro(post.data, post.url) | concat(post.templateContent) | htmlToAbsoluteUrls(absolutePostUrl) | dump | safe }},
"date_published": "{{ post.data.published | dateObj | dateToRfc3339 }}"
}
{% if not loop.last %},{% endif %}
{%- endfor %}
]
}

18
_content/posts/index.njk Normal file
View file

@ -0,0 +1,18 @@
---
title: My Feed
layout: layout-feed.njk
pagination:
data: collections.feed
size: 20
eleventyExcludeFromCollections: true
---
{% from "macro-entry.njk" import entryMacro %}
<ul>
{% for item in pagination.items %}
<li>
{{ entryMacro(item.data, item.data.author, item.url, item.templateContent, true) }}
</li>
{% endfor %}
</ul>

36
_content/rss.njk Normal file
View file

@ -0,0 +1,36 @@
---js
{
"layout": null,
"permalink": "rss.xml",
"eleventyExcludeFromCollections": true,
"metadata": {
"subtitle": "A feed of all my posts on the fediverse",
"language": "en"
}
}
---
<?xml version="1.0" encoding="utf-8"?>
{% from "macro-summary.njk" import summaryMacro %}
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:base="{{ ACTOR.url }}" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{{ ACTOR.name }}'s feed</title>
<link>{{ ACTOR.url }}</link>
<atom:link href="{{ permalink | absoluteUrl(ACTOR.url) }}" rel="self" type="application/rss+xml" />
<description>{{ metadata.subtitle }}</description>
<language>{{ metadata.language }}</language>
{%- for post in collections.feed | reverse %}
{%- set absolutePostUrl = post.url | absoluteUrl(ACTOR.url) %}
<item>
<title>{{ post.data.title }}</title>
<link>{{ absolutePostUrl }}</link>
<description>
{{ summaryMacro(post.data, post.url) | htmlToAbsoluteUrls(absolutePostUrl) }}
{{ post.templateContent | htmlToAbsoluteUrls(absolutePostUrl) }}
</description>
<pubDate>{{ post.data.published | dateObj | dateToRfc822 }}</pubDate>
<dc:creator>{{ ACTOR.name }}</dc:creator>
<guid>{{ absolutePostUrl }}</guid>
</item>
{%- endfor %}
</channel>
</rss>

114
actor.ts Normal file
View file

@ -0,0 +1,114 @@
import { BASE_URL, HOSTNAME, PUBLIC_KEY } from "./src/env"
// change "activitypub" to whatever you want your account name to be
export const preferredUsername:string = process.env.ACCOUNT || "activitypub"
export const name = process.env.REAL_NAME || preferredUsername
export const summary = ""
// avatar image
const icon:{ type:"Image", mediaType:string, url:string, name:string } = {
type: "Image",
mediaType: "image/svg+xml",
url: BASE_URL + "/assets/img/avatar-tt.svg",
name: "My profile photo — a pixelated version of me"
}
// banner image
const image:{ type:"Image", mediaType:string, url:string, name:string } = {
type: "Image",
mediaType: "image/jpeg",
url: BASE_URL + "/assets/img/banner-1500x500.jpg",
name: "A grim reaper in a decorated cubicle, writing and daydreaming, surrounded by many other grim reapers in bland, grey, cubicles"
}
// This is a list of other actor ids you identify as
const alsoKnownAs:string[] = []
// I'm not exactly sure what this time represents.
// The date your website got published?
const published:string = "2023-09-14T00:00:00Z"
// customize this to add or remove PropertyValues
// this is the table that appears on Mastodon, etc, profile pages
const attachment:{ type:"PropertyValue", name:string, value:string }[] = [
{
type: "PropertyValue",
name: "Pronouns",
value: "they/them"
},
{
type: "PropertyValue",
name: "Website",
value: `<a href="${BASE_URL}" target="_blank" rel="nofollow noopener noreferrer me">${BASE_URL}</a>`
}
]
const ACTOR = {
"@context": [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
{
manuallyApprovesFollowers: "as:manuallyApprovesFollowers",
toot: "http://joinmastodon.org/ns#",
alsoKnownAs: {
"@id": "as:alsoKnownAs",
"@type": "@id"
},
schema: "http://schema.org#",
PropertyValue: "schema:PropertyValue",
value: "schema:value",
discoverable: "toot:discoverable",
Ed25519Signature: "toot:Ed25519Signature",
Ed25519Key: "toot:Ed25519Key",
Curve25519Key: "toot:Curve25519Key",
EncryptedMessage: "toot:EncryptedMessage",
publicKeyBase64: "toot:publicKeyBase64"
}
],
id: BASE_URL,
type: "Person",
following: `${BASE_URL}/following`,
followers: `${BASE_URL}/followers`,
inbox: `${BASE_URL}/inbox`,
outbox: `${BASE_URL}/outbox`,
preferredUsername,
name,
summary,
hostname: HOSTNAME,
url: BASE_URL,
manuallyApprovesFollowers: false,
discoverable: true,
published,
alsoKnownAs,
publicKey: {
id: `${BASE_URL}#main-key`,
owner: BASE_URL,
publicKeyPem: PUBLIC_KEY,
},
attachment,
icon,
image
}
export const handle = `${ACTOR.preferredUsername}@${HOSTNAME}`
export const webfinger = {
subject: `acct:${ACTOR.preferredUsername}@${HOSTNAME}`,
aliases: [ACTOR.id],
links: [
{
"rel": "http://webfinger.net/rel/profile-page",
"type": "text/html",
"href": ACTOR.url
},
{
rel: "self",
type: "application/activity+json",
href: ACTOR.id,
},
],
}
export default ACTOR

BIN
bun.lockb

Binary file not shown.

211
css/styles.css Normal file
View file

@ -0,0 +1,211 @@
:root {
--bg-rgb: 238, 238, 238;
--on-bg-rgb: 4, 4, 4;
--primary-rgb: 160, 116, 196;
--on-primary-rgb: 238, 238, 238;
--bg: rgb(var(--bg-rgb));
--on-bg: rgb(var(--on-bg-rgb));
--primary: rgb(var(--primary-rgb));
--on-primary: rgb(var(--on-primary-rgb));
--fade-alpha: 0.06;
--mute-alpha: 0.3;
--bg-fade: rgba(var(--bg-rgb), var(--fade-alpha));
--on-bg-fade: rgba(var(--on-bg-rgb), var(--fade-alpha));
--primary-fade: rgba(var(--primary-rgb), var(--fade-alpha));
--on-primary-fade: rgba(var(--on-primary-rgb), var(--fade-alpha));
--bg-muted: rgba(var(--bg-rgb), var(--mute-alpha));
--on-bg-muted: rgba(var(--on-bg-rgb), var(--mute-alpha));
--primary-muted: rgba(var(--primary-rgb), var(--mute-alpha));
--on-primary-muted: rgba(var(--on-primary-rgb), var(--mute-alpha));
}
@media (prefers-color-scheme: dark) {
:root{
--bg-rgb: 17, 17, 17;
--on-bg-rgb: 251, 251, 251;
--on-primary-rgb: 251, 251, 251;
--fade-alpha: 0.16;
}
}
html {
background-color: var(--bg);
color: var(--on-bg);
}
a {
color: var(--primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
body {
line-height: 1.6;
font-family: system-ui, -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif;
text-align: center;
margin: 0;
min-height: 90vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-x: hidden;
}
p:last-child {
margin-block-end: 0;
}
img.u-photo { border-radius: 50%; max-height:200px; }
/* .p-author img.u-photo{
max-height: 48px;
} */
ul { padding: 0; list-style: none; }
img.u-featured {
display:block;
z-index:0;
margin-bottom:-125px
}
button.icon-button {
line-height: 24px;
background-color: #666289;
color:#fff;
border:none;
border-radius:4px;
}
button.icon-button>img {
max-height: 24px;
vertical-align: bottom;
}
.button-input-container>label{
display:block;
}
.button-input-container>input{
background-color: #666289;
color:#fff;
border:none;
border-radius: 4px;
padding: 4px 66px 4px 6px;
margin-right: -60px;
}
.button-input-container>input:focus{
border:none;
}
.button-input-container>button{
background-color: #666289;
color:#fff;
border-radius: 4px;
border-color: #fff;
}
i>img{
max-height: 1em;
vertical-align: middle;
}
img.tiny-avatar {
max-height: 17px;
}
img.small-avatar {
max-height: 40px;
}
/* Pagination */
.pagination {
margin: 50px auto;
}
.pagination li {
display: inline-block;
}
.pagination a {
padding: 8px 16px;
text-decoration: none;
border-radius: 5px;
border: 1px solid var(--on-bg-fade);
}
.pagination a.active {
background-color: var(--primary);
color: var(--on-primary);
}
.pagination a:hover:not(.active) { background-color: var(--on-bg-fade); }
.pagination a.disabled {
color: var(--primary-fade);
pointer-events: none;
}
/* End Pagination */
/* Feed Entries */
.h-entry {
max-width: 500px;
min-width: 320px;
background-color: var(--primary-fade);
padding: 20px;
margin: 0;
border: 1px solid var(--on-bg-fade);
text-align: left;
}
.h-entry:not(:last-child) {
border-bottom: none;
}
.h-entry .p-author {
max-width: calc(100% - 80px);
display: flex;
align-items: center;
gap: 10px;
overflow: hidden;
}
.h-entry .u-photo {
vertical-align: baseline;
}
.h-entry .display-name {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.h-entry .display-name .p-name {
white-space: nowrap;
display: block;
overflow: hidden;
text-overflow: ellipsis;
font-weight: 700;
}
.h-entry .display-name .p-nickname {
white-space: nowrap;
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--on-primary-muted);
}
.h-entry .permalink {
float:right;
text-align: right;
font-size: 0.8em;
color: var(--on-primary-muted);
display: block;
overflow: hidden;
text-overflow: ellipsis;
max-width:80px;
}
/* End Feed Entries */

View file

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="196.52mm"
height="196.52mm"
viewBox="0 0 196.52 196.52"
version="1.1"
id="svg8"
inkscape:version="0.92.2 2405546, 2018-03-11"
sodipodi:docname="Logo_penta_connectat-imbrincat_retallats-color.svg"
inkscape:export-filename="/home/nestor/Pictures/Fediversal/Logo_penta_connectat-imbrincat_retallats-color-512x.png"
inkscape:export-xdpi="66.175453"
inkscape:export-ydpi="66.175453">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.50411932"
inkscape:cx="-209.83484"
inkscape:cy="399.15332"
inkscape:document-units="mm"
inkscape:current-layer="layer2"
showgrid="false"
inkscape:snap-smooth-nodes="true"
inkscape:snap-midpoints="true"
inkscape:snap-global="false"
inkscape:window-width="1366"
inkscape:window-height="736"
inkscape:window-x="0"
inkscape:window-y="32"
inkscape:window-maximized="1"
fit-margin-top="5"
fit-margin-left="5"
fit-margin-right="5"
fit-margin-bottom="5" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Linies"
style="display:inline"
transform="translate(6.6789703,-32.495842)">
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#a730b8;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 181.13086,275.13672 a 68.892408,68.892408 0 0 1 -29.46484,29.32812 l 161.75781,162.38868 38.99805,-19.76368 z m 213.36328,214.1875 -38.99805,19.76367 81.96289,82.2832 a 68.892409,68.892409 0 0 1 29.47071,-29.33203 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path9722"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#5496be;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 581.64648,339.39062 -91.57617,46.41016 6.75196,43.18945 103.61523,-52.51367 A 68.892409,68.892409 0 0 1 581.64648,339.39062 Z M 436.9082,412.74219 220.38281,522.47656 a 68.892408,68.892408 0 0 1 18.79492,37.08985 L 443.66016,455.93359 Z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path9729"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#ce3d1a;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="M 367.27539,142.4375 262.79492,346.4082 293.64258,377.375 404.26562,161.41797 A 68.892408,68.892408 0 0 1 367.27539,142.4375 Z m -131.6543,257.02148 -52.92187,103.31446 a 68.892409,68.892409 0 0 1 36.98633,18.97851 l 46.78125,-91.32812 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path9713"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#d0188f;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 150.76758,304.91797 a 68.892408,68.892408 0 0 1 -34.41602,7.19531 68.892408,68.892408 0 0 1 -6.65039,-0.69531 l 30.90235,197.66211 a 68.892409,68.892409 0 0 1 34.41601,-7.19531 68.892409,68.892409 0 0 1 6.64649,0.69531 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path1015"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#5b36e9;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 239.3418,560.54492 a 68.892408,68.892408 0 0 1 0.7207,13.87696 68.892408,68.892408 0 0 1 -7.26758,27.17968 l 197.62891,31.71289 a 68.892409,68.892409 0 0 1 -0.72266,-13.8789 68.892409,68.892409 0 0 1 7.26953,-27.17774 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path1674"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#30b873;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 601.13281,377.19922 -91.21875,178.08203 a 68.892408,68.892408 0 0 1 36.99414,18.98242 L 638.125,396.18359 a 68.892409,68.892409 0 0 1 -36.99219,-18.98437 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path1676"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#ebe305;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 476.72266,125.33008 a 68.892408,68.892408 0 0 1 -29.47071,29.33203 l 141.26563,141.81055 a 68.892409,68.892409 0 0 1 29.46875,-29.33204 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path1678"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#f47601;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 347.78711,104.63086 -178.57617,90.49805 a 68.892409,68.892409 0 0 1 18.79297,37.08593 l 178.57421,-90.50195 a 68.892408,68.892408 0 0 1 -18.79101,-37.08203 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path1680"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#57c115;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 446.92578,154.82617 a 68.892408,68.892408 0 0 1 -34.98242,7.48242 68.892408,68.892408 0 0 1 -6.0293,-0.63281 l 15.81836,101.29102 43.16211,6.92578 z m -16,167.02735 37.40039,239.48242 a 68.892409,68.892409 0 0 1 33.91406,-6.94336 68.892409,68.892409 0 0 1 7.20704,0.79101 L 474.08984,328.77734 Z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path9758"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#dbb210;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:41.5748024;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 188.13086,232.97461 a 68.892408,68.892408 0 0 1 0.75781,14.0957 68.892408,68.892408 0 0 1 -7.16015,26.98242 l 101.36914,16.28125 19.92382,-38.9082 z m 173.73633,27.90039 -19.92578,38.91211 239.51367,38.4668 a 68.892409,68.892409 0 0 1 -0.69531,-13.71875 68.892409,68.892409 0 0 1 7.34961,-27.32422 z"
transform="matrix(0.26458333,0,0,0.26458333,-6.6789703,32.495842)"
id="path9760"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="Nodes"
style="display:inline;opacity:1"
transform="translate(6.6789703,-32.495842)">
<circle
style="fill:#ffca00;fill-opacity:0.99596773;stroke:none;stroke-width:0.26458332;stroke-opacity:0.96078431"
id="path817"
cx="106.26596"
cy="51.535553"
r="16.570711"
transform="rotate(3.1178174)" />
<circle
id="path819"
style="fill:#64ff00;fill-opacity:0.99596773;stroke:none;stroke-width:0.26458332;stroke-opacity:0.96078431"
cx="171.42836"
cy="110.19328"
r="16.570711"
transform="rotate(3.1178174)" />
<circle
id="path823"
style="fill:#00a3ff;fill-opacity:0.99596773;stroke:none;stroke-width:0.26458332;stroke-opacity:0.96078431"
cx="135.76379"
cy="190.27704"
r="16.570711"
transform="rotate(3.1178174)" />
<circle
style="fill:#9500ff;fill-opacity:0.99596773;stroke:none;stroke-width:0.26458332;stroke-opacity:0.96078431"
id="path825"
cx="48.559471"
cy="181.1138"
r="16.570711"
transform="rotate(3.1178174)" />
<circle
id="path827"
style="fill:#ff0000;fill-opacity:0.99596773;stroke:none;stroke-width:0.26458332;stroke-opacity:0.96078431"
cx="30.328812"
cy="95.366837"
r="16.570711"
transform="rotate(3.1178174)" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 19 KiB

6
img/Obsidian.svg Normal file
View file

@ -0,0 +1,6 @@
<svg width="140" height="180" viewBox="0 0 140 180" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M49.775 105.089C54.3828 103.715 61.8069 101.605 70.3434 101.082C65.2222 88.1449 63.986 76.8242 64.9803 66.7442C66.1285 55.1033 70.23 45.3874 74.228 37.1201C75.0811 35.3561 75.9012 33.7135 76.6879 32.1378C77.8017 29.9069 78.8486 27.81 79.8278 25.6916C81.4579 22.1652 82.6674 19.051 83.2791 16.1576C83.8806 13.3125 83.8838 10.7715 83.1727 8.3342C82.4607 5.89352 80.9475 3.26635 78.0704 0.386692C74.3134 -0.587559 70.1448 0.267767 67.0197 3.08162L29.9298 36.4772C27.861 38.34 26.503 40.8642 26.0879 43.6182L22.8899 64.8384C27.9185 69.2873 40.33 82.2201 47.8789 100.165C48.5525 101.766 49.1875 103.408 49.775 105.089Z" fill="white"/>
<path d="M21.3902 74.5293C21.2153 75.2761 20.9692 76.0051 20.6549 76.7063L1.05225 120.436C-0.961131 124.928 -0.0336421 130.194 3.39276 133.726L34.2418 165.523C49.9952 142.262 47.6984 120.379 40.5026 103.274C35.0465 90.3037 26.777 80.1526 21.3902 74.5293Z" fill="white"/>
<path d="M41.3687 169.269C41.9093 169.355 42.4575 169.407 43.0096 169.424C48.864 169.6 58.7098 170.109 66.6947 171.582C73.2088 172.783 86.1213 176.397 96.747 179.505C104.855 181.877 113.211 175.396 114.387 167.024C115.245 160.917 116.855 154.009 119.821 147.677L119.753 147.702C114.73 133.682 108.34 124.629 101.641 118.849C94.9619 113.086 87.7708 110.397 80.8276 109.42C69.2835 107.795 58.7071 110.832 52.0453 112.791C56.0353 129.428 54.8074 149.004 41.3687 169.269Z" fill="white"/>
<path d="M124.96 139.034C131.626 128.965 136.375 121.134 138.881 116.888C140.135 114.764 139.907 112.102 138.423 110.133C134.554 105.002 127.152 94.5755 123.12 84.9218C118.973 74.9962 118.355 59.5866 118.319 52.081C118.306 49.2279 117.402 46.4413 115.639 44.1994L91.6762 13.73C91.5918 15.1034 91.3946 16.4659 91.1093 17.8158C90.3118 21.5882 88.8073 25.3437 87.0916 29.0552C86.086 31.2306 84.9238 33.5612 83.7497 35.9157C82.9682 37.4827 82.1814 39.0607 81.432 40.6102C77.5579 48.6212 73.9528 57.3151 72.9451 67.5313C72.011 77.0006 73.2894 88.014 79.0482 101.162C80.0074 101.243 80.9727 101.351 81.9422 101.487C90.2067 102.651 98.8807 105.891 106.866 112.781C113.73 118.704 119.932 127.19 124.96 139.034Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
img/avatar-tiny.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

37
img/avatar-tt-trans.svg Normal file
View file

@ -0,0 +1,37 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -0.5 13 17" shape-rendering="crispEdges">
<metadata>Made with Pixels to Svg https://codepen.io/shshaw/pen/XbxvNj</metadata>
<path stroke="#522301" d="M3 0h1M2 1h1M1 2h2M2 4h1M1 7h1M2 9h1M4 9h1" />
<path stroke="#512201" d="M4 0h1M3 1h1M1 3h2M1 4h1M1 5h1M1 6h1M1 8h2M0 9h1M3 9h1M0 10h2M0 11h3M1 12h1" />
<path stroke="#805130" d="M5 0h1M11 2h1" />
<path stroke="#815231" d="M6 0h2M3 2h1" />
<path stroke="#8d5e3d" d="M8 0h1M6 1h1M11 1h1" />
<path stroke="#8c5d3c" d="M9 0h1M12 2h1" />
<path stroke="#8d5e3c" d="M10 0h1M5 1h1M7 1h1M9 1h2" />
<path stroke="#7f5231" d="M4 1h1" />
<path stroke="#8c5e3c" d="M8 1h1M4 2h1" />
<path stroke="#fecbcb" d="M5 2h3M9 2h1M5 3h1M4 5h1M9 5h1M4 6h2M12 6h1M7 7h1" />
<path stroke="#ffcbcb" d="M8 2h1M10 2h1M10 7h1" />
<path stroke="#e9b6b6" d="M3 3h1M3 5h1M4 7h1M10 13h1" />
<path stroke="#ffcccc" d="M4 3h1M8 3h3M4 4h1M7 4h4M12 4h1M6 5h2M11 5h2M6 6h1M11 6h1M6 7h1M8 7h2M3 13h1" />
<path stroke="#fecccc" d="M6 3h2M11 3h2M6 4h1M8 5h1M10 5h1" />
<path stroke="#e9b5b5" d="M3 4h1M3 6h1M3 7h1" />
<path stroke="#000000" d="M5 4h1M11 4h1M4 10h1M6 10h1M3 11h1M7 11h1M4 12h1M10 12h1" />
<path stroke="#a97777" d="M2 5h1" />
<path stroke="#fbc8c8" d="M5 5h1M12 7h1" />
<path stroke="#aa7676" d="M2 6h1M2 7h1" />
<path stroke="#ce9a9a" d="M7 6h1" />
<path stroke="#ce9b9b" d="M8 6h2" />
<path stroke="#fcc8c8" d="M10 6h1" />
<path stroke="#b55916" d="M5 7h1M5 8h1M6 9h1M7 10h1" />
<path stroke="#e47726" d="M11 7h1M7 8h4M8 9h3" />
<path stroke="#aa7777" d="M3 8h2M5 9h1" />
<path stroke="#d06d25" d="M6 8h1M11 8h1M7 9h1M8 10h2M8 11h1" />
<path stroke="#4d3ca6" d="M1 9h1M2 10h1" />
<path stroke="#2a2a2a" d="M5 10h1M4 11h2M7 12h1M5 13h4M5 14h1M8 14h1" />
<path stroke="#2b2b2b" d="M6 11h1M5 12h2M8 12h1M6 14h2" />
<path stroke="#323232" d="M9 11h1M3 12h1M4 16h2M8 16h2" />
<path stroke="#333333" d="M9 12h1M9 13h1M9 14h1" />
<path stroke="#232323" d="M4 13h1M4 14h1" />
<path stroke="#003298" d="M4 15h2M9 15h1" />
<path stroke="#003399" d="M6 15h3" />
</svg>

After

Width:  |  Height:  |  Size: 2 KiB

38
img/avatar-tt.svg Normal file
View file

@ -0,0 +1,38 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -0.5 20 20" shape-rendering="crispEdges">
<metadata>Made with Pixels to Svg https://codepen.io/shshaw/pen/XbxvNj</metadata>
<path stroke="#666289" d="M0 0h20M0 1h20M0 2h20M0 3h6M14 3h6M0 4h5M15 4h5M0 5h4M16 5h4M0 6h4M16 6h4M0 7h4M16 7h4M0 8h4M16 8h4M0 9h4M16 9h4M0 10h4M16 10h4M0 11h4M15 11h5M0 12h3M14 12h6M0 13h3M6 13h1M13 13h7M0 14h3M13 14h7M0 15h4M5 15h1M14 15h6M0 16h6M14 16h6M0 17h7M13 17h7M0 18h7M13 18h7M0 19h7M9 19h2M13 19h7" />
<path stroke="#522301" d="M6 3h1M5 4h1M4 5h2M5 7h1M4 10h1M5 12h1M7 12h1" />
<path stroke="#512201" d="M7 3h1M6 4h1M4 6h2M4 7h1M4 8h1M4 9h1M4 11h2M3 12h1M6 12h1M3 13h2M3 14h3M4 15h1" />
<path stroke="#805130" d="M8 3h1M14 5h1" />
<path stroke="#815231" d="M9 3h2M6 5h1" />
<path stroke="#8d5e3d" d="M11 3h1M9 4h1M14 4h1" />
<path stroke="#8c5d3c" d="M12 3h1M15 5h1" />
<path stroke="#8d5e3c" d="M13 3h1M8 4h1M10 4h1M12 4h2" />
<path stroke="#7f5231" d="M7 4h1" />
<path stroke="#8c5e3c" d="M11 4h1M7 5h1" />
<path stroke="#fecbcb" d="M8 5h3M12 5h1M8 6h1M7 8h1M12 8h1M7 9h2M15 9h1M10 10h1" />
<path stroke="#ffcbcb" d="M11 5h1M13 5h1M13 10h1" />
<path stroke="#e9b6b6" d="M6 6h1M6 8h1M7 10h1M13 16h1" />
<path stroke="#ffcccc" d="M7 6h1M11 6h3M7 7h1M10 7h4M15 7h1M9 8h2M14 8h2M9 9h1M14 9h1M9 10h1M11 10h2M6 16h1" />
<path stroke="#fecccc" d="M9 6h2M14 6h2M9 7h1M11 8h1M13 8h1" />
<path stroke="#e9b5b5" d="M6 7h1M6 9h1M6 10h1" />
<path stroke="#000000" d="M8 7h1M14 7h1M7 13h1M9 13h1M6 14h1M10 14h1M7 15h1M13 15h1" />
<path stroke="#a97777" d="M5 8h1" />
<path stroke="#fbc8c8" d="M8 8h1M15 10h1" />
<path stroke="#aa7676" d="M5 9h1M5 10h1" />
<path stroke="#ce9a9a" d="M10 9h1" />
<path stroke="#ce9b9b" d="M11 9h2" />
<path stroke="#fcc8c8" d="M13 9h1" />
<path stroke="#b55916" d="M8 10h1M8 11h1M9 12h1M10 13h1" />
<path stroke="#e47726" d="M14 10h1M10 11h4M11 12h3" />
<path stroke="#aa7777" d="M6 11h2M8 12h1" />
<path stroke="#d06d25" d="M9 11h1M14 11h1M10 12h1M11 13h2M11 14h1" />
<path stroke="#4d3ca6" d="M4 12h1M5 13h1" />
<path stroke="#2a2a2a" d="M8 13h1M7 14h2M10 15h1M8 16h4M8 17h1M11 17h1" />
<path stroke="#2b2b2b" d="M9 14h1M8 15h2M11 15h1M9 17h2" />
<path stroke="#323232" d="M12 14h1M6 15h1M7 19h2M11 19h2" />
<path stroke="#333333" d="M12 15h1M12 16h1M12 17h1" />
<path stroke="#232323" d="M7 16h1M7 17h1" />
<path stroke="#003298" d="M7 18h2M12 18h1" />
<path stroke="#003399" d="M9 18h3" />
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

BIN
img/avatar-tt@800.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
img/banner-1500x500.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

61
js/button-input.js Normal file
View file

@ -0,0 +1,61 @@
function buttonInputClick() {
this.style.display = 'none'
const buttonInput = document.createElement('div')
buttonInput.classList.add('button-input-container')
if(this.dataset.instruction){
const label = document.createElement('label')
buttonInput.appendChild(label)
label.innerText = this.dataset.instruction
}
const input = document.createElement('input')
buttonInput.appendChild(input)
input.type = 'text'
if(this.dataset.placeholder){
input.placeholder = this.dataset.placeholder
}
const button = document.createElement('button')
buttonInput.appendChild(button)
button.innerText = "Submit"
button.addEventListener('click', () => {
if(this.onsubmit){
const event = new Event('button-input-value')
event.value = input.value
this.onsubmit(event)
}
buttonInput.parentNode.removeChild(buttonInput)
if(this.dataset.success){
const span = document.createElement('span')
span.classList.add('success')
span.innerText = this.dataset.success
setTimeout(() => {
span.parentNode.removeChild(span)
this.style.display = null
}, 5000);
this.parentNode.insertBefore(span, this.nextSibling)
}
else{
this.style.display = null
}
})
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
button.click();
}
});
this.parentNode.insertBefore(buttonInput, this.nextSibling)
input.focus()
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.button-input').forEach(button => {
button.addEventListener('click', buttonInputClick)
});
}, false);

35
js/follow.js Normal file
View file

@ -0,0 +1,35 @@
const SUBSCRIBE_LINK_REL = 'http://ostatus.org/schema/1.0/subscribe'
function follow(username, handle) {
if(!handle){
handle = prompt("Please enter your fediverse / mastodon handle (e.g. '@user@domain.social')", "@")
}
if(handle) {
const input = handle
handle = handle.trim().replace(/^@/,'')
const split = handle.split('@')
if(split.length == 2) {
const resource = `acct:${handle}`
const domain = split[1]
// look up remote user via webfinger
const url = `https://${domain}/.well-known/webfinger?resource=${resource}`
fetch(url, {headers: {
'Content-Type': 'application/activity+json'
}}).then(async result => {
const json = await result.json()
const subscribe = json.links.find(link => link.rel && link.rel == SUBSCRIBE_LINK_REL)
let template = subscribe.template
window.open(template.replace("{uri}", username), '_blank').focus()
})
.catch(e => {
console.error(e)
throw `Sorry, we couldn't find a subscribe uri for ${input}.\n\nTry searching for "${username}" on ${domain} (or in your fediverse client of choice)`
})
}
else {
throw 'Please enter your fediverse address in @user@domain.social format'
}
}
}

6
js/relative-time.js Normal file
View file

@ -0,0 +1,6 @@
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('time').forEach(time => {
const datetime = luxon.DateTime.fromISO(time.getAttribute('datetime'))
time.innerText = datetime.toRelative()
});
}, false);

View file

@ -7,12 +7,15 @@
"ngrok": "ngrok tunnel --label edge=edghts_2VNJvaPttrFlAPWxrGyVKu0s3ad http://localhost:3000"
},
"devDependencies": {
"@types/node-forge": "^1.3.5"
"@types/node-forge": "^1.3.5",
"bun-types": "^1.0.3"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"dependencies": {
"@11ty/eleventy": "^2.0.1",
"@11ty/eleventy-plugin-rss": "^1.2.0",
"gray-matter": "^4.0.3",
"node-forge": "^1.3.1"
}

View file

@ -1,25 +1,32 @@
import { ACCOUNT, ACTOR, HOSTNAME, PUBLIC_KEY } from "./env"
import * as db from "./db"
import { reqIsActivityPub, send, verify } from "./request"
import { verify } from "./request"
import outbox from "./outbox"
import inbox from "./inbox"
import ACTOR from "../actor"
import { activityPubTypes } from "./env"
export default (req: Request): Response | Promise<Response> | undefined => {
const url = new URL(req.url)
let match
if(req.method === "GET" && url.pathname === "/test") return new Response("", { status: 204 })
else if(req.method == "POST" && (match = url.pathname.match(/^\/([^\/]+)\/inbox\/?$/i))) return postInbox(req, match[1])
else if(req.method == "POST" && (match = url.pathname.match(/^\/([^\/]+)\/outbox\/?$/i))) return postOutbox(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/outbox\/?$/i))) return getOutbox(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/followers\/?$/i))) return getFollowers(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/following\/?$/i))) return getFollowing(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/?$/i))) return getActor(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/posts\/([^\/]+)\/?$/i))) return getPost(req, match[1], match[2])
else if(req.method == "GET" && (match = url.pathname.match(/^\/([^\/]+)\/posts\/([^\/]+)\/activity\/?$/i))) return getActivity(req, match[1], match[2])
if(!reqIsActivityPub(req)) return undefined
else if(req.method == "GET" && (match = url.pathname.match(/^\/?$/i))) return getActor(req)
else if(req.method == "GET" && (match = url.pathname.match(/^\/outbox\/?$/i))) return getOutbox(req)
else if(req.method == "POST" && (match = url.pathname.match(/^\/inbox\/?$/i))) return postInbox(req)
else if(req.method == "POST" && (match = url.pathname.match(/^\/outbox\/?$/i))) return postOutbox(req)
else if(req.method == "GET" && (match = url.pathname.match(/^\/followers\/?$/i))) return getFollowers(req)
else if(req.method == "GET" && (match = url.pathname.match(/^\/following\/?$/i))) return getFollowing(req)
else if(req.method == "GET" && (match = url.pathname.match(/^\/posts\/([^\/]+)\/?$/i))) return getPost(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/posts\/([^\/]+)\/activity\/?$/i))) return getOutboxActivity(req, match[1])
else if(req.method == "GET" && (match = url.pathname.match(/^\/outbox\/([^\/]+)\/?$/i))) return getOutboxActivity(req, match[1])
return undefined
}
export function reqIsActivityPub(req:Request) {
const contentType = req.headers.get("Accept")
return activityPubTypes.some(t => contentType?.includes(t))
}
export function idsFromValue(value:any):string[] {
if (!value) return []
@ -29,9 +36,8 @@ export function idsFromValue(value:any):string[] {
return []
}
const postOutbox = async (req:Request, account:string):Promise<Response> => {
console.log("PostOutbox", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const postOutbox = async (req:Request):Promise<Response> => {
console.log("PostOutbox")
const bodyText = await req.text()
@ -39,16 +45,13 @@ const postOutbox = async (req:Request, account:string):Promise<Response> => {
const body = JSON.parse(bodyText)
// ensure that the verified actor matches the actor in the request body
if (ACTOR !== body.actor) return new Response("", { status: 401 })
// console.log(body)
if (ACTOR.id !== body.actor) return new Response("", { status: 401 })
return await outbox(body)
}
const postInbox = async (req:Request, account:string):Promise<Response> => {
console.log("PostInbox", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const postInbox = async (req:Request):Promise<Response> => {
console.log("PostInbox")
const bodyText = await req.text()
@ -66,70 +69,29 @@ const postInbox = async (req:Request, account:string):Promise<Response> => {
// ensure that the verified actor matches the actor in the request body
if (from !== body.actor) return new Response("", { status: 401 })
// console.log(body)
// TODO: add support for more types! we want replies, likes, boosts, etc!
switch (body.type) {
case "Follow": await follow(body);
case "Undo": await undo(body);
case "Accept": await accept(body);
case "Reject": await reject(body);
}
return new Response("", { status: 204 })
return await inbox(body)
}
const follow = async (body:any) => {
await send(ACTOR, body.actor, {
"@context": "https://www.w3.org/ns/activitystreams",
id: `https://${HOSTNAME}/${crypto.randomUUID()}`, // TODO: de-randomise this?
type: "Accept",
actor: ACTOR,
object: body,
});
await db.createFollower(body.actor, body.id);
}
const undo = async (body:any) => {
switch (body.object.type) {
case "Follow": await db.deleteFollower(body.actor); break
}
}
const accept = async (body:any) => {
switch (body.object.type) {
case "Follow": await db.acceptFollowing(body.actor); break
}
}
const reject = async (body:any) => {
switch (body.object.type) {
case "Follow": await db.deleteFollowing(body.actor); break
}
}
const getOutbox = async (req:Request, account:string):Promise<Response> => {
console.log("GetOutbox", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getOutbox = async (req:Request):Promise<Response> => {
console.log("GetOutbox")
// TODO: Paging?
const posts = await db.listOutboxActivities()
return Response.json({
"@context": "https://www.w3.org/ns/activitystreams",
id: `${ACTOR}/outbox`,
id: ACTOR.outbox,
type: "OrderedCollection",
totalItems: posts.length,
orderedItems: posts.map((post) => ({
...post,
actor: ACTOR
actor: ACTOR.id
})).sort( (a,b) => new Date(b.published).getTime() - new Date(a.published).getTime())
}, { headers: { "Content-Type": "application/activity+json"} })
}
const getFollowers = async (req:Request, account:String):Promise<Response> => {
console.log("GetFollowers", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getFollowers = async (req:Request):Promise<Response> => {
console.log("GetFollowers")
const url = new URL(req.url)
const page = url.searchParams.get("page")
@ -137,24 +99,23 @@ const getFollowers = async (req:Request, account:String):Promise<Response> => {
if(!page) return Response.json({
"@context": "https://www.w3.org/ns/activitystreams",
id: `${ACTOR}/followers`,
id: ACTOR.followers,
type: "OrderedCollection",
totalItems: followers.length,
first: `${ACTOR}/followers?page=1`,
first: `${ACTOR.followers}?page=1`,
})
else return Response.json({
"@context": "https://www.w3.org/ns/activitystreams",
id: `${ACTOR}/followers?page=${page}`,
id: `${ACTOR.followers}?page=${page}`,
type: "OrderedCollectionPage",
partOf: `${ACTOR}/followers`,
partOf: ACTOR.followers,
totalItems: followers.length,
orderedItems: followers.map(follower => follower.actor)
})
}
const getFollowing = async (req:Request, account:String):Promise<Response> => {
console.log("GetFollowing", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getFollowing = async (req:Request):Promise<Response> => {
console.log("GetFollowing")
const url = new URL(req.url)
const page = url.searchParams.get("page")
@ -162,61 +123,37 @@ const getFollowing = async (req:Request, account:String):Promise<Response> => {
if(!page) return Response.json({
"@context": "https://www.w3.org/ns/activitystreams",
id: `${ACTOR}/following`,
id: ACTOR.following,
type: "OrderedCollection",
totalItems: following.length,
first: `${ACTOR}/following?page=1`,
first: `${ACTOR.following}?page=1`,
})
else return Response.json({
"@context": "https://www.w3.org/ns/activitystreams",
id: `${ACTOR}/following?page=${page}`,
id: `${ACTOR.following}?page=${page}`,
type: "OrderedCollectionPage",
partOf: `${ACTOR}/following`,
partOf: ACTOR.following,
totalItems: following.length,
orderedItems: following.map(follow => follow.actor)
})
}
const getActor = async (req:Request, account:string):Promise<Response> => {
console.log("GetActor", account)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getActor = async (req:Request):Promise<Response> => {
console.log("GetActor")
if(reqIsActivityPub(req)) return Response.json({
"@context": [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
],
id: ACTOR,
type: "Person",
preferredUsername: ACCOUNT,
url: ACTOR,
manuallyApprovesFollowers: false,
discoverable: true,
published: "2023-09-14T00:00:00Z",
inbox: `${ACTOR}/inbox`,
outbox: `${ACTOR}/outbox`,
followers: `${ACTOR}/followers`,
following: `${ACTOR}/following`,
publicKey: {
id: `${ACTOR}#main-key`,
owner: ACTOR,
publicKeyPem: PUBLIC_KEY,
},
}, { headers: { "Content-Type": "application/activity+json"}})
if(reqIsActivityPub(req)) return Response.json(ACTOR, { headers: { "Content-Type": "application/activity+json"}})
else return Response.json(await db.listPosts())
}
const getPost = async (req:Request, account:string, id:string):Promise<Response> => {
console.log("GetPost", account, id)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getPost = async (req:Request, id:string):Promise<Response> => {
console.log("GetPost", id)
if(reqIsActivityPub(req)) return Response.json((await db.getActivity(id)).object, { headers: { "Content-Type": "application/activity+json"}})
if(reqIsActivityPub(req)) return Response.json((await db.getOutboxActivity(id)).object, { headers: { "Content-Type": "application/activity+json"}})
else return Response.json(await db.getPost(id))
}
const getActivity = async (req:Request, account:string, id:string):Promise<Response> => {
console.log("GetActivity", account, id)
if (ACCOUNT !== account) return new Response("", { status: 404 })
const getOutboxActivity = async (req:Request, id:string):Promise<Response> => {
console.log("GetOutboxActivity", id)
return Response.json((await db.getActivity(id)), { headers: { "Content-Type": "application/activity+json"}})
return Response.json((await db.getOutboxActivity(id)), { headers: { "Content-Type": "application/activity+json"}})
}

View file

@ -1,8 +1,9 @@
import { idsFromValue } from "./activitypub"
import { getFollowing, getOutboxActivity, listLiked } from "./db"
import { ACTOR, ADMIN_PASSWORD, ADMIN_USERNAME, BASE_URL } from "./env"
import * as db from "./db"
import { ADMIN_PASSWORD, ADMIN_USERNAME, activityPubTypes } from "./env"
import outbox from "./outbox"
import { fetchObject } from "./request"
import ACTOR from "../actor"
export default (req: Request): Response | Promise<Response> | undefined => {
const url = new URL(req.url)
@ -14,11 +15,18 @@ export default (req: Request): Response | Promise<Response> | undefined => {
let match
if(req.method === "GET" && (match = url.pathname.match(/^\/test\/?$/i))) return new Response("", { status: 204 })
else if(req.method == "POST" && (match = url.pathname.match(/^\/rebuild\/?$/i))) return rebuild(req)
else if(req.method == "POST" && (match = url.pathname.match(/^\/create\/?$/i))) return create(req)
else if(req.method == "POST" && (match = url.pathname.match(/^\/follow\/([^\/]+)\/?$/i))) return follow(req, match[1])
else if(req.method == "DELETE" && (match = url.pathname.match(/^\/follow\/([^\/]+)\/?$/i))) return unfollow(req, match[1])
else if(req.method == "POST" && (match = url.pathname.match(/^\/like\/(.+)\/?$/i))) return like(req, match[1])
else if(req.method == "DELETE" && (match = url.pathname.match(/^\/like\/(.+)\/?$/i))) return unlike(req, match[1])
else if(req.method == "POST" && (match = url.pathname.match(/^\/dislike\/(.+)\/?$/i))) return dislike(req, match[1])
else if(req.method == "DELETE" && (match = url.pathname.match(/^\/dislike\/(.+)\/?$/i))) return undislike(req, match[1])
else if(req.method == "POST" && (match = url.pathname.match(/^\/share\/(.+)\/?$/i))) return share(req, match[1])
else if(req.method == "DELETE" && (match = url.pathname.match(/^\/share\/(.+)\/?$/i))) return unshare(req, match[1])
else if(req.method == "POST" && (match = url.pathname.match(/^\/reply\/(.+)\/?$/i))) return create(req, match[1])
else if(req.method == "DELETE" && (match = url.pathname.match(/^\/delete\/(.+)\/?$/i))) return deletePost(req, match[1])
console.log(`Couldn't match admin path ${req.method} "${url.pathname}"`)
@ -35,27 +43,41 @@ const checkAuth = (headers: Headers): Boolean => {
return username === ADMIN_USERNAME && password === ADMIN_PASSWORD
}
// rebuild the 11ty static pages
export const rebuild = async(req:Request):Promise<Response> => {
await db.rebuild()
return new Response("", { status: 201 })
}
// create an activity
const create = async (req:Request):Promise<Response> => {
const create = async (req:Request, inReplyTo:string|null = null):Promise<Response> => {
const body = await req.json()
if(!inReplyTo && body.object.inReplyTo) inReplyTo = body.object.inReplyTo
const original = inReplyTo ? await (await fetchObject(inReplyTo)).json() : null
// create the object, merging in supplied data
const date = new Date()
const object = {
attributedTo: ACTOR,
attributedTo: ACTOR.id,
published: date.toISOString(),
to: ["https://www.w3.org/ns/activitystreams#Public"],
cc: [`${ACTOR}/followers`],
cc: [ACTOR.followers],
...body.object
}
if(inReplyTo){
object.inReplyTo = original || inReplyTo
object.cc.push(inReplyTo)
}
const activity = {
"@context": "https://www.w3.org/ns/activitystreams",
type: "Create",
published: date.toISOString(),
actor: ACTOR,
to: ["https://www.w3.org/ns/activitystreams#Public"],
cc: [`${ACTOR}/followers`],
actor: ACTOR.id,
to: object.to,
cc: object.cc,
...body,
object: { ...object }
}
@ -64,62 +86,166 @@ const create = async (req:Request):Promise<Response> => {
}
const follow = async (req:Request, handle:string):Promise<Response> => {
let url
if(handle.startsWith('@')) handle = handle.substring(1)
try {
url = new URL(handle).href
}
catch {
// this is not a valid url. Probably a someone@domain.tld format
const [_, host] = handle.split('@')
if(!host) return new Response('account not url or name@domain.tld', { status: 400 })
const res = await fetch(`https://${host}/.well-known/webfinger/?resource=acct:${handle}`, { headers: { 'accept': 'application/jrd+json'}})
const webfinger = await res.json()
if(!webfinger.links) return new Response("", { status: 404 })
const links:any[] = webfinger.links
const actorLink = links.find(l => l.rel === "self" && (activityPubTypes.includes(l.type)))
if(!actorLink) return new Response("", { status: 404 })
url = actorLink.href
}
console.log(`Following ${url}`)
// send the follow request to the supplied actor
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Follow",
actor: ACTOR,
object: handle,
to: [handle, "https://www.w3.org/ns/activitystreams#Public"]
actor: ACTOR.id,
object: url,
to: [url, "https://www.w3.org/ns/activitystreams#Public"]
})
}
const unfollow = async (req:Request, handle:string):Promise<Response> => {
// check to see if we are already following. If not, just return success
const existing = await getFollowing(handle)
const existing = await db.getFollowing(handle)
if (!existing) return new Response("", { status: 204 })
const activity = await getOutboxActivity(existing.id)
const activity = await db.getOutboxActivity(existing.id)
// outbox will also take care of the deletion
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Undo",
actor: ACTOR,
actor: ACTOR.id,
object: activity,
to: activity.to
})
}
const like = async (req:Request, object_url:string):Promise<Response> => {
const object = await (await fetchObject(ACTOR, object_url)).json()
const object = await (await fetchObject(object_url)).json()
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Like",
actor: ACTOR,
actor: ACTOR.id,
object: object,
to: [...idsFromValue(object.attributedTo), "https://www.w3.org/ns/activitystreams#Public"]
to: [...idsFromValue(object.attributedTo), "https://www.w3.org/ns/activitystreams#Public"],
cc: [ACTOR.followers]
})
}
const unlike = async (req:Request, object_id:string):Promise<Response> => {
// check to see if we are already following. If not, just return success
const liked = await listLiked()
const liked = await db.listLiked()
let existing = liked.find(o => o.object_id === object_id)
if (!existing){
const object = await (await fetchObject(ACTOR, object_id)).json()
const object = await (await fetchObject(object_id)).json()
idsFromValue(object).forEach(id => {
const e = liked.find(o => o.object_id === id)
if(e) existing = e
})
}
if (!existing) return new Response("No like found to delete", { status: 204 })
const activity = await getOutboxActivity(existing.id)
const activity = await db.getOutboxActivity(existing.id)
return undo(activity)
}
const dislike = async (req:Request, object_url:string):Promise<Response> => {
const object = await (await fetchObject(object_url)).json()
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Dislike",
actor: ACTOR.id,
object: object,
to: [...idsFromValue(object.attributedTo), "https://www.w3.org/ns/activitystreams#Public"],
cc: [ACTOR.followers]
})
}
const undislike = async (req:Request, object_id:string):Promise<Response> => {
// check to see if we are already following. If not, just return success
const disliked = await db.listDisliked()
let existing = disliked.find(o => o.object_id === object_id)
if (!existing){
const object = await (await fetchObject(object_id)).json()
idsFromValue(object).forEach(id => {
const e = disliked.find(o => o.object_id === id)
if(e) existing = e
})
}
if (!existing) return new Response("No dislike found to delete", { status: 204 })
const activity = await db.getOutboxActivity(existing.id)
return undo(activity)
}
const share = async (req:Request, object_url:string):Promise<Response> => {
const object = await (await fetchObject(object_url)).json()
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Announce",
actor: ACTOR.id,
object: object,
to: [...idsFromValue(object.attributedTo), "https://www.w3.org/ns/activitystreams#Public"],
cc: [ACTOR.followers]
})
}
const unshare = async (req:Request, object_id:string):Promise<Response> => {
// check to see if we are already following. If not, just return success
const shared = await db.listShared()
let existing = shared.find(o => o.object_id === object_id)
if (!existing){
const object = await (await fetchObject(object_id)).json()
idsFromValue(object).forEach(id => {
const e = shared.find(o => o.object_id === id)
if(e) existing = e
})
}
if (!existing) return new Response("No share found to delete", { status: 204 })
const activity = await db.getOutboxActivity(existing.id)
return undo(activity)
}
const undo = async(activity:any):Promise<Response> => {
// outbox will also take care of the deletion
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Undo",
actor: ACTOR,
actor: ACTOR.id,
object: activity,
to: activity.to
to: activity.to,
cc: activity.cc
})
}
const deletePost = async (req:Request, id:string):Promise<Response> => {
const post = await db.getPostByURL(id)
if(!post) return new Response("", { status: 404 })
const activity = await db.getOutboxActivity(post.local_id)
return await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Delete",
actor: ACTOR.id,
to: activity.to,
cc: activity.cc,
audience: activity.audience,
object: {
id,
type: "Tombstone"
}
})
}

104
src/db.ts
View file

@ -1,19 +1,17 @@
import { ACTIVITY_INBOX_PATH, ACTIVITY_OUTBOX_PATH, ACTIVITY_PATH, ACTOR, BASE_URL, DATA_PATH, POSTS_PATH } from "./env";
import { ACTIVITY_INBOX_PATH, ACTIVITY_OUTBOX_PATH, CONTENT_PATH, DATA_PATH, POSTS_PATH, STATIC_PATH } from "./env"
import path from "path"
import { readdir } from "fs/promises"
import { unlinkSync } from "node:fs"
import { fetchObject } from "./request"
import { idsFromValue } from "./activitypub"
import ACTOR from "../actor"
const matter = require('gray-matter')
const Eleventy = require("@11ty/eleventy")
export async function doActivity(activity:any, object_id:string|null|undefined) {
if(activity.type === "Create" && activity.object) {
if(!object_id) object_id = new Date(activity.object.published).getTime().toString(16)
const file = Bun.file(path.join(POSTS_PATH, `${object_id}.md`))
const { content, published, id, attributedTo } = activity.object
//TODO: add appropriate content for different types (e.g. like-of, etc)
await Bun.write(file, matter.stringify(content || "", { id, published, attributedTo }))
const activityFile = Bun.file(path.join(ACTIVITY_PATH, `${object_id}.activity.json`))
await Bun.write(activityFile, JSON.stringify(activity))
}
// rebuild the 11ty static pages
export async function rebuild() {
console.info(`Building 11ty from ${CONTENT_PATH}, to ${STATIC_PATH}`)
await new Eleventy(CONTENT_PATH, STATIC_PATH, { configPath: '.eleventy.js' }).write()
}
export async function createInboxActivity(activity:any, object_id:any) {
@ -52,7 +50,9 @@ export async function listOutboxActivities() {
export async function createPost(post_object:any, object_id:string) {
const file = Bun.file(path.join(POSTS_PATH, `${object_id}.md`))
const {type, object} = post_object
let {type, object, inReplyTo} = post_object
if(inReplyTo && typeof inReplyTo === 'string') inReplyTo = await fetchObject(inReplyTo)
if(object){
let { content, published, id, attributedTo } = object
if(content as string) content = '> ' + content.replace('\n', '\n> ') + '\n'
@ -60,12 +60,25 @@ export async function createPost(post_object:any, object_id:string) {
content += post_object.content || ""
//TODO: add appropriate content for different types (e.g. like, etc)
await Bun.write(file, matter.stringify(content, { id, published, attributedTo, type }))
const data:any = { id, published, attributedTo, type }
if(inReplyTo) data.inReplyTo = idsFromValue(inReplyTo).at(0)
await Bun.write(file, matter.stringify(content, data))
}
else {
const { content, published, id, attributedTo } = post_object
await Bun.write(file, matter.stringify(content || "", { id, published, attributedTo, type }))
let reply_content = ""
if(!object && inReplyTo) {
reply_content = inReplyTo.content
if(reply_content as string) reply_content = '> ' + reply_content.replace('\n', '\n> ') + '\n'
else reply_content = ""
}
const data:any = { id, published, attributedTo, type }
if(inReplyTo) data.inReplyTo = idsFromValue(inReplyTo).at(0)
await Bun.write(file, matter.stringify((reply_content || "") + (content || ""), data))
}
rebuild()
}
export async function getPost(id:string) {
@ -73,34 +86,40 @@ export async function getPost(id:string) {
const { data, content } = matter(await file.text())
return {
...data,
content: content.trim()
content: content.trim(),
local_id: id
}
}
export async function getPostByURL(url_id:string) {
if(!url_id || !url_id.startsWith(ACTOR.url + '/posts/')) return null
const match = url_id.match(/\/([0-9a-f]+)\/?$/)
const local_id = match ? match[1] : url_id
return await getPost(local_id)
}
export async function deletePost(id:string) {
unlinkSync(path.join(POSTS_PATH, id + '.md'))
rebuild()
}
export async function listPosts() {
return await Promise.all((await readdir(POSTS_PATH)).filter(v => v.endsWith('.md')).map(async filename => await getPost(filename.slice(0, -3))))
}
export async function getActivity(id:string) {
const file = Bun.file(path.join(ACTIVITY_PATH, `${id}.activity.json`))
return await file.json()
}
export async function createFollowing(handle:string, id:string) {
const file = Bun.file(path.join(DATA_PATH, `following.json`))
const following_list = await file.json() as Array<any>
if(!following_list.find(v => v.id === id || v.handle === handle)) following_list.push({id, handle, createdAt: new Date().toISOString()})
await Bun.write(file, JSON.stringify(following_list))
rebuild()
}
export async function deleteFollowing(handle:string) {
const file = Bun.file(path.join(DATA_PATH, `following.json`))
const following_list = await file.json() as Array<any>
await Bun.write(file, JSON.stringify(following_list.filter(v => v.handle !== handle)))
rebuild()
}
export async function getFollowing(handle:string) {
@ -120,6 +139,7 @@ export async function acceptFollowing(handle:string) {
const following = following_list.find(v => v.handle === handle)
if(following) following.accepted = new Date().toISOString()
await Bun.write(file, JSON.stringify(following_list))
rebuild()
}
export async function createFollower(actor:string, id:string) {
@ -127,12 +147,14 @@ export async function createFollower(actor:string, id:string) {
const followers_list = await file.json() as Array<any>
if(!followers_list.find(v => v.id === id || v.actor === actor)) followers_list.push({id, actor, createdAt: new Date().toISOString()})
await Bun.write(file, JSON.stringify(followers_list))
rebuild()
}
export async function deleteFollower(actor:string) {
const file = Bun.file(path.join(DATA_PATH, `followers.json`))
const followers_list = await file.json() as Array<any>
await Bun.write(file, JSON.stringify(followers_list.filter(v => v.actor !== actor)))
rebuild()
}
export async function getFollower(actor:string) {
@ -151,15 +173,57 @@ export async function createLiked(object_id:string, id:string) {
const liked_list = await file.json() as Array<any>
if(!liked_list.find(v => v.object_id === object_id)) liked_list.push({id, object_id, createdAt: new Date().toISOString()})
await Bun.write(file, JSON.stringify(liked_list))
rebuild()
}
export async function deleteLiked(object_id:string) {
const file = Bun.file(path.join(DATA_PATH, `liked.json`))
const liked_list = await file.json() as Array<any>
await Bun.write(file, JSON.stringify(liked_list.filter(v => v.object_id !== object_id)))
rebuild()
}
export async function listLiked() {
const file = Bun.file(path.join(DATA_PATH, `liked.json`))
return await file.json() as Array<any>
}
export async function createDisliked(object_id:string, id:string) {
const file = Bun.file(path.join(DATA_PATH, `disliked.json`))
const disliked_list = await file.json() as Array<any>
if(!disliked_list.find(v => v.object_id === object_id)) disliked_list.push({id, object_id, createdAt: new Date().toISOString()})
await Bun.write(file, JSON.stringify(disliked_list))
rebuild()
}
export async function deleteDisliked(object_id:string) {
const file = Bun.file(path.join(DATA_PATH, `disliked.json`))
const disliked_list = await file.json() as Array<any>
await Bun.write(file, JSON.stringify(disliked_list.filter(v => v.object_id !== object_id)))
rebuild()
}
export async function listDisliked() {
const file = Bun.file(path.join(DATA_PATH, `disliked.json`))
return await file.json() as Array<any>
}
export async function createShared(object_id:string, id:string) {
const file = Bun.file(path.join(DATA_PATH, `shared.json`))
const shared_list = await file.json() as Array<any>
if(!shared_list.find(v => v.object_id === object_id)) shared_list.push({id, object_id, createdAt: new Date().toISOString()})
await Bun.write(file, JSON.stringify(shared_list))
rebuild()
}
export async function deleteShared(object_id:string) {
const file = Bun.file(path.join(DATA_PATH, `shared.json`))
const shared_list = await file.json() as Array<any>
await Bun.write(file, JSON.stringify(shared_list.filter(v => v.object_id !== object_id)))
rebuild()
}
export async function listShared() {
const file = Bun.file(path.join(DATA_PATH, `shared.json`))
return await file.json() as Array<any>
}

View file

@ -1,21 +1,16 @@
import forge from "node-forge" // import crypto from "node:crypto"
import path from "path"
// change "activitypub" to whatever you want your account name to be
export const ACCOUNT = Bun.env.ACCOUNT || "activitypub"
// set up username and password for admin actions
export const ADMIN_USERNAME = process.env.ADMIN_USERNAME || "";
export const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "";
// get the hostname (`PROJECT_DOMAIN` is set via glitch, but since we're using Bun now, this won't matter)
export const HOSTNAME = /*(Bun.env.PROJECT_DOMAIN && `${Bun.env.PROJECT_DOMAIN}.glitch.me`) ||*/ Bun.env.HOSTNAME || "localhost"
export const NODE_ENV = Bun.env.NODE_ENV || "development"
export const PORT = Bun.env.PORT || "3000"
export const HOSTNAME = /*(process.env.PROJECT_DOMAIN && `${process.env.PROJECT_DOMAIN}.glitch.me`) ||*/ process.env.HOSTNAME || "localhost"
export const NODE_ENV = process.env.NODE_ENV || "development"
export const PORT = process.env.PORT || "3000"
export const BASE_URL = (HOSTNAME === "localhost" ? "http://" : "https://") + HOSTNAME + "/"
export const ACTOR = BASE_URL + ACCOUNT
export const BASE_URL = (HOSTNAME === "localhost" ? "http://" : "https://") + HOSTNAME
// in development, generate a key pair to make it easier to get started
const keypair =
@ -32,9 +27,26 @@ export const PRIVATE_KEY =
(keypair && forge.pki.privateKeyToPem(keypair.privateKey)) || //keypair?.privateKey.export({ type: "pkcs8", format: "pem" }) ||
""
export const STATIC_PATH = path.join('.', '_site')
export const CONTENT_PATH = path.join('.', '_content')
export const POSTS_PATH = path.join(CONTENT_PATH, "posts")
export const ACTIVITY_PATH = path.join(CONTENT_PATH, "posts")
export const DATA_PATH = path.join(CONTENT_PATH, "_data")
export const ACTIVITY_INBOX_PATH = path.join(DATA_PATH, "_inbox")
export const ACTIVITY_OUTBOX_PATH = path.join(DATA_PATH, "_outbox")
export const ACTIVITY_OUTBOX_PATH = path.join(DATA_PATH, "_outbox")
export const DEFAULT_DOCUMENTS = process.env.DEFAULT_DOCUMENTS || [
'index.html',
'index.shtml',
'index.htm',
'Index.html',
'Index.shtml',
'Index.htm',
'default.html',
'default.htm'
]
export const activityPubTypes = [
'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'application/activity+json'
]
export const contentTypeHeader = { 'Content-Type': activityPubTypes[0]}

View file

@ -1,17 +1,17 @@
import { idsFromValue } from "./activitypub";
import * as db from "./db";
import { ACTOR, BASE_URL } from "./env";
import outbox from "./outbox";
import { send } from "./request";
import { idsFromValue } from "./activitypub"
import * as db from "./db"
import outbox from "./outbox"
import { send } from "./request"
import ACTOR from "../actor"
export default async function inbox(activity:any) {
const date = new Date()
// get the main recipients ([...new Set()] is to dedupe)
const recipientList = [...new Set(idsFromValue(activity.to).concat(idsFromValue(activity.cc)).concat(idsFromValue(activity.audience)))]
const recipientList = [...new Set([...idsFromValue(activity.to), ...idsFromValue(activity.cc), ...idsFromValue(activity.audience)])]
// if my list of followers in the list of recipients, then forward to them as well
if(recipientList.includes(ACTOR + "/followers")) {
(await db.listFollowers()).forEach(f => send(activity.attributedTo, f, activity))
if(recipientList.includes(ACTOR.url + "/followers")) {
(await db.listFollowers()).forEach(f => send(f, activity, activity.attributedTo))
}
// save this activity to my inbox
@ -25,6 +25,8 @@ export default async function inbox(activity:any) {
case "Reject": reject(activity); break;
case "Undo": undo(activity); break;
}
return new Response("", { status: 204 })
}
const follow = async (activity:any, id:string) => {
@ -35,7 +37,7 @@ const follow = async (activity:any, id:string) => {
await outbox({
"@context": "https://www.w3.org/ns/activitystreams",
type: "Accept",
actor: ACTOR,
actor: ACTOR.id,
to: [activity.actor],
object: activity,
});

View file

@ -1,40 +1,75 @@
import { ACCOUNT, ACTOR, HOSTNAME, PORT } from "./env";
import { DEFAULT_DOCUMENTS, STATIC_PATH } from "./env"
import admin from './admin'
import activitypub from "./activitypub";
import { fetchObject } from "./request";
import activitypub from "./activitypub"
import { fetchObject } from "./request"
import path from "path"
import { BunFile } from "bun"
import { rebuild } from "./db"
import { handle, webfinger } from "../actor"
rebuild()
const server = Bun.serve({
port: 3000,
fetch(req): Response | Promise<Response> {
fetch(req: Request): Response | Promise<Response> {
const url = new URL(req.url)
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`)
// log the incoming request info
console.info(`${new Date().toISOString()} 📥 ${req.method} ${req.url}`)
if(req.method === "GET" && url.pathname === "/.well-known/webfinger") {
const resource = url.searchParams.get("resource")
if(resource !== `acct:${ACCOUNT}@${HOSTNAME}`) return new Response("", { status: 404 })
return Response.json({
subject: `acct:${ACCOUNT}@${HOSTNAME}`,
links: [
{
rel: "self",
type: "application/activity+json",
href: ACTOR,
},
],
}, { headers: { "content-type": "application/activity+json" }})
// CORS route (for now, any domain has access)
if(req.method === "OPTIONS") {
const headers:any = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE',
'Access-Control-Max-Age': '86400',
}
let h
if (h = req.headers.get('Access-Control-Request-Headers'))
headers['Access-Control-Allow-Headers'] = 'Accept, Content-Type, Authorization, Signature, Digest, Date, Host'
return new Response('', { status: 204, headers })
}
else if(req.method === "GET" && url.pathname === "/fetch") {
const object_url = url.searchParams.get('url')
// Webfinger route
else if(req.method === "GET" && url.pathname === "/.well-known/webfinger") {
// make sure the resource matches the current handle. If it doesn't, 404
if(url.searchParams.get("resource") !== `acct:${handle}`) return new Response("", { status: 404 })
// return the webfinger
return Response.json(webfinger, { headers: { 'content-type': 'application/jrd+json' }})
}
else if(req.method === "GET" && url.pathname.startsWith("/fetch/")) {
const object_url = url.pathname.substring(7)
if(!object_url) return new Response("No url supplied", { status: 400})
return fetchObject(ACTOR, object_url)
return fetchObject(object_url)
}
return admin(req) || activitypub(req) || new Response("How did we get here?", { status: 404 })
return admin(req) || activitypub(req) || staticFile(req)
},
});
const getDefaultDocument = async(base_path: string) => {
for(const d of DEFAULT_DOCUMENTS){
const filePath = path.join(base_path, d)
const file = Bun.file(filePath)
if(await file.exists()) return file
}
}
const staticFile = async (req:Request): Promise<Response> => {
try{
const url = new URL(req.url)
const filePath = path.join(STATIC_PATH, url.pathname)
let file:BunFile|undefined = Bun.file(filePath)
// if the file doesn't exist, attempt to get the default document for the path
if(!(await file.exists())) file = await getDefaultDocument(filePath)
if(file && await file.exists()) return new Response(file)
// if the file still doesn't exist, just return a 404
else return new Response("", { status: 404 })
}
catch(err) {
console.error(err)
return new Response("", { status: 404 })
}
}
console.log(`Listening on http://localhost:${server.port} ...`);

View file

@ -1,7 +1,7 @@
import { idsFromValue } from "./activitypub"
import * as db from "./db";
import { ACTOR } from "./env"
import { fetchObject, send } from "./request";
import * as db from "./db"
import { fetchObject, send } from "./request"
import ACTOR from "../actor"
export default async function outbox(activity:any):Promise<Response> {
const date = new Date()
@ -14,7 +14,7 @@ export default async function outbox(activity:any):Promise<Response> {
activity = {
"@context": "https://www.w3.org/ns/activitystreams",
type: "Create",
actor: ACTOR,
actor: ACTOR.id,
object
}
const { to, bto, cc, bcc, audience } = object
@ -25,7 +25,7 @@ export default async function outbox(activity:any):Promise<Response> {
if(audience) activity.audience = audience
}
activity.id = `${ACTOR}/outbox/${id}`
activity.id = `${ACTOR.url}/outbox/${id}`
if(!activity.published) activity.published = date.toISOString()
if(activity.type === 'Create' && activity.object && Object(activity.object) === activity.object) {
@ -35,9 +35,9 @@ export default async function outbox(activity:any):Promise<Response> {
}
// get the main recipients ([...new Set()] is to dedupe)
const recipientList = [...new Set(idsFromValue(activity.to).concat(idsFromValue(activity.cc)).concat(idsFromValue(activity.audience)))]
const recipientList = [...new Set([...idsFromValue(activity.to), ...idsFromValue(activity.cc), ...idsFromValue(activity.audience)])]
// add in the blind recipients
const finalRecipientList = [...new Set(recipientList.concat(idsFromValue(activity.bto)).concat(idsFromValue(activity.bcc)))]
const finalRecipientList = [...new Set([...recipientList, ...idsFromValue(activity.bto), ...idsFromValue(activity.bcc)])]
// remove the blind recipients from the activity
delete activity.bto
delete activity.bcc
@ -47,8 +47,11 @@ export default async function outbox(activity:any):Promise<Response> {
case "Accept": await accept(activity, id); break;
case "Follow": await follow(activity, id); break;
case "Like": await like(activity, id); break;
case "Dislike": await dislike(activity, id); break;
case "Annouce": await announce(activity, id); break;
case "Create": await create(activity, id); break;
case "Undo": await undo(activity); break;
case "Delete": await deletePost(activity); break;
// TODO: case "Anncounce": return await share(activity)
}
// save the activity data for the outbox
@ -56,16 +59,16 @@ export default async function outbox(activity:any):Promise<Response> {
// send to the appropriate recipients
finalRecipientList.forEach((to) => {
if (to.startsWith(ACTOR + "/followers")) db.listFollowers().then(followers => followers.forEach(f => send(ACTOR, f.actor, activity)))
if (to.startsWith(ACTOR.url + "/followers")) db.listFollowers().then(followers => followers.forEach(f => send(f.actor, activity)))
else if (to === "https://www.w3.org/ns/activitystreams#Public") return // there's nothing to "send" to here
else if (to) send(ACTOR, to, activity)
else if (to) send(to, activity)
})
return new Response("", { status: 201, headers: { location: activity.id } })
}
async function create(activity:any, id:string) {
activity.object.id = activity.object.url = `${ACTOR}/post/${id}`
activity.object.id = activity.object.url = `${ACTOR.url}/posts/${id}`
await db.createPost(activity.object, id)
return true
}
@ -82,7 +85,7 @@ async function follow(activity:any, id:string) {
async function like(activity:any, id:string) {
if(typeof activity.object === 'string'){
await db.createLiked(activity.object, id)
activity.object = await fetchObject(ACTOR, activity.object)
activity.object = await fetchObject(activity.object)
}
else {
const liked = await idsFromValue(activity.object)
@ -92,6 +95,32 @@ async function like(activity:any, id:string) {
return true
}
async function dislike(activity:any, id:string) {
if(typeof activity.object === 'string'){
await db.createDisliked(activity.object, id)
activity.object = await fetchObject(activity.object)
}
else {
const disliked = await idsFromValue(activity.object)
disliked.forEach(l => db.createDisliked(l, id))
}
await db.createPost(activity, id)
return true
}
async function announce(activity:any, id:string) {
if(typeof activity.object === 'string'){
await db.createShared(activity.object, id)
activity.object = await fetchObject(activity.object)
}
else {
const shared = await idsFromValue(activity.object)
shared.forEach(l => db.createShared(l, id))
}
await db.createPost(activity, id)
return true
}
// async function share(activity:any) {
// let object = activity.object
// if(typeof object === 'string') {
@ -116,12 +145,23 @@ async function undo(activity:any) {
switch(activity.object.type) {
case "Follow": await db.deleteFollowing(existing.object); break;
case "Like": idsFromValue(existing.object).forEach(async id => await db.deleteLiked(id)); await db.deletePost(local_id); break;
// case "Share": await db.deleteShared(existing.object)
case "Dislike": idsFromValue(existing.object).forEach(async id => await db.deleteDisliked(id)); await db.deletePost(local_id); break;
case "Announce": idsFromValue(existing.object).forEach(async id => await db.deleteShared(id)); await db.deletePost(local_id); break;
}
}
catch {
return false
}
return true
}
async function deletePost(activity:any) {
const id = await idsFromValue(activity.object).at(0)
if(!id) return false
const post = await db.getPostByURL(id)
if(!post) return false
await db.deletePost(post.local_id)
return true
}

View file

@ -1,60 +1,60 @@
import forge from "node-forge" // import crypto from "node:crypto"
import { ACTOR, PRIVATE_KEY } from "./env";
import { PRIVATE_KEY } from "./env";
import ACTOR from "../actor"
export function reqIsActivityPub(req:Request) {
const contentType = req.headers.get("Accept")
return contentType?.includes('application/activity+json')
|| contentType?.includes('application/ld+json; profile="https://www.w3.org/ns/activitystreams"')
|| contentType?.includes('application/ld+json')
}
// this function adds / modifies the appropriate headers for signing a request, then calls fetch
export function signedFetch(url: string | URL | Request, init?: FetchRequestInit): Promise<Response>
{
const urlObj = typeof url === 'string' ? new URL(url)
: url instanceof Request ? new URL(url.url)
: url
/** Fetches and returns an actor at a URL. */
async function fetchActor(url:string) {
return (await fetchObject(ACTOR, url)).json()
}
/** Fetches and returns an object at a URL. */
// export async function fetchObject(url:string) {
// const res = await fetch(url, {
// headers: { accept: "application/activity+json" },
// });
// if (res.status < 200 || 299 < res.status) {
// throw new Error(`Received ${res.status} fetching object.`);
// }
// return res.json();
// }
/** Fetches and returns an object at a URL. */
export async function fetchObject(sender:string, object_url:string) {
console.log(`fetch ${object_url}`)
const url = new URL(object_url)
const path = url.pathname
if(!init) init = {}
const headers:any = init.headers || {}
const method = init.method || (url instanceof Request ? url.method : 'GET')
const path = urlObj.pathname + urlObj.search + urlObj.hash
const body = init.body ? (typeof init.body === 'string' ? init.body : JSON.stringify(init?.body)) : null
const digest = body ? new Bun.CryptoHasher("sha256").update(body).digest("base64") : null
const d = new Date();
const key = forge.pki.privateKeyFromPem(PRIVATE_KEY)
const data = [
`(request-target): get ${path}`,
`host: ${url.hostname}`,
`date: ${d.toUTCString()}`
].join("\n")
const dataObj:any = { }
dataObj['(request-target)'] = `${method.toLowerCase()} ${path}`
dataObj.host = urlObj.hostname
dataObj.date = d.toUTCString()
if(digest) dataObj.digest = `SHA-256=${digest}`
const data = Object.entries(dataObj).map(([key, value]) => `${key}: ${value}`).join('\n')
const signature = forge.util.encode64(key.sign(forge.md.sha256.create().update(data)))
const signatureObj = {
keyId: `${ACTOR.id}#main-key`,
headers: Object.keys(dataObj).join(' '),
signature: signature
}
const res = await fetch(object_url, {
method: "GET",
headers: {
host: url.hostname,
date: d.toUTCString(),
"content-type": "application/json",
signature: `keyId="${sender}#main-key",headers="(request-target) host date",signature="${signature}"`,
accept: "application/json",
}
});
headers.host = urlObj.hostname
headers.date = d.toUTCString()
if(digest) headers.digest = `SHA-256=${digest}`
headers.signature = Object.entries(signatureObj).map(([key,value]) => `${key}="${value}"`).join(',')
headers.accept = 'application/ld+json; profile="http://www.w3.org/ns/activitystreams"'
if(body) headers["Content-Type"] = 'application/ld+json; profile="http://www.w3.org/ns/activitystreams"'
return fetch(url, {...init, headers })
}
/** Fetches and returns an actor at a URL. */
async function fetchActor(url:string) {
return await (await fetchObject(url)).json()
}
/** Fetches and returns an object at a URL. */
export async function fetchObject(object_url:string) {
console.log(`fetch ${object_url}`)
const res = await signedFetch(object_url);
if (res.status < 200 || 299 < res.status) {
throw new Error(res.statusText + ": " + (await res.text()));
@ -68,38 +68,15 @@ export async function fetchObject(sender:string, object_url:string) {
* @param recipient The recipient's actor URL.
* @param message the body of the request to send.
*/
export async function send(sender:string, recipient:string, message:any) {
export async function send(recipient:string, message:any, from:string=ACTOR.id) {
console.log(`Sending to ${recipient}`, message)
const url = new URL(recipient)
// TODO: revisit fetch actor to use webfinger to get the inbox maybe?
const actor = await fetchActor(recipient)
const path = actor.inbox.replace("https://" + url.hostname, "")
const body = JSON.stringify(message)
const digest = new Bun.CryptoHasher("sha256").update(body).digest("base64")
const d = new Date();
const key = forge.pki.privateKeyFromPem(PRIVATE_KEY)
const data = [
`(request-target): post ${path}`,
`host: ${url.hostname}`,
`date: ${d.toUTCString()}`,
`digest: SHA-256=${digest}`,
].join("\n")
const signature = forge.util.encode64(key.sign(forge.md.sha256.create().update(data)))
const res = await fetch(actor.inbox, {
const res = await signedFetch(actor.inbox, {
method: "POST",
headers: {
host: url.hostname,
date: d.toUTCString(),
digest: `SHA-256=${digest}`,
"content-type": "application/json",
signature: `keyId="${sender}#main-key",headers="(request-target) host date digest",signature="${signature}"`,
accept: "application/json",
},
body,
});