Files
itflow/js/http.js

265 lines
9.9 KiB
JavaScript

/**
* Drop-in replacements for itflowGet() and itflowPost().
*
* These keep jQuery's exact call shape - itflowGet(url, data, success, error) -
* so the ~28 existing call sites did not have to be restructured when jQuery
* was removed. Every one of them uses the plain callback form; none chained
* .done()/.fail() or passed a dataType, so nothing else is reproduced here.
*
* The success callback receives the raw response TEXT, matching jQuery's
* behaviour when the server does not send a JSON content type. Several call
* sites do their own JSON.parse(), so returning a parsed object here would
* break them.
*/
/*
* What an editor holds, sent as a file. A web application firewall in front of ITFlow -
* ModSecurity, Cloudflare's, CrowdSec's with the OWASP Core Rule Set - takes a rich-text
* editor's HTML for an attack: an <img>, a pasted picture's data: address or a colour (style=)
* blocks the post, and a few soon ban whoever sent them. So each rich-text editor's and Markdown
* box's field, and what itflowPost() sends that looks like HTML, goes as one JSON file beside the
* form - itflow_fields[0], [1]..., which a firewall doesn't read as fields - and
* functions/request_fields.php puts them back before anything reads the post.
*
* - A form posted, or read with new FormData(form): its editors' fields, on its formdata event
* - itflowPost(): any value that looks like HTML
* - itflowFields.pack(formData, names) / itflowFields.body(data, names): a post built by hand
*
* Within what the server takes - this script's data-max-files and data-max-bytes (php.ini's
* max_file_uploads, and upload_max_filesize within post_max_size): what won't fit goes as
* fields, as before.
*/
var itflowFields = window.itflowFields || (function () {
'use strict';
var script = document.currentScript;
var attr = function (name, fallback) {
var value = script ? parseInt(script.getAttribute(name) || '', 10) : NaN;
return isNaN(value) ? fallback : value;
};
var maxFiles = attr('data-max-files', 20);
var maxBytes = attr('data-max-bytes', 2 * 1024 * 1024);
var FIELD = 'itflow_fields';
// What a firewall takes for HTML or script - a tag, a data: or javascript: address
var LOOKS_RICH = /<[a-z!\/?]|data:[a-z]|javascript:/i;
function rich(value) {
return typeof value === 'string' && LOOKS_RICH.test(value);
}
/*
* names' values taken out of formData into the JSON file - every value each has, in order -
* true when they were. A name with a file among its values stays, and so does everything
* when it won't fit.
*/
function pack(formData, names) {
if (!formData || typeof TextEncoder !== 'function' || typeof Blob !== 'function' || maxFiles < 1) {
return false;
}
var fields = [];
var moving = [];
names.forEach(function (name) {
if (!name || moving.indexOf(name) !== -1 || !formData.has(name)) {
return;
}
var values = formData.getAll(name);
if (values.some(function (value) { return typeof value !== 'string'; })) {
return;
}
moving.push(name);
values.forEach(function (value) {
fields.push([name, value]);
});
});
if (!moving.length) {
return false;
}
var bytes = new TextEncoder().encode(JSON.stringify({ v: 1, fields: fields }));
var size = Math.max(16 * 1024, maxBytes - 8 * 1024); // room for each part's headers
var parts = Math.ceil(bytes.length / size);
var files = 0;
formData.forEach(function (value) {
if (typeof value !== 'string' && value.name) {
files++; // a file input left empty doesn't count against max_file_uploads
}
});
if (files + parts > maxFiles || maxBytes < 16 * 1024) {
return false;
}
moving.forEach(function (name) {
formData.delete(name);
});
for (var i = 0; i < parts; i++) {
formData.append(FIELD + '[' + i + ']', new Blob([bytes.subarray(i * size, (i + 1) * size)], { type: 'application/json' }), 'fields-' + i + '.json');
}
return true;
}
/*
* A body to post: FormData with names' values - and any other that looks like HTML - in
* the file, or a URL-encoded string when there is nothing to move. data is an object, as
* itflowSerialize() takes, or URLSearchParams.
*/
function body(data, names) {
var params = data instanceof URLSearchParams ? data : new URLSearchParams(itflowSerialize(data));
var moving = (names || []).slice();
params.forEach(function (value, name) {
if (rich(value)) {
moving.push(name);
}
});
if (!moving.length || typeof FormData !== 'function') {
return params.toString();
}
var formData = new FormData();
params.forEach(function (value, name) {
formData.append(name, value);
});
return pack(formData, moving) ? formData : params.toString();
}
// A form's editors - the fields of its rich-text editors and Markdown boxes - when it posts
function editorNames(form) {
var names = [];
if (form && form.tagName === 'FORM' && (form.getAttribute('method') || '').toLowerCase() === 'post') {
form.querySelectorAll('textarea[name]').forEach(function (field) {
if (field.hasAttribute('data-markdown-input') || /(^|\s)tinymce/.test(field.className)
|| (window.tinymce && field.id && window.tinymce.get(field.id))) {
names.push(field.name);
}
});
}
return names;
}
/*
* A form with an editor posts as multipart/form-data, so the file can go with it - set as it
* is sent, before the browser reads how (and by js/tinymce_defaults.js as each editor starts,
* for a form a script sends with submit())
*/
function multipart(form) {
if (editorNames(form).length) {
form.enctype = 'multipart/form-data';
}
}
document.addEventListener('submit', function (e) {
multipart(e.target);
}, true);
// Its editors' fields into the file - as it posts, or is read with new FormData(form)
document.addEventListener('formdata', function (e) {
var names = editorNames(e.target);
if (names.length) {
pack(e.formData, names);
}
}, true);
return { pack: pack, body: body, rich: rich, multipart: multipart };
})();
window.itflowFields = itflowFields;
/** Serialise to PHP-style bracket params, the way jQuery did. */
function itflowSerialize(data) {
const params = new URLSearchParams();
(function add(prefix, value) {
if (Array.isArray(value)) {
value.forEach(function (v, i) {
add(prefix + '[' + i + ']', v);
});
} else if (value !== null && typeof value === 'object') {
Object.keys(value).forEach(function (k) {
add(prefix ? prefix + '[' + k + ']' : k, value[k]);
});
} else {
params.append(prefix, value === true ? 'true' : String(value));
}
})('', data || {});
return params.toString();
}
function itflowGet(url, data, success, error) {
const query = itflowSerialize(data);
const sep = url.indexOf('?') === -1 ? '?' : '&';
return fetch(query ? url + sep + query : url, {
method: 'GET',
credentials: 'same-origin'
})
.then(function (res) {
if (!res.ok) {
throw new Error('HTTP ' + res.status);
}
return res.text();
})
.then(function (text) {
if (typeof success === 'function') {
success(text);
}
return text;
})
.catch(function (err) {
if (typeof error === 'function') {
error(err);
} else {
console.error('itflowGet ' + url + ':', err);
}
});
}
function itflowPost(url, data, success, error) {
// What looks like HTML goes as a file, past a web application firewall (itflowFields above)
const body = itflowFields.body(data);
return fetch(url, {
method: 'POST',
headers: typeof body === 'string' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {},
credentials: 'same-origin',
body: body
})
.then(function (res) {
if (!res.ok) {
throw new Error('HTTP ' + res.status);
}
return res.text();
})
.then(function (text) {
if (typeof success === 'function') {
success(text);
}
return text;
})
.catch(function (err) {
if (typeof error === 'function') {
error(err);
} else {
console.error('itflowPost ' + url + ':', err);
}
});
}
/*
* fetch() options posting payload as JSON, to an endpoint that reads it with requestJson()
* (functions/request_fields.php) - in itflowFields' file when it holds HTML, so a web
* application firewall doesn't read it, else as the JSON body it always was.
*/
function itflowJsonPost(payload) {
const json = JSON.stringify(payload);
if (itflowFields.rich(json) && typeof FormData === 'function') {
const formData = new FormData();
formData.append('itflow_json', json);
if (itflowFields.pack(formData, ['itflow_json'])) {
return { method: 'POST', credentials: 'same-origin', body: formData };
}
}
return { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: json };
}
/** Kept for the kanban and invoice item-order callers, which use this name. */
function itflowPostForm(url, data) {
return itflowPost(url, data);
}