Skip to main content

3 posts tagged with "Web"

View All Tags

Tauri Plugin System Design

· 8 min read
Huakun Shen
Website Owner

In Raycast Analysis and uTools Analysis I discussed the two successful app launchers and their plugin system designs. But both of them have big limitations. Raycast is mac-only. uTools is cross-platform (almost perfect), but it is built with Electron, thus large bundle size and memory consumption.

Tauri is a new framework that can build cross-platform desktop apps with Rust and Web. With much smaller bundle size and memory consumption. It’s a good choice for building a cross-platform app launcher.

Requirements

  • Plugins can be built with JS frontend framework, so it’s easier for develop to build
  • UI can be controlled by plugin
  • Sandbox preferred, never trust plugins not developed by official team, community plugin could be malicious. Neither of Raycast, Alfred, uTools used sandbox. So we can discuss this as well.

Solution

Plugins will be developed as regular single page application. They will be saved in a directory like the following.

plugins/
├── plugin-a/
│ └── dist/
│ ├── index.html
│ └── ...
└── plugin-b/
└── dist/
├── index.html
└── ...

Optionally use symbolic link to build the following structure (link dist of each plugin to the plugin name. You will see why this could be helpful later.

plugins-link/
├── plugin-a/
│ ├── index.html
│ └── ...
└── plugin-b/
├── index.html
└── ...

When a plugin is triggered, the main Tauri core process will start a new process running a http server serving the entire plugins or plugins-link folder as static asset. The http server can be actix-web.

Then open a new WebView process

const w = new WebviewWindow('plugin-a', {
url: 'http://localhost:8000/plugin-a'
});

If we didn’t do the dist folder symlink step, the url would be http://localhost:8000/plugin-a/dist

Do the linking could avoid some problem.

One problem is base url. A single page application like react and vue does routing with url, but the base url is / by default. i.e. index page is loaded on http://localhost:8000. If the plugin redirects to /login, it should redirect to http://localhost:8000/login instead of http://localhost:8000/plugin-a/login

In this case, https://vite-plugin-ssr.com/base-url, https://vitejs.dev/guide/build#public-base-path can be configured in vite config.

Another solution is to use proxy in the http server. Like proxy_pass in nginx config.

API

Now the plugin’s page can be loaded in a WebView window.

However, a plugin not only needs to display a UI, but also need to interact with system API to implement more features, such as interacting with file system. Now IPC is involved.

Tauri by default won’t allow WebView loaded from other sources to run commands or call Tauri APIs.

See this security config dangerousRemoteDomainIpcAccess

https://tauri.app/v1/api/config/#securityconfig.dangerousremotedomainipcaccess

"security": {
"csp": null,
"dangerousRemoteDomainIpcAccess": [
{
"domain": "localhost:8000",
"enableTauriAPI": true,
"windows": ["plugin-a"],
"plugins": []
}
]
},

enableTauriAPI determines whether the plugin will have access to the Tauri APIs. If you don’t want the plugin to have the same level of permission as the main app, then set it to false.

This not only work with localhost hosted plugins. The plugin can also be hosted on public web (but you won’t be able to access it if there is no internet). This will be very dangerous, as compromised plugin on public web will affect all users. In addition, it’s unstable. Local plugin is always safer.

There is another plugins attribute used to control which tauri plugin’s (The plugin here means plugin in rust for Tauri framework, not our plugin) command the plugin can call.

https://tauri.app/v1/api/config/#remotedomainaccessscope.plugins

plugins is The list of plugins that are allowed in this scope. The names should be without the tauri-plugin- prefix, for example "store" for tauri-plugin-store.

For example, Raycast has a list of APIs exposed to extensions (https://developers.raycast.com/api-reference/clipboard)

Raycast uses NodeJS runtime to run plugins, so plugins can access file system and more. This is dangerous. From their blog https://www.raycast.com/blog/how-raycast-api-extensions-work, their solution is to open source all plugins and let the community verify the plugins.

This gives plugins more freedom and introduces more risks. In our approach with Tauri, we can provide a Tauri plugin for app plugins with all APIs to expose to the extensions. For example, get list of all applications, access storage, clipboard, shell, and more. File system access can also be checked and limited to some folders (could be set by users with a whitelist/blacklist). Just don’t give plugin access to Tauri’s FS API, but our provided, limited, and censored API plugin.

How to give plugin full access to OS and FS?

Unlike Raycast where the plugin is run directly with NodeJS, and render the UI by turning React into Swift AppKit native components. The Tauri approach has its UI part in browser. There is no way to let the UI plugin access OS API (like FS) directly. The advantage of this approach is that the UI can be any shape, while Raycast’s UI is limited by its pre-defined UI components.

If a plugin needs to run some binary like ffmpeg to convert/compress files, the previous sandbox API method with a custom Tauri plugin won’t work. In this scenario, this will be more complicated. Here are some immature thoughts

  • The non-UI part of the plugin will need a JS runtime if written in JS, like NodeJS or bun.js
  • Include plugin script written in python, Lua, JS… and UI plugin runs them using a shell API command (like calling a CLI command)
  • If the plugin need a long running backend, a process must be run separately, but how can the UI plugin communicate with the backend plugin? The backend plugin will probably need to be an http server or TCP server.
    • And how to stop this long running process?

Implementation Design

User Interface

Raycast supports multiple user interfaces, such as list, detail, form.

To implement this in Jarvis, there are 2 options.

  1. The extension returns a json list, and Jarvis render it as a list view.
  2. Let the extension handles everything, including list rendering.

Option 1

Could be difficult in our case, as we need to call a JS function to get data, this requires importing JS from Tauri WebView or run the JS script with a JS runtime and get a json response.

To do this, we need a common API contract in JSON format on how to render the response.

  1. Write a command script cmd1.js

  2. Jarvis will call bun cmd1.js with argv, get response

    Example of a list view

    {
    "view": "list",
    "data": [
    {
    "title": "Title 1",
    "description": "Description 1"
    },
    {
    "title": "Title 2",
    "description": "Description 2"
    },
    {
    "title": "Title 3",
    "description": "Description 3"
    }
    ]
    }

This method requires shipping the app with a bun runtime (or download the runtime when app is first launched).

After some thinking, I believe this is similar to script command. Any other language can support this. One difference is, “script command” relies on users’ local dependency, custom libraries must be installed for special tasks, e.g. pandas in python. It’s fine for script command because users are coders who know what they are doing. In a plugin, we don’t expect users to know programming, and install libraries. So shipping a built JS dist with all dependencies is a better idea. e.g. bun build index.ts --target=node > index.js, then bun index.js to run it without installing node_modules.

https://bun.sh/docs/bundler

In the plugin’s package.json, list all commands available and their entrypoints (e.g. dist/cmd1.js, dist/cmd2.js).

{
"commands": [
{
"name": "list-translators",
"title": "List all translators",
"description": "List all available translators",
"mode": "cmd"
}
]
}

Option 2

If we let the extension handle everything, it’s more difficult to develop, but less UI to worry about.

e.g. translate input1 , press enter, open extension window, and pass the input1 to the WebView.

By default, load dist/index.html as the plugin’s UI. There is only one entrypoint to the plugin UI, but a single plugin can have multiple sub-commands with url path. e.g. http://localhost:8080/plugin-a/command1

i.e. Routes in single page app

All available sub-commands can be specified in package.json

{
"commands": [
{
"name": "list-translators",
"title": "List all translators",
"description": "List all available translators",
"mode": "cmd"
},
{
"name": "google-translate",
"title": "Google Translate",
"description": "Translate a text to another language with Google",
"mode": "view"
},
{
"name": "bing-translate",
"title": "Bing Translate",
"description": "Translate a text to another language with Bing",
"mode": "view"
}
]
}

If mode is view, render it. For example, bing-translate will try to load http://localhost:8080/translate-plugin/bing-translate

If mode is cmd, it will try to run bun dist/list-translators and render the response.

mode cmd can have an optional language field, to allow using Python or other languages.

Script Command

Script Command from Raycast is a simple way to implement a plugin. A script file is created, and can be run when triggered. The stdout is sent back to the main app process.

Supported languages by Raycast script command are

  • Bash
  • Apple Script
  • Swift
  • Python
  • Ruby
  • Node.js

In fact, let users specify an interpreter, any script can be run, even executable binaries.

Alfred has a similar feature in workflow. The difference is, Raycast saves the code in a separate file, and Alfred saves the code within the workflow/plugin (in fact also in a file in some hidden folder).

Reference

NestJS + Neo4j + GraphQL Setup

· 5 min read
Huakun Shen
Website Owner

GitHub Repo: https://github.com/HuakunShen/nestjs-neo4j-graphql-demo

I haven't found a good update-to-date example of using Neo4j with NestJS and GraphQL. So I decided to write one myself.

Neo4j's graphql library has updated its API, some examples I found online were outdated (https://neo4j.com/developer-blog/creating-api-in-nestjs-with-graphql-neo4j-and-aws-cognito/). This demo uses v5.x.x.

GraphQL Schema

type Mutation {
signUp(username: String!, password: String!): String
signIn(username: String!, password: String!): String
}

# Only authenticated users can access this type
type Movie @authentication {
title: String
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
}

# Anyone can access this type
type Actor {
name: String
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}

# Only authenticated users can access this type
type User @authentication {
id: ID! @id
username: String!
# this is just an example of how to use @authorization to restrict access to a field
# If you list all users without the plaintextPassword field, you will see all users
# If you list all users with the plaintextPassword field, you will only see the user whose id matches the jwt.sub (which is the id of the authenticated user)
# in reality, never store plaintext passwords in the database
plaintextPassword: String!
@authorization(filter: [{ where: { node: { id: "$jwt.sub" } } }])
password: String! @private
}

NestJS Server Configuration

GraphQL Module

A GraphQL module can be generated with bunx nest g mo graphql.

Here is the configuration. In new Neo4jGraphQL(), authorization key is provided for JWT auth. Queries can be restricted by adding @authentication or @authorization to the type.

One important thing to note is the custom auth resolvers. Neo4jGraphQL auto-generate types, queries, mutations implementations for the types in the schema to provide basic CRUD operations, but custom functions like sign in and sign up must be implemented separately. Either as regular REST endpoints in other modules or provide a custom resolver to the Neo4jGraphQL instance.

Usually in NestJS, you would add resolvers to the providers list of the module, but in this case, the resolvers must be added to the Neo4jGraphQL instance. Otherwise you will see the custom queries defined in schema in the playground, but they always return null.

@Module({
imports: [
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
useFactory: async () => {
export const { NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD } =
envSchema.parse(process.env);
export const neo4jDriver = neo4j.driver(
NEO4J_URI,
neo4j.auth.basic(NEO4J_USERNAME, NEO4J_PASSWORD)
);

const typedefPath = path.join(RootDir, "src/graphql/schema.gql");
export const typeDefs = fs.readFileSync(typedefPath).toString();

const neoSchema = new Neo4jGraphQL({
typeDefs: typeDefs,
driver: neo4jDriver,
resolvers: authResolvers, // custom resolvers must be added to Neo4jGraphQL instead of providers list of NestJS module
features: {
authorization: {
key: "huakun",
},
},
});

const schema = await neoSchema.getSchema();
return {
schema,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
playground: false,
context: ({ req }) => ({
token: req.headers.authorization,
}),
};
},
}),
],
providers: [],
})
export class GraphqlModule {}

