Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: MSC2918 initial implementation #235

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions src/matrix/SessionContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {Reconnector, ConnectionStatus} from "./net/Reconnector.js";
import {ExponentialRetryDelay} from "./net/ExponentialRetryDelay.js";
import {MediaRepository} from "./net/MediaRepository.js";
import {RequestScheduler} from "./net/RequestScheduler.js";
import {TokenRefresher} from "./net/TokenRefresher.js";
import {Sync, SyncStatus} from "./Sync.js";
import {Session} from "./Session.js";

Expand Down Expand Up @@ -120,7 +121,13 @@ export class SessionContainer {
lastUsed: clock.now()
};
log.set("id", sessionId);
await this._platform.sessionInfoStorage.add(sessionInfo);

if (loginData.refresh_token) {
sessionInfo.accessTokenExpiresAt = clock.now() + loginData.expires_in_ms;
sessionInfo.refreshToken = loginData.refresh_token;
}

await this._platform.sessionInfoStorage.add(sessionInfo);
} catch (err) {
this._error = err;
if (err.name === "HomeServerError") {
Expand Down Expand Up @@ -163,12 +170,42 @@ export class SessionContainer {
retryDelay: new ExponentialRetryDelay(clock.createTimeout),
createMeasure: clock.createMeasure
});

let accessToken;
if (sessionInfo.refreshToken) {
this._tokenRefresher = new TokenRefresher({
accessToken: sessionInfo.accessToken,
accessTokenExpiresAt: sessionInfo.accessTokenExpiresAt,
refreshToken: sessionInfo.refreshToken,
anticipation: 10 * 1000, // Refresh 10 seconds before the expiration
clock,
});
accessToken = this._tokenRefresher.accessToken;
} else {
accessToken = new ObservableValue(sessionInfo.accessToken);
}

const hsApi = new HomeServerApi({
homeServer: sessionInfo.homeServer,
accessToken: sessionInfo.accessToken,
accessToken,
request: this._platform.request,
reconnector: this._reconnector,
});
if (this._tokenRefresher) {
this._tokenRefresher.accessToken.subscribe(token => {
this._platform.sessionInfoStorage.updateAccessToken(sessionInfo.id, token);
});

this._tokenRefresher.accessTokenExpiresAt.subscribe(expiresAt => {
this._platform.sessionInfoStorage.updateAccessTokenExpiresAt(sessionInfo.id, expiresAt);
});

this._tokenRefresher.refreshToken.subscribe(token => {
this._platform.sessionInfoStorage.updateRefreshToken(sessionInfo.id, token);
});

await this._tokenRefresher.start(hsApi);
}
this._sessionId = sessionInfo.id;
this._storage = await this._platform.storageFactory.create(sessionInfo.id);
// no need to pass access token to session
Expand Down Expand Up @@ -306,6 +343,9 @@ export class SessionContainer {
this._storage.close();
this._storage = null;
}
if (this._tokenRefresher) {
this._tokenRefresher.stop();
}
}

