-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Typescriptify & use service worker for MSC3916 authentication #27326
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
Merged
Merged
Changes from 3 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
69817ca
Typescriptify & use service worker for MSC3916 authentication
turt2live 296c82c
appease the linter
turt2live 8542ce2
appease jest
turt2live b333b29
appease linter
turt2live 6cf7dca
Merge branch 'develop' into travis/msc3916
turt2live af1ba39
Get the access token directly
turt2live 9494257
Add a bit of jitter
turt2live 7d63b90
Merge remote-tracking branch 'origin/develop' into travis/msc3916
turt2live 8067197
Improve legibility, use factored-out functions for pickling
turt2live ea7e8fb
Add docs
turt2live d0dcf89
Appease the linter
turt2live 3fa2a42
Merge remote-tracking branch 'origin/develop' into travis/msc3916
turt2live 80dd415
Document risks of postMessage
turt2live 0395ee4
Split service worker post message handling out to function
turt2live 2ad00c0
Move registration to async function
turt2live 0951fe7
Use more early returns
turt2live c20d5f1
Thanks(?), WebStorm
turt2live 3947d90
Handle case of no access token for /versions
turt2live 7d9e7d6
Appease linter
turt2live d4efdf2
Merge branch 'develop' into travis/msc3916
turt2live 37e3dfd
Apply suggestions from code review
turt2live 0d5e2a9
Remove spurious try/catch
turt2live ec159a3
Factor out fetch config stuff
turt2live 310284b
Merge branch 'develop' into travis/msc3916
turt2live b80adc5
Apply suggestions from code review
turt2live cdbfd80
Merge branch 'develop' into travis/msc3916
turt2live a57c111
Finish applying code review suggestions
turt2live File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| const serverSupportMap: { | ||
| [serverUrl: string]: { | ||
| supportsMSC3916: boolean; | ||
| cacheExpires: number; | ||
| }; | ||
| } = {}; | ||
|
|
||
| const credentialStore: { | ||
| [serverUrl: string]: string; | ||
| } = {}; | ||
|
|
||
| // We skipWaiting() to update the service worker more frequently, particularly in development environments. | ||
| // @ts-expect-error - service worker types are not available. See 'fetch' event handler. | ||
| skipWaiting(); | ||
|
|
||
| self.addEventListener("message", (event) => { | ||
Check failureCode scanning / SonarCloud Origins should be verified during cross-origin communications
<!--SONAR_ISSUE_KEY:AY7PWlWeuP8G6MXDcCy--->Verify the origin of the received message. <p>See more on <a href="https://sonarcloud.io/project/issues?id=element-web&issues=AY7PWlWeuP8G6MXDcCy-&open=AY7PWlWeuP8G6MXDcCy-&pullRequest=27326">SonarCloud</a></p>
|
||
| if (event.data?.type !== "credentials") return; // ignore | ||
| credentialStore[event.data.homeserverUrl] = event.data.accessToken; | ||
| console.log( | ||
| `[Service Worker] Updated access token for ${event.data.homeserverUrl} (accessToken? ${Boolean(event.data.accessToken)})`, | ||
| ); | ||
| }); | ||
|
|
||
| // @ts-expect-error - getting types to work for this is difficult, so we anticipate that "addEventListener" doesn't | ||
| // have a valid signature. | ||
| self.addEventListener("fetch", (event: FetchEvent) => { | ||
| // This is the authenticated media (MSC3916) check, proxying what was unauthenticated to the authenticated variants. | ||
|
|
||
| if (event.request.method !== "GET") { | ||
| return; // not important to us | ||
| } | ||
|
|
||
| // Note: ideally we'd keep the request headers and etc, but in practice we can't even see those details. | ||
|
turt2live marked this conversation as resolved.
Outdated
|
||
| // See https://stackoverflow.com/a/59152482 | ||
| let url = event.request.url; | ||
|
|
||
| // We only intercept v3 download and thumbnail requests as presumably everything else is deliberate. | ||
| // For example, `/_matrix/media/unstable` or `/_matrix/media/v3/preview_url` are something well within | ||
| // the control of the application, and appear to be choices made at a higher level than us. | ||
| if (url.includes("/_matrix/media/v3/download") || url.includes("/_matrix/media/v3/thumbnail")) { | ||
|
turt2live marked this conversation as resolved.
Outdated
|
||
| // We need to call respondWith synchronously, otherwise we may never execute properly. This means | ||
| // later on we need to proxy the request through if it turns out the server doesn't support authentication. | ||
| event.respondWith( | ||
| (async (): Promise<Response> => { | ||
| // Figure out which homeserver we're communicating with | ||
| const csApi = url.substring(0, url.indexOf("/_matrix/media/v3")); | ||
|
|
||
| // Locate our access token, and populate the fetchConfig with the authentication header. | ||
| const accessToken = credentialStore[csApi]; | ||
| let fetchConfig: { headers?: { [key: string]: string } } = {}; | ||
| if (accessToken) { | ||
| fetchConfig = { | ||
| headers: { | ||
| Authorization: `Bearer ${accessToken}`, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| // Update or populate the server support map using a (usually) authenticated `/versions` call. | ||
| if (!serverSupportMap[csApi] || serverSupportMap[csApi].cacheExpires <= new Date().getTime()) { | ||
| const versions = await (await fetch(`${csApi}/_matrix/client/versions`, fetchConfig)).json(); | ||
| serverSupportMap[csApi] = { | ||
| supportsMSC3916: Boolean(versions?.unstable_features?.["org.matrix.msc3916"]), | ||
| cacheExpires: new Date().getTime() + 2 * 60 * 60 * 1000, // 2 hours from now | ||
| }; | ||
| } | ||
|
|
||
| // If we have server support (and a means of authentication), rewrite the URL to use MSC3916 endpoints. | ||
| if (serverSupportMap[csApi].supportsMSC3916 && accessToken) { | ||
| // Currently unstable only. | ||
| url = url.replace(/\/media\/v3\/(.*)\//, "/client/unstable/org.matrix.msc3916/media/$1/"); | ||
| } // else by default we make no changes | ||
|
|
||
| // Add authentication and send the request. We add authentication even if MSC3916 endpoints aren't | ||
| // being used to ensure patches like this work: | ||
| // https://github.com/matrix-org/synapse/commit/2390b66bf0ec3ff5ffb0c7333f3c9b239eeb92bb | ||
| return fetch(url, fetchConfig); | ||
| })(), | ||
| ); | ||
| } | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.