Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | import ConfigurationError from "../Exception/ConfigurationError";
import { DEFAULT_NEXTCLOUD_SERVER_FETCH_CONFIGURATION } from "../Interfaces/NextcloudServer/NextcloudServerFetchConfigurationInterface";
import { PassmanServerConnection } from "./PassmanServerConnection";
export class NextcloudServerError extends Error {
statusCode;
response;
constructor(message, statusCode, response) {
super(message);
this.statusCode = statusCode;
this.response = response;
}
}
export class NextcloudServer {
serverData;
logger;
persistence;
fetchConfiguration;
static getRequestCachePrefix = 'cache-getJson-';
/**
* Create NextcloudServer instance.
* @param serverData
* @param logger
* @param persistence
* @param fetchConfiguration
* @throws ConfigurationError
*/
constructor(serverData, logger, persistence, fetchConfiguration = DEFAULT_NEXTCLOUD_SERVER_FETCH_CONFIGURATION) {
this.serverData = serverData;
this.logger = logger;
this.persistence = persistence;
this.fetchConfiguration = fetchConfiguration;
if (!serverData.baseUrl.startsWith('https://') && !serverData.baseUrl.startsWith('http://')) {
this.logger.onThrow(new ConfigurationError('Base URL (or protocol) is invalid'));
}
if (serverData.token.length < 1) {
// Nextcloud does not accept passwords shorter than 10 characters be default; user policies may change this
this.logger.onThrow(new ConfigurationError('Password or token is invalid'));
}
}
getBaseUrl() {
return this.serverData.baseUrl;
}
setBaseUrl(value) {
if (!value.startsWith('https://') && !value.startsWith('http://')) {
this.logger.onThrow(new ConfigurationError('Base URL (or protocol) is invalid'));
}
this.serverData.baseUrl = value;
}
getUser() {
return this.serverData.user;
}
setUser(value) {
this.serverData.user = value;
}
getToken() {
return this.serverData.token;
}
setToken(value) {
this.serverData.token = value;
}
getApiUrl() {
return `${this.getBaseUrl()}/index.php/apps/${this.serverData.backendAppId ?? 'passman'}/api/v2/`;
}
/**
* Stable identifier of the connection this server represents.
*/
getConnectionId() {
return PassmanServerConnection.buildConnectionId(this.serverData);
}
getEncodedLogin() {
return btoa(this.getUser() + ":" + this.getToken());
}
setTemporaryBackendAppId(backendAppId) {
this.serverData.backendAppId = backendAppId;
}
/**
* Perform a fetch with the configured credentials/cache/redirect and optional request timeout.
* On network/abort failure, logs and invokes errorCallback, then returns undefined.
*
* Native `redirect: 'follow'` strips Authorization on cross-origin redirects (http to https is cross-origin).
* When that happens on the same host, we upgrade baseUrl and retry once against
* {@link Response.url} with the original headers.
*/
async fetchJson(url, init, errorCallback) {
const { credentials, cache, redirect, timeoutMs } = this.fetchConfiguration;
const requestInit = {
...init,
credentials,
cache,
redirect,
};
let timeoutId;
if (timeoutMs > 0) {
const controller = new AbortController();
requestInit.signal = controller.signal;
timeoutId = setTimeout(() => controller.abort(), timeoutMs);
}
try {
return await fetch(url, requestInit)
.then((res) => this.retryAfterAuthStrippingRedirect(url, requestInit, res))
.catch((err) => {
this.logPossibleTypeOrSyntaxParsingError(err);
errorCallback(err);
return undefined;
});
}
finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
}
}
/**
* If fetch followed a same-host cross-origin redirect (typically http to https), Authorization was stripped.
* Upgrade baseUrl and re-issue the request once against the final URL.
*/
async retryAfterAuthStrippingRedirect(requestUrl, init, res) {
if (!res.redirected || init.redirect === 'manual' || init.redirect === 'error') {
return res;
}
let from;
let to;
try {
from = new URL(requestUrl);
to = new URL(res.url);
}
catch {
return res;
}
if (from.origin === to.origin) {
return res;
}
if (from.hostname.toLowerCase() !== to.hostname.toLowerCase()) {
return res;
}
if (from.protocol === 'http:' && to.protocol === 'https:' && this.serverData.baseUrl.startsWith('http://')) {
this.setBaseUrl('https://' + this.serverData.baseUrl.slice('http://'.length));
}
return fetch(res.url, init);
}
/**
* @returns true if the response is an error state, false otherwise
*/
async handleResponseErrorState(res, errorCallback) {
if (res.status >= 400) {
/** possible error response "message" from the nextcloud api */
let apiMessage;
try {
// with code >=400 we cannot be sure that the response is valid JSON, so we cannot simply parse it
if (res.headers.get('Content-Type')?.includes('application/json')) {
const data = await res.json();
this.logger.onError(data.message ?? data);
if (typeof data.message === 'string' && data.message.length > 0) {
apiMessage = data.message;
}
}
else {
// log the raw response text for easier debugging
const text = await res.text();
this.logger.onError(text);
}
}
catch (error) {
this.logPossibleTypeOrSyntaxParsingError(error);
}
// prefer API message; statusText is often empty on HTTP/2
const userMessage = apiMessage || res.statusText?.trim();
errorCallback(new NextcloudServerError(userMessage, res.status, res));
return true;
}
return false;
}
/**
* Log a possible type or syntax parsing error.
* Does not throw an exception, nor errorCallback gets called.
* Accepts expected SyntaxError/TypeError (native Response.json) and other Error wrappers
* (e.g. node-fetch/cross-fetch FetchError) so the useful parse message is preserved.
* @param error
*/
logPossibleTypeOrSyntaxParsingError(error) {
const unknownErrorMessage = 'Unknown error while parsing response';
if (error instanceof Error) {
this.logger.onError(error.message ?? unknownErrorMessage);
}
else {
this.logger.onError(unknownErrorMessage);
// ignore the unexpected error, continue with the error callback
}
}
getJson = async (endpoint, errorCallback, getCachedIfPossible = false) => {
if (getCachedIfPossible) {
const cachedValue = await this.persistence.getRequestCacheHandler()?.get(NextcloudServer.getRequestCachePrefix + endpoint);
if (cachedValue && cachedValue !== '') {
try {
return JSON.parse(cachedValue);
}
catch (_) {
// ignore all exceptions, just continue with the non-cached request logic
}
}
}
const res = await this.fetchJson(this.getApiUrl() + endpoint, {
headers: {
Accept: 'application/json',
Authorization: `Basic ${this.getEncodedLogin()}`
},
}, errorCallback);
if (!res) {
// already handled by the fetch.catch block
return;
}
if (await this.handleResponseErrorState(res, errorCallback)) {
return;
}
try {
const jsonResponse = await res.json();
const requestCacheHandler = this.persistence.getRequestCacheHandler();
if (requestCacheHandler) {
await requestCacheHandler.set(NextcloudServer.getRequestCachePrefix + endpoint, JSON.stringify(jsonResponse));
}
return (jsonResponse);
}
catch (error) {
this.logPossibleTypeOrSyntaxParsingError(error);
errorCallback(new Error('Invalid JSON response'));
return;
}
};
deleteJson = async (endpoint, errorCallback) => {
const res = await this.fetchJson(this.getApiUrl() + endpoint, {
method: 'DELETE',
headers: {
Authorization: `Basic ${this.getEncodedLogin()}`
},
}, errorCallback);
if (!res) {
// already handled by the fetch.catch block
return;
}
if (await this.handleResponseErrorState(res, errorCallback)) {
return;
}
try {
return (await res.json());
}
catch (error) {
this.logPossibleTypeOrSyntaxParsingError(error);
errorCallback(new Error('Invalid JSON response'));
return;
}
};
/**
* Do a post request.
*
* @param endpoint
* @param data will be converted to a json string
* @param errorCallback
* @param method
*/
postJson = async (endpoint, data, errorCallback, method = 'POST') => {
const res = await this.fetchJson(this.getApiUrl() + endpoint, {
method: method,
headers: {
Accept: 'application/json',
Authorization: `Basic ${this.getEncodedLogin()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}, errorCallback);
if (!res) {
// already handled by the fetch.catch block
return;
}
if (await this.handleResponseErrorState(res, errorCallback)) {
return;
}
try {
return (await res.json());
}
catch (error) {
this.logPossibleTypeOrSyntaxParsingError(error);
errorCallback(new Error('Invalid JSON response'));
return;
}
};
}
|