async deleteSession() {
Expand Down
16 changes: 14 additions & 2 deletions src/matrix/net/HomeServerApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export class HomeServerApi {
return `${this._homeserver}/_matrix/client/r0${csPath}`;
}

_unstableUrl(feature, csPath) {
return `${this._homeserver}/_matrix/client/unstable/${feature}${csPath}`;
}

_baseRequest(method, url, queryParams, body, options, accessToken) {
const queryString = encodeQueryParams(queryParams);
url = `${url}?${queryString}`;
Expand Down Expand Up @@ -88,7 +92,7 @@ export class HomeServerApi {
}

_authedRequest(method, url, queryParams, body, options) {
return this._baseRequest(method, url, queryParams, body, options, this._accessToken);
return this._baseRequest(method, url, queryParams, body, options, this._accessToken.get());
}

_post(csPath, queryParams, body, options) {
Expand Down Expand Up @@ -127,7 +131,9 @@ export class HomeServerApi {
}

passwordLogin(username, password, initialDeviceDisplayName, options = null) {
return this._unauthedRequest("POST", this._url("/login"), null, {
return this._unauthedRequest("POST", this._url("/login"), {
"org.matrix.msc2918.refresh_token": "true"
}, {
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
Expand All @@ -138,6 +144,12 @@ export class HomeServerApi {
}, options);
}

refreshToken(token, options = null) {
return this._unauthedRequest("POST", this._unstableUrl("org.matrix.msc2918.refresh_token", "/refresh"), null, {
"refresh_token": token
}, options);
}

createFilter(userId, filter, options = null) {
return this._post(`/user/${encodeURIComponent(userId)}/filter`, null, filter, options);
}
Expand Down
78 changes: 78 additions & 0 deletions src/matrix/net/TokenRefresher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { ObservableValue } from "../../observable/ObservableValue.js";

export class TokenRefresher {
constructor({
refreshToken,
accessToken,
accessTokenExpiresAt,
anticipation,
clock,
}) {
this._refreshToken = new ObservableValue(refreshToken);
this._accessToken = new ObservableValue(accessToken);
this._accessTokenExpiresAt = new ObservableValue(accessTokenExpiresAt);
this._anticipation = anticipation;
this._clock = clock;
}

async start(hsApi) {
this._hsApi = hsApi;
if (this.needsRenewing) {
await this.renew();
}

this._renewingLoop();
}

stop() {
// TODO
}

get needsRenewing() {
const remaining = this._accessTokenExpiresAt.get() - this._clock.now();
const anticipated = remaining - this._anticipation;
return anticipated < 0;
}

async _renewingLoop() {
while (true) {
const remaining =
this._accessTokenExpiresAt.get() - this._clock.now();
const anticipated = remaining - this._anticipation;

if (anticipated > 0) {
this._timeout = this._clock.createTimeout(anticipated);
await this._timeout.elapsed();
}

await this.renew();
}
}

async renew() {
const response = await this._hsApi
.refreshToken(this._refreshToken.get())
.response();

if (response["refresh_token"]) {
this._refreshToken.set(response["refresh_token"]);
}

this._accessToken.set(response["access_token"]);
this._accessTokenExpiresAt.set(
this._clock.now() + response["expires_in_ms"]
);
}

get accessToken() {
return this._accessToken;
}

get accessTokenExpiresAt() {
return this._accessTokenExpiresAt;
}

get refreshToken() {
return this._refreshToken;
}
}
44 changes: 41 additions & 3 deletions src/matrix/sessioninfo/localstorage/SessionInfoStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@ export class SessionInfoStorage {
this._name = name;
}

getAll() {
_getAllSync() {
const sessionsJson = localStorage.getItem(this._name);
if (sessionsJson) {
const sessions = JSON.parse(sessionsJson);
if (Array.isArray(sessions)) {
return Promise.resolve(sessions);
return sessions;
}
}
return Promise.resolve([]);
return [];
}

async getAll() {
return this._getAllSync();
}

async updateLastUsed(id, timestamp) {
Expand All @@ -41,6 +45,40 @@ export class SessionInfoStorage {
}
}

// Update to the session tokens are all done synchronousely to avoid data races
updateAccessToken(id, accessToken) {
const sessions = this._getAllSync();
if (sessions) {
const session = sessions.find(session => session.id === id);
if (session) {
session.accessToken = accessToken;
localStorage.setItem(this._name, JSON.stringify(sessions));
}
}
}

updateAccessTokenExpiresAt(id, accessTokenExpiresAt) {
const sessions = this._getAllSync();
if (sessions) {
const session = sessions.find(session => session.id === id);
if (session) {
session.accessTokenExpiresAt = accessTokenExpiresAt;
localStorage.setItem(this._name, JSON.stringify(sessions));
}
}
}

updateRefreshToken(id, refreshToken) {
const sessions = this._getAllSync();
if (sessions) {
const session = sessions.find(session => session.id === id);
if (session) {
session.refreshToken = refreshToken;
localStorage.setItem(this._name, JSON.stringify(sessions));
}
}
}

async get(id) {
const sessions = await this.getAll();
if (sessions) {
Expand Down