There was an error connecting to Chrome. Make sure you download and install the native application on your system.
12 |
Error:
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1.0.3
4 |
5 | Gervasio Marchand Cassataro
6 | Gervasio Marchand Cassataro
7 | Native application for https://onchrome.gervas.io
8 | (c) 2020 Gervasio Marchand. MIT License.
9 | https://onchrome.gervas.io
10 | https://github.com/g3rv4/OnChrome
11 | OnChrome
12 |
13 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Actions/OpenChromeAction.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using OnChrome.Core.Helpers;
3 | using OnChrome.Core.Models;
4 |
5 | namespace OnChrome.Core.Actions
6 | {
7 | public static class OpenChromeAction
8 | {
9 | public static BaseNMResponse Process(OpenChromeRequest request)
10 | {
11 | try
12 | {
13 | OsDependentTasks.OpenChrome(request.Url, request.Profile);
14 | return new OpenChromeResponse();
15 | }
16 | catch (Exception e)
17 | {
18 | return new FailedResponse($"{e.GetType()}: {e.Message}");
19 | }
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/OnChrome/OnChrome.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 | 8
7 | enable
8 |
9 | OnChrome
10 | logo.ico
11 | logo.ico
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | True
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Actions/CompatibilityAction.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using OnChrome.Core.Helpers;
4 | using OnChrome.Core.Models;
5 |
6 | namespace OnChrome.Core.Actions
7 | {
8 | public static class CompatibilityAction
9 | {
10 | public static BaseNMResponse Process(CompatibilityRequest request)
11 | {
12 | try
13 | {
14 | var status = ExtensionVersionHelper.GetCompatibiltyStatus(request.ExtensionVersion, out var appVersion);
15 | return new CompatibilityResponse(appVersion, status);
16 | }
17 | catch (Exception e)
18 | {
19 | return new FailedResponse(e.Message);
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Models/NativeMessagingRequests.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using OnChrome.Core.Helpers;
3 |
4 | namespace OnChrome.Core.Models
5 | {
6 | public abstract class BaseNMRequest
7 | {
8 | public string Command { get; set; }
9 |
10 | public static BaseNMRequest? Deserialize(string json) =>
11 | (BaseNMRequest?)JsonConvert.DeserializeObject(json, typeof(BaseNMRequest), IncomingMessageConverter.Instance);
12 | }
13 |
14 | public class CompatibilityRequest : BaseNMRequest
15 | {
16 | public string ExtensionVersion { get; set; }
17 | }
18 |
19 | public class OpenChromeRequest : BaseNMRequest
20 | {
21 | public string Url { get; set; }
22 | public string? Profile { get; set; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Extensions/StreamExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace OnChrome.Core
5 | {
6 | public static class StreamExtensions
7 | {
8 | public static byte[] ReadExactly(this Stream stream, int size)
9 | {
10 | var result = new byte[size];
11 | var readInto = result.AsSpan();
12 | while (!readInto.IsEmpty)
13 | {
14 | var readChars = stream.Read(readInto);
15 | if (readChars == -1)
16 | {
17 | throw new Exception("Reached the end of the stream unexpectedly");
18 | }
19 |
20 | readInto = readInto.Slice(readChars);
21 | }
22 |
23 | return result;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/extension/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Open certain URLs on Chrome",
3 | "manifest_version": 2,
4 | "name": "OnChrome",
5 | "version": "1.0.2",
6 | "applications": {
7 | "gecko": {
8 | "id": "onchrome@gervas.io",
9 | "strict_min_version": "61.0"
10 | }
11 | },
12 | "icons": {
13 | "128": "images/icon128.png",
14 | "48": "images/icon48.png",
15 | "16": "images/icon16.png"
16 | },
17 | "background": {
18 | "scripts": [
19 | "background.js"
20 | ]
21 | },
22 | "browser_action": {
23 | "default_popup": "options.html",
24 | "default_icon": {
25 | "128": "images/icon128.png",
26 | "48": "images/icon48.png",
27 | "16": "images/icon16.png"
28 | }
29 | },
30 | "permissions": [
31 | "nativeMessaging",
32 | "tabs",
33 | "contextMenus",
34 | "storage",
35 | "webRequest",
36 | "webRequestBlocking",
37 | ""
38 | ]
39 | }
40 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Gervasio Marchand
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/OnChrome.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | #
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OnChrome.Core", "OnChrome.Core\OnChrome.Core.csproj", "{2A6A5A39-83AA-4CBD-99D1-9999EA5A47BA}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OnChrome", "OnChrome\OnChrome.csproj", "{8203B4E5-1C60-4EF7-B87C-3C80D4DA7E64}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {2A6A5A39-83AA-4CBD-99D1-9999EA5A47BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {2A6A5A39-83AA-4CBD-99D1-9999EA5A47BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {2A6A5A39-83AA-4CBD-99D1-9999EA5A47BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {2A6A5A39-83AA-4CBD-99D1-9999EA5A47BA}.Release|Any CPU.Build.0 = Release|Any CPU
18 | {8203B4E5-1C60-4EF7-B87C-3C80D4DA7E64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {8203B4E5-1C60-4EF7-B87C-3C80D4DA7E64}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {8203B4E5-1C60-4EF7-B87C-3C80D4DA7E64}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {8203B4E5-1C60-4EF7-B87C-3C80D4DA7E64}.Release|Any CPU.Build.0 = Release|Any CPU
22 | EndGlobalSection
23 | EndGlobal
24 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Models/NativeMessagingResponses.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Converters;
3 | using OnChrome.Core.Models.Enums;
4 |
5 | namespace OnChrome.Core.Models
6 | {
7 | public abstract class BaseNMResponse
8 | {
9 | public bool Success { get; }
10 |
11 | protected BaseNMResponse(bool success)
12 | {
13 | Success = success;
14 | }
15 | }
16 |
17 | public class FailedResponse : BaseNMResponse
18 | {
19 | public string ErrorMessage { get; }
20 |
21 | public FailedResponse(string errorMessage) : base(success: false)
22 | {
23 | ErrorMessage = errorMessage;
24 | }
25 | }
26 |
27 | public class CompatibilityResponse : BaseNMResponse
28 | {
29 | public string? AppVersion { get; }
30 |
31 | [JsonConverter(typeof(StringEnumConverter))]
32 | public CompatibilityStatus CompatibilityStatus { get; }
33 |
34 | public CompatibilityResponse(string? appVersion, CompatibilityStatus compatibilityStatus) : base(success: true)
35 | {
36 | AppVersion = appVersion;
37 | CompatibilityStatus = compatibilityStatus;
38 | }
39 | }
40 |
41 | public class OpenChromeResponse : BaseNMResponse
42 | {
43 | public OpenChromeResponse() : base(success: true)
44 | {
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OnChrome 
2 |
3 | A Firefox extension so that certain urls are opened using Chrome. I built it because I wanted to switch to Firefox, but certain sites I use all the time require Chrome. I want links and everything to work just as it used to, but if it ends opening one of those sites, it should open them in Chrome.
4 |
5 | The extension lets you define [url match patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) to determine which sites should always be opened with Chrome.
6 |
7 | Read [my blog post about it](https://g3rv4.com/2019/06/how-to-migrate-to-firefox) where I explain why I built it.
8 |
9 | ## How do I install it?
10 |
11 | 1. Install the extension on [the Firefox store](https://addons.mozilla.org/en-US/firefox/addon/onchrome/)
12 | 2. Install the [supporting application](https://onchrome.gervas.io/native-applications)
13 |
14 | ## Requirements
15 |
16 | * Windows x64 or MacOs (other environments can be supported later, ask!)
17 | * Chrome installed
18 |
19 | ## Why do I need to install software on my machine? I never had to do it for an extension before!
20 |
21 | Ugh, yeah... I know... that sucks. The reason is that Firefox can't talk to Chrome directly... you need to use [Native Messaging](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging), and that requires a native app that understands the messages from the extension and in turn opens Chrome.
22 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/ExtensionVersionHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Text.RegularExpressions;
4 | using OnChrome.Core.Models.Enums;
5 |
6 | namespace OnChrome.Core.Helpers
7 | {
8 | public static class ExtensionVersionHelper
9 | {
10 | private static Regex _versionWithoutRevision = new Regex(@"^([0-9]+\.[0-9]+\.[0-9]+)", RegexOptions.Compiled);
11 | public static CompatibilityStatus GetCompatibiltyStatus(string? extensionVersion, out string appVersion)
12 | {
13 | var version = Assembly.GetEntryAssembly()?.GetName().Version;
14 | if (version == null)
15 | {
16 | throw new Exception("Could not determine the app version");
17 | }
18 |
19 | appVersion = _versionWithoutRevision.Match(version.ToString()).Groups[1].Value;
20 | if (extensionVersion.IsNullOrEmpty())
21 | {
22 | return CompatibilityStatus.MissingExtension;
23 | }
24 |
25 | if (!Version.TryParse(extensionVersion, out var extVersion))
26 | {
27 | throw new Exception("Could not parse the received extension version");
28 | }
29 |
30 | if (version.Major > extVersion.Major)
31 | {
32 | return CompatibilityStatus.ExtensionNeedsUpdate;
33 | }
34 | else if (version.Major < extVersion.Major)
35 | {
36 | return CompatibilityStatus.AppNeedsUpdate;
37 | }
38 |
39 | return CompatibilityStatus.Ok;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/OnChrome.wxs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
25 |
26 |
28 |
29 |
30 | NOT Installed OR NOT REMOVE OR REINSTALL OR UPGRADINGPRODUCTCODE
31 | Installed
32 |
33 |
34 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Models/AppManifest.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Serialization;
3 | using OnChrome.Core.Helpers;
4 |
5 | namespace OnChrome.Core.Models
6 | {
7 | public class AppManifest
8 | {
9 | private static AppManifest? _instance;
10 | public static AppManifest Instance => _instance ??= new AppManifest
11 | (
12 | name: "me.onchro.netcore",
13 | description: "Extension to open certain urls on chrome. Visit onchrome.gervas.io for details",
14 | path: OsDependentTasks.PathToExecutable ?? "",
15 | type: "stdio",
16 | allowedExtensions: new [] { "onchrome@gervas.io" }
17 | );
18 |
19 | private static JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
20 | {
21 | ContractResolver = new DefaultContractResolver
22 | {
23 | NamingStrategy = new SnakeCaseNamingStrategy()
24 | }
25 | };
26 |
27 | public string ToJson() =>
28 | JsonConvert.SerializeObject(this, _jsonSettings);
29 |
30 | public static AppManifest? FromJson(string json) =>
31 | JsonConvert.DeserializeObject(json, _jsonSettings);
32 |
33 | public string Name { get; private set; }
34 | public string Description { get; private set; }
35 | public string Path { get; private set; }
36 | public string Type { get; private set; }
37 | public string[] AllowedExtensions { get; private set; }
38 |
39 | [JsonConstructor]
40 | private AppManifest(string name, string description, string path, string type, string[] allowedExtensions)
41 | {
42 | Name = name;
43 | Description = description;
44 | Path = path;
45 | Type = type;
46 | AllowedExtensions = allowedExtensions;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/OSDependentTasks.MacOS.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.IO;
4 |
5 | namespace OnChrome.Core.Helpers
6 | {
7 | internal class MacOsTasks : OsDependentTasks
8 | {
9 | private string? _manifestPath;
10 | protected override string ManifestPath => _manifestPath ??= GetManifestPath();
11 |
12 | private string GetManifestPath()
13 | {
14 | var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
15 | return Path.Combine(home, "Library/Application Support/Mozilla/NativeMessagingHosts/me.onchro.netcore.json");
16 | }
17 |
18 | protected override void OpenChromeImpl(string url, string? profile)
19 | {
20 | var arguments = @"-a ""Google Chrome"" ";
21 | if (profile.HasValue())
22 | {
23 | arguments += $@"-n --args --profile-directory=""{profile}"" ";
24 | }
25 |
26 | arguments += url;
27 |
28 | Process.Start("open", arguments);
29 | }
30 |
31 | protected override (bool, string?) UninstallImpl()
32 | {
33 | var directory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()?.Location);
34 | if (directory == null)
35 | throw new Exception("Could not get the directory of the entry assembly");
36 |
37 | var uninstallerPath = Path.Combine(directory, "OnChrome.Uninstall.pkg");
38 |
39 | if (!File.Exists(uninstallerPath))
40 | return (false, "Could not find uninstall package at " + directory);
41 |
42 | Process.Start("open", uninstallerPath);
43 | return (true, null);
44 | }
45 |
46 | protected override string? GetExecutablePathFromAssemblyLocation(string? assemblyLocation) =>
47 | assemblyLocation?.Replace(".dll", "");
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/IncomingMessageConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using Newtonsoft.Json;
4 | using Newtonsoft.Json.Linq;
5 | using Newtonsoft.Json.Serialization;
6 | using OnChrome.Core.Models;
7 |
8 | namespace OnChrome.Core.Helpers
9 | {
10 | public class IncomingMessageConverter : JsonConverter
11 | {
12 | private static IncomingMessageConverter? _instance;
13 | public static IncomingMessageConverter Instance => _instance ??= new IncomingMessageConverter();
14 |
15 | private static Dictionary> _factories =
16 | new Dictionary>
17 | {
18 | ["compatibility"] = () => new CompatibilityRequest(),
19 | ["open"] = () => new OpenChromeRequest(),
20 | };
21 |
22 | public override bool CanConvert(Type objectType) => objectType == typeof(BaseNMRequest);
23 |
24 | public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) =>
25 | serializer.Serialize(writer, value);
26 |
27 | public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
28 | {
29 | var jObject = JObject.Load(reader);
30 |
31 | if (jObject.TryGetValue("command", out var typeToken) &&
32 | typeToken.Type == JTokenType.String &&
33 | _factories.TryGetValue(typeToken.Value(), out var instanceFactory))
34 | {
35 | existingValue = instanceFactory();
36 | using var innerReader = jObject.CreateReader();
37 | serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
38 | serializer.Populate(innerReader, existingValue);
39 | return existingValue;
40 | }
41 |
42 | return existingValue;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/app/OnChrome/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Reflection;
4 | using System.Threading;
5 | using OnChrome.Core.Helpers;
6 |
7 | namespace OnChrome
8 | {
9 | class Program
10 | {
11 | private static string[] _validCommands = new[] {"register", "unregister", "uninstall"};
12 | static void Main(string[] args)
13 | {
14 | var command = args.Length > 0 && _validCommands.Contains(args[0])
15 | ? args[0]
16 | : null;
17 |
18 | if (command == null && Console.IsInputRedirected)
19 | {
20 | // when this happens, it's because Firefox is sending us a native message.
21 | #if DEBUG
22 | // useful to be able to attach a debugger to the process and see what's going on
23 | Thread.Sleep(10000);
24 | #endif
25 | NativeMessagesProcessor.Process();
26 | }
27 | else
28 | {
29 | switch (command)
30 | {
31 | case "register":
32 | OsDependentTasks.SetupNativeMessaging();
33 | break;
34 | case "unregister":
35 | OsDependentTasks.UnregisterNativeMessaging();
36 | break;
37 | case "uninstall":
38 | var (success, message) = OsDependentTasks.Uninstall();
39 | if (!success)
40 | {
41 | Console.WriteLine("Failure: " + message);
42 | }
43 | break;
44 | default:
45 | Console.WriteLine("OnChrome v" + Assembly.GetEntryAssembly()?.GetName().Version);
46 | Console.WriteLine("Supported commands: " + String.Join(',', _validCommands));
47 | break;
48 | }
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/NativeMessagesProcessor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 | using Newtonsoft.Json.Serialization;
4 | using OnChrome.Core.Actions;
5 | using OnChrome.Core.Models;
6 |
7 | namespace OnChrome.Core.Helpers
8 | {
9 | public static class NativeMessagesProcessor
10 | {
11 | public static void Process()
12 | {
13 | var request = GetNativeMessagingContent();
14 |
15 | var response = request switch
16 | {
17 | CompatibilityRequest m => CompatibilityAction.Process(m),
18 | OpenChromeRequest m => OpenChromeAction.Process(m),
19 | _ => new FailedResponse("Could not process the incoming message"),
20 | };
21 |
22 | SendNativeMessagingResponse(response);
23 | }
24 |
25 | private static BaseNMRequest? GetNativeMessagingContent()
26 | {
27 | using var stdin = Console.OpenStandardInput();
28 | var lengthBytes = stdin.ReadExactly(4);
29 | var length = BitConverter.ToInt32(lengthBytes);
30 |
31 | var messageJson = System.Text.Encoding.UTF8.GetString(stdin.ReadExactly(length));
32 | return BaseNMRequest.Deserialize(messageJson);
33 | }
34 |
35 | private static void SendNativeMessagingResponse(BaseNMResponse response)
36 | {
37 | using var stdout = Console.OpenStandardOutput();
38 |
39 | var responseJson = JsonConvert.SerializeObject(response, new JsonSerializerSettings
40 | {
41 | ContractResolver = new DefaultContractResolver
42 | {
43 | NamingStrategy = new CamelCaseNamingStrategy()
44 | }
45 | });
46 | var responseBytes = System.Text.Encoding.UTF8.GetBytes(responseJson);
47 | var lengthBytes = BitConverter.GetBytes(responseBytes.Length);
48 |
49 | var isBigEndian = !BitConverter.IsLittleEndian;
50 | if (isBigEndian)
51 | {
52 | Array.Reverse(lengthBytes);
53 | }
54 |
55 | stdout.Write(lengthBytes);
56 | stdout.Write(responseBytes);
57 | stdout.Flush();
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/OSDependentTasks.Windows.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Win32;
2 | using System;
3 | using System.IO;
4 | using System.Threading.Tasks;
5 |
6 | namespace OnChrome.Core.Helpers
7 | {
8 | internal partial class WindowsOsTasks : OsDependentTasks
9 | {
10 | protected override string ManifestPath
11 | {
12 | get
13 | {
14 | var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
15 | var directory = Path.Join(appData, "OnChrome");
16 | if (directory == null)
17 | throw new Exception("Could not get the directory of the entry assembly");
18 |
19 | return Path.Combine(directory, "me.onchro.netcore.json");
20 | }
21 | }
22 |
23 | protected override void OpenChromeImpl(string url, string? profile)
24 | {
25 | var registryValue = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe").GetValue(null);
26 | if (registryValue is string pathToChrome && pathToChrome.HasValue())
27 | {
28 | var args = url;
29 | if (profile.HasValue())
30 | {
31 | args = $@"--profile-directory=""{profile}"" " + args;
32 | }
33 | CreateProcess(pathToChrome, args, Path.GetDirectoryName(pathToChrome) ?? @"c:\");
34 | }
35 | else
36 | {
37 | throw new Exception("Could not get the path to chrome");
38 | }
39 | }
40 |
41 | protected override (bool, string?) UninstallImpl() =>
42 | (false, "Please uninstall it from the control panel");
43 |
44 | protected override string? GetExecutablePathFromAssemblyLocation(string? assemblyLocation) =>
45 | assemblyLocation?.Replace(".dll", ".exe");
46 |
47 | protected override void FinishSettingUpNativeMessaging()
48 | {
49 | var key = Registry.CurrentUser.CreateSubKey(@"Software\Mozilla\NativeMessagingHosts\me.onchro.netcore");
50 | key.SetValue(null, ManifestPath);
51 | }
52 |
53 | protected override void FinishUnregisteringNativeMessaging()
54 | {
55 | try
56 | {
57 | Registry.CurrentUser.DeleteSubKey(@"Software\Mozilla\NativeMessagingHosts\me.onchro.netcore");
58 | }
59 | catch { }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/extension/background.js:
--------------------------------------------------------------------------------
1 | function onError(error) {
2 | // we couldn't send the native message! maybe it's not installed?
3 | const encodedError = encodeURIComponent(error);
4 | browser.tabs.create({
5 | url: browser.runtime.getURL("error.html?error=" + encodedError)
6 | });
7 | }
8 |
9 | var currentProfile, currentExclusions;
10 | const blockUrl = function (requestDetails) {
11 | return new Promise(function (resolve, reject) {
12 | if (currentExclusions.find(r => requestDetails.url.match(r))) {
13 | resolve({ cancel: false });
14 | return
15 | }
16 | browser.runtime.sendNativeMessage(
17 | "me.onchro.netcore",
18 | { command: "open", url: requestDetails.url, profile: currentProfile })
19 | .then(r => {
20 | if (r.success) {
21 | browser.tabs.remove(requestDetails.tabId)
22 | } else {
23 | onError(r.errorMessage);
24 | }
25 | }, onError);
26 | resolve({ cancel: true });
27 | });
28 | }
29 |
30 | // from http://devdoc.net/web/developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/match_patterns.html
31 | const matchPattern = (/^(?:(\*|http|https|file|ftp|app):\/\/(\*|(?:\*\.)?[^\/\*]+|)\/(.*))$/i);
32 | function registerUrls(urls, exclusions, profile) {
33 | currentProfile = profile;
34 | if (urls) {
35 | urls = JSON.parse(urls).filter(u => matchPattern.exec(u));
36 | currentExclusions = exclusions ? JSON.parse(exclusions).map(s => new RegExp(s)) : [];
37 | if (urls && urls.length) {
38 | browser.webRequest.onBeforeRequest.addListener(blockUrl, { urls: urls, types: ["main_frame"] }, ["blocking"])
39 | }
40 | }
41 | }
42 |
43 | chrome.storage.sync.get(["urls", "profile", "exclusions"], res => registerUrls(res.urls, res.exclusions, res.profile))
44 |
45 | browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
46 | if (request.type === "urlsUpdated") {
47 | browser.webRequest.onBeforeRequest.removeListener(blockUrl)
48 | chrome.storage.sync.get(["urls", "profile", "exclusions"], res => registerUrls(res.urls, res.exclusions, res.profile))
49 | }
50 | });
51 |
52 | // have the extension check the status of the native app
53 | async function checkStatus()
54 | {
55 | let success = false;
56 | try {
57 | const response = await browser.runtime.sendNativeMessage("me.onchro.netcore", {
58 | command: "compatibility",
59 | extensionVersion: browser.runtime.getManifest().version
60 | });
61 | success = response.success && response.compatibilityStatus === "Ok"
62 | } catch {}
63 |
64 | browser.browserAction.setBadgeText({text: success ? "" : "!"});
65 |
66 | setTimeout(checkStatus, 10000);
67 | }
68 |
69 | checkStatus()
70 |
--------------------------------------------------------------------------------
/BuildAppWindows.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding(DefaultParametersetName='None')]
2 | param(
3 | [Parameter()][switch] $Sign
4 | )
5 |
6 | if (Test-Path "bin"){
7 | Remove-Item -LiteralPath "bin" -Force -Recurse
8 | }
9 | New-Item -Path "." -Name "bin" -ItemType "directory" | Out-Null
10 | $bin = New-Item -Path "bin" -Name "win64" -ItemType "directory"
11 |
12 | [xml]$xmlDoc = Get-Content app/Directory.Build.props
13 | $version = $xmlDoc['Project']['PropertyGroup']['AssemblyVersion'].InnerText
14 |
15 | Copy-Item -Path app/OnChrome.wxs $bin
16 |
17 | Push-Location "app/OnChrome"
18 | dotnet publish -c Release -r win-x64 /property:Version=$version -o "$($bin)/publish"
19 | Pop-Location
20 |
21 | Push-Location $bin
22 |
23 | # build the wix file
24 | $wxsPath = Join-Path $bin OnChrome.wxs
25 | [xml]$xmlDoc = Get-Content $wxsPath
26 | $wix = $xmlDoc['Wix']
27 | $product = $wix['Product']
28 | $product.SetAttribute("Version", $version)
29 | $dirRef = $product['DirectoryRef']
30 | $feature = $product['Feature']
31 |
32 | $filesToSign = @()
33 |
34 | $files = Get-ChildItem -Path publish
35 | foreach ($file in $files){
36 | $isDllOrExe = $file.Name.EndsWith(".exe") -or $file.Name.EndsWith(".dll")
37 | if ($isDllOrExe) {
38 | $signature = Get-AuthenticodeSignature $file.FullName
39 | if ($signature.Status -eq "NotSigned") {
40 | $filesToSign += $file.FullName
41 | } elseif ($signature.Status -eq "Valid") {
42 | } else {
43 | Write-Error "Signature of file $($File.Name) is $($signature.Status)"
44 | exit 1
45 | }
46 | }
47 |
48 | $id = $file.Name -replace '[^a-zA-Z0-9_\.]', '_'
49 |
50 | $component = $xmlDoc.CreateElement("Component", $wix.NamespaceURI)
51 | $component.SetAttribute("Id", $id)
52 | $dirRef.AppendChild($component) | Out-Null
53 |
54 | $fileObj = $xmlDoc.CreateElement("File", $wix.NamespaceURI)
55 | $fileObj.SetAttribute("Id", $id)
56 | $fileObj.SetAttribute("Source", "publish\$($file.Name)")
57 | $fileObj.SetAttribute("KeyPath", "yes")
58 | if ($isDllOrExe) {
59 | $fileObj.SetAttribute("Checksum", "yes")
60 | }
61 | $component.AppendChild($fileObj) | Out-Null
62 |
63 | $componentRef = $xmlDoc.CreateElement("ComponentRef", $wix.NamespaceURI)
64 | $componentRef.SetAttribute("Id", $id)
65 | $feature.AppendChild($componentRef) | Out-Null
66 | }
67 |
68 | if ($Sign) {
69 | & "C:\Program Files (x86)\Microsoft SDKs\ClickOnce\SignTool\signtool.exe" sign /fd SHA256 /t http://timestamp.comodoca.com $filesToSign
70 | }
71 |
72 | $xmlDoc.Save($wxsPath)
73 |
74 | & "C:\Program Files (x86)\WiX Toolset v3.11\bin\candle.exe" OnChrome.wxs
75 | & "C:\Program Files (x86)\WiX Toolset v3.11\bin\light.exe" OnChrome.wixobj
76 |
77 | if ($Sign) {
78 | & "C:\Program Files (x86)\Microsoft SDKs\ClickOnce\SignTool\signtool.exe" sign /fd SHA256 /t http://timestamp.comodoca.com /d OnChrome.msi OnChrome.msi
79 | }
80 |
81 | Move-Item -Path OnChrome.msi -Destination $bin.FullName
82 | Pop-Location
83 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/OSDependentTasks.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Reflection;
4 | using System.Runtime.InteropServices;
5 | using System.Threading.Tasks;
6 | using OnChrome.Core.Models;
7 | using OnChrome.Core.Models.Enums;
8 |
9 | namespace OnChrome.Core.Helpers
10 | {
11 | public abstract class OsDependentTasks
12 | {
13 | private static OsDependentTasks? _instance;
14 | private static OsDependentTasks Instance => _instance ??= GetInstance();
15 |
16 | private static OsDependentTasks GetInstance()
17 | {
18 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
19 | {
20 | return new WindowsOsTasks();
21 | }
22 | else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
23 | {
24 | return new MacOsTasks();
25 | }
26 |
27 | throw new Exception("Non supported OS");
28 | }
29 |
30 | public static void OpenChrome(string url, string? profile) =>
31 | Instance.OpenChromeImpl(url, profile);
32 |
33 | public static (bool, string?) Uninstall() =>
34 | Instance.UninstallImpl();
35 |
36 | public static RegistrationState GetNativeMessagingState()
37 | {
38 | if (!File.Exists(Instance.ManifestPath))
39 | {
40 | return RegistrationState.Unregistered;
41 | }
42 |
43 | var manifest = AppManifest.FromJson(File.ReadAllText(Instance.ManifestPath));
44 | if (manifest?.Path != PathToExecutable)
45 | {
46 | return RegistrationState.RegisteredDifferentHandler;
47 | }
48 |
49 | return RegistrationState.Registered;
50 | }
51 |
52 | public static void SetupNativeMessaging()
53 | {
54 | var manifestDirectory = Path.GetDirectoryName(Instance.ManifestPath);
55 | if (!Directory.Exists(manifestDirectory))
56 | {
57 | Directory.CreateDirectory(manifestDirectory);
58 | }
59 |
60 | File.WriteAllText(Instance.ManifestPath, AppManifest.Instance.ToJson());
61 |
62 | Instance.FinishSettingUpNativeMessaging();
63 | }
64 |
65 | public static void UnregisterNativeMessaging()
66 | {
67 | if (File.Exists(Instance.ManifestPath))
68 | {
69 | File.Delete(Instance.ManifestPath);
70 | }
71 |
72 | Instance.FinishUnregisteringNativeMessaging();
73 | }
74 |
75 | public static string? PathToExecutable =>
76 | Instance.GetExecutablePathFromAssemblyLocation(Assembly.GetEntryAssembly()?.Location);
77 |
78 | protected abstract string ManifestPath { get; }
79 |
80 | protected abstract void OpenChromeImpl(string url, string? profile);
81 |
82 | protected abstract (bool, string?) UninstallImpl();
83 |
84 | protected abstract string? GetExecutablePathFromAssemblyLocation(string? assemblyLocation);
85 |
86 | protected virtual void FinishSettingUpNativeMessaging() { }
87 |
88 | protected virtual void FinishUnregisteringNativeMessaging() { }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at gmc@gmc.uy. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/extension/options.js:
--------------------------------------------------------------------------------
1 | const save = document.getElementById("save");
2 | save.addEventListener("click", () => {
3 | let urls = document.getElementById("urls").value;
4 | let exclusions = document.getElementById("exclusions").value;
5 | let profile = document.getElementById("profile").value;
6 | let urlMatchPatternsToSave = [];
7 |
8 | if (urls) {
9 | urls = urls.split(/\r?\n/);
10 | if (urls.length) {
11 | urlMatchPatternsToSave = urls;
12 | }
13 | }
14 |
15 | if (exclusions) {
16 | exclusions = exclusions.split(/\r?\n/);
17 | if (exclusions.length) {
18 | exclusionsToSave = exclusions;
19 | }
20 | } else {
21 | exclusionsToSave = [];
22 | }
23 | browser.storage.sync.set({
24 | urls: JSON.stringify(urlMatchPatternsToSave),
25 | profile: profile,
26 | exclusions: JSON.stringify(exclusionsToSave)
27 | }, () => {
28 | chrome.runtime.sendMessage({ type: "urlsUpdated" });
29 | window.close();
30 | });
31 | })
32 |
33 | chrome.storage.sync.get(["urls","profile","exclusions"], res => {
34 | var urls = res.urls;
35 | if (urls) {
36 | urls = JSON.parse(urls);
37 | if (urls.length) {
38 | document.getElementById("urls").value = urls.join("\n");
39 | }
40 | }
41 | var exclusions = res.exclusions;
42 | if (exclusions) {
43 | exclusions = JSON.parse(exclusions);
44 | if (exclusions.length) {
45 | document.getElementById("exclusions").value = exclusions.join("\n");
46 | }
47 | }
48 | if (res.profile) {
49 | document.getElementById("profile").value = res.profile;
50 | }
51 | })
52 |
53 | function closeModal()
54 | {
55 | Array.from(document.getElementsByClassName("modal")).forEach(e => {
56 | e.classList.remove("is-active");
57 | });
58 | }
59 |
60 | function bindCloseModal()
61 | {
62 | Array.from(document.querySelectorAll(".modal .delete, .modal-background")).forEach(e => {
63 | e.onclick = closeModal;
64 | });
65 | }
66 |
67 | document.querySelectorAll("a").forEach(e => {
68 | e.addEventListener("click", el => {
69 | el.preventDefault();
70 |
71 | chrome.tabs.create({ url: el.target.href }, ()=> window.close());
72 | });
73 | });
74 |
75 | async function showWarningIfNeeded()
76 | {
77 | let modalToShow = undefined;
78 | try {
79 | const response = await browser.runtime.sendNativeMessage("me.onchro.netcore", {
80 | command: "compatibility",
81 | extensionVersion: browser.runtime.getManifest().version,
82 | url: '?' // passing this as url so that old versions (the golang ones) error out
83 | });
84 | if (!response.success) {
85 | modalToShow = "AppNeedsUpdate"
86 | } else if (response.compatibilityStatus != "Ok") {
87 | modalToShow = response.compatibilityStatus;
88 | }
89 | } catch {
90 | modalToShow = "AppNotInstalled";
91 | }
92 |
93 | closeModal();
94 |
95 | if (modalToShow) {
96 | document.getElementById(modalToShow).classList.add("is-active");
97 | bindCloseModal();
98 | }
99 | }
100 |
101 | showWarningIfNeeded();
102 |
--------------------------------------------------------------------------------
/extension/options.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | OnChrome
6 |
7 |
9 |
11 |
13 |
14 |
15 |
16 |
18 |
19 |
21 |
22 |
23 |
24 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
75 |
76 |
77 |
78 | You have successfully installed OnChrome's extension. You now need to install its native application. To
79 | read about it and download it, visit onchrome.gervas.io
80 |
101 |
102 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/BuildAppMacOS.ps1:
--------------------------------------------------------------------------------
1 | [CmdletBinding(DefaultParametersetName='None')]
2 | param(
3 | [Parameter(ParameterSetName='CodeSign',Mandatory=$false)][switch] $CodeSign,
4 | [Parameter(ParameterSetName='CodeSign',Mandatory=$true)][string] $CodeSignIdentity,
5 | [Parameter(ParameterSetName='CodeSign',Mandatory=$true)][string] $CodeSignPackageIdentity,
6 | [Parameter(ParameterSetName='CodeSign',Mandatory=$true)][string] $AppleAccountId,
7 | [Parameter(ParameterSetName='CodeSign',Mandatory=$true)][securestring] $AppleAccountPassword
8 | )
9 |
10 | function copyFileCreatingFolder
11 | {
12 | param(
13 | [Parameter(Mandatory=$True)][string] $Source,
14 | [Parameter(Mandatory=$True)][string] $Dest,
15 | [Parameter(Mandatory=$false)][switch] $MakeExecutable
16 | )
17 |
18 | New-Item -ItemType File -Path $Dest -Force
19 | Copy-Item $Source $Dest -Force
20 | if ($MakeExecutable) {
21 | chmod u+x $Dest
22 | }
23 | }
24 |
25 | $binMac = Join-Path (pwd) bin
26 | if (Test-Path $binMac){
27 | Remove-Item -LiteralPath "bin" -Force -Recurse
28 | }
29 | New-Item -Path "." -Name "bin" -ItemType "directory" | Out-Null
30 | $binMac = New-Item -Path "bin" -Name "macOS" -ItemType "directory"
31 |
32 | [xml]$xmlDoc = Get-Content app/Directory.Build.props
33 | $version = $xmlDoc['Project']['PropertyGroup']['AssemblyVersion'].InnerText
34 |
35 | $macOsInstallerFilesPath = Join-Path (pwd) "app" "MacOSPackages"
36 |
37 | $installerPath = Join-Path $binMac "Installers"
38 | copyFileCreatingFolder -Source "$($macOsInstallerFilesPath)/Installer/postinstall" -Dest "$($installerPath)/Installer/scripts/postinstall" -MakeExecutable
39 | copyFileCreatingFolder -Source "$($macOsInstallerFilesPath)/Uninstaller/postinstall" -Dest "$($installerPath)/Uninstaller/scripts/postinstall" -MakeExecutable
40 |
41 | Push-Location "app/OnChrome"
42 | dotnet publish -c Release -r osx-x64 -o "$($installerPath)/Installer/payload/usr/local/share/OnChrome"
43 | Pop-Location
44 |
45 | if ($CodeSign) {
46 | Push-Location "$($installerPath)/Installer/payload/usr/local/share/OnChrome"
47 | codesign -s $CodeSignIdentity -v --timestamp --options runtime *.dylib
48 | if ($LASTEXITCODE) {
49 | "Error code signing the dylib libraries"
50 | exit $LASTEXITCODE
51 | }
52 |
53 | codesign -s $CodeSignIdentity -v --timestamp --options runtime --entitlements "$($macOsInstallerFilesPath)/entitlements.plist" OnChrome
54 | if ($LASTEXITCODE) {
55 | "Error code signing the app"
56 | exit $LASTEXITCODE
57 | }
58 | Pop-Location
59 | }
60 |
61 | Push-Location $installerPath
62 |
63 | function buildInstaller
64 | {
65 | param(
66 | [Parameter(Mandatory=$True)][string] $pkg,
67 | [Parameter(Mandatory=$True)][string] $resources,
68 | [Parameter(Mandatory=$True)][string] $title
69 | )
70 |
71 | productbuild --synthesize --package $pkg distribution.xml
72 |
73 | $distributionPath = Join-Path (pwd) distribution.xml
74 | [xml]$xmlDoc = Get-Content $distributionPath
75 | $gui = $xmlDoc['installer-gui-script']
76 |
77 | $titleElement = $xmlDoc.CreateElement("title")
78 | $titleValue = $xmlDoc.CreateTextNode($title)
79 | $titleElement.AppendChild($titleValue);
80 | $gui.AppendChild($titleElement)
81 |
82 | $domains = $xmlDoc.CreateElement("domains")
83 | $domains.SetAttribute("enable_anywhere", "false")
84 | $domains.SetAttribute("enable_currentUserHome", "false")
85 | $domains.SetAttribute("enable_localSystem", "true")
86 | $gui.AppendChild($domains);
87 |
88 | $welcome = $xmlDoc.CreateElement("welcome")
89 | $welcome.SetAttribute("file", "welcome.html")
90 | $welcome.SetAttribute("mime-type", "text/html")
91 | $gui.AppendChild($welcome)
92 |
93 | $conclusion = $xmlDoc.CreateElement("conclusion")
94 | $conclusion.SetAttribute("file", "conclusion.html")
95 | $conclusion.SetAttribute("mime-type", "text/html")
96 | $gui.AppendChild($conclusion)
97 |
98 | $xmlDoc.Save($distributionPath)
99 |
100 | productbuild --distribution $distributionPath --package-path $pkg --resources $resources temp.pkg
101 | Remove-Item $pkg
102 | Move-Item temp.pkg $pkg
103 | }
104 |
105 | pkgbuild --nopayload --scripts Uninstaller/scripts --identifier me.onchro.uninstall --version $version OnChrome.Uninstall.unsigned.pkg
106 | buildInstaller OnChrome.Uninstall.unsigned.pkg "$($macOsInstallerFilesPath)/Uninstaller/resources" "OnChrome Uninstaller"
107 |
108 | if ($CodeSign) {
109 | productsign --sign $CodeSignPackageIdentity --timestamp OnChrome.Uninstall.unsigned.pkg OnChrome.Uninstall.pkg
110 | } else {
111 | Rename-Item OnChrome.Uninstall.unsigned.pkg OnChrome.Uninstall.pkg
112 | }
113 |
114 | Copy-Item OnChrome.Uninstall.pkg Installer/payload/usr/local/share/OnChrome/
115 |
116 | pkgbuild --root Installer/payload --scripts Installer/scripts --identifier me.onchro --version $version OnChrome.unsigned.pkg
117 | buildInstaller OnChrome.unsigned.pkg "$($macOsInstallerFilesPath)/Installer/resources" "OnChrome"
118 |
119 | if ($CodeSign) {
120 | productsign --sign $CodeSignPackageIdentity --timestamp OnChrome.unsigned.pkg OnChrome.pkg
121 | } else {
122 | Rename-Item OnChrome.unsigned.pkg OnChrome.pkg
123 | }
124 |
125 | Pop-Location
126 |
127 | function staple {
128 | param (
129 | [Parameter(Mandatory=$True)][string] $File,
130 | [Parameter(Mandatory=$True)][string] $Bundle
131 | )
132 |
133 | $timestamp = [int][double]::Parse((Get-Date -UFormat %s))
134 | $bundle = "$($Bundle).$($version)-$($timestamp)"
135 |
136 | "Sending the bundle $bundle to Apple for notarization"
137 |
138 | $applePwd = ConvertFrom-SecureString $AppleAccountPassword -AsPlainText
139 |
140 | $response = (xcrun altool --notarize-app --primary-bundle-id $bundle --username $AppleAccountId --password $applePwd 2>&1 --file $File) | Out-String
141 |
142 | $id = [regex]::match($response,'RequestUUID = ([a-z0-9-]+)\b').Groups[1].Value
143 |
144 | if (!$id) {
145 | "Unexpected response: $response"
146 | exit 1
147 | }
148 |
149 | "Uploaded! Request id: $id"
150 |
151 | Do {
152 | "Waiting 10 seconds"
153 | Start-Sleep -Seconds 10
154 |
155 | "Retrieving status"
156 | $response = (xcrun altool --notarization-info $id -u $AppleAccountId -p $applePwd 2>&1) | Out-String
157 |
158 | $status = [regex]::match($response,'Status: ([a-z ]+)').Groups[1].Value
159 |
160 | "Status: $status"
161 | } While ($status -eq "in progress")
162 |
163 | if ($status -ne "success") {
164 | "ERROR: Unexpected status: $status"
165 | $response
166 | exit 1
167 | }
168 |
169 | xcrun stapler staple $File
170 | }
171 |
172 | if ($CodeSign) {
173 | staple -File "$($installerPath)/OnChrome.pkg" -Bundle me.onchro
174 | copyFileCreatingFolder -Source "$($installerPath)/OnChrome.pkg" -Dest "dist/$($version)/OnChrome.pkg"
175 | }
176 |
--------------------------------------------------------------------------------
/app/OnChrome.Core/Helpers/OSDependentTasks.Windows.Process.cs:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Code taken from https://github.com/jmderuty/JobObject.Net/blob/master/JobObject.Net/Process.cs
4 | * under the following license
5 | *
6 | * Apache License
7 | Version 2.0, January 2004
8 | http://www.apache.org/licenses/
9 |
10 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11 |
12 | 1. Definitions.
13 |
14 | "License" shall mean the terms and conditions for use, reproduction,
15 | and distribution as defined by Sections 1 through 9 of this document.
16 |
17 | "Licensor" shall mean the copyright owner or entity authorized by
18 | the copyright owner that is granting the License.
19 |
20 | "Legal Entity" shall mean the union of the acting entity and all
21 | other entities that control, are controlled by, or are under common
22 | control with that entity. For the purposes of this definition,
23 | "control" means (i) the power, direct or indirect, to cause the
24 | direction or management of such entity, whether by contract or
25 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
26 | outstanding shares, or (iii) beneficial ownership of such entity.
27 |
28 | "You" (or "Your") shall mean an individual or Legal Entity
29 | exercising permissions granted by this License.
30 |
31 | "Source" form shall mean the preferred form for making modifications,
32 | including but not limited to software source code, documentation
33 | source, and configuration files.
34 |
35 | "Object" form shall mean any form resulting from mechanical
36 | transformation or translation of a Source form, including but
37 | not limited to compiled object code, generated documentation,
38 | and conversions to other media types.
39 |
40 | "Work" shall mean the work of authorship, whether in Source or
41 | Object form, made available under the License, as indicated by a
42 | copyright notice that is included in or attached to the work
43 | (an example is provided in the Appendix below).
44 |
45 | "Derivative Works" shall mean any work, whether in Source or Object
46 | form, that is based on (or derived from) the Work and for which the
47 | editorial revisions, annotations, elaborations, or other modifications
48 | represent, as a whole, an original work of authorship. For the purposes
49 | of this License, Derivative Works shall not include works that remain
50 | separable from, or merely link (or bind by name) to the interfaces of,
51 | the Work and Derivative Works thereof.
52 |
53 | "Contribution" shall mean any work of authorship, including
54 | the original version of the Work and any modifications or additions
55 | to that Work or Derivative Works thereof, that is intentionally
56 | submitted to Licensor for inclusion in the Work by the copyright owner
57 | or by an individual or Legal Entity authorized to submit on behalf of
58 | the copyright owner. For the purposes of this definition, "submitted"
59 | means any form of electronic, verbal, or written communication sent
60 | to the Licensor or its representatives, including but not limited to
61 | communication on electronic mailing lists, source code control systems,
62 | and issue tracking systems that are managed by, or on behalf of, the
63 | Licensor for the purpose of discussing and improving the Work, but
64 | excluding communication that is conspicuously marked or otherwise
65 | designated in writing by the copyright owner as "Not a Contribution."
66 |
67 | "Contributor" shall mean Licensor and any individual or Legal Entity
68 | on behalf of whom a Contribution has been received by Licensor and
69 | subsequently incorporated within the Work.
70 |
71 | 2. Grant of Copyright License. Subject to the terms and conditions of
72 | this License, each Contributor hereby grants to You a perpetual,
73 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74 | copyright license to reproduce, prepare Derivative Works of,
75 | publicly display, publicly perform, sublicense, and distribute the
76 | Work and such Derivative Works in Source or Object form.
77 |
78 | 3. Grant of Patent License. Subject to the terms and conditions of
79 | this License, each Contributor hereby grants to You a perpetual,
80 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81 | (except as stated in this section) patent license to make, have made,
82 | use, offer to sell, sell, import, and otherwise transfer the Work,
83 | where such license applies only to those patent claims licensable
84 | by such Contributor that are necessarily infringed by their
85 | Contribution(s) alone or by combination of their Contribution(s)
86 | with the Work to which such Contribution(s) was submitted. If You
87 | institute patent litigation against any entity (including a
88 | cross-claim or counterclaim in a lawsuit) alleging that the Work
89 | or a Contribution incorporated within the Work constitutes direct
90 | or contributory patent infringement, then any patent licenses
91 | granted to You under this License for that Work shall terminate
92 | as of the date such litigation is filed.
93 |
94 | 4. Redistribution. You may reproduce and distribute copies of the
95 | Work or Derivative Works thereof in any medium, with or without
96 | modifications, and in Source or Object form, provided that You
97 | meet the following conditions:
98 |
99 | (a) You must give any other recipients of the Work or
100 | Derivative Works a copy of this License; and
101 |
102 | (b) You must cause any modified files to carry prominent notices
103 | stating that You changed the files; and
104 |
105 | (c) You must retain, in the Source form of any Derivative Works
106 | that You distribute, all copyright, patent, trademark, and
107 | attribution notices from the Source form of the Work,
108 | excluding those notices that do not pertain to any part of
109 | the Derivative Works; and
110 |
111 | (d) If the Work includes a "NOTICE" text file as part of its
112 | distribution, then any Derivative Works that You distribute must
113 | include a readable copy of the attribution notices contained
114 | within such NOTICE file, excluding those notices that do not
115 | pertain to any part of the Derivative Works, in at least one
116 | of the following places: within a NOTICE text file distributed
117 | as part of the Derivative Works; within the Source form or
118 | documentation, if provided along with the Derivative Works; or,
119 | within a display generated by the Derivative Works, if and
120 | wherever such third-party notices normally appear. The contents
121 | of the NOTICE file are for informational purposes only and
122 | do not modify the License. You may add Your own attribution
123 | notices within Derivative Works that You distribute, alongside
124 | or as an addendum to the NOTICE text from the Work, provided
125 | that such additional attribution notices cannot be construed
126 | as modifying the License.
127 |
128 | You may add Your own copyright statement to Your modifications and
129 | may provide additional or different license terms and conditions
130 | for use, reproduction, or distribution of Your modifications, or
131 | for any such Derivative Works as a whole, provided Your use,
132 | reproduction, and distribution of the Work otherwise complies with
133 | the conditions stated in this License.
134 |
135 | 5. Submission of Contributions. Unless You explicitly state otherwise,
136 | any Contribution intentionally submitted for inclusion in the Work
137 | by You to the Licensor shall be under the terms and conditions of
138 | this License, without any additional terms or conditions.
139 | Notwithstanding the above, nothing herein shall supersede or modify
140 | the terms of any separate license agreement you may have executed
141 | with Licensor regarding such Contributions.
142 |
143 | 6. Trademarks. This License does not grant permission to use the trade
144 | names, trademarks, service marks, or product names of the Licensor,
145 | except as required for reasonable and customary use in describing the
146 | origin of the Work and reproducing the content of the NOTICE file.
147 |
148 | 7. Disclaimer of Warranty. Unless required by applicable law or
149 | agreed to in writing, Licensor provides the Work (and each
150 | Contributor provides its Contributions) on an "AS IS" BASIS,
151 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152 | implied, including, without limitation, any warranties or conditions
153 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154 | PARTICULAR PURPOSE. You are solely responsible for determining the
155 | appropriateness of using or redistributing the Work and assume any
156 | risks associated with Your exercise of permissions under this License.
157 |
158 | 8. Limitation of Liability. In no event and under no legal theory,
159 | whether in tort (including negligence), contract, or otherwise,
160 | unless required by applicable law (such as deliberate and grossly
161 | negligent acts) or agreed to in writing, shall any Contributor be
162 | liable to You for damages, including any direct, indirect, special,
163 | incidental, or consequential damages of any character arising as a
164 | result of this License or out of the use or inability to use the
165 | Work (including but not limited to damages for loss of goodwill,
166 | work stoppage, computer failure or malfunction, or any and all
167 | other commercial damages or losses), even if such Contributor
168 | has been advised of the possibility of such damages.
169 |
170 | 9. Accepting Warranty or Additional Liability. While redistributing
171 | the Work or Derivative Works thereof, You may choose to offer,
172 | and charge a fee for, acceptance of support, warranty, indemnity,
173 | or other liability obligations and/or rights consistent with this
174 | License. However, in accepting such obligations, You may act only
175 | on Your own behalf and on Your sole responsibility, not on behalf
176 | of any other Contributor, and only if You agree to indemnify,
177 | defend, and hold each Contributor harmless for any liability
178 | incurred by, or claims asserted against, such Contributor by reason
179 | of your accepting any such warranty or additional liability.
180 |
181 | END OF TERMS AND CONDITIONS
182 |
183 | APPENDIX: How to apply the Apache License to your work.
184 |
185 | To apply the Apache License to your work, attach the following
186 | boilerplate notice, with the fields enclosed by brackets "{}"
187 | replaced with your own identifying information. (Don't include
188 | the brackets!) The text should be enclosed in the appropriate
189 | comment syntax for the file format. We also recommend that a
190 | file or class name and description of purpose be included on the
191 | same "printed page" as the copyright notice for easier
192 | identification within third-party archives.
193 |
194 | Copyright {yyyy} {name of copyright owner}
195 |
196 | Licensed under the Apache License, Version 2.0 (the "License");
197 | you may not use this file except in compliance with the License.
198 | You may obtain a copy of the License at
199 |
200 | http://www.apache.org/licenses/LICENSE-2.0
201 |
202 | Unless required by applicable law or agreed to in writing, software
203 | distributed under the License is distributed on an "AS IS" BASIS,
204 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205 | See the License for the specific language governing permissions and
206 | limitations under the License.
207 | *
208 | */
209 | using System;
210 | using System.IO;
211 | using System.Runtime.InteropServices;
212 |
213 | namespace OnChrome.Core.Helpers
214 | {
215 | partial class WindowsOsTasks
216 | {
217 | private const int CREATE_BREAKAWAY_FROM_JOB = 0x01000000;
218 | private const int CREATE_NO_WINDOW = 0x08000000;
219 |
220 | [DllImport("kernel32.dll", SetLastError = true)]
221 | private static extern bool CreateProcess(
222 | string? lpApplicationName,
223 | string? lpCommandLine,
224 | IntPtr lpProcessAttributes,
225 | IntPtr lpThreadAttributes,
226 | bool bInheritHandles,
227 | uint dwCreationFlags,
228 | IntPtr lpEnvironment,
229 | string? lpCurrentDirectory,
230 | ref StartupInfo lpStartupInfo,
231 | out ProcessInfo lpProcessInformation
232 | );
233 |
234 | [DllImport("kernel32.dll", SetLastError = true)]
235 | [return: MarshalAs(UnmanagedType.Bool)]
236 | public static extern bool CloseHandle(IntPtr hObject);
237 |
238 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
239 | private struct ProcessInfo
240 | {
241 | public IntPtr hProcess;
242 | public IntPtr hThread;
243 | public Int32 ProcessId;
244 | public Int32 ThreadId;
245 | }
246 |
247 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
248 | private struct SecurityAttributes
249 | {
250 | public int length;
251 | public IntPtr lpSecurityDescriptor;
252 | public bool bInheritHandle;
253 | }
254 |
255 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
256 | private struct StartupInfo
257 | {
258 | public uint cb;
259 | public string lpReserved;
260 | public string lpDesktop;
261 | public string lpTitle;
262 | public uint dwX;
263 | public uint dwY;
264 | public uint dwXSize;
265 | public uint dwYSize;
266 | public uint dwXCountChars;
267 | public uint dwYCountChars;
268 | public uint dwFillAttribute;
269 | public uint dwFlags;
270 | public short wShowWindow;
271 | public short cbReserved2;
272 | public IntPtr lpReserved2;
273 | public IntPtr hStdInput;
274 | public IntPtr hStdOutput;
275 | public IntPtr hStdError;
276 | }
277 |
278 |
279 | public static System.Diagnostics.Process CreateProcess(string path, string args, string currentDirectory)
280 | {
281 | if (!File.Exists(path))
282 | {
283 | throw new ArgumentException("File does not exist");
284 | }
285 | ProcessInfo proc = new ProcessInfo();
286 | try
287 | {
288 | var inf = new StartupInfo();
289 |
290 | inf.cb = (uint)Marshal.SizeOf(typeof(StartupInfo));
291 | var cmd = path;
292 | if (!string.IsNullOrWhiteSpace(args))
293 | {
294 | cmd += " " + args;
295 | }
296 | if (!CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, false, CREATE_BREAKAWAY_FROM_JOB | CREATE_NO_WINDOW, IntPtr.Zero, currentDirectory, ref inf, out proc))
297 | {
298 | throw new InvalidOperationException("Couldn't create process");
299 | }
300 |
301 | return System.Diagnostics.Process.GetProcessById(proc.ProcessId);
302 | }
303 | finally
304 | {
305 | if (proc.hProcess != IntPtr.Zero)
306 | {
307 | CloseHandle(proc.hProcess);
308 | }
309 | }
310 | }
311 | }
312 | }
313 |
--------------------------------------------------------------------------------
/extension/images/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
1114 |
--------------------------------------------------------------------------------