The resolver must be provided to Neo4jGraphQL constructor. It must be an object, so NestJS's class-based resolver won't work.

You must provide regular apollo stype resolvers. See https://neo4j.com/docs/graphql/current/ogm/installation/ for similar example.

export const authResolvers = {
Mutation: {
signUp: async (_source, { username, password }) => {
...
return createJWT({ sub: users[0].id });
},
signIn: async (_source, { username, password }) => {
...
return createJWT({ sub: user.id });
},
},
};

Read the README.md of this repo for more details. Run the code and read the source code to understand how it works. It's a minimal example.

Codegen

https://the-guild.dev/graphql/codegen is used to generate TypeScript types and more from the GraphQL schema.

Usually you provide the graphql schema file, but in this demo, the schema is designed for neo4j and not recognized by the codegen tool.

You need to let Neo4jGraphQL generate the schema and deploy it to a server first, then provide the server's endpoint to the codegen tool. Then the codegen tool will introspect the schema from the server and generate the types.

Make sure the server is running before running codegen

cd packages/codegen
pnpm codegen

The generated files are in the packages/codegen/src/gql folder.

Sample operations can be added to packages/codegen/operations. Types and caller for operations will also be generated.

Read the documentation of codegen for more details.

Examples is always provided in the packages/codegen folder.

