Carbon/src/js/login.js

217 lines
5.1 KiB
JavaScript
Raw Normal View History

const tippy = require("tippy.js");
2020-10-23 14:15:14 +00:00
const {q, ElemJS, ejs} = require("./basic.js")
2020-10-23 16:04:02 +00:00
const {S_RE_DOMAIN, S_RE_IPV6, S_RE_IPV4} = require("./re.js")
2020-10-21 06:33:36 +00:00
const password = q("#password")
2020-10-23 16:04:02 +00:00
// A regex matching a lossy MXID
// Groups:
// 1: username/localpart
// MAYBE WITH
// 2: hostname/serverpart
// 3: domain
// OR
// 4: IP address
// 5: IPv4 address
// OR
// 6: IPv6 address
// MAYBE WITH
// 7: port number
2020-10-24 09:52:05 +00:00
const RE_LOSSY_MXID = new RegExp(`^@?([a-z0-9._=-]+?)(?::((?:(${S_RE_DOMAIN})|((${S_RE_IPV4})|(\\[${S_RE_IPV6}])))(?::(\\d+))?))?$`)
2020-10-23 16:04:02 +00:00
window.RE_LOSSY_MXID = RE_LOSSY_MXID
2020-10-21 06:33:36 +00:00
class Username extends ElemJS {
2020-10-23 16:04:02 +00:00
constructor(homeserver) {
2020-10-21 06:33:36 +00:00
super(q("#username"))
2020-10-23 16:04:02 +00:00
this.homeserver = homeserver;
2020-10-21 06:33:36 +00:00
this.on("change", this.updateServer.bind(this))
}
isValid() {
2020-10-23 16:04:02 +00:00
return !!this.element.value.match(RE_LOSSY_MXID)
2020-10-21 06:33:36 +00:00
}
getUsername() {
2020-10-23 16:04:02 +00:00
return this.element.value.match(RE_LOSSY_MXID)[1]
2020-10-21 06:33:36 +00:00
}
getServer() {
2020-10-23 16:04:02 +00:00
const server = this.element.value.match(RE_LOSSY_MXID)
if (server && server[2]) return server[2]
2020-10-21 06:33:36 +00:00
else return null
}
updateServer() {
if (!this.isValid()) return
2020-10-23 16:04:02 +00:00
if (this.getServer()) this.homeserver.suggest(this.getServer())
2020-10-21 06:33:36 +00:00
}
}
2020-10-23 16:04:02 +00:00
class Homeserver extends ElemJS {
constructor() {
super(q("#homeserver"));
this.tippy = tippy.default(q("#homeserver-question"), {
content: q("#homeserver-popup-template").innerHTML,
allowHTML: true,
interactive: true,
interactiveBorder: 10,
trigger: "mouseenter",
theme: "carbon",
arrow: tippy.roundArrow,
})
2020-10-23 16:04:02 +00:00
}
suggest(value) {
this.element.placeholder = value
}
getServer() {
return this.element.value || this.element.placeholder;
}
}
2020-10-21 06:33:36 +00:00
2020-10-21 07:23:51 +00:00
class Feedback extends ElemJS {
constructor() {
super(q("#feedback"))
this.loading = false
this.loadingIcon = ejs("span").class("loading-icon")
this.messageSpan = ejs("span")
this.child(this.messageSpan)
}
setLoading(state) {
if (this.loading && !state) {
this.loadingIcon.remove()
} else if (!this.loading && state) {
this.childAt(0, this.loadingIcon)
}
this.loading = state
}
2020-10-21 17:22:23 +00:00
message(content, isError) {
this.removeClass("form-feedback")
this.removeClass("form-error")
if (content) this.class("form-feedback")
if (isError) this.class("form-error")
2020-10-21 17:22:23 +00:00
2020-10-21 07:23:51 +00:00
this.messageSpan.text(content)
}
}
2020-10-21 06:33:36 +00:00
class Form extends ElemJS {
2020-10-23 16:04:02 +00:00
constructor(username, feedback, homeserver) {
2020-10-21 06:33:36 +00:00
super(q("#form"))
this.processing = false
2020-10-23 16:04:02 +00:00
this.username = username
this.feedback = feedback
this.homeserver = homeserver
2020-10-21 06:33:36 +00:00
this.on("submit", this.submit.bind(this))
}
async submit() {
if (this.processing) return
this.processing = true
2020-10-23 16:04:02 +00:00
if (!this.username.isValid()) return this.cancel("Username is not valid.")
2020-10-21 06:33:36 +00:00
// Resolve homeserver address
2020-10-21 19:11:45 +00:00
let domain
try {
2020-10-23 16:04:02 +00:00
domain = await this.findHomeserver(this.homeserver.getServer())
} catch (e) {
2020-10-21 19:11:45 +00:00
return this.cancel(e.message)
2020-10-21 06:33:36 +00:00
}
// Request access token
this.status("Logging in...")
2020-10-21 19:11:45 +00:00
const root = await fetch(`${domain}/_matrix/client/r0/login`, {
2020-10-21 06:33:36 +00:00
method: "POST",
body: JSON.stringify({
type: "m.login.password",
2020-10-23 16:04:02 +00:00
user: this.username.getUsername(),
2020-10-21 06:33:36 +00:00
password: password.value
})
}).then(res => res.json())
if (!root.access_token) {
if (root.error) {
this.cancel(`Server said: ${root.error}`)
} else {
this.cancel("Login mysteriously failed.")
console.error(root)
}
return
}
localStorage.setItem("mx_user_id", root.user_id)
2020-10-21 19:11:45 +00:00
localStorage.setItem("domain", domain)
2020-10-21 06:33:36 +00:00
localStorage.setItem("access_token", root.access_token)
location.assign("../")
2020-10-21 06:33:36 +00:00
}
2020-10-21 19:11:45 +00:00
async findHomeserver(address, maxDepth = 5) {
2020-10-22 07:14:58 +00:00
//Protects from servers sending us on a redirect loop
2020-10-21 19:11:45 +00:00
maxDepth--
2020-10-22 07:14:58 +00:00
if (maxDepth <= 0) throw new Error(`Failed to look up homeserver, maximum search depth reached`)
2020-10-22 07:14:58 +00:00
//Normalise the address
2020-10-21 19:11:45 +00:00
if (!address.match(/^https?:\/\//)) {
console.warn(`${address} doesn't specify the protocol, assuming https`)
address = "https://" + address
}
address = address.replace(/\/*$/, "")
2020-10-21 19:11:45 +00:00
this.status(`Looking up homeserver... trying ${address}`)
2020-10-21 19:19:17 +00:00
// Check if we found the actual matrix server
2020-10-23 08:51:04 +00:00
try {
const versionsReq = await fetch(`${address}/_matrix/client/versions`)
if (versionsReq.ok) {
const versions = await versionsReq.json()
if (Array.isArray(versions.versions)) return address
}
} catch (e) {}
2020-10-22 07:14:58 +00:00
// Find the next matrix server in the chain
2020-10-21 19:11:45 +00:00
const root = await fetch(`${address}/.well-known/matrix/client`).then(res => res.json()).catch(e => {
console.error(e)
2020-10-21 19:11:45 +00:00
throw new Error(`Failed to look up server ${address}`)
})
let nextAddress = root["m.homeserver"].base_url
nextAddress = nextAddress.replace(/\/*$/, "")
if (address === nextAddress) {
throw new Error(`Failed to look up server ${address}, /.well-known/matrix/client found a redirect loop`);
}
return this.findHomeserver(nextAddress, maxDepth)
}
2020-10-21 06:33:36 +00:00
status(message) {
2020-10-23 16:04:02 +00:00
this.feedback.setLoading(true)
this.feedback.message(message)
2020-10-21 06:33:36 +00:00
}
cancel(message) {
this.processing = false
2020-10-23 16:04:02 +00:00
this.feedback.setLoading(false)
this.feedback.message(message, true)
2020-10-21 06:33:36 +00:00
}
}
2020-10-23 16:04:02 +00:00
const homeserver = new Homeserver()
const username = new Username(homeserver)
const feedback = new Feedback()
const form = new Form(username, feedback, homeserver)