#!/usr/bin/env node
// search "Copyright" in this file for licensing info
// configuration
const appName = 'WuppìMini';
const serverPort = 8135;
const detailedLogging = true;
const serverLanUpstreams = false;
const serverPlaintextUpstreams = false;
const appSelfContained = false;
let staticFiles = [ 'package.json', 'package-lock.json' ];
let linkStyles = [ 'index.css' ];
const appTerms = `
(These terms apply to the server-hosted version of the app only.)
This service is offered for free, in the hope that it can be useful, but without any warranty.
For the service to be able to publish your posts, your content is transmitted to our server, which then forwards it to the server of the service you specified at the time of login, operating on your behalf with the credentials you provided.
Usage of the service might be automatically monitored, and the metadata generated by you might be archived for analytics, debugging, or legal reasons, for as long as we see fit. For every web request, this could include: your IP address, your user agent, the time of request, the requested URL. On any request to an upstream server, this could include: the requested URL on the upstream server, your username hash. On request for posting content, this could include: the hash of each text field's content of your post, the metadata of your uploaded files (filename hash, content hash, content length, mime type). Your content itself, and all normal data, is never stored.
You are forbidden from using the service in any way that is damaging to the service itself or our infrastructure, or that is illegal in the jurisdiction this server is hosted in (Italy, Europe).
We reserve the right to ban you from using the service at any time, for any reason, and without any explanation or prior warning.
By continuing with the usage of this site, you declare to understand and agree to these terms.
If you don't agree with these terms, discontinue usage of this site immediately, and instead get the source code to host it yourself, find another instance, or use the local, client-side version.
`;
const suggestedTags = [ 'fromWuppiMini' ];
const corsProxies = [ 'corsproxy.io?', 'corsproxy.org?', 'hlb0.octt.eu.org/cors-main.php/' ];
const SpaccDotWebServer = require('SpaccDotWeb/SpaccDotWeb.Server.js');
var crypto, escapeHtml;
let isEnvServer = SpaccDotWebServer.envIsNode;
let isEnvBrowser = SpaccDotWebServer.envIsBrowser;
const httpCodes = { success: [ 200, 201 ] };
const appPlatforms = {
"wp.org": { name: "WordPress.org (Community/Self-hosted)", writing: true },
//"greader": { name: "RSS with Google Reader API (FreshRSS, ...)", reading: true },
};
const appLanguages = {
en: "🇬🇧️ English",
it: "🇮🇹️ Italiano",
};
const appStrings = {
compose: { en: `Compose`, it: `Componi` },
read: { en: `Read`, it: `Leggi` },
settings: { en: `Settings`, it: `Impostazioni` },
language: { en: `Language`, it: `Lingua` },
composePost: {
en: `Compose Post`,
it: `Componi Post`,
},
postTitle: {
en: `Post Title`,
it: `Titolo del Post`,
},
includeTags: {
en: `Include suggested Tags`,
it: `Includi Tag suggeriti`,
},
postingHint: {
en: `What's on your mind?`,
it: `A cosa stai pensando?`,
},
uploadDraft: {
en: `Upload Draft`,
it: `Carica Bozza`,
},
publish: {
en: `Publish!`,
it: `Pubblica!`,
},
postPublished: {
en: `Post published`,
it: `Post pubblicato`,
},
draftUploaded: {
en: `Draft uploaded`,
it: `Bozza caricata`,
},
unknownError: {
en: `An unknown error just happened. Please check that your data is correct, and try again.`,
it: `Si è verificato un errore sconosciuto. Per favore, controlla che i dati inseriti siano corretti, e riprova.`,
},
upstreamError: {
en: `Upstream server responded with error`,
it: `Il server di upstream ha risposto con errore`,
},
csrfError: {
en: `Authorization token mismatch. Please try resubmitting.`,
it: `Il token di autorizzazione non combacia. Per favore ritenta l'invio.`,
},
upstreamDisallowed: {
en: `Upstream destination is not allowed from backend. (Only global HTTPS sites are allowed.)`,
it: `La destinazione di upstream non è permessa dal backend. (Solo i siti HTTPS globali sono permessi.)`,
},
currentAccounts: {
en: `Current Accounts`,
it: `Account Correnti`,
},
addNewAccount: {
en: `Add New Account`,
it: `Aggiungi Nuovo Account`,
},
siteInstanceUrl: {
en: `Site/Instance URL`,
it: `URL Sito/Istanza`,
},
rememberMe: {
en: `Remember me`,
it: `Ricordami`,
},
loginAndSave: {
en: `Login and Save`,
it: `Login e Salva`,
},
mustAddAccount: {
en: (type) => `You must add ${type === 'compose' ? 'a writing' : type === 'read' ? 'a reading' : 'an'} account to continue. Go to Settings.`,
it: (type) => `Devi aggiungere un account ${type === 'compose' ? 'di scrittura' : type === 'read' ? 'di lettura' : ''} per continuare. Vai alle Impostazioni.`,
},
accountExists: {
en: `The account you tried to add is already registered.`,
it: `L'account che hai provato ad aggiungere è già registrato.`,
},
logoutAccounts: {
en: `Logout Selected Accounts`,
it: `Logout Account Selezionati`,
},
noAccountSelected: {
en: `You haven't selected any account to be removed.`,
it: `Non hai selezionato alcun account da rimuovere.`
},
applyLanguage: {
en: `Apply Language`,
it: `Applica Lingua`,
},
postEmpty: {
en: `Post content is empty. Please write some text or upload a media.`,
it: `Il post è vuoto. Per favore scrivi del testo o carica un file.`,
},
};
appStrings.get = (string, language='en') => (appStrings[string][language] || Object.values(appStrings[string])[0]);
const appPager = (content, title, opts={}, ctx) => `
${appName} (temporary name?) is a minimalist, basic HTML-based frontend, designed for quickly and efficiently publishing to social media and content management services (note that only WordPress is currently supported).
Mainly aimed at old systems that might not support modern web-apps, the server-hosted version of this application works without any client-side scripts, and should be optionally reachable via unencrypted HTTP.
About practical use cases, you ask? I made this to upload game posts from my 3DS, and possibly microblog with my Kindle! (See an example: this post was published from my n3DS.)
Check out all my other web endeavors at ${A('https://hub.octt.eu.org')}, or join my Matrix space to chat or if you need help: ${A('https://matrix.to/#/#Spacc:matrix.org')}.
Versions
This app uses a novel approach behind the scenes to be able to run in one of either two modes, while reusing a single codebase: a classical server-side-rendered application, which works well on very limited systems but requires connection with a dedicated backend server that runs it, or a modern client-side single-page-application, relying on many modern web technologies, but working without an hosting server. Occasional bugs or update delays aside, the two essentially have feature parity and the same interface, but can be useful in different situations. Use whatever you prefer in each possible situation.
Copyright (C) 2024 OctoSpacc
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see ${A('https://www.gnu.org/licenses/')}.
${isEnvServer ? `You can obtain the full source code and assets by downloading the following files:
${staticFiles.map(file => ` • ${file}`).join('')}.
` : 'To get the original, unminified source code, visit this same page on the server-side version (refer to the Versions section above).'}
Alternatively, you can also find the source code on my shared Git repo: ${A('https://gitlab.com/octospacc/octospacc.gitlab.io/-/tree/master/source/WuppiMini/')}.
${isEnvServer ? `
Terms of Use and Privacy Policy
${appTerms}` : ''}
Changelog
2024-07-15 (deployed 2024-07-30)
Multi-account support (required changes to the cookie format), allowing for selection of destination in Compose and filtering of sources in Read.
New multi-language support, using browser language as a default and allowing change in Settings.
Slight UX improvements and bugfixes to existing forms and screens.
Made a preview of the Compose screen visible before logging-in.
2024-02-24
Allow uploading posts as published or draft, via 2 distinct buttons.
Migrated fancy portable-server-codebase to SpaccDotWeb for code reuse and slimming down of the application core.
2024-02-12
First working client-side version of the current app, without backend server (still a bit buggy).
Fixed suggested tags handling not working and making the post error out, by instead simply writing them in the post body
2024-02-10
Add "remember me" login option.
Add "suggested tags" publishing option, will automatically add this list of tags to the post: [${suggestedTags}].
2024-02-09
First working version, with an UI reminiscent of [that dead social network that rhymes with Meterse], and Info, Settings, and Composition pages!
Allow logging in with a WordPress.org profile, and creating new posts, including uploading images.
Add licensing and proper source code listing.
Tested on New and Old 3DS.
`);
} ];
const endpointCompose = [ 'GET|POST /compose/', async (ctx) => {
let [noticeErrorHtml, noticeSuccessHtml] = ['', ''];
const language = getUserLanguage(ctx);
const accountString = ctx.getCookie('account');
const accounts = accountsDataFromCookieString(accountString)?.filter(account => appPlatforms[account.platform].writing);//getAccountsData(ctx);
ctx.response.statusCode = 200;
const postUploadStatus = ((ctx.bodyParameters?.publish && 'publish') || (ctx.bodyParameters?.draft && 'draft'));
if (ctx.request.method === 'POST' && postUploadStatus) {
if (!matchCsrfToken(ctx.bodyParameters, accountString)) {
ctx.response.statusCode = 401;
noticeErrorHtml = appStrings.get('csrfError', language);
}
const isThereAnyFile = ((ctx.bodyParameters.file?.data?.length || ctx.bodyParameters.file?.size) > 0);
if (!ctx.bodyParameters.text?.trim() && !isThereAnyFile) {
ctx.response.statusCode = 500;
noticeErrorHtml = appStrings.get('postEmpty', language);
}
const account = accountDataFromFormId(accounts, ctx.account); //accountsDataFromCookieString(accountString)[0];
if (!checkUpstreamAllowed(account.instance)) {
ctx.response.statusCode = 500;
noticeErrorHtml = appStrings.get('upstreamDisallowed', language);
}
let mediaData;
try {
// there is a media to upload first
if (httpCodes.success.includes(ctx.response.statusCode) && isThereAnyFile) {
const mediaReq = await fetch(`${corsProxyIfNeed(account.cors)}${account.instance}/wp-json/wp/v2/media`, { headers: {
...getBackendHeaders(account),
"Content-Type": ctx.bodyParameters.file.type,
"Content-Disposition": `attachment; filename=${ctx.bodyParameters.file.filename}`,
}, method: "POST", body: (ctx.bodyParameters.file.data || ctx.bodyParameters.file) });
mediaData = await mediaReq.json();
if (!httpCodes.success.includes(mediaReq.status)) {
noticeErrorHtml = `${appStrings.get('upstreamError', language)} ${ctx.response.statusCode = mediaReq.status}: ${escapeHtml(JSON.stringify(mediaData))}`;
}
}
// upload actual post if nothing has errored before
if (httpCodes.success.includes(ctx.response.statusCode)) {
const tagsHtml = (ctx.bodyParameters.tags === 'on' ? `