This is roughly how the generated code it works:

You get full type safety when calling the operations. The operations documents are predefined in a central place rather than in the code. This is useful when you have a large project with many operations. Modifying one operation will update all the callers. And if the type is no longer valid, the compiler will tell you.

The input variables are also protected by TypeScript. You won't need to guess what the input variables are. The compiler will tell you.

import { CreateMoviesDocument } from "./src/gql/graphql";

async function main() {
const client = new ApolloClient({
uri: "http://localhost:3000/graphql",
cache: new InMemoryCache(),
});
client
.mutate({
mutation: CreateMoviesDocument,
variables: {
input: [
{
actors: {
create: [
{
node: {
name: "jacky",
},
},
],
},
title: "fallout",
},
],
},
})
.then((res) => {
console.log(res);
});
}

Tauri Deployment (Auto Update and CICD)

· 2 min read
Huakun Shen
Website Owner

Docs

Tauri Updater

Bundler Artifacts has sample CI and config script.

Cross-Platform Compilation has a sample GitHub Action CI script for cross-platform compilation (Windows, MacOS and Linux). Compiled files are stored as artifacts in a draft GitHub release. The release assets will be read by updater server for auto-update.

Sample tauri.config.json

Building

For updater to work, a public key is required.

tauri.config.json
"updater": {
"active": true,
"endpoints": [
"https://releases.myapp.com/{{target}}/{{current_version}}"
],
"dialog": true,
"pubkey": "YOUR_UPDATER_SIGNATURE_PUBKEY_HERE"
}

