1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-05 17:46:19 +00:00
TiddlyWiki5/plugins/tiddlywiki/tiddlyweb/tiddlywebadaptor.js

381 lines
11 KiB
JavaScript
Raw Normal View History

/*\
title: $:/plugins/tiddlywiki/tiddlyweb/tiddlywebadaptor.js
type: application/javascript
module-type: syncadaptor
A sync adaptor module for synchronising with TiddlyWeb compatible servers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var CONFIG_HOST_TIDDLER = "$:/config/tiddlyweb/host",
DEFAULT_HOST_TIDDLER = "$protocol$//$host$/";
function TiddlyWebAdaptor(options) {
this.wiki = options.wiki;
this.host = this.getHost();
this.recipe = undefined;
this.hasStatus = false;
this.logger = new $tw.utils.Logger("TiddlyWebAdaptor");
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
this.isLoggedIn = false;
this.isReadOnly = false;
this.logoutIsAvailable = true;
}
TiddlyWebAdaptor.prototype.name = "tiddlyweb";
Fix syncer to handler errors properly (#4373) * First commit * Add throttling of saves Now we refuse to save a tiddler more often than once per second. * Wait for a timeout before trying again after an error * Modest optimisations of isDirty() method * Synchronise system tiddlers and deletions from the server Fixes two long-standing issues: * Changes to system tiddlers are not synchronised from the server to the browser * Deletions of tiddlers on the server are not propagated to browser clients * Make sure we update the dirty status even if there isn't a task to perform * Replace save-wiki button with popup sync menu * Remove the "Server" control panel tab We don't need it with the enhanced sync dropdown * Add indentation to the save-wiki button * Fix spacing in dropdown menu items * Switch between cloud icons according to dirty status * Add a menu item to copy syncer logs to the clipboard * Improve animated icon * Remove indentation from save-wiki button @pmario the annoying thing is that using `\trim whitespace` trims significant whitespace too, so it means we have to use <$text text=" "/> when we need a space that won't be trimmed. For the moment, I've removed the indentation but will keep thinking about it. * Further icon, UI and copy text tweaks Move the icons and styles from the core into the TiddlyWeb plugin * Clean up PR diff * Tweak animation durations * Break the actions from the syncer dropdown into separate tiddlers @pmario I think this makes things a bit easier to follow * Refactor syncadaptor creation and logging The goal is for the syncadaptor to be able to log to the same logger as the syncer, so that the "copy syncer logs to clipboard" data is more useful. * Don't transition the dirty indicator container colour, just the SVG's colour * Only trigger a sync for changes to tiddlers we're interested in Otherwise it is triggered by the creation of the alert tiddlers used to display errors. * Restore deleting local tiddlers removed from the server (I had commented it out for some testing and accidentally commited it). * Guard against missing adaptor info * We still need to trigger a timeout when there was no task to process * Avoid repeatedly polling for changes Instead we only trigger a timeout call at if there is a pending task (ie a tiddler that has changed but isn't yet old enough to save). * Lazy loading: include skinny versions of lazily loaded tiddlers in the index.html * Introduce _is_skinny field for indicating that a tiddler is subject to lazy loading * Remove savetrail plugin from prerelease It doesn't yet work with the new syncer * Make the savetrail plugin work again * Clear outstanding alerts when synchronisation is restored * Logger: only remove alerts from the same component Missed off 9f5c0de07 * Make the saving throttle interval configurable (#4385) After switching Bob to use the core syncer the throttle interval makes saving feel very sluggish compared to the message queue setup that I had before. The editing lock that I use to prevent conflicts with multiple users doesn't go away until the save is completed, and with the 1 second delay it means that if you edit a tiddler and save it than you have to wait one second before you can edit it again. * Tweaks to appearance of alerts * Exclude temp tiddlers from offline snapshots Otherwise alerts will persist * Tweak appearance of status line in dropdown * Update release note * Web server: Don't include full path in error messages Fixes #3724 * In change event handler check for deletions * Disable the official plugin library when the tiddlyweb plugin is loaded * Hide error details from browser for /files/ route See https://github.com/Jermolene/TiddlyWiki5/issues/3724#issuecomment-565702492 -- thanks @pmario * Revert all the changes to the relationship between the syncer and the syncadaptor Previously we had some major rearrangements to make it possible for the syncadaptor to route it's logging to the logger used by the syncer. The motivation is so that the "copy logs to clipboard" button is more useful. On reflection, changing the interface this drastically is undesirable from a backwards compatibility perspective, so I'm going to investigate other ways to achieve the logger sharing * Make the tiddlyweb adaptor use the syncer's logger So that both are availavble when copying the syncer logs to the clipboard * Update release note * Support setting port=0 to get an OS assigned port Quite useful * Update code comment * UI: Use "Get latest changes from server" instead of "Refresh" * Add getUpdatedTiddlers() method to syncadaptor API See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573579495 * Refactor revision handling within the syncer Thanks @pmario * Fix typo in tiddlywebadaptor * Improve presentation of errors See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573695267 * Add docs for getTiddlerRevision() * Remove unused error animation * Update comment for GET /recipes/default/tiddlers/tiddlers.json * Optimise SVG cloud image * Add optional list of allowed filters for get all tiddlers route An attempt to address @Arlen22's concern here: https://github.com/Jermolene/TiddlyWiki5/pull/4373#pullrequestreview-342146190 * Fix network error alert text translatability * Fix error code and logging for GET /recipes/default/tiddlers/tiddlers.json Thanks @Arlen22 * Flip GET /recipes/default/tiddlers/tiddlers.json allowed filter handling to be secure by default * Validate updates received from getUpdatedTiddlers() * Add syncer method to force loading of a tiddler from the server * Remove the release note update to remove the merge conflict * Fix crash when there's no config section in the tiddlywiki.info file * Use config tiddler title to check filter query (merge into fix-syncer) (#4478) * Use config tiddler title to check filter query * Create config-tiddlers-filter.tid * Add config switch to enable all filters on GET /recipes/default/tiddlers/tiddlers.json And update docs * Fix bug when deleting a tiddler with a shadow Reported by @kookma at https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-604027528 Co-authored-by: jed <inmysocks@fastmail.com> Co-authored-by: Arlen22 <arlenbee@gmail.com>
2020-03-30 14:24:05 +00:00
TiddlyWebAdaptor.prototype.supportsLazyLoading = true;
TiddlyWebAdaptor.prototype.setLoggerSaveBuffer = function(loggerForSaving) {
this.logger.setSaveBuffer(loggerForSaving);
};
TiddlyWebAdaptor.prototype.isReady = function() {
return this.hasStatus;
};
TiddlyWebAdaptor.prototype.getHost = function() {
var text = this.wiki.getTiddlerText(CONFIG_HOST_TIDDLER,DEFAULT_HOST_TIDDLER),
substitutions = [
{name: "protocol", value: document.location.protocol},
{name: "host", value: document.location.host},
{name: "pathname", value: document.location.pathname}
];
for(var t=0; t<substitutions.length; t++) {
var s = substitutions[t];
text = $tw.utils.replaceString(text,new RegExp("\\$" + s.name + "\\$","mg"),s.value);
}
return text;
};
TiddlyWebAdaptor.prototype.getTiddlerInfo = function(tiddler) {
return {
bag: tiddler.fields.bag
};
};
Fix syncer to handler errors properly (#4373) * First commit * Add throttling of saves Now we refuse to save a tiddler more often than once per second. * Wait for a timeout before trying again after an error * Modest optimisations of isDirty() method * Synchronise system tiddlers and deletions from the server Fixes two long-standing issues: * Changes to system tiddlers are not synchronised from the server to the browser * Deletions of tiddlers on the server are not propagated to browser clients * Make sure we update the dirty status even if there isn't a task to perform * Replace save-wiki button with popup sync menu * Remove the "Server" control panel tab We don't need it with the enhanced sync dropdown * Add indentation to the save-wiki button * Fix spacing in dropdown menu items * Switch between cloud icons according to dirty status * Add a menu item to copy syncer logs to the clipboard * Improve animated icon * Remove indentation from save-wiki button @pmario the annoying thing is that using `\trim whitespace` trims significant whitespace too, so it means we have to use <$text text=" "/> when we need a space that won't be trimmed. For the moment, I've removed the indentation but will keep thinking about it. * Further icon, UI and copy text tweaks Move the icons and styles from the core into the TiddlyWeb plugin * Clean up PR diff * Tweak animation durations * Break the actions from the syncer dropdown into separate tiddlers @pmario I think this makes things a bit easier to follow * Refactor syncadaptor creation and logging The goal is for the syncadaptor to be able to log to the same logger as the syncer, so that the "copy syncer logs to clipboard" data is more useful. * Don't transition the dirty indicator container colour, just the SVG's colour * Only trigger a sync for changes to tiddlers we're interested in Otherwise it is triggered by the creation of the alert tiddlers used to display errors. * Restore deleting local tiddlers removed from the server (I had commented it out for some testing and accidentally commited it). * Guard against missing adaptor info * We still need to trigger a timeout when there was no task to process * Avoid repeatedly polling for changes Instead we only trigger a timeout call at if there is a pending task (ie a tiddler that has changed but isn't yet old enough to save). * Lazy loading: include skinny versions of lazily loaded tiddlers in the index.html * Introduce _is_skinny field for indicating that a tiddler is subject to lazy loading * Remove savetrail plugin from prerelease It doesn't yet work with the new syncer * Make the savetrail plugin work again * Clear outstanding alerts when synchronisation is restored * Logger: only remove alerts from the same component Missed off 9f5c0de07 * Make the saving throttle interval configurable (#4385) After switching Bob to use the core syncer the throttle interval makes saving feel very sluggish compared to the message queue setup that I had before. The editing lock that I use to prevent conflicts with multiple users doesn't go away until the save is completed, and with the 1 second delay it means that if you edit a tiddler and save it than you have to wait one second before you can edit it again. * Tweaks to appearance of alerts * Exclude temp tiddlers from offline snapshots Otherwise alerts will persist * Tweak appearance of status line in dropdown * Update release note * Web server: Don't include full path in error messages Fixes #3724 * In change event handler check for deletions * Disable the official plugin library when the tiddlyweb plugin is loaded * Hide error details from browser for /files/ route See https://github.com/Jermolene/TiddlyWiki5/issues/3724#issuecomment-565702492 -- thanks @pmario * Revert all the changes to the relationship between the syncer and the syncadaptor Previously we had some major rearrangements to make it possible for the syncadaptor to route it's logging to the logger used by the syncer. The motivation is so that the "copy logs to clipboard" button is more useful. On reflection, changing the interface this drastically is undesirable from a backwards compatibility perspective, so I'm going to investigate other ways to achieve the logger sharing * Make the tiddlyweb adaptor use the syncer's logger So that both are availavble when copying the syncer logs to the clipboard * Update release note * Support setting port=0 to get an OS assigned port Quite useful * Update code comment * UI: Use "Get latest changes from server" instead of "Refresh" * Add getUpdatedTiddlers() method to syncadaptor API See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573579495 * Refactor revision handling within the syncer Thanks @pmario * Fix typo in tiddlywebadaptor * Improve presentation of errors See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573695267 * Add docs for getTiddlerRevision() * Remove unused error animation * Update comment for GET /recipes/default/tiddlers/tiddlers.json * Optimise SVG cloud image * Add optional list of allowed filters for get all tiddlers route An attempt to address @Arlen22's concern here: https://github.com/Jermolene/TiddlyWiki5/pull/4373#pullrequestreview-342146190 * Fix network error alert text translatability * Fix error code and logging for GET /recipes/default/tiddlers/tiddlers.json Thanks @Arlen22 * Flip GET /recipes/default/tiddlers/tiddlers.json allowed filter handling to be secure by default * Validate updates received from getUpdatedTiddlers() * Add syncer method to force loading of a tiddler from the server * Remove the release note update to remove the merge conflict * Fix crash when there's no config section in the tiddlywiki.info file * Use config tiddler title to check filter query (merge into fix-syncer) (#4478) * Use config tiddler title to check filter query * Create config-tiddlers-filter.tid * Add config switch to enable all filters on GET /recipes/default/tiddlers/tiddlers.json And update docs * Fix bug when deleting a tiddler with a shadow Reported by @kookma at https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-604027528 Co-authored-by: jed <inmysocks@fastmail.com> Co-authored-by: Arlen22 <arlenbee@gmail.com>
2020-03-30 14:24:05 +00:00
TiddlyWebAdaptor.prototype.getTiddlerRevision = function(title) {
var tiddler = this.wiki.getTiddler(title);
return tiddler.fields.revision;
};
/*
Get the current status of the TiddlyWeb connection
*/
TiddlyWebAdaptor.prototype.getStatus = function(callback) {
// Get status
var self = this;
this.logger.log("Getting status");
$tw.utils.httpRequest({
url: this.host + "status",
callback: function(err,data) {
self.hasStatus = true;
if(err) {
return callback(err);
}
//If Browser-Storage plugin is present, cache pre-loaded tiddlers and add back after sync from server completes
if($tw.browserStorage && $tw.browserStorage.isEnabled()) {
$tw.browserStorage.cachePreloadTiddlers();
}
// Decode the status JSON
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
var json = null;
try {
json = JSON.parse(data);
} catch (e) {
}
if(json) {
self.logger.log("Status:",data);
// Record the recipe
if(json.space) {
self.recipe = json.space.recipe;
}
// Check if we're logged in
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
self.isLoggedIn = json.username !== "GUEST";
self.isReadOnly = !!json["read_only"];
self.isAnonymous = !!json.anonymous;
self.logoutIsAvailable = "logout_is_available" in json ? !!json["logout_is_available"] : true;
}
// Invoke the callback if present
if(callback) {
callback(null,self.isLoggedIn,json.username,self.isReadOnly,self.isAnonymous);
}
}
});
};
/*
Attempt to login and invoke the callback(err)
*/
TiddlyWebAdaptor.prototype.login = function(username,password,callback) {
2014-01-26 20:59:30 +00:00
var options = {
url: this.host + "challenge/tiddlywebplugins.tiddlyspace.cookie_form",
type: "POST",
data: {
user: username,
password: password,
tiddlyweb_redirect: "/status" // workaround to marginalize automatic subsequent GET
},
callback: function(err) {
callback(err);
},
headers: {
"accept": "application/json",
"X-Requested-With": "TiddlyWiki"
}
2014-01-26 20:59:30 +00:00
};
this.logger.log("Logging in:",options);
2014-01-26 20:59:30 +00:00
$tw.utils.httpRequest(options);
};
/*
*/
TiddlyWebAdaptor.prototype.logout = function(callback) {
if(this.logoutIsAvailable) {
var options = {
url: this.host + "logout",
type: "POST",
data: {
csrf_token: this.getCsrfToken(),
tiddlyweb_redirect: "/status" // workaround to marginalize automatic subsequent GET
},
callback: function(err,data,xhr) {
callback(err);
},
headers: {
"accept": "application/json",
"X-Requested-With": "TiddlyWiki"
}
};
this.logger.log("Logging out:",options);
$tw.utils.httpRequest(options);
} else {
alert("This server does not support logging out. If you are using basic authentication the only way to logout is close all browser windows");
callback(null);
}
};
/*
Retrieve the CSRF token from its cookie
*/
TiddlyWebAdaptor.prototype.getCsrfToken = function() {
var regex = /^(?:.*; )?csrf_token=([^(;|$)]*)(?:;|$)/,
match = regex.exec(document.cookie),
csrf = null;
if (match && (match.length === 2)) {
csrf = match[1];
}
return csrf;
};
/*
Get an array of skinny tiddler fields from the server
*/
TiddlyWebAdaptor.prototype.getSkinnyTiddlers = function(callback) {
2013-11-08 20:18:26 +00:00
var self = this;
$tw.utils.httpRequest({
url: this.host + "recipes/" + this.recipe + "/tiddlers.json",
Fix syncer to handler errors properly (#4373) * First commit * Add throttling of saves Now we refuse to save a tiddler more often than once per second. * Wait for a timeout before trying again after an error * Modest optimisations of isDirty() method * Synchronise system tiddlers and deletions from the server Fixes two long-standing issues: * Changes to system tiddlers are not synchronised from the server to the browser * Deletions of tiddlers on the server are not propagated to browser clients * Make sure we update the dirty status even if there isn't a task to perform * Replace save-wiki button with popup sync menu * Remove the "Server" control panel tab We don't need it with the enhanced sync dropdown * Add indentation to the save-wiki button * Fix spacing in dropdown menu items * Switch between cloud icons according to dirty status * Add a menu item to copy syncer logs to the clipboard * Improve animated icon * Remove indentation from save-wiki button @pmario the annoying thing is that using `\trim whitespace` trims significant whitespace too, so it means we have to use <$text text=" "/> when we need a space that won't be trimmed. For the moment, I've removed the indentation but will keep thinking about it. * Further icon, UI and copy text tweaks Move the icons and styles from the core into the TiddlyWeb plugin * Clean up PR diff * Tweak animation durations * Break the actions from the syncer dropdown into separate tiddlers @pmario I think this makes things a bit easier to follow * Refactor syncadaptor creation and logging The goal is for the syncadaptor to be able to log to the same logger as the syncer, so that the "copy syncer logs to clipboard" data is more useful. * Don't transition the dirty indicator container colour, just the SVG's colour * Only trigger a sync for changes to tiddlers we're interested in Otherwise it is triggered by the creation of the alert tiddlers used to display errors. * Restore deleting local tiddlers removed from the server (I had commented it out for some testing and accidentally commited it). * Guard against missing adaptor info * We still need to trigger a timeout when there was no task to process * Avoid repeatedly polling for changes Instead we only trigger a timeout call at if there is a pending task (ie a tiddler that has changed but isn't yet old enough to save). * Lazy loading: include skinny versions of lazily loaded tiddlers in the index.html * Introduce _is_skinny field for indicating that a tiddler is subject to lazy loading * Remove savetrail plugin from prerelease It doesn't yet work with the new syncer * Make the savetrail plugin work again * Clear outstanding alerts when synchronisation is restored * Logger: only remove alerts from the same component Missed off 9f5c0de07 * Make the saving throttle interval configurable (#4385) After switching Bob to use the core syncer the throttle interval makes saving feel very sluggish compared to the message queue setup that I had before. The editing lock that I use to prevent conflicts with multiple users doesn't go away until the save is completed, and with the 1 second delay it means that if you edit a tiddler and save it than you have to wait one second before you can edit it again. * Tweaks to appearance of alerts * Exclude temp tiddlers from offline snapshots Otherwise alerts will persist * Tweak appearance of status line in dropdown * Update release note * Web server: Don't include full path in error messages Fixes #3724 * In change event handler check for deletions * Disable the official plugin library when the tiddlyweb plugin is loaded * Hide error details from browser for /files/ route See https://github.com/Jermolene/TiddlyWiki5/issues/3724#issuecomment-565702492 -- thanks @pmario * Revert all the changes to the relationship between the syncer and the syncadaptor Previously we had some major rearrangements to make it possible for the syncadaptor to route it's logging to the logger used by the syncer. The motivation is so that the "copy logs to clipboard" button is more useful. On reflection, changing the interface this drastically is undesirable from a backwards compatibility perspective, so I'm going to investigate other ways to achieve the logger sharing * Make the tiddlyweb adaptor use the syncer's logger So that both are availavble when copying the syncer logs to the clipboard * Update release note * Support setting port=0 to get an OS assigned port Quite useful * Update code comment * UI: Use "Get latest changes from server" instead of "Refresh" * Add getUpdatedTiddlers() method to syncadaptor API See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573579495 * Refactor revision handling within the syncer Thanks @pmario * Fix typo in tiddlywebadaptor * Improve presentation of errors See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573695267 * Add docs for getTiddlerRevision() * Remove unused error animation * Update comment for GET /recipes/default/tiddlers/tiddlers.json * Optimise SVG cloud image * Add optional list of allowed filters for get all tiddlers route An attempt to address @Arlen22's concern here: https://github.com/Jermolene/TiddlyWiki5/pull/4373#pullrequestreview-342146190 * Fix network error alert text translatability * Fix error code and logging for GET /recipes/default/tiddlers/tiddlers.json Thanks @Arlen22 * Flip GET /recipes/default/tiddlers/tiddlers.json allowed filter handling to be secure by default * Validate updates received from getUpdatedTiddlers() * Add syncer method to force loading of a tiddler from the server * Remove the release note update to remove the merge conflict * Fix crash when there's no config section in the tiddlywiki.info file * Use config tiddler title to check filter query (merge into fix-syncer) (#4478) * Use config tiddler title to check filter query * Create config-tiddlers-filter.tid * Add config switch to enable all filters on GET /recipes/default/tiddlers/tiddlers.json And update docs * Fix bug when deleting a tiddler with a shadow Reported by @kookma at https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-604027528 Co-authored-by: jed <inmysocks@fastmail.com> Co-authored-by: Arlen22 <arlenbee@gmail.com>
2020-03-30 14:24:05 +00:00
data: {
filter: "[all[tiddlers]] -[[$:/isEncrypted]] -[prefix[$:/temp/]] -[prefix[$:/status/]] -[[$:/boot/boot.js]] -[[$:/boot/bootprefix.js]] -[[$:/library/sjcl.js]] -[[$:/core]]"
Fix syncer to handler errors properly (#4373) * First commit * Add throttling of saves Now we refuse to save a tiddler more often than once per second. * Wait for a timeout before trying again after an error * Modest optimisations of isDirty() method * Synchronise system tiddlers and deletions from the server Fixes two long-standing issues: * Changes to system tiddlers are not synchronised from the server to the browser * Deletions of tiddlers on the server are not propagated to browser clients * Make sure we update the dirty status even if there isn't a task to perform * Replace save-wiki button with popup sync menu * Remove the "Server" control panel tab We don't need it with the enhanced sync dropdown * Add indentation to the save-wiki button * Fix spacing in dropdown menu items * Switch between cloud icons according to dirty status * Add a menu item to copy syncer logs to the clipboard * Improve animated icon * Remove indentation from save-wiki button @pmario the annoying thing is that using `\trim whitespace` trims significant whitespace too, so it means we have to use <$text text=" "/> when we need a space that won't be trimmed. For the moment, I've removed the indentation but will keep thinking about it. * Further icon, UI and copy text tweaks Move the icons and styles from the core into the TiddlyWeb plugin * Clean up PR diff * Tweak animation durations * Break the actions from the syncer dropdown into separate tiddlers @pmario I think this makes things a bit easier to follow * Refactor syncadaptor creation and logging The goal is for the syncadaptor to be able to log to the same logger as the syncer, so that the "copy syncer logs to clipboard" data is more useful. * Don't transition the dirty indicator container colour, just the SVG's colour * Only trigger a sync for changes to tiddlers we're interested in Otherwise it is triggered by the creation of the alert tiddlers used to display errors. * Restore deleting local tiddlers removed from the server (I had commented it out for some testing and accidentally commited it). * Guard against missing adaptor info * We still need to trigger a timeout when there was no task to process * Avoid repeatedly polling for changes Instead we only trigger a timeout call at if there is a pending task (ie a tiddler that has changed but isn't yet old enough to save). * Lazy loading: include skinny versions of lazily loaded tiddlers in the index.html * Introduce _is_skinny field for indicating that a tiddler is subject to lazy loading * Remove savetrail plugin from prerelease It doesn't yet work with the new syncer * Make the savetrail plugin work again * Clear outstanding alerts when synchronisation is restored * Logger: only remove alerts from the same component Missed off 9f5c0de07 * Make the saving throttle interval configurable (#4385) After switching Bob to use the core syncer the throttle interval makes saving feel very sluggish compared to the message queue setup that I had before. The editing lock that I use to prevent conflicts with multiple users doesn't go away until the save is completed, and with the 1 second delay it means that if you edit a tiddler and save it than you have to wait one second before you can edit it again. * Tweaks to appearance of alerts * Exclude temp tiddlers from offline snapshots Otherwise alerts will persist * Tweak appearance of status line in dropdown * Update release note * Web server: Don't include full path in error messages Fixes #3724 * In change event handler check for deletions * Disable the official plugin library when the tiddlyweb plugin is loaded * Hide error details from browser for /files/ route See https://github.com/Jermolene/TiddlyWiki5/issues/3724#issuecomment-565702492 -- thanks @pmario * Revert all the changes to the relationship between the syncer and the syncadaptor Previously we had some major rearrangements to make it possible for the syncadaptor to route it's logging to the logger used by the syncer. The motivation is so that the "copy logs to clipboard" button is more useful. On reflection, changing the interface this drastically is undesirable from a backwards compatibility perspective, so I'm going to investigate other ways to achieve the logger sharing * Make the tiddlyweb adaptor use the syncer's logger So that both are availavble when copying the syncer logs to the clipboard * Update release note * Support setting port=0 to get an OS assigned port Quite useful * Update code comment * UI: Use "Get latest changes from server" instead of "Refresh" * Add getUpdatedTiddlers() method to syncadaptor API See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573579495 * Refactor revision handling within the syncer Thanks @pmario * Fix typo in tiddlywebadaptor * Improve presentation of errors See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573695267 * Add docs for getTiddlerRevision() * Remove unused error animation * Update comment for GET /recipes/default/tiddlers/tiddlers.json * Optimise SVG cloud image * Add optional list of allowed filters for get all tiddlers route An attempt to address @Arlen22's concern here: https://github.com/Jermolene/TiddlyWiki5/pull/4373#pullrequestreview-342146190 * Fix network error alert text translatability * Fix error code and logging for GET /recipes/default/tiddlers/tiddlers.json Thanks @Arlen22 * Flip GET /recipes/default/tiddlers/tiddlers.json allowed filter handling to be secure by default * Validate updates received from getUpdatedTiddlers() * Add syncer method to force loading of a tiddler from the server * Remove the release note update to remove the merge conflict * Fix crash when there's no config section in the tiddlywiki.info file * Use config tiddler title to check filter query (merge into fix-syncer) (#4478) * Use config tiddler title to check filter query * Create config-tiddlers-filter.tid * Add config switch to enable all filters on GET /recipes/default/tiddlers/tiddlers.json And update docs * Fix bug when deleting a tiddler with a shadow Reported by @kookma at https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-604027528 Co-authored-by: jed <inmysocks@fastmail.com> Co-authored-by: Arlen22 <arlenbee@gmail.com>
2020-03-30 14:24:05 +00:00
},
callback: function(err,data) {
// Check for errors
if(err) {
return callback(err);
}
// Process the tiddlers to make sure the revision is a string
var tiddlers = JSON.parse(data);
for(var t=0; t<tiddlers.length; t++) {
tiddlers[t] = self.convertTiddlerFromTiddlyWebFormat(tiddlers[t]);
}
// Invoke the callback with the skinny tiddlers
callback(null,tiddlers);
// If Browswer Storage tiddlers were cached on reloading the wiki, add them after sync from server completes in the above callback.
if($tw.browserStorage && $tw.browserStorage.isEnabled()) {
$tw.browserStorage.addCachedTiddlers();
}
}
});
};
/*
Save a tiddler and invoke the callback with (err,adaptorInfo,revision)
*/
TiddlyWebAdaptor.prototype.saveTiddler = function(tiddler,callback,options) {
var self = this;
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
if(this.isReadOnly) {
return callback(null);
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
}
$tw.utils.httpRequest({
url: this.host + "recipes/" + encodeURIComponent(this.recipe) + "/tiddlers/" + encodeURIComponent(tiddler.fields.title),
type: "PUT",
headers: {
"Content-type": "application/json"
},
data: this.convertTiddlerToTiddlyWebFormat(tiddler),
callback: function(err,data,request) {
if(err) {
return callback(err);
}
//If Browser-Storage plugin is present, remove tiddler from local storage after successful sync to the server
if($tw.browserStorage && $tw.browserStorage.isEnabled()) {
$tw.browserStorage.removeTiddlerFromLocalStorage(tiddler.fields.title)
}
// Save the details of the new revision of the tiddler
var etag = request.getResponseHeader("Etag");
if(!etag) {
callback("Response from server is missing required `etag` header");
} else {
var etagInfo = self.parseEtag(etag);
// Invoke the callback
callback(null,{
bag: etagInfo.bag
},etagInfo.revision);
}
}
});
};
/*
Load a tiddler and invoke the callback with (err,tiddlerFields)
*/
TiddlyWebAdaptor.prototype.loadTiddler = function(title,callback) {
var self = this;
$tw.utils.httpRequest({
url: this.host + "recipes/" + encodeURIComponent(this.recipe) + "/tiddlers/" + encodeURIComponent(title),
callback: function(err,data,request) {
if(err) {
return callback(err);
}
// Invoke the callback
2013-11-08 20:18:26 +00:00
callback(null,self.convertTiddlerFromTiddlyWebFormat(JSON.parse(data)));
}
});
};
/*
Delete a tiddler and invoke the callback with (err)
options include:
tiddlerInfo: the syncer's tiddlerInfo for this tiddler
*/
TiddlyWebAdaptor.prototype.deleteTiddler = function(title,callback,options) {
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
var self = this;
if(this.isReadOnly) {
return callback(null);
Module-ize server routes, add static file support and other enhancements(#2679) * Module-ize server routes and add static file support (#2510) * Refactor server routes to modules New module type: serverroute Caveats: Loading order is not deterministic but this would only matter if two route modules attempted to use the same path regexp (that would be silly). * Add static assets plugin This plugin allows the node server to fetch static assets in the /assets directory. I felt that this was a feature that goes above the core functionality. That is why I added it as a plugin. with the modular route extensions this was a breeze. * Add serverroute description to ModuleTypes * Coding standards tweaks * Fix filename typo * Move support for attachments from a plugin into the core * Missing "else" * Refactor server handling * Introduce a new named parameter scheme for commands * Move the SimpleServer class into it's own module * Deprecate the --server command because of the unwieldy syntax * Add a new --listen command using the new syntax For example: tiddlywiki mywiki --listen host:0.0.0.0 port:8090 * Add check for unknown parameters * Add support for multiple basic authentication credentials in a CSV file Beware: Passwords are stored in plain text. If that's a problem, use an authenticating proxy and the trusted header authentication approach. * Refactor module locations * Rename "serverroute" module type to "route" * Remove support for verifying optional named command parameters The idea was to be able to flag unknown parameter names, but requiring a command to pre-specify all the parameter names makes it harder for (say) the listen command to be extensible so that plugins can add new optional parameters that they handle. (This is particularly in the context of work in progress to encapsulate authenticators into their own modules). * Refactor the two authenticators into separate modules and add support for authorization * Correct mistaken path.join vs. path.resolve See https://stackoverflow.com/a/39836259 * Docs for the named command parameters I'd be grateful if anyone with sufficient Windows experience could confirm that the note about double quotes in "NamedCommandParameters" is correct. * Be consistent about lower case parameter names * Do the right thing when we have a username but no password With a username parameter but no password parameter we'll attribute edits to that username, but not require authentication. * Remove obsolete code * Add support for requiring authentication without restricting the username * Refactor authorization checks * Return read_only status in /status response * Fix two code typos * Add basic support for detecting readonly status and avoiding write errors We now have syncadaptors returning readonly status and avoid attempting to write to the server if it's going to fail * Add readonly-styles We hide editing-related buttons in read only mode I've made this part of the tiddlyweb plugin but I think a case could be made for putting it into the core. * Add custom request header as CSRF mitigation By default we require the header X-Requested-With to be set to TiddlyWiki. Can be overriden by setting csrfdisable to "yes" See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers * Add support for HTTPS * First pass at a route for serving rendered tiddlers cc @Drakor * Tweaks to the single tiddler static view Adding a simple sidebar * Switch to "dash" separated parameter names * Typo * Docs: Update ServerCommand and ListenCommand * First pass at docs for the new web server stuff Writing the docs is turning out to be quite an undertaking, much harder than writing the code! * Get rid of extraneous paragraphs in static renderings * Rejig anonymous user handling Now we can support wikis that are read-only for anonymous access, but allow a user to login for read/write access. * More docs Slowly getting there... * Static tiddler rendering: Fix HTML content in page title * Docs updates * Fix server command parameter names Missed off 30ce7ea * Docs: Missing quotes * Avoid inadvertent dependency on Node.js > v9.6.0 The listenOptions parameter of the plain HTTP version of CreateServer was only introduced in v9.6.0 cc @Drakor @pmario * Typo
2018-07-18 15:54:43 +00:00
}
2014-01-26 20:59:30 +00:00
// If we don't have a bag it means that the tiddler hasn't been seen by the server, so we don't need to delete it
Fix syncer to handler errors properly (#4373) * First commit * Add throttling of saves Now we refuse to save a tiddler more often than once per second. * Wait for a timeout before trying again after an error * Modest optimisations of isDirty() method * Synchronise system tiddlers and deletions from the server Fixes two long-standing issues: * Changes to system tiddlers are not synchronised from the server to the browser * Deletions of tiddlers on the server are not propagated to browser clients * Make sure we update the dirty status even if there isn't a task to perform * Replace save-wiki button with popup sync menu * Remove the "Server" control panel tab We don't need it with the enhanced sync dropdown * Add indentation to the save-wiki button * Fix spacing in dropdown menu items * Switch between cloud icons according to dirty status * Add a menu item to copy syncer logs to the clipboard * Improve animated icon * Remove indentation from save-wiki button @pmario the annoying thing is that using `\trim whitespace` trims significant whitespace too, so it means we have to use <$text text=" "/> when we need a space that won't be trimmed. For the moment, I've removed the indentation but will keep thinking about it. * Further icon, UI and copy text tweaks Move the icons and styles from the core into the TiddlyWeb plugin * Clean up PR diff * Tweak animation durations * Break the actions from the syncer dropdown into separate tiddlers @pmario I think this makes things a bit easier to follow * Refactor syncadaptor creation and logging The goal is for the syncadaptor to be able to log to the same logger as the syncer, so that the "copy syncer logs to clipboard" data is more useful. * Don't transition the dirty indicator container colour, just the SVG's colour * Only trigger a sync for changes to tiddlers we're interested in Otherwise it is triggered by the creation of the alert tiddlers used to display errors. * Restore deleting local tiddlers removed from the server (I had commented it out for some testing and accidentally commited it). * Guard against missing adaptor info * We still need to trigger a timeout when there was no task to process * Avoid repeatedly polling for changes Instead we only trigger a timeout call at if there is a pending task (ie a tiddler that has changed but isn't yet old enough to save). * Lazy loading: include skinny versions of lazily loaded tiddlers in the index.html * Introduce _is_skinny field for indicating that a tiddler is subject to lazy loading * Remove savetrail plugin from prerelease It doesn't yet work with the new syncer * Make the savetrail plugin work again * Clear outstanding alerts when synchronisation is restored * Logger: only remove alerts from the same component Missed off 9f5c0de07 * Make the saving throttle interval configurable (#4385) After switching Bob to use the core syncer the throttle interval makes saving feel very sluggish compared to the message queue setup that I had before. The editing lock that I use to prevent conflicts with multiple users doesn't go away until the save is completed, and with the 1 second delay it means that if you edit a tiddler and save it than you have to wait one second before you can edit it again. * Tweaks to appearance of alerts * Exclude temp tiddlers from offline snapshots Otherwise alerts will persist * Tweak appearance of status line in dropdown * Update release note * Web server: Don't include full path in error messages Fixes #3724 * In change event handler check for deletions * Disable the official plugin library when the tiddlyweb plugin is loaded * Hide error details from browser for /files/ route See https://github.com/Jermolene/TiddlyWiki5/issues/3724#issuecomment-565702492 -- thanks @pmario * Revert all the changes to the relationship between the syncer and the syncadaptor Previously we had some major rearrangements to make it possible for the syncadaptor to route it's logging to the logger used by the syncer. The motivation is so that the "copy logs to clipboard" button is more useful. On reflection, changing the interface this drastically is undesirable from a backwards compatibility perspective, so I'm going to investigate other ways to achieve the logger sharing * Make the tiddlyweb adaptor use the syncer's logger So that both are availavble when copying the syncer logs to the clipboard * Update release note * Support setting port=0 to get an OS assigned port Quite useful * Update code comment * UI: Use "Get latest changes from server" instead of "Refresh" * Add getUpdatedTiddlers() method to syncadaptor API See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573579495 * Refactor revision handling within the syncer Thanks @pmario * Fix typo in tiddlywebadaptor * Improve presentation of errors See https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-573695267 * Add docs for getTiddlerRevision() * Remove unused error animation * Update comment for GET /recipes/default/tiddlers/tiddlers.json * Optimise SVG cloud image * Add optional list of allowed filters for get all tiddlers route An attempt to address @Arlen22's concern here: https://github.com/Jermolene/TiddlyWiki5/pull/4373#pullrequestreview-342146190 * Fix network error alert text translatability * Fix error code and logging for GET /recipes/default/tiddlers/tiddlers.json Thanks @Arlen22 * Flip GET /recipes/default/tiddlers/tiddlers.json allowed filter handling to be secure by default * Validate updates received from getUpdatedTiddlers() * Add syncer method to force loading of a tiddler from the server * Remove the release note update to remove the merge conflict * Fix crash when there's no config section in the tiddlywiki.info file * Use config tiddler title to check filter query (merge into fix-syncer) (#4478) * Use config tiddler title to check filter query * Create config-tiddlers-filter.tid * Add config switch to enable all filters on GET /recipes/default/tiddlers/tiddlers.json And update docs * Fix bug when deleting a tiddler with a shadow Reported by @kookma at https://github.com/Jermolene/TiddlyWiki5/pull/4373#issuecomment-604027528 Co-authored-by: jed <inmysocks@fastmail.com> Co-authored-by: Arlen22 <arlenbee@gmail.com>
2020-03-30 14:24:05 +00:00
var bag = options.tiddlerInfo.adaptorInfo && options.tiddlerInfo.adaptorInfo.bag;
2014-01-26 20:59:30 +00:00
if(!bag) {
2021-02-04 16:11:07 +00:00
return callback(null,options.tiddlerInfo.adaptorInfo);
2014-01-26 20:59:30 +00:00
}
// Issue HTTP request to delete the tiddler
$tw.utils.httpRequest({
url: this.host + "bags/" + encodeURIComponent(bag) + "/tiddlers/" + encodeURIComponent(title),
type: "DELETE",
callback: function(err,data,request) {
if(err) {
return callback(err);
}
2021-02-04 16:11:07 +00:00
// Invoke the callback & return null adaptorInfo
callback(null,null);
}
});
};
/*
Convert a tiddler to a field set suitable for PUTting to TiddlyWeb
*/
TiddlyWebAdaptor.prototype.convertTiddlerToTiddlyWebFormat = function(tiddler) {
var result = {},
knownFields = [
"bag", "created", "creator", "modified", "modifier", "permissions", "recipe", "revision", "tags", "text", "title", "type", "uri"
];
if(tiddler) {
$tw.utils.each(tiddler.fields,function(fieldValue,fieldName) {
var fieldString = fieldName === "tags" ?
tiddler.fields.tags :
tiddler.getFieldString(fieldName); // Tags must be passed as an array, not a string
if(knownFields.indexOf(fieldName) !== -1) {
// If it's a known field, just copy it across
result[fieldName] = fieldString;
} else {
// If it's unknown, put it in the "fields" field
result.fields = result.fields || {};
result.fields[fieldName] = fieldString;
}
});
}
// Default the content type
2013-11-08 20:18:26 +00:00
result.type = result.type || "text/vnd.tiddlywiki";
return JSON.stringify(result,null,$tw.config.preferences.jsonSpaces);
};
/*
Convert a field set in TiddlyWeb format into ordinary TiddlyWiki5 format
*/
2013-11-08 20:18:26 +00:00
TiddlyWebAdaptor.prototype.convertTiddlerFromTiddlyWebFormat = function(tiddlerFields) {
var self = this,
result = {};
// Transfer the fields, pulling down the `fields` hashmap
$tw.utils.each(tiddlerFields,function(element,title,object) {
if(title === "fields") {
$tw.utils.each(element,function(element,subTitle,object) {
result[subTitle] = element;
});
} else {
result[title] = tiddlerFields[title];
}
});
// Make sure the revision is expressed as a string
if(typeof result.revision === "number") {
result.revision = result.revision.toString();
}
// Some unholy freaking of content types
if(result.type === "text/javascript") {
result.type = "application/javascript";
} else if(!result.type || result.type === "None") {
result.type = "text/x-tiddlywiki";
}
return result;
};
/*
Split a TiddlyWeb Etag into its constituent parts. For example:
```
"system-images_public/unsyncedIcon/946151:9f11c278ccde3a3149f339f4a1db80dd4369fc04"
```
Note that the value includes the opening and closing double quotes.
The parts are:
```
<bag>/<title>/<revision>:<hash>
```
*/
TiddlyWebAdaptor.prototype.parseEtag = function(etag) {
var firstSlash = etag.indexOf("/"),
lastSlash = etag.lastIndexOf("/"),
colon = etag.lastIndexOf(":");
if(firstSlash === -1 || lastSlash === -1 || colon === -1) {
return null;
} else {
return {
bag: $tw.utils.decodeURIComponentSafe(etag.substring(1,firstSlash)),
title: $tw.utils.decodeURIComponentSafe(etag.substring(firstSlash + 1,lastSlash)),
revision: etag.substring(lastSlash + 1,colon)
};
}
};
if($tw.browser && document.location.protocol.substr(0,4) === "http" ) {
exports.adaptorClass = TiddlyWebAdaptor;
}
})();