@life-os/obsidian-web 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -2
- package/browser.cjs +527 -0
- package/download-archive.mjs +33 -0
- package/fs-queue.cjs +90 -0
- package/install.mjs +75 -0
- package/markdown-write.cjs +35 -0
- package/package.json +23 -4
- package/prepare.sh +94 -0
- package/request-url.cjs +108 -0
- package/server.cjs +299 -0
- package/skill/obsidian-web/SKILL.md +20 -0
- package/vault-switch.cjs +54 -0
- package/vault-ui.mjs +184 -0
package/fs-queue.cjs
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Keep Chromium's pending request queue bounded during the initial vault scan.
|
|
2
|
+
const metadata = new Set(['access', 'exists', 'realpath', 'readdir', 'stat', 'lstat']);
|
|
3
|
+
function createFileQueue(send, batchMetadata) {
|
|
4
|
+
const pending = [];
|
|
5
|
+
let active = 0;
|
|
6
|
+
let scheduled = false;
|
|
7
|
+
function schedule() {
|
|
8
|
+
if (!scheduled) {
|
|
9
|
+
scheduled = true;
|
|
10
|
+
queueMicrotask(drain);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function drain() {
|
|
14
|
+
scheduled = false;
|
|
15
|
+
while (active < 6 && pending.length) {
|
|
16
|
+
const first = pending.shift();
|
|
17
|
+
const group = [first];
|
|
18
|
+
if (batchMetadata && metadata.has(first.data.operation)) {
|
|
19
|
+
while (group.length < 128 && pending.length && metadata.has(pending[0].data.operation)) {
|
|
20
|
+
group.push(pending.shift());
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
active++;
|
|
24
|
+
void (async () => {
|
|
25
|
+
try {
|
|
26
|
+
if (group.length === 1) first.resolve(await send('fs', first.data, first.signal));
|
|
27
|
+
else {
|
|
28
|
+
const results = await send('metadata', group.map(item => item.data));
|
|
29
|
+
if (results.length !== group.length) throw Error('Incomplete filesystem response');
|
|
30
|
+
group.forEach((item, i) => item.resolve(results[i]));
|
|
31
|
+
}
|
|
32
|
+
} catch (error) {
|
|
33
|
+
group.forEach(item => item.reject(error));
|
|
34
|
+
} finally {
|
|
35
|
+
active--;
|
|
36
|
+
schedule();
|
|
37
|
+
}
|
|
38
|
+
})();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return (data, signal) => new Promise((resolve, reject) => {
|
|
42
|
+
pending.push({ data, signal, resolve, reject });
|
|
43
|
+
schedule();
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function postFileRequest(route, data, signal) {
|
|
47
|
+
const retryable = route === 'read-batch' || route === 'metadata' ||
|
|
48
|
+
metadata.has(data.operation) || data.operation === 'readFile' || data.operation === 'watchSnapshot';
|
|
49
|
+
const body = JSON.stringify(data);
|
|
50
|
+
for (let attempt = 0; ; attempt++) {
|
|
51
|
+
signal?.throwIfAborted();
|
|
52
|
+
try {
|
|
53
|
+
const response = await fetch('/_local/' + route, {
|
|
54
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Vault-UI': '1' },
|
|
55
|
+
body, signal,
|
|
56
|
+
});
|
|
57
|
+
if (!response.ok) throw Error('Local vault service returned ' + response.status);
|
|
58
|
+
return await response.json();
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof TypeError && data.operation === 'writeFile' && /\.md$/i.test(data.args[0])) {
|
|
61
|
+
// A lost response can follow a completed save. Check the exact bytes
|
|
62
|
+
// without replaying the write or changing a newer disk version.
|
|
63
|
+
const saved = await postFileRequest('fs', { operation: 'readFile', args: [data.args[0]] });
|
|
64
|
+
if (!saved.error && saved.revision && saved.value === data.args[1]) {
|
|
65
|
+
return { value: null, revision: saved.revision };
|
|
66
|
+
}
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
if (!retryable || !(error instanceof TypeError) || signal?.aborted || attempt >= 3) throw error;
|
|
70
|
+
await new Promise(resolve => setTimeout(resolve, 250 * 3 ** attempt));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Remap known revisions only after the filesystem confirms the move.
|
|
76
|
+
function moveRevisions(revisions, source, destination) {
|
|
77
|
+
if (source === destination) return;
|
|
78
|
+
const moved = [];
|
|
79
|
+
for (const [file, version] of revisions) {
|
|
80
|
+
if (file === source || file.startsWith(source + '/')) {
|
|
81
|
+
moved.push([destination + file.slice(source.length), version]);
|
|
82
|
+
revisions.delete(file);
|
|
83
|
+
} else if (file === destination || file.startsWith(destination + '/')) {
|
|
84
|
+
revisions.delete(file);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const [file, version] of moved) revisions.set(file, version);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { createFileQueue, metadata, postFileRequest, moveRevisions };
|
package/install.mjs
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { lstatSync, mkdirSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const source = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const binDirectory = process.env.VAULT_UI_BIN_DIR || path.join(homedir(), '.local/bin');
|
|
10
|
+
const skillDirectory = process.env.VAULT_UI_WORKBUDDY_SKILL_DIR || path.join(homedir(), '.workbuddy/skills');
|
|
11
|
+
const links = [
|
|
12
|
+
[binDirectory, 'obsidian-web', 'vault-ui.mjs'],
|
|
13
|
+
[binDirectory, 'vault-ui', 'vault-ui.mjs'],
|
|
14
|
+
[skillDirectory, 'obsidian-web', 'skill/obsidian-web'],
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
function needsLink(destination, target) {
|
|
18
|
+
const stat = lstatSync(destination, { throwIfNoEntry: false });
|
|
19
|
+
if (!stat) return true;
|
|
20
|
+
if (stat.isSymbolicLink() &&
|
|
21
|
+
path.resolve(path.dirname(destination), readlinkSync(destination)) === target) return false;
|
|
22
|
+
throw new Error('Check the existing file at the installation path ' + destination);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function install(archive) {
|
|
26
|
+
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
27
|
+
if (major < 22 || (major === 22 && minor < 16)) throw new Error('Node.js 22.16 or later is required');
|
|
28
|
+
const targets = links.map(([directory, filename, relative]) => ({
|
|
29
|
+
directory: path.resolve(directory),
|
|
30
|
+
destination: path.resolve(directory, filename),
|
|
31
|
+
target: path.join(source, relative),
|
|
32
|
+
}));
|
|
33
|
+
for (const { destination, target } of targets) needsLink(destination, target);
|
|
34
|
+
|
|
35
|
+
const prep = spawnSync('sh', [path.join(source, 'prepare.sh'), ...(archive ? [archive] : [])], { stdio: 'inherit' });
|
|
36
|
+
if (prep.error) throw prep.error;
|
|
37
|
+
if (prep.status !== 0) throw new Error('Could not prepare the Obsidian runtime. Check the error above and rerun the installer.');
|
|
38
|
+
|
|
39
|
+
const created = [];
|
|
40
|
+
try {
|
|
41
|
+
for (const { directory, destination, target } of targets) {
|
|
42
|
+
if (!needsLink(destination, target)) continue;
|
|
43
|
+
mkdirSync(directory, { recursive: true });
|
|
44
|
+
symlinkSync(target, destination);
|
|
45
|
+
created.push({ destination, target });
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
for (const { destination, target } of created.reverse()) {
|
|
49
|
+
try {
|
|
50
|
+
if (readlinkSync(destination) === target) unlinkSync(destination);
|
|
51
|
+
} catch {
|
|
52
|
+
// The incomplete link was already removed or replaced.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
const legacySkill = path.resolve(skillDirectory, 'vault-ui');
|
|
58
|
+
if (lstatSync(legacySkill, { throwIfNoEntry: false })?.isSymbolicLink() &&
|
|
59
|
+
path.resolve(skillDirectory, readlinkSync(legacySkill)) === path.join(source, 'skill/vault-ui')) {
|
|
60
|
+
unlinkSync(legacySkill);
|
|
61
|
+
}
|
|
62
|
+
for (const { destination } of targets) console.log(destination);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const args = process.argv.slice(2);
|
|
66
|
+
if (args.includes('--help') || args.length > 1 || args.some(argument => argument.startsWith('-'))) {
|
|
67
|
+
console.log('Usage: ./install.mjs [path to an Obsidian 1.14.4 .asar or official .asar.gz]');
|
|
68
|
+
if (!args.includes('--help')) process.exitCode = 1;
|
|
69
|
+
} else {
|
|
70
|
+
try { install(args[0]); }
|
|
71
|
+
catch (error) {
|
|
72
|
+
console.error(error.message);
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const { createHash } = require('node:crypto');
|
|
4
|
+
|
|
5
|
+
function revision(bytes) {
|
|
6
|
+
return createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function writeMarkdown(file, bytes, expectedRevision, conflicts) {
|
|
10
|
+
if (expectedRevision !== undefined) {
|
|
11
|
+
if (typeof expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(expectedRevision)) {
|
|
12
|
+
throw new Error('Invalid file revision');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
let current;
|
|
16
|
+
try {
|
|
17
|
+
current = fs.readFileSync(file);
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error.code !== 'ENOENT') throw error;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (!current || revision(current) !== expectedRevision) {
|
|
23
|
+
fs.mkdirSync(conflicts, { recursive: true, mode: 0o700 });
|
|
24
|
+
const directory = fs.mkdtempSync(path.join(conflicts, 'edit-'));
|
|
25
|
+
const recovery = path.join(directory, path.basename(file));
|
|
26
|
+
fs.writeFileSync(recovery, bytes, { mode: 0o600, flag: 'wx' });
|
|
27
|
+
throw Object.assign(Error('The note changed on disk. Your edit was saved to ' + recovery), { code: 'ESTALE' });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fs.writeFileSync(file, bytes);
|
|
32
|
+
return revision(bytes);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { revision, writeMarkdown };
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@life-os/obsidian-web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Open and edit local Obsidian vaults in your browser or AI client. An unofficial CLI by LifeOS.",
|
|
5
|
+
"bin": {
|
|
6
|
+
"obsidian-web": "./vault-ui.mjs",
|
|
7
|
+
"vault-ui": "./vault-ui.mjs"
|
|
8
|
+
},
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=22.16.0"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"vault-ui.mjs",
|
|
14
|
+
"install.mjs",
|
|
15
|
+
"prepare.sh",
|
|
16
|
+
"download-archive.mjs",
|
|
17
|
+
"browser.cjs",
|
|
18
|
+
"fs-queue.cjs",
|
|
19
|
+
"vault-switch.cjs",
|
|
20
|
+
"server.cjs",
|
|
21
|
+
"markdown-write.cjs",
|
|
22
|
+
"request-url.cjs",
|
|
23
|
+
"skill/obsidian-web/SKILL.md"
|
|
24
|
+
]
|
|
25
|
+
}
|
package/prepare.sh
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
set -eu
|
|
3
|
+
umask 077
|
|
4
|
+
source_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
|
5
|
+
root="${VAULT_UI_HOME:-$HOME/.local/share/vault-ui}"
|
|
6
|
+
version=1.14.4
|
|
7
|
+
target="$root/obsidian-$version"
|
|
8
|
+
archive_name="obsidian-$version.asar.gz"
|
|
9
|
+
archive_url="https://github.com/obsidianmd/obsidian-releases/releases/download/v$version/$archive_name"
|
|
10
|
+
archive_sha256=d1ed428c363968774f0f3906e67d8a53a058ece0b6cdd924b07865977b2ada21
|
|
11
|
+
case "$(uname -s)" in
|
|
12
|
+
Darwin) obsidian_data="$HOME/Library/Application Support/obsidian" ;;
|
|
13
|
+
*) obsidian_data="${XDG_CONFIG_HOME:-$HOME/.config}/obsidian" ;;
|
|
14
|
+
esac
|
|
15
|
+
local_archive="${VAULT_UI_OBSIDIAN_DATA_DIR:-$obsidian_data}/obsidian-$version.asar"
|
|
16
|
+
cached_archive="$root/archives/$archive_name"
|
|
17
|
+
|
|
18
|
+
verify_archive() {
|
|
19
|
+
node -e 'const { createHash } = require("node:crypto");
|
|
20
|
+
const { readFileSync } = require("node:fs");
|
|
21
|
+
const actual = createHash("sha256").update(readFileSync(process.argv[1])).digest("hex");
|
|
22
|
+
process.exitCode = actual === process.argv[2] ? 0 : 1;' "$1" "$archive_sha256"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if [ "$#" -gt 0 ] && { [ ! -f "$1" ] || [ ! -r "$1" ]; }; then
|
|
26
|
+
echo "Cannot read the Obsidian archive at $1" >&2
|
|
27
|
+
exit 1
|
|
28
|
+
fi
|
|
29
|
+
mkdir -p "$root"
|
|
30
|
+
tmp=$(mktemp -d "$root/.install.XXXXXXXX")
|
|
31
|
+
trap 'rm -rf "$tmp"' EXIT
|
|
32
|
+
if [ "$#" -gt 0 ]; then
|
|
33
|
+
archive="$1"
|
|
34
|
+
elif [ -f "$local_archive" ] && [ -r "$local_archive" ]; then
|
|
35
|
+
archive="$local_archive"
|
|
36
|
+
else
|
|
37
|
+
if [ ! -f "$cached_archive" ] || ! verify_archive "$cached_archive"; then
|
|
38
|
+
echo "Downloading the official Obsidian $version runtime" >&2
|
|
39
|
+
if ! node "$source_dir/download-archive.mjs" "$archive_url" "$tmp/$archive_name" "$archive_sha256"; then
|
|
40
|
+
echo "Could not download a verified runtime. Pass the path to a local .asar or official .asar.gz file." >&2
|
|
41
|
+
exit 1
|
|
42
|
+
fi
|
|
43
|
+
mkdir -p "$root/archives"
|
|
44
|
+
mv -f "$tmp/$archive_name" "$cached_archive"
|
|
45
|
+
fi
|
|
46
|
+
archive="$cached_archive"
|
|
47
|
+
fi
|
|
48
|
+
case "$archive" in
|
|
49
|
+
*.gz)
|
|
50
|
+
if ! verify_archive "$archive"; then
|
|
51
|
+
echo "The Obsidian archive failed SHA-256 verification" >&2
|
|
52
|
+
exit 1
|
|
53
|
+
fi
|
|
54
|
+
gzip -dc -- "$archive" > "$tmp/obsidian.asar"
|
|
55
|
+
archive="$tmp/obsidian.asar"
|
|
56
|
+
;;
|
|
57
|
+
esac
|
|
58
|
+
npm exec --yes --package=@electron/asar@3.4.1 -- asar extract "$archive" "$tmp/assets"
|
|
59
|
+
node -e 'if (require(process.argv[1]).version !== process.argv[2]) throw Error("Obsidian " + process.argv[2] + " is required")' "$tmp/assets/package.json" "$version"
|
|
60
|
+
npm install --prefix "$tmp" --ignore-scripts --no-audit --no-fund --no-save esbuild@0.25.12 buffer@6.0.3 path-browserify@1.0.1
|
|
61
|
+
cp "$source_dir/browser.cjs" "$source_dir/fs-queue.cjs" "$tmp/"
|
|
62
|
+
"$tmp/node_modules/.bin/esbuild" "$tmp/browser.cjs" --bundle --platform=browser --outfile="$tmp/assets/vault-ui.js"
|
|
63
|
+
# The pinned desktop loader gives plugins the Electron platform flag. Keep the
|
|
64
|
+
# desktop UI and filesystem adapter, and report the actual host to plugins.
|
|
65
|
+
node - "$tmp/assets" <<'JS'
|
|
66
|
+
const fs = require('node:fs');
|
|
67
|
+
const path = require('node:path');
|
|
68
|
+
const assets = process.argv[2];
|
|
69
|
+
function patch(name, from, to) {
|
|
70
|
+
const file = path.join(assets, name);
|
|
71
|
+
const code = fs.readFileSync(file, 'utf8');
|
|
72
|
+
if (code.split(from).length !== 2) throw Error('Unexpected pinned runtime in ' + name);
|
|
73
|
+
fs.writeFileSync(file, code.replace(from, () => to));
|
|
74
|
+
}
|
|
75
|
+
patch('app.js', ':N3.hasOwnProperty(e)?N3[e]:a?', ':N3.hasOwnProperty(e)?(e==="obsidian"?window.vaultWebPluginApi(N3[e]):N3[e]):a?');
|
|
76
|
+
const read = 'e.prototype.read=function(e){var t=this;return this.queue((function(){return y(t,void 0,void 0,(function(){var t,n=this;return b(this,(function(i){t=this.getFullPath(e);try{return[2,this.fsPromises.readFile(t,"utf8")]';
|
|
77
|
+
patch('app.js', read, read.replace('var t=this;', 'if(window.vaultWebRead&&/\\.md$/i.test(e))return window.vaultWebRead(this,e);var t=this;'));
|
|
78
|
+
const queue = 'e.prototype.queue=function(e){var t=this,n=function(){var n=new Promise';
|
|
79
|
+
patch('app.js', queue, queue.replace('var t=this', 'window.vaultWebEndReadGroup?.(this);var t=this'));
|
|
80
|
+
// Report completed child reconciliations during a long scan of a flat directory.
|
|
81
|
+
// The original inactivity deadline still applies when no child completes.
|
|
82
|
+
const child = '[4,this.reconcileFileInternal(n,i)];case 3:return o.sent(),[3,8]';
|
|
83
|
+
patch('app.js', child, child.replace('o.sent(),', 'o.sent(),this.thingsHappening(),'));
|
|
84
|
+
// An empty Markdown destination in YAML has no target capture.
|
|
85
|
+
patch('worker.js', 'var u=c[5];if(u.startsWith', 'var u=c[5];if(!u)return;if(u.startsWith');
|
|
86
|
+
JS
|
|
87
|
+
if test -d "$target"; then
|
|
88
|
+
mv -f "$tmp/assets/vault-ui.js" "$target/vault-ui.js"
|
|
89
|
+
mv -f "$tmp/assets/app.js" "$target/app.js"
|
|
90
|
+
mv -f "$tmp/assets/worker.js" "$target/worker.js"
|
|
91
|
+
else
|
|
92
|
+
node -e 'const fs=require("node:fs"); const [src,dst]=process.argv.slice(1); fs.renameSync(src,dst);' "$tmp/assets" "$target"
|
|
93
|
+
fi
|
|
94
|
+
echo "$target"
|
package/request-url.cjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The browser may send requests only to origins approved by the local operator.
|
|
2
|
+
const LIFEOS_ORIGINS = [
|
|
3
|
+
'https://service.lifeos.vip',
|
|
4
|
+
'https://1300647093-ju7r3209b1-gz.scf.tencentcs.com',
|
|
5
|
+
];
|
|
6
|
+
|
|
7
|
+
const publicCatalogUrls = new Set(['https://releases.obsidian.md/stats/theme']);
|
|
8
|
+
for (const file of ['community-plugins.json', 'community-plugin-deprecation.json',
|
|
9
|
+
'community-plugin-stats.json', 'community-css-themes.json']) {
|
|
10
|
+
const url = 'https://raw.githubusercontent.com/obsidianmd/obsidian-releases/HEAD/' + file;
|
|
11
|
+
publicCatalogUrls.add(url);
|
|
12
|
+
publicCatalogUrls.add('https://releases.obsidian.md/proxy?url=' + url);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const restrictedHeaders = new Set([
|
|
16
|
+
'accept-encoding', 'connection', 'content-length', 'cookie', 'host', 'origin',
|
|
17
|
+
'proxy-authorization', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade',
|
|
18
|
+
]);
|
|
19
|
+
const redirectStatuses = new Set([301, 302, 303, 307, 308]);
|
|
20
|
+
const responseLimit = 32 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
function parseTarget(value) {
|
|
23
|
+
if (typeof value !== 'string') throw new Error('Expected an HTTP URL');
|
|
24
|
+
const target = new URL(value);
|
|
25
|
+
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
|
26
|
+
throw new Error('Expected an HTTP URL without embedded credentials');
|
|
27
|
+
}
|
|
28
|
+
return target;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function originSet(configuredOrigins) {
|
|
32
|
+
const allowed = new Set();
|
|
33
|
+
for (const value of configuredOrigins.split(',').map(origin => origin.trim()).filter(Boolean)) {
|
|
34
|
+
const target = parseTarget(value);
|
|
35
|
+
if (target.pathname !== '/' || target.search || target.hash) {
|
|
36
|
+
throw new Error('VAULT_UI_NETWORK_ORIGINS accepts full origins without paths, query or fragments');
|
|
37
|
+
}
|
|
38
|
+
if (target.protocol === 'http:' && !['127.0.0.1', '[::1]', 'localhost'].includes(target.hostname)) {
|
|
39
|
+
throw new Error('VAULT_UI_NETWORK_ORIGINS requires HTTPS except for loopback');
|
|
40
|
+
}
|
|
41
|
+
allowed.add(target.origin);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return allowed;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function createRequestUrl(configuredOrigins = '', readOrigins = '', syncOrigins = '') {
|
|
48
|
+
const allowed = new Set([...LIFEOS_ORIGINS, ...originSet(configuredOrigins)]);
|
|
49
|
+
const readable = originSet(readOrigins);
|
|
50
|
+
const sync = originSet(syncOrigins);
|
|
51
|
+
const readMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'PROPFIND', 'REPORT']);
|
|
52
|
+
return async ({ url, method = 'GET', contentType, headers: sourceHeaders, bodyBase64 }) => {
|
|
53
|
+
let target = parseTarget(url);
|
|
54
|
+
method = method.toUpperCase();
|
|
55
|
+
const publicRead = (method === 'GET' || method === 'HEAD') && publicCatalogUrls.has(target.href);
|
|
56
|
+
if (!publicRead && !allowed.has(target.origin)) {
|
|
57
|
+
if (sync.has(target.origin)) {
|
|
58
|
+
if (!readMethods.has(method) && !['POST', 'PUT', 'PATCH'].includes(method)) {
|
|
59
|
+
throw new Error('This method requires full access to the sync origin');
|
|
60
|
+
}
|
|
61
|
+
if (Object.keys(sourceHeaders ?? {}).some(name => /^(x-http-method|x-http-method-override|x-method-override)$/i.test(name))) {
|
|
62
|
+
throw new Error('Method overrides require full access to the sync origin');
|
|
63
|
+
}
|
|
64
|
+
} else if (!readable.has(target.origin)) throw new Error('Request origin is not configured in VAULT_UI_NETWORK_ORIGINS');
|
|
65
|
+
else if (!readMethods.has(method)) throw new Error('This vault has read-only access to the request origin');
|
|
66
|
+
}
|
|
67
|
+
const headers = new Headers(publicRead ? undefined : sourceHeaders);
|
|
68
|
+
for (const name of Array.from(headers.keys())) {
|
|
69
|
+
if (restrictedHeaders.has(name) || name.startsWith('sec-') || name.startsWith('proxy-')) headers.delete(name);
|
|
70
|
+
}
|
|
71
|
+
if (!publicRead && contentType && !headers.has('content-type')) headers.set('content-type', contentType);
|
|
72
|
+
let body = publicRead || bodyBase64 == null ? undefined : Buffer.from(bodyBase64, 'base64');
|
|
73
|
+
const signal = AbortSignal.timeout(30000);
|
|
74
|
+
let response;
|
|
75
|
+
for (let redirects = 0; ; redirects++) {
|
|
76
|
+
response = await fetch(target, { method, headers, body, signal, redirect: 'manual' });
|
|
77
|
+
const location = response.headers.get('location');
|
|
78
|
+
if (!location || !redirectStatuses.has(response.status)) break;
|
|
79
|
+
await response.body?.cancel();
|
|
80
|
+
if (redirects >= 5) throw new Error('Too many redirects for this request');
|
|
81
|
+
const next = parseTarget(new URL(location, target).href);
|
|
82
|
+
if (publicRead && !publicCatalogUrls.has(next.href)) throw new Error('Unknown catalog redirect');
|
|
83
|
+
if (next.origin !== target.origin) throw new Error('Cross-origin redirects are not available through requestUrl');
|
|
84
|
+
if ((response.status === 303 && method !== 'HEAD') ||
|
|
85
|
+
((response.status === 301 || response.status === 302) && method === 'POST')) {
|
|
86
|
+
method = 'GET';
|
|
87
|
+
body = undefined;
|
|
88
|
+
headers.delete('content-type');
|
|
89
|
+
}
|
|
90
|
+
target = next;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const parts = [];
|
|
94
|
+
let size = 0;
|
|
95
|
+
if (response.body) {
|
|
96
|
+
for await (const chunk of response.body) {
|
|
97
|
+
size += chunk.byteLength;
|
|
98
|
+
if (size > responseLimit) throw new Error('Response exceeds 32 MiB');
|
|
99
|
+
parts.push(chunk);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const resultHeaders = Object.fromEntries(response.headers);
|
|
103
|
+
delete resultHeaders['set-cookie'];
|
|
104
|
+
return { status: response.status, headers: resultHeaders, body: Buffer.concat(parts, size).toString('base64') };
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
module.exports = { createRequestUrl };
|