/* Copyright 2022 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { type MatrixError } from "./errors.ts"; import { type Logger } from "../logger.ts"; import { type QueryDict } from "../utils.ts"; import { type ValidatedAuthMetadata } from "../oauth/discover.ts"; export type Body = Record | BodyInit; /** * Unencrypted access and (optional) refresh token */ export type AccessTokens = { /** * The new access token to use for authenticated requests */ accessToken: string; /** * The new refresh token to use for refreshing tokens, optional */ refreshToken?: string; /** * Approximate date when the access token will expire, optional */ expiry?: Date; }; /** * A callback function called when tokens are refreshed such that stored tokens can be updated with * the refreshed ones. */ export type TokenRefreshCallback = (newTokens: AccessTokens) => void; /** * Configuration required for {@link IHttpOpts} to allow the SDK to manage the full lifecycle of tokens for an * OAuth2-native session (as per MSC2965/MSC3861): discovering the delegated auth server's metadata, refreshing * access/refresh tokens, and revoking them (e.g. on logout). * * The SDK constructs the underlying OAuth2 client itself, lazily, the first time it is actually needed (so that, * for example, a client started with no network connection does not fail to ever set up token refresh). */ export interface OAuth2ClientConfig { /** The OAuth2 client ID this application is registered with the delegated auth server under. */ clientId: string; /** The device ID of the current session, used to scope refreshed/revoked tokens to this session. */ deviceId?: string; } /** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */ export interface IHttpOpts { /** * The function to invoke for HTTP requests, including those made to the OAuth 2.0 authorization server * when refreshing or revoking tokens. Defaults to the global `fetch`. */ fetchFn?: typeof globalThis.fetch; baseUrl: string; idBaseUrl?: string; prefix: string; extraParams?: QueryDict; accessToken?: string; /** * Used in conjunction with oauth2ClientConfig to attempt token refresh */ refreshToken?: string; /** * Callback called when tokens are refreshed. Must be supplied if refreshToken is supplied. */ onTokenRefresh?: TokenRefreshCallback; /** * Configuration needed to refresh (given refreshToken) and revoke (e.g. on logout) tokens for an * OAuth2-native session. Optional; if omitted, tokens will not be refreshed or revoked by the SDK. * authMetadataCallback must also be supplied to refresh tokens. */ oauth2ClientConfig?: OAuth2ClientConfig; /** * Discovers and validates the delegated auth server's metadata for the current homeserver. * Must be supplied along with oauth2ClientConfig in order to refresh tokens. * * @returns validated authentication metadata * @throws when delegated auth config is invalid or unreachable */ authMetadataCallback?: () => Promise; /** * Whether to use the HTTP Authorization header over the `access_token` query parameter * @deprecated as of v1.11 in https://spec.matrix.org/v1.17/client-server-api/#using-access-tokens */ useAuthorizationHeader?: boolean; // defaults to true /** For historical reasons, must be set to `true`. Will eventually be removed. */ onlyData?: boolean; localTimeoutMs?: number; /** Optional logger instance. If provided, requests and responses will be logged. */ logger?: Logger; } /** Options object for `FetchHttpApi.requestOtherUrl`. */ export interface BaseRequestOpts extends Pick { /** * map of additional request headers */ headers?: Record; abortSignal?: AbortSignal; /** * The maximum amount of time to wait before * timing out the request. If not specified, there is no timeout. */ localTimeoutMs?: number; keepAlive?: boolean; // defaults to false /** * By default, we will: * * * If the `body` is an object, JSON-encode it and set `Content-Type: application/json` in the * request headers (unless overridden by {@link headers}). * * * Set `Accept: application/json` in the request headers (again, unless overridden by {@link headers}). * * * Parse the response as JSON and return the parsed response. * * Setting this to `false` inhibits all three behaviors, and the response is instead parsed as a UTF-8 string. It * defaults to `true`, unless {@link rawResponseBody} is set. * * @deprecated Instead of setting this to `false`, set {@link rawResponseBody} to `true`. */ json?: boolean; /** * Setting this to `true` does two things: * * * Inhibits the automatic addition of `Accept: application/json` in the request headers. * * * Causes the raw response to be returned as a {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob|Blob} * instead of parsing it as JSON. */ rawResponseBody?: boolean; } export interface IRequestOpts extends BaseRequestOpts { /** * The alternative base url to use. * If not specified, uses this.opts.baseUrl */ baseUrl?: string; /** * The full prefix to use e.g. * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix. */ prefix?: string; // Set to true to prevent the request function from emitting a Session.logged_out event. // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response, // such as with token refreshes. inhibitLogoutEmit?: boolean; } export enum HttpApiEvent { SessionLoggedOut = "Session.logged_out", NoConsent = "no_consent", } export type HttpApiEventHandlerMap = { /** * Fires whenever the login session the JS SDK is using is no * longer valid and the user must log in again. * NB. This only fires when action is required from the user, not * when then login session can be renewed by using a refresh token. * @example * ``` * matrixClient.on("Session.logged_out", function(errorObj){ * // show the login screen * }); * ``` */ [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void; /** * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response * to a HTTP request. * @example * ``` * matrixClient.on("no_consent", function(message, contentUri) { * console.info(message + ' Go to ' + contentUri); * }); * ``` */ [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void; }; export interface UploadProgress { loaded: number; total: number; } export interface UploadOpts { /** * Name to give the file on the server. Defaults to file.name. */ name?: string; /** * Content-type for the upload. Defaults to * file.type, or applicaton/octet-stream. */ type?: string; /** * if false will not send the filename, * e.g for encrypted file uploads where filename leaks are undesirable. * Defaults to true. */ includeFilename?: boolean; /** * Optional. Called when a chunk of * data has been uploaded, with an object containing the fields `loaded` * (number of bytes transferred) and `total` (total size, if known). */ progressHandler?(progress: UploadProgress): void; abortController?: AbortController; } export interface Upload { loaded: number; total: number; promise: Promise; abortController: AbortController; } export interface UploadResponse { content_uri: string; } export type FileType = XMLHttpRequestBodyInit;