@cossackframework/desktop 0.8.3 → 0.9.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/dist/index.js CHANGED
@@ -1,314 +1,2 @@
1
- import { execFile as e } from "node:child_process";
2
- import { readFile as t, realpath as n, stat as r } from "node:fs/promises";
3
- import i from "node:path";
4
- import a from "electron";
5
- //#region src/error.ts
6
- var o = class extends Error {
7
- constructor() {
8
- super("@cossackframework/desktop can only create applications and shells in the Electron main process."), this.name = "DesktopUnavailableError";
9
- }
10
- }, { app: s, BrowserWindow: c, dialog: l, Menu: u, nativeImage: d, Notification: f, protocol: p, shell: m, Tray: h } = typeof a == "object" && a ? a : {}, g = {
11
- name: "electron",
12
- supportedTransports: ["http"],
13
- getClientMetadata: () => ({
14
- platform: "desktop",
15
- adapter: "electron"
16
- })
17
- }, _ = "cossack", v = "cossack://app", y = !1, b, x = 0;
18
- function S(e) {
19
- process.env.COSSACK_DESKTOP_DEBUG === "1" && console.error(`[Cossack Desktop] ${e}`);
20
- }
21
- function C() {
22
- y || p?.registerSchemesAsPrivileged && (p.registerSchemesAsPrivileged([{
23
- scheme: _,
24
- privileges: {
25
- standard: !0,
26
- secure: !0,
27
- supportFetchAPI: !0,
28
- corsEnabled: !1,
29
- stream: !0
30
- }
31
- }]), y = !0);
32
- }
33
- C();
34
- function w() {
35
- if (!process.versions.electron || process.type === "renderer" || !s || !c) throw new o();
36
- }
37
- function T(t, n) {
38
- if (process.platform !== "linux") return;
39
- let r = `org.freedesktop.StatusNotifierItem-${process.pid}-${n}`;
40
- setTimeout(() => {
41
- t.isDestroyed() || e("dbus-send", [
42
- "--session",
43
- "--print-reply",
44
- "--type=method_call",
45
- "--dest=org.kde.StatusNotifierWatcher",
46
- "/StatusNotifierWatcher",
47
- "org.kde.StatusNotifierWatcher.RegisterStatusNotifierItem",
48
- `string:${r}`
49
- ], { timeout: 2e3 }, (e) => {
50
- e && S(`could not repair Linux tray registration: ${e.message}`);
51
- });
52
- }, 4e3).unref();
53
- }
54
- function E(e) {
55
- w();
56
- let t = ++x, n = e.guid ? new h(e.image, e.guid) : new h(e.image);
57
- return e.toolTip && n.setToolTip(e.toolTip), e.menu !== void 0 && n.setContextMenu(e.menu), T(n, t), n;
58
- }
59
- function D(e) {
60
- w();
61
- let t = e.window ?? c.getFocusedWindow() ?? c.getAllWindows()[0];
62
- if (!t) throw new o();
63
- if (e.behavior === "hide-to-tray" && !e.tray) throw TypeError("Desktop hide-to-tray behavior requires a tray.");
64
- let n = !1, r = !1, i = !1, a = () => {
65
- r = !0;
66
- }, u = () => {
67
- r || (r = !0, (e.onQuit ?? (() => s.quit()))());
68
- }, d = {
69
- behavior: e.behavior,
70
- quit: u,
71
- dispose() {
72
- n || (n = !0, t.removeListener("close", f), s.removeListener("before-quit", a));
73
- }
74
- }, f = (a) => {
75
- if (n || r) return;
76
- if (a.preventDefault(), e.behavior === "quit") {
77
- u();
78
- return;
79
- }
80
- if (e.behavior === "hide-to-tray") {
81
- e.tray && !e.tray.isDestroyed() ? t.hide() : u();
82
- return;
83
- }
84
- if (i) return;
85
- i = !0;
86
- let o = s.getName();
87
- l.showMessageBox(t, {
88
- type: "question",
89
- title: o,
90
- message: `Quit ${o}?`,
91
- buttons: ["Quit", "Cancel"],
92
- defaultId: 1,
93
- cancelId: 1,
94
- noLink: !0,
95
- ...e.confirmation
96
- }).then(({ response: t }) => {
97
- t === (e.confirmResponse ?? 0) && u();
98
- }).catch((e) => {
99
- console.error("[Cossack Desktop] Could not show the close confirmation.", e);
100
- }).finally(() => {
101
- i = !1;
102
- });
103
- };
104
- return t.on("close", f), s.on("before-quit", a), d;
105
- }
106
- function O(e) {
107
- let t;
108
- try {
109
- t = decodeURIComponent(e);
110
- } catch {
111
- throw URIError("Malformed Desktop URL path.");
112
- }
113
- if (t.includes("\0") || t.includes("\\")) throw URIError("Unsafe Desktop URL path.");
114
- if (t.split("/").includes("..")) throw URIError("Desktop URL traversal is not allowed.");
115
- return t.replace(/^\/+/, "");
116
- }
117
- function k(e, t) {
118
- let n = i.resolve(e), r = i.resolve(n, t || "__cossack_ssr__"), a = i.relative(n, r);
119
- if (a.startsWith("..") || i.isAbsolute(a)) throw URIError("Desktop URL traversal is not allowed.");
120
- return r;
121
- }
122
- var A = {
123
- ".css": "text/css; charset=utf-8",
124
- ".gif": "image/gif",
125
- ".html": "text/html; charset=utf-8",
126
- ".ico": "image/x-icon",
127
- ".jpeg": "image/jpeg",
128
- ".jpg": "image/jpeg",
129
- ".js": "text/javascript; charset=utf-8",
130
- ".json": "application/json; charset=utf-8",
131
- ".map": "application/json; charset=utf-8",
132
- ".mjs": "text/javascript; charset=utf-8",
133
- ".png": "image/png",
134
- ".svg": "image/svg+xml; charset=utf-8",
135
- ".txt": "text/plain; charset=utf-8",
136
- ".wasm": "application/wasm",
137
- ".webp": "image/webp",
138
- ".woff": "font/woff",
139
- ".woff2": "font/woff2"
140
- };
141
- async function j(e, a) {
142
- if (a.method !== "GET" && a.method !== "HEAD") return;
143
- let o = O(new URL(a.url).pathname);
144
- if (!o) return;
145
- let s = k(e, o);
146
- try {
147
- let [o, c] = await Promise.all([n(e), n(s)]), l = i.relative(o, c);
148
- if (l === ".." || l.startsWith(`..${i.sep}`) || i.isAbsolute(l)) return;
149
- let u = await r(c);
150
- if (!u.isFile()) return;
151
- let d = new Headers({
152
- "content-type": A[i.extname(s).toLowerCase()] ?? "application/octet-stream",
153
- "content-length": String(u.size)
154
- });
155
- return new Response(a.method === "HEAD" ? null : await t(c), { headers: d });
156
- } catch (e) {
157
- if (e.code === "ENOENT" || e.code === "ENOTDIR") return;
158
- throw e;
159
- }
160
- }
161
- function M(e) {
162
- let t = new URL(e.url), n = new URL(`${t.pathname}${t.search}`, "https://app");
163
- n.searchParams.delete("__cossack_window");
164
- let r = new Request(n, e);
165
- return e.headers.get("origin") === v && r.headers.set("origin", n.origin), r;
166
- }
167
- function N(e) {
168
- return e.protocol === `${_}:` && e.hostname === "app" && e.username === "" && e.password === "" && e.port === "";
169
- }
170
- function P(e = {}) {
171
- let { webPreferences: t, ...n } = e;
172
- return {
173
- width: 1e3,
174
- height: 720,
175
- show: !1,
176
- ...n,
177
- webPreferences: {
178
- ...t,
179
- contextIsolation: !0,
180
- sandbox: !0,
181
- nodeIntegration: !1,
182
- nodeIntegrationInWorker: !1,
183
- nodeIntegrationInSubFrames: !1,
184
- webSecurity: !0,
185
- allowRunningInsecureContent: !1,
186
- webviewTag: !1,
187
- preload: void 0
188
- }
189
- };
190
- }
191
- function F(e) {
192
- e.webContents.on("will-navigate", (e, t) => {
193
- try {
194
- let n = new URL(t);
195
- N(n) || (e.preventDefault(), (n.protocol === "https:" || n.protocol === "http:") && m.openExternal(n.href));
196
- } catch {
197
- e.preventDefault();
198
- }
199
- }), e.webContents.setWindowOpenHandler(({ url: e }) => {
200
- try {
201
- let t = new URL(e);
202
- (t.protocol === "https:" || t.protocol === "http:") && m.openExternal(t.href);
203
- } catch {}
204
- return { action: "deny" };
205
- });
206
- }
207
- function I(e = {}) {
208
- w();
209
- let t = e.window ?? c.getFocusedWindow() ?? c.getAllWindows()[0];
210
- if (!t) throw new o();
211
- return {
212
- app: s,
213
- window: t,
214
- Menu: u,
215
- Tray: h,
216
- dialog: l,
217
- Notification: f,
218
- nativeImage: d,
219
- shell: m,
220
- get dock() {
221
- return s.dock;
222
- },
223
- show() {
224
- t.show();
225
- },
226
- hide() {
227
- t.hide();
228
- },
229
- focus() {
230
- t.focus();
231
- },
232
- quit() {
233
- s.quit();
234
- },
235
- setBadge(e) {
236
- return s.setBadgeCount(e === null ? 0 : typeof e == "number" ? e : Number(e) || 0);
237
- },
238
- setOverlayIcon(e, n = "") {
239
- t.setOverlayIcon(e, n);
240
- }
241
- };
242
- }
243
- async function L(e) {
244
- if (w(), S("initializing Electron application"), !e.identifier.trim()) throw TypeError("Desktop identifier is required.");
245
- if (!e.productName.trim()) throw TypeError("Desktop productName is required.");
246
- let t = i.resolve(e.assetsRoot), n = `/${(e.startPath ?? "/").replace(/^\/+/, "")}`, r = !1, a;
247
- s.setName(e.productName), process.platform === "linux" && s.commandLine.appendSwitch("class", e.identifier), process.platform === "win32" && s.setAppUserModelId(e.identifier), S("requesting single-instance lock");
248
- let o = s.requestSingleInstanceLock();
249
- if (S(`single-instance lock ${o ? "acquired" : "unavailable"}`), !o) throw s.quit(), Error(`[Cossack] Another ${e.productName} instance is already running.`);
250
- await s.whenReady(), S("Electron app is ready");
251
- let l = (t = {}) => {
252
- let { path: r = n, ...i } = t, a = new URL(r, `${v}/`);
253
- if (!N(a)) throw TypeError("Desktop window paths must stay within cossack://app.");
254
- let o = new c(P({
255
- ...e.window,
256
- ...i
257
- }));
258
- return S(`created BrowserWindow ${o.id}`), F(o), a.searchParams.set("__cossack_window", String(o.id)), o.loadURL(a.href).then(() => S(`loaded ${a.href}`), (e) => console.error(`[Cossack Desktop] Failed to load ${a.href}`, e)), o.once("ready-to-show", () => o.show()), o;
259
- };
260
- await p.handle(_, async (n) => {
261
- S(`handling ${n.method} ${n.url}`);
262
- let r, i;
263
- try {
264
- if (r = new URL(n.url), !N(r)) return new Response("Forbidden Desktop authority", { status: 403 });
265
- let e = n.headers.get("origin");
266
- if (e && e !== v) return new Response("Forbidden Desktop origin", { status: 403 });
267
- O(r.pathname);
268
- let t = n.headers.get("referer");
269
- if (i = new URL(t || n.url), !N(i)) return new Response("Forbidden Desktop authority", { status: 403 });
270
- } catch {
271
- return new Response("Invalid Desktop URL", { status: 400 });
272
- }
273
- let o = i.searchParams.get("__cossack_window"), s = o ? c.fromId(Number(o)) ?? a : a, l = s ? I({ window: s }) : void 0, u = await j(t, n);
274
- if (u) return u;
275
- let d = { fetch: async (e) => await j(t, e) ?? new Response("Not found", { status: 404 }) };
276
- return e.fetch(M(n), {
277
- ...e.env ?? {},
278
- ASSETS: d,
279
- COSSACK_DESKTOP: l
280
- });
281
- }), S("registered cossack:// protocol handler"), a = l();
282
- let u = I({ window: a }), d = {
283
- app: s,
284
- mainWindow: a,
285
- shell: u,
286
- get quitting() {
287
- return r;
288
- },
289
- createWindow: l,
290
- show() {
291
- a.show(), a.focus();
292
- },
293
- hide() {
294
- a.hide();
295
- },
296
- quit() {
297
- r = !0, s.quit();
298
- }
299
- };
300
- return s.on("before-quit", () => {
301
- r = !0;
302
- }), s.on("activate", () => {
303
- c.getAllWindows().length === 0 ? a = l() : d.show();
304
- }), s.on("second-instance", () => d.show()), process.on("message", (e) => {
305
- if (e?.type === "cossack:renderer-reload") for (let e of c.getAllWindows()) e.webContents.reloadIgnoringCache();
306
- }), d;
307
- }
308
- function R(e) {
309
- return w(), b ??= L(e).catch((e) => {
310
- throw b = void 0, e;
311
- });
312
- }
313
- //#endregion
314
- export { c as BrowserWindow, o as DesktopUnavailableError, u as Menu, f as Notification, h as Tray, s as app, D as configureDesktopClose, R as createDesktopApp, I as createDesktopShell, E as createDesktopTray, l as dialog, g as electronRuntimeAdapter, m as electronShell, m as shell, d as nativeImage, p as protocol };
1
+ import { a as e, c as t, d as n, f as r, g as i, h as a, i as o, l as s, m as c, n as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./src-LxY0vJPo.js";
2
+ export { m as BrowserWindow, l as DESKTOP_DEFAULT_PERMISSIONS, i as DesktopUnavailableError, f as Menu, o as Notification, e as Tray, u as app, p as configureDesktopClose, t as createDesktopApp, s as createDesktopShell, h as createDesktopTray, n as dialog, r as electronRuntimeAdapter, d as electronShell, d as shell, c as nativeImage, a as protocol };
@@ -0,0 +1,9 @@
1
+ import type { OnBeforeSendHeadersListenerDetails } from 'electron';
2
+ export declare const desktopOrigin = "cossack://app";
3
+ export declare const desktopOwnerHeader = "x-cossack-desktop-owner";
4
+ export declare const desktopTokenHeader = "x-cossack-desktop-token";
5
+ type RequestDetails = Pick<OnBeforeSendHeadersListenerDetails, 'url' | 'method' | 'resourceType' | 'initiatorOrigin' | 'webContentsId' | 'requestHeaders'>;
6
+ export declare function isDesktopAppUrl(url: URL): boolean;
7
+ /** Use native initiator evidence, never renderer-supplied Origin, Referer or query IDs. */
8
+ export declare function authorizeDesktopRequest(details: RequestDetails, owned: boolean, token: string): Record<string, string> | undefined;
9
+ export {};