A pair of keys can be generated with tauri signer generate -w ~/.tauri/ezup.key.

If update is configured, then private key and password environment variables must be set.

The following script can automatically load the private key as environment variable. Assuming password is an empty string.

#!/usr/bin/env bash
PRIVATE_KEY_PATH="$HOME/.tauri/ezup.key";
if test -f "$PRIVATE_KEY_PATH"; then
export TAURI_PRIVATE_KEY=$(cat ~/.tauri/ezup.key); # if the private key is stored on disk
export TAURI_KEY_PASSWORD="";
else
echo "Warning: Private Key File Not Found";
fi

CICD (GitHub Action)

In GitHub Action, environment variables can be set like this in the top level of yml file.

env:
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}

I encountered a error during compilation on Ubuntu platform.

Error: thread '<unnamed>' panicked at 'Can't detect any appindicator library', src/build.rs:326:17

I found a solution in this issue.

Install libayatana-appindicator3-1-dev with apt for ubuntu.

Updater Server

vercel/hazel is a updater server for electron, can be deployed in a few clicks on vercel.

lemarier/tauri-update-server forks vercel/hazel.

I forked lemarier/tauri-update-server to be HuakunShen/tauri-update-server.

The reason I made a fork is that, new upates were made in vercel/hazel, and I merged the new commits to lemarier/tauri-update-server.

With one click, an update server can be deployed on Vercel.

See EzUp and HuakunShen/tauri-ezup-updater for and example.

The former is the actual Tauri app. The later is the corresponding update server.