default indieauth profile entry to https if scheme not specified
[squeep-authentication-module] / lib / template / login-html.js
index 7d059e0d505caf4d4fb503f554dcd91d9d05ccc3..d6a45f5be36053cc4e2b96f2ac6fde479b1fdf50 100644 (file)
@@ -15,6 +15,7 @@ function indieAuthSection(ctx, options) {
 \t\t\t\t\t\t<legend>IndieAuth</legend>
 \t\t\t\t\t\t<label for="me">Profile URL:</label>
 \t\t\t\t\t\t<input id="me" name="me" type="url" size="40" placeholder="https://example.com/my_profile_url" value="" autofocus>
+\t\t\t\t\t\t<input type="hidden" name="me_auto_scheme">
 \t\t\t\t\t\t<button>Login</button>
 ${indieAuthBlurb}
 \t\t\t\t\t</fieldset>
@@ -24,6 +25,44 @@ ${indieAuthBlurb}
 }
 
 
+/**
+ * Default all URL inputs to https if scheme not specified,
+ * and set a flag if that happened.
+ * From https://aaronparecki.com/2019/05/13/2/https
+ */
+function indieAuthURLTrySecureFirstScript(ctx, options) {
+  const showIndieAuthForm = options.authnEnabled.includes('indieAuth');
+  return showIndieAuthForm ? `
+<script>
+document.addEventListener('DOMContentLoaded', function() {
+  function addDefaultScheme(target) {
+    if (target.value.match(/^(?!https?:).+\\..+/)) {
+      const autoSchemeField = document.querySelector('input[name=' + target.getAttribute('name') + '_auto_scheme]');
+      let scheme;
+      if (autoSchemeField) {
+        scheme = 'https://';
+        autoSchemeField.value = '1';
+      } else {
+        scheme = 'http://';
+      }
+      target.value = scheme + target.value;
+    }
+  }
+  const elements = document.querySelectorAll('input[type=url]');
+  Array.prototype.forEach.call(elements, function (el, i) {
+    el.addEventListener('blur', function(e) {
+      addDefaultScheme(e.target);
+    });
+    el.addEventListener('keydown', function(e) {
+      if (e.keyCode === 13) {
+        addDefaultScheme(e.target);
+      }
+    });
+  });
+});
+</script>` : '';
+}
+
 const userAuthn = ['argon2', 'pam', 'DEBUG_ANY'];
 function userSection(ctx, options) {
   const userBlurb = (options.userBlurb || []).map((x) => '\t'.repeat(6) + x).join('\n');
@@ -78,6 +117,7 @@ module.exports = (ctx, options) => {
   };
   const mainContent = [
     ...(options.authenticator.loginBlurb || []),
+    indieAuthURLTrySecureFirstScript(ctx, htmlOptions),
     indieAuthSection(ctx, htmlOptions),
     userSection(ctx, htmlOptions),
   ];