init.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. import {watchService} from '../wl_clipboard.js';
  5. import Gio from 'gi://Gio';
  6. import GIRepository from 'gi://GIRepository';
  7. import GLib from 'gi://GLib';
  8. import Config from '../config.js';
  9. import setup, {setupGettext} from '../utils/setup.js';
  10. // Promise Wrappers
  11. // We don't use top-level await since it returns control flow to importing module, causing bugs
  12. import('gi://EBook').then(({default: EBook}) => {
  13. Gio._promisify(EBook.BookClient, 'connect');
  14. Gio._promisify(EBook.BookClient.prototype, 'get_view');
  15. Gio._promisify(EBook.BookClient.prototype, 'get_contacts');
  16. }).catch(console.debug);
  17. import('gi://EDataServer').then(({default: EDataServer}) => {
  18. Gio._promisify(EDataServer.SourceRegistry, 'new');
  19. }).catch(console.debug);
  20. Gio._promisify(Gio.AsyncInitable.prototype, 'init_async');
  21. Gio._promisify(Gio.DBusConnection.prototype, 'call');
  22. Gio._promisify(Gio.DBusProxy.prototype, 'call');
  23. Gio._promisify(Gio.DataInputStream.prototype, 'read_line_async',
  24. 'read_line_finish_utf8');
  25. Gio._promisify(Gio.File.prototype, 'delete_async');
  26. Gio._promisify(Gio.File.prototype, 'enumerate_children_async');
  27. Gio._promisify(Gio.File.prototype, 'load_contents_async');
  28. Gio._promisify(Gio.File.prototype, 'mount_enclosing_volume');
  29. Gio._promisify(Gio.File.prototype, 'query_info_async');
  30. Gio._promisify(Gio.File.prototype, 'read_async');
  31. Gio._promisify(Gio.File.prototype, 'replace_async');
  32. Gio._promisify(Gio.File.prototype, 'replace_contents_bytes_async',
  33. 'replace_contents_finish');
  34. Gio._promisify(Gio.FileEnumerator.prototype, 'next_files_async');
  35. Gio._promisify(Gio.Mount.prototype, 'unmount_with_operation');
  36. Gio._promisify(Gio.InputStream.prototype, 'close_async');
  37. Gio._promisify(Gio.OutputStream.prototype, 'close_async');
  38. Gio._promisify(Gio.OutputStream.prototype, 'splice_async');
  39. Gio._promisify(Gio.OutputStream.prototype, 'write_all_async');
  40. Gio._promisify(Gio.SocketClient.prototype, 'connect_async');
  41. Gio._promisify(Gio.SocketListener.prototype, 'accept_async');
  42. Gio._promisify(Gio.Subprocess.prototype, 'communicate_utf8_async');
  43. Gio._promisify(Gio.Subprocess.prototype, 'wait_check_async');
  44. Gio._promisify(Gio.TlsConnection.prototype, 'handshake_async');
  45. Gio._promisify(Gio.DtlsConnection.prototype, 'handshake_async');
  46. // User Directories
  47. Config.CACHEDIR = GLib.build_filenamev([GLib.get_user_cache_dir(), 'gsconnect']);
  48. Config.CONFIGDIR = GLib.build_filenamev([GLib.get_user_config_dir(), 'gsconnect']);
  49. Config.RUNTIMEDIR = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'gsconnect']);
  50. // Bootstrap
  51. const serviceFolder = GLib.path_get_dirname(GLib.filename_from_uri(import.meta.url)[0]);
  52. const extensionFolder = GLib.path_get_dirname(serviceFolder);
  53. setup(extensionFolder);
  54. setupGettext();
  55. if (Config.IS_USER) {
  56. // Infer libdir by assuming gnome-shell shares a common prefix with gjs;
  57. // assume the parent directory if it's not there
  58. let libdir = GIRepository.Repository.get_search_path().find(path => {
  59. return path.endsWith('/gjs/girepository-1.0');
  60. }).replace('/gjs/girepository-1.0', '');
  61. const gsdir = GLib.build_filenamev([libdir, 'gnome-shell']);
  62. if (!GLib.file_test(gsdir, GLib.FileTest.IS_DIR)) {
  63. const currentDir = `/${GLib.path_get_basename(libdir)}`;
  64. libdir = libdir.replace(currentDir, '');
  65. }
  66. Config.GNOME_SHELL_LIBDIR = libdir;
  67. }
  68. // Load DBus interfaces
  69. Config.DBUS = (() => {
  70. const bytes = Gio.resources_lookup_data(
  71. GLib.build_filenamev([Config.APP_PATH, `${Config.APP_ID}.xml`]),
  72. Gio.ResourceLookupFlags.NONE
  73. );
  74. const xml = new TextDecoder().decode(bytes.toArray());
  75. const dbus = Gio.DBusNodeInfo.new_for_xml(xml);
  76. dbus.nodes.forEach(info => info.cache_build());
  77. return dbus;
  78. })();
  79. // Init User Directories
  80. for (const path of [Config.CACHEDIR, Config.CONFIGDIR, Config.RUNTIMEDIR])
  81. GLib.mkdir_with_parents(path, 0o755);
  82. globalThis.HAVE_GNOME = GLib.getenv('GSCONNECT_MODE')?.toLowerCase() !== 'cli' && (GLib.getenv('GNOME_SETUP_DISPLAY') !== null || GLib.getenv('XDG_CURRENT_DESKTOP')?.toUpperCase()?.includes('GNOME') || GLib.getenv('XDG_SESSION_DESKTOP')?.toLowerCase() === 'gnome');
  83. /**
  84. * A custom debug function that logs at LEVEL_MESSAGE to avoid the need for env
  85. * variables to be set.
  86. *
  87. * @param {Error|string} message - A string or Error to log
  88. * @param {string} [prefix] - An optional prefix for the warning
  89. */
  90. const _debugCallerMatch = new RegExp(/([^@]*)@([^:]*):([^:]*)/);
  91. // eslint-disable-next-line func-style
  92. const _debugFunc = function (error, prefix = null) {
  93. let caller, message;
  94. if (error.stack) {
  95. caller = error.stack.split('\n')[0];
  96. message = `${error.message}\n${error.stack}`;
  97. } else {
  98. caller = (new Error()).stack.split('\n')[1];
  99. message = JSON.stringify(error, null, 2);
  100. }
  101. if (prefix)
  102. message = `${prefix}: ${message}`;
  103. const [, func, file, line] = _debugCallerMatch.exec(caller);
  104. const script = file.replace(Config.PACKAGE_DATADIR, '');
  105. GLib.log_structured('GSConnect', GLib.LogLevelFlags.LEVEL_MESSAGE, {
  106. 'MESSAGE': `[${script}:${func}:${line}]: ${message}`,
  107. 'SYSLOG_IDENTIFIER': 'org.gnome.Shell.Extensions.GSConnect',
  108. 'CODE_FILE': file,
  109. 'CODE_FUNC': func,
  110. 'CODE_LINE': line,
  111. });
  112. };
  113. globalThis._debugFunc = _debugFunc;
  114. const settings = new Gio.Settings({
  115. settings_schema: Config.GSCHEMA.lookup(Config.APP_ID, true),
  116. });
  117. if (settings.get_boolean('debug')) {
  118. globalThis.debug = globalThis._debugFunc;
  119. } else {
  120. // Swap the function out for a no-op anonymous function for speed
  121. globalThis.debug = () => {};
  122. }
  123. /**
  124. * Start wl_clipboard if not under Gnome
  125. */
  126. if (!globalThis.HAVE_GNOME) {
  127. debug('Not running as a Gnome extension');
  128. watchService();
  129. }
  130. /**
  131. * A simple (for now) pre-comparison sanitizer for phone numbers
  132. * See: https://github.com/KDE/kdeconnect-kde/blob/master/smsapp/conversationlistmodel.cpp#L200-L210
  133. *
  134. * @return {string} Return the string stripped of leading 0, and ' ()-+'
  135. */
  136. String.prototype.toPhoneNumber = function () {
  137. const strippedNumber = this.replace(/^0*|[ ()+-]/g, '');
  138. if (strippedNumber.length)
  139. return strippedNumber;
  140. return this;
  141. };
  142. /**
  143. * A simple equality check for phone numbers based on `toPhoneNumber()`
  144. *
  145. * @param {string} number - A phone number string to compare
  146. * @return {boolean} If `this` and @number are equivalent phone numbers
  147. */
  148. String.prototype.equalsPhoneNumber = function (number) {
  149. const a = this.toPhoneNumber();
  150. const b = number.toPhoneNumber();
  151. return (a.length && b.length && (a.endsWith(b) || b.endsWith(a)));
  152. };
  153. /**
  154. * An implementation of `rm -rf` in Gio
  155. *
  156. * @param {Gio.File|string} file - a GFile or filepath
  157. */
  158. Gio.File.rm_rf = function (file) {
  159. try {
  160. if (typeof file === 'string')
  161. file = Gio.File.new_for_path(file);
  162. try {
  163. const iter = file.enumerate_children(
  164. 'standard::name',
  165. Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
  166. null
  167. );
  168. let info;
  169. while ((info = iter.next_file(null)))
  170. Gio.File.rm_rf(iter.get_child(info));
  171. iter.close(null);
  172. } catch (e) {
  173. // Silence errors
  174. }
  175. file.delete(null);
  176. } catch (e) {
  177. // Silence errors
  178. }
  179. };
  180. /**
  181. * Extend GLib.Variant with a static method to recursively pack a variant
  182. *
  183. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  184. * @return {GLib.Variant} The resulting GVariant
  185. */
  186. function _full_pack(obj) {
  187. let packed;
  188. const type = typeof obj;
  189. switch (true) {
  190. case (obj instanceof GLib.Variant):
  191. return obj;
  192. case (type === 'string'):
  193. return GLib.Variant.new('s', obj);
  194. case (type === 'number'):
  195. return GLib.Variant.new('d', obj);
  196. case (type === 'boolean'):
  197. return GLib.Variant.new('b', obj);
  198. case (obj instanceof Uint8Array):
  199. return GLib.Variant.new('ay', obj);
  200. case (obj === null):
  201. return GLib.Variant.new('mv', null);
  202. case (typeof obj.map === 'function'):
  203. return GLib.Variant.new(
  204. 'av',
  205. obj.filter(e => e !== undefined).map(e => _full_pack(e))
  206. );
  207. case (obj instanceof Gio.Icon):
  208. return obj.serialize();
  209. case (type === 'object'):
  210. packed = {};
  211. for (const [key, val] of Object.entries(obj)) {
  212. if (val !== undefined)
  213. packed[key] = _full_pack(val);
  214. }
  215. return GLib.Variant.new('a{sv}', packed);
  216. default:
  217. throw Error(`Unsupported type '${type}': ${obj}`);
  218. }
  219. }
  220. GLib.Variant.full_pack = _full_pack;
  221. /**
  222. * Extend GLib.Variant with a method to recursively deepUnpack() a variant
  223. *
  224. * @param {*} [obj] - May be a GLib.Variant, Array, standard Object or literal.
  225. * @return {*} The resulting object
  226. */
  227. function _full_unpack(obj) {
  228. obj = (obj === undefined) ? this : obj;
  229. const unpacked = {};
  230. switch (true) {
  231. case (obj === null):
  232. return obj;
  233. case (obj instanceof GLib.Variant):
  234. return _full_unpack(obj.deepUnpack());
  235. case (obj instanceof Uint8Array):
  236. return obj;
  237. case (typeof obj.map === 'function'):
  238. return obj.map(e => _full_unpack(e));
  239. case (typeof obj === 'object'):
  240. for (const [key, value] of Object.entries(obj)) {
  241. // Try to detect and deserialize GIcons
  242. try {
  243. if (key === 'icon' && value.get_type_string() === '(sv)')
  244. unpacked[key] = Gio.Icon.deserialize(value);
  245. else
  246. unpacked[key] = _full_unpack(value);
  247. } catch (e) {
  248. unpacked[key] = _full_unpack(value);
  249. }
  250. }
  251. return unpacked;
  252. default:
  253. return obj;
  254. }
  255. }
  256. GLib.Variant.prototype.full_unpack = _full_unpack;
  257. /**
  258. * Creates a GTlsCertificate from the PEM-encoded data in @cert_path and
  259. * @key_path. If either are missing a new pair will be generated.
  260. *
  261. * Additionally, the private key will be added using ssh-add to allow sftp
  262. * connections using Gio.
  263. *
  264. * See: https://github.com/KDE/kdeconnect-kde/blob/master/core/kdeconnectconfig.cpp#L119
  265. *
  266. * @param {string} certPath - Absolute path to a x509 certificate in PEM format
  267. * @param {string} keyPath - Absolute path to a private key in PEM format
  268. * @param {string} commonName - A unique common name for the certificate
  269. * @return {Gio.TlsCertificate} A TLS certificate
  270. */
  271. Gio.TlsCertificate.new_for_paths = function (certPath, keyPath, commonName = null) {
  272. // Check if the certificate/key pair already exists
  273. const certExists = GLib.file_test(certPath, GLib.FileTest.EXISTS);
  274. const keyExists = GLib.file_test(keyPath, GLib.FileTest.EXISTS);
  275. // Create a new certificate and private key if necessary
  276. if (!certExists || !keyExists) {
  277. // If we weren't passed a common name, generate a random one
  278. if (!commonName)
  279. commonName = GLib.uuid_string_random();
  280. const proc = new Gio.Subprocess({
  281. argv: [
  282. Config.OPENSSL_PATH, 'req',
  283. '-new', '-x509', '-sha256',
  284. '-out', certPath,
  285. '-newkey', 'rsa:4096', '-nodes',
  286. '-keyout', keyPath,
  287. '-days', '3650',
  288. '-subj', `/O=andyholmes.github.io/OU=GSConnect/CN=${commonName}`,
  289. ],
  290. flags: (Gio.SubprocessFlags.STDOUT_SILENCE |
  291. Gio.SubprocessFlags.STDERR_SILENCE),
  292. });
  293. proc.init(null);
  294. proc.wait_check(null);
  295. }
  296. return Gio.TlsCertificate.new_from_files(certPath, keyPath);
  297. };
  298. Object.defineProperties(Gio.TlsCertificate.prototype, {
  299. /**
  300. * The common name of the certificate.
  301. */
  302. 'common_name': {
  303. get: function () {
  304. if (!this.__common_name) {
  305. const proc = new Gio.Subprocess({
  306. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-subject', '-inform', 'pem'],
  307. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  308. });
  309. proc.init(null);
  310. const stdout = proc.communicate_utf8(this.certificate_pem, null)[1];
  311. this.__common_name = /(?:cn|CN) ?= ?([^,\n]*)/.exec(stdout)[1];
  312. }
  313. return this.__common_name;
  314. },
  315. configurable: true,
  316. enumerable: true,
  317. },
  318. /**
  319. * Get just the pubkey as a DER ByteArray of a certificate.
  320. *
  321. * @return {GLib.Bytes} The pubkey as DER of the certificate.
  322. */
  323. 'pubkey_der': {
  324. value: function () {
  325. if (!this.__pubkey_der) {
  326. let proc = new Gio.Subprocess({
  327. argv: [Config.OPENSSL_PATH, 'x509', '-noout', '-pubkey', '-inform', 'pem'],
  328. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  329. });
  330. proc.init(null);
  331. const pubkey = proc.communicate_utf8(this.certificate_pem, null)[1];
  332. proc = new Gio.Subprocess({
  333. argv: [Config.OPENSSL_PATH, 'pkey', '-pubin', '-inform', 'pem', '-outform', 'der'],
  334. flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
  335. });
  336. proc.init(null);
  337. this.__pubkey_der = proc.communicate(new TextEncoder().encode(pubkey), null)[1];
  338. }
  339. return this.__pubkey_der;
  340. },
  341. configurable: true,
  342. enumerable: false,
  343. },
  344. });