create-signet-app 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -3
- package/src/desktop.ts +50 -0
- package/src/index.ts +104 -16
- package/template-cli/README.md +51 -0
- package/template-cli/_github/workflows/ci.yml +42 -0
- package/template-cli/_gitignore +9 -0
- package/template-cli/biome.json +49 -0
- package/template-cli/src/config.ts +23 -0
- package/template-cli/src/index.ts +104 -0
- package/template-cli/src/poll.ts +58 -0
- package/template-cli/src/ui.ts +16 -0
- package/template-cli/test/poll.test.ts +68 -0
- package/template-cli/tsconfig.json +15 -0
- package/template-cli/tsconfig.test.json +7 -0
- package/template-desktop/README.md +39 -0
- package/template-desktop/_github/workflows/ci.yml +48 -0
- package/template-desktop/_gitignore +6 -0
- package/template-desktop/biome.json +49 -0
- package/template-desktop/index.html +16 -0
- package/template-desktop/src/App.tsx +59 -0
- package/template-desktop/src/app.css +9 -0
- package/template-desktop/src/lib/auth.ts +102 -0
- package/template-desktop/src/lib/pkce.ts +21 -0
- package/template-desktop/src/main.tsx +16 -0
- package/template-desktop/src/pkce.test.ts +15 -0
- package/template-desktop/src-tauri/Cargo.toml +13 -0
- package/template-desktop/src-tauri/build.rs +3 -0
- package/template-desktop/src-tauri/capabilities/default.json +18 -0
- package/template-desktop/src-tauri/icons/128x128.png +0 -0
- package/template-desktop/src-tauri/icons/32x32.png +0 -0
- package/template-desktop/src-tauri/icons/icon.icns +0 -0
- package/template-desktop/src-tauri/icons/icon.ico +0 -0
- package/template-desktop/src-tauri/icons/icon.png +0 -0
- package/template-desktop/src-tauri/src/main.rs +124 -0
- package/template-desktop/src-tauri/tauri.conf.json +42 -0
- package/template-desktop/tsconfig.json +22 -0
- package/template-desktop/vite.config.ts +12 -0
- package/template-extension/.env.example +3 -0
- package/template-extension/README.md +64 -0
- package/template-extension/_github/workflows/ci.yml +22 -0
- package/template-extension/_gitignore +8 -0
- package/template-extension/biome.json +50 -0
- package/template-extension/options.html +13 -0
- package/template-extension/popup.html +13 -0
- package/template-extension/public/manifest.json +11 -0
- package/template-extension/public/theme-init.js +9 -0
- package/template-extension/src/app.css +9 -0
- package/template-extension/src/background.ts +23 -0
- package/template-extension/src/chrome.d.ts +21 -0
- package/template-extension/src/config.ts +11 -0
- package/template-extension/src/lib/api.ts +15 -0
- package/template-extension/src/lib/auth.ts +67 -0
- package/template-extension/src/lib/pkce.test.ts +13 -0
- package/template-extension/src/lib/pkce.ts +17 -0
- package/template-extension/src/lib/use-auth.ts +31 -0
- package/template-extension/src/options.tsx +56 -0
- package/template-extension/src/popup.tsx +44 -0
- package/template-extension/tsconfig.json +21 -0
- package/template-extension/vite.config.ts +23 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { pollDeviceToken } from "../src/poll.ts"
|
|
3
|
+
|
|
4
|
+
/** A fake token endpoint that answers from a script and records each call. */
|
|
5
|
+
function fake(script: Array<{ status: number; body: object }>) {
|
|
6
|
+
const calls: URLSearchParams[] = []
|
|
7
|
+
const f = (async (_url: string, init: RequestInit) => {
|
|
8
|
+
calls.push(init.body as URLSearchParams)
|
|
9
|
+
const step = script[Math.min(calls.length, script.length) - 1] as (typeof script)[number]
|
|
10
|
+
return new Response(JSON.stringify(step.body), { status: step.status })
|
|
11
|
+
}) as unknown as typeof fetch
|
|
12
|
+
return { f, calls }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function run(script: Parameters<typeof fake>[0], expiresIn = 600) {
|
|
16
|
+
const { f, calls } = fake(script)
|
|
17
|
+
const waits: number[] = []
|
|
18
|
+
let t = 0
|
|
19
|
+
const p = pollDeviceToken({
|
|
20
|
+
tokenUrl: "http://x/token",
|
|
21
|
+
clientId: "cli",
|
|
22
|
+
deviceCode: "dc",
|
|
23
|
+
interval: 5,
|
|
24
|
+
expiresIn,
|
|
25
|
+
fetch: f,
|
|
26
|
+
sleep: async (ms) => {
|
|
27
|
+
waits.push(ms / 1000)
|
|
28
|
+
t += ms
|
|
29
|
+
},
|
|
30
|
+
now: () => t,
|
|
31
|
+
})
|
|
32
|
+
return { p, calls, waits }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const pending = { status: 400, body: { error: "authorization_pending" } }
|
|
36
|
+
const ok = { status: 200, body: { access_token: "a", refresh_token: "r", expires_in: 900 } }
|
|
37
|
+
|
|
38
|
+
describe("pollDeviceToken", () => {
|
|
39
|
+
test("pending then success, sending the device grant", async () => {
|
|
40
|
+
const { p, calls, waits } = run([pending, pending, ok])
|
|
41
|
+
expect((await p).access_token).toBe("a")
|
|
42
|
+
expect(waits).toEqual([5, 5, 5])
|
|
43
|
+
expect(calls[0]?.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code")
|
|
44
|
+
expect(calls[0]?.get("device_code")).toBe("dc")
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test("slow_down adds 5 seconds to every later wait", async () => {
|
|
48
|
+
const { p, waits } = run([pending, { status: 400, body: { error: "slow_down" } }, pending, ok])
|
|
49
|
+
await p
|
|
50
|
+
expect(waits).toEqual([5, 5, 10, 10])
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
test("expired_token stops", async () => {
|
|
54
|
+
const { p } = run([pending, { status: 400, body: { error: "expired_token" } }])
|
|
55
|
+
await expect(p).rejects.toThrow(/expired/)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
test("gives up at expires_in even if the server keeps saying pending", async () => {
|
|
59
|
+
const { p, calls } = run([pending], 12)
|
|
60
|
+
await expect(p).rejects.toThrow(/expired/)
|
|
61
|
+
expect(calls.length).toBe(2)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
test("any other error surfaces its message", async () => {
|
|
65
|
+
const { p } = run([{ status: 400, body: { error: "access_denied", error_description: "No." } }])
|
|
66
|
+
await expect(p).rejects.toThrow("No.")
|
|
67
|
+
})
|
|
68
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"lib": ["ES2022"],
|
|
7
|
+
"types": ["bun"],
|
|
8
|
+
"strict": true,
|
|
9
|
+
"skipLibCheck": true,
|
|
10
|
+
"isolatedModules": true,
|
|
11
|
+
"allowImportingTsExtensions": true,
|
|
12
|
+
"noEmit": true
|
|
13
|
+
},
|
|
14
|
+
"include": ["src", "*.ts"]
|
|
15
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# __APP_NAME__
|
|
2
|
+
|
|
3
|
+
A Tauri v2 desktop and menu-bar app: React + Vite in the webview, styled with Signet's tokens and UI, signed in through the system browser.
|
|
4
|
+
|
|
5
|
+
## Run
|
|
6
|
+
|
|
7
|
+
You need [Rust](https://rustup.rs) and [Tauri's system dependencies](https://tauri.app/start/prerequisites/).
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
__PM_INSTALL__
|
|
11
|
+
__PM_X__ tauri dev
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`__PM_RUN__ dev` alone runs just the webview (no sign-in or tray; those need Tauri).
|
|
15
|
+
|
|
16
|
+
## What is here
|
|
17
|
+
|
|
18
|
+
- `src/` the webview. `src/lib/auth.ts` is sign-in; `src/lib/pkce.ts` the PKCE helper.
|
|
19
|
+
- `src-tauri/src/main.rs` the tray icon (left click toggles the small `tray` window, right click opens the menu), the two windows and the loopback listener.
|
|
20
|
+
- `src-tauri/tauri.conf.json` windows, CSP and bundling. The identifier `com.example.__APP_ID__` is a placeholder: set your own before you ship.
|
|
21
|
+
- `src-tauri/capabilities/default.json` what the windows may call. Narrow the `opener:allow-open-url` scope to your API's origin.
|
|
22
|
+
- `src-tauri/icons/` placeholder icons. Replace them: `__PM_X__ tauri icon path/to/logo.png`.
|
|
23
|
+
- `.github/workflows/ci.yml` lint, typecheck and test, then an installer build on macOS, Windows and Linux.
|
|
24
|
+
|
|
25
|
+
## Sign-in
|
|
26
|
+
|
|
27
|
+
Authorization code + PKCE (S256) against signet-server's `clientLoginRoutes`, mounted at `<API>/auth`. The app opens `/authorize` in your browser (you must be signed in to the web app there), the server redirects to `http://127.0.0.1:<port>/callback`, a one-shot listener in Rust hands the code to the webview, and the webview swaps it for tokens. Tokens are kept in the Tauri store (`auth.json`) through `createSession`.
|
|
28
|
+
|
|
29
|
+
Register the client on the server:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
clients: { "__APP_ID__-desktop": { redirectUris: ["http://127.0.0.1/callback"] } }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The server matches a port-less loopback URI on any port. Set `VITE_API_BASE` (default `http://localhost:8787/api`) to your API. The webview calls the API cross-origin, so the server's CORS must allow the webview's origin (`tauri://localhost` on macOS and Linux, `http://tauri.localhost` on Windows). In `tauri.conf.json`, narrow the CSP's `connect-src https:` to your API's origin.
|
|
36
|
+
|
|
37
|
+
## Release
|
|
38
|
+
|
|
39
|
+
CI builds unsigned installers. Code signing and notarization (Apple, Windows) are yours to add; see [Tauri's distribution guide](https://tauri.app/distribute/).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
verify:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: oven-sh/setup-bun@v2
|
|
17
|
+
# Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
|
|
18
|
+
- run: bun install --frozen-lockfile
|
|
19
|
+
- run: bun run lint
|
|
20
|
+
- run: bun run typecheck
|
|
21
|
+
- run: bun run test
|
|
22
|
+
|
|
23
|
+
# The Rust half: builds the installer on each OS (no signing, no release).
|
|
24
|
+
build:
|
|
25
|
+
needs: verify
|
|
26
|
+
strategy:
|
|
27
|
+
fail-fast: false
|
|
28
|
+
matrix:
|
|
29
|
+
os: [macos-latest, windows-latest, ubuntu-latest]
|
|
30
|
+
runs-on: ${{ matrix.os }}
|
|
31
|
+
steps:
|
|
32
|
+
- uses: actions/checkout@v4
|
|
33
|
+
- uses: oven-sh/setup-bun@v2
|
|
34
|
+
- uses: dtolnay/rust-toolchain@stable
|
|
35
|
+
- uses: Swatinem/rust-cache@v2
|
|
36
|
+
with:
|
|
37
|
+
workspaces: src-tauri
|
|
38
|
+
- name: Linux system libraries
|
|
39
|
+
if: matrix.os == 'ubuntu-latest'
|
|
40
|
+
run: |
|
|
41
|
+
sudo apt-get update
|
|
42
|
+
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
|
|
43
|
+
- run: bun install --frozen-lockfile
|
|
44
|
+
- run: bunx tauri build
|
|
45
|
+
- uses: actions/upload-artifact@v4
|
|
46
|
+
with:
|
|
47
|
+
name: __APP_ID__-${{ matrix.os }}
|
|
48
|
+
path: src-tauri/target/release/bundle/**
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"vcs": {
|
|
3
|
+
"enabled": true,
|
|
4
|
+
"clientKind": "git",
|
|
5
|
+
"useIgnoreFile": true
|
|
6
|
+
},
|
|
7
|
+
"files": {
|
|
8
|
+
"ignoreUnknown": true,
|
|
9
|
+
"includes": ["**", "!**/routeTree.gen.ts"]
|
|
10
|
+
},
|
|
11
|
+
"formatter": {
|
|
12
|
+
"enabled": true,
|
|
13
|
+
"indentStyle": "space",
|
|
14
|
+
"indentWidth": 2,
|
|
15
|
+
"lineWidth": 100
|
|
16
|
+
},
|
|
17
|
+
"javascript": {
|
|
18
|
+
"formatter": {
|
|
19
|
+
"quoteStyle": "double",
|
|
20
|
+
"semicolons": "asNeeded"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"linter": {
|
|
24
|
+
"enabled": true,
|
|
25
|
+
"rules": {
|
|
26
|
+
"correctness": {
|
|
27
|
+
"useExhaustiveDependencies": "warn",
|
|
28
|
+
"useHookAtTopLevel": "error"
|
|
29
|
+
},
|
|
30
|
+
"suspicious": {
|
|
31
|
+
"noExplicitAny": "warn"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"assist": {
|
|
36
|
+
"actions": {
|
|
37
|
+
"source": {
|
|
38
|
+
"organizeImports": "on"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"css": {
|
|
43
|
+
"parser": {
|
|
44
|
+
"cssModules": false,
|
|
45
|
+
"allowWrongLineComments": false,
|
|
46
|
+
"tailwindDirectives": true
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>__APP_NAME__</title>
|
|
7
|
+
<!-- Applies the stored theme before first paint; React mounts too late. -->
|
|
8
|
+
<script>
|
|
9
|
+
(() => { try { const t = localStorage.getItem("signet-theme"); const d = t === "dark" || ((!t || t === "system") && matchMedia("(prefers-color-scheme: dark)").matches); document.documentElement.classList.toggle("dark", d); document.documentElement.style.colorScheme = d ? "dark" : "light" } catch {} })()
|
|
10
|
+
</script>
|
|
11
|
+
</head>
|
|
12
|
+
<body>
|
|
13
|
+
<div id="root"></div>
|
|
14
|
+
<script type="module" src="/src/main.tsx"></script>
|
|
15
|
+
</body>
|
|
16
|
+
</html>
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Button } from "@dapplelight/signet-ui/components/button"
|
|
2
|
+
import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
|
|
3
|
+
import { ThemeToggle } from "@dapplelight/signet-ui/components/theme-toggle"
|
|
4
|
+
import { getCurrentWindow } from "@tauri-apps/api/window"
|
|
5
|
+
import { useEffect, useState } from "react"
|
|
6
|
+
import { session, signIn, signOut } from "./lib/auth"
|
|
7
|
+
|
|
8
|
+
/** null while the stored session loads. */
|
|
9
|
+
function useSignedIn(): boolean | null {
|
|
10
|
+
const [signedIn, setSignedIn] = useState<boolean | null>(null)
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
session.get().then((t) => setSignedIn(t !== null))
|
|
13
|
+
return session.subscribe((t) => setSignedIn(t !== null))
|
|
14
|
+
}, [])
|
|
15
|
+
return signedIn
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function App() {
|
|
19
|
+
const signedIn = useSignedIn()
|
|
20
|
+
const [error, setError] = useState<string>()
|
|
21
|
+
// One flow at a time: a second click would start a second PKCE flow.
|
|
22
|
+
const [busy, setBusy] = useState(false)
|
|
23
|
+
// One webview app, two windows: the small tray window and the main window.
|
|
24
|
+
const compact = getCurrentWindow().label === "tray"
|
|
25
|
+
|
|
26
|
+
const run = (fn: () => Promise<void>) => {
|
|
27
|
+
setError(undefined)
|
|
28
|
+
setBusy(true)
|
|
29
|
+
fn()
|
|
30
|
+
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)))
|
|
31
|
+
.finally(() => setBusy(false))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return (
|
|
35
|
+
<main className={compact ? "p-3" : "mx-auto max-w-md p-8"}>
|
|
36
|
+
<Card>
|
|
37
|
+
<CardHeader className="flex-row items-center justify-between">
|
|
38
|
+
<CardTitle>__APP_NAME__</CardTitle>
|
|
39
|
+
<ThemeToggle />
|
|
40
|
+
</CardHeader>
|
|
41
|
+
<CardContent className="space-y-3">
|
|
42
|
+
<p className="text-sm text-muted-foreground">
|
|
43
|
+
{signedIn === null ? "Loading..." : signedIn ? "Signed in." : "Signed out."}
|
|
44
|
+
</p>
|
|
45
|
+
{signedIn ? (
|
|
46
|
+
<Button variant="outline" disabled={busy} onClick={() => run(signOut)}>
|
|
47
|
+
Sign out
|
|
48
|
+
</Button>
|
|
49
|
+
) : (
|
|
50
|
+
<Button disabled={signedIn === null || busy} onClick={() => run(signIn)}>
|
|
51
|
+
Sign in with your browser
|
|
52
|
+
</Button>
|
|
53
|
+
)}
|
|
54
|
+
{error && <p className="text-sm text-destructive">{error}</p>}
|
|
55
|
+
</CardContent>
|
|
56
|
+
</Card>
|
|
57
|
+
</main>
|
|
58
|
+
)
|
|
59
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
@import "tailwindcss";
|
|
2
|
+
@import "@dapplelight/signet-tokens/__THEME__.css";
|
|
3
|
+
@import "@dapplelight/signet-tokens/base.css";
|
|
4
|
+
|
|
5
|
+
/* Tailwind does not scan node_modules, and @dapplelight/signet-ui ships compiled JS
|
|
6
|
+
whose class names must be seen or every component renders unstyled. The theme
|
|
7
|
+
cannot declare this — a package does not know where it is installed.
|
|
8
|
+
Must come after the @import rules: CSS requires imports first. */
|
|
9
|
+
@source "../node_modules/@dapplelight/signet-ui/dist";
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in against signet-server's `clientLoginRoutes` (mounted at `<API>/auth`):
|
|
3
|
+
* authorization code + PKCE through the system browser, with the code returned
|
|
4
|
+
* to a one-shot loopback listener in Rust (`listen_for_callback`). The server
|
|
5
|
+
* matches a port-less registered `http://127.0.0.1/callback` on any port.
|
|
6
|
+
*
|
|
7
|
+
* Tokens live in the Tauri store (`auth.json`) behind `createSession`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createApiClient } from "@dapplelight/signet-lib/api"
|
|
11
|
+
import {
|
|
12
|
+
createSession,
|
|
13
|
+
fromTokenResponse,
|
|
14
|
+
tokenEndpointRefresh,
|
|
15
|
+
} from "@dapplelight/signet-lib/session"
|
|
16
|
+
import { tauriStorage } from "@dapplelight/signet-lib/storage"
|
|
17
|
+
import { invoke } from "@tauri-apps/api/core"
|
|
18
|
+
import { listen } from "@tauri-apps/api/event"
|
|
19
|
+
import { openUrl } from "@tauri-apps/plugin-opener"
|
|
20
|
+
import { LazyStore } from "@tauri-apps/plugin-store"
|
|
21
|
+
import { createPkce } from "./pkce"
|
|
22
|
+
|
|
23
|
+
export const API_BASE: string = import.meta.env.VITE_API_BASE ?? "http://localhost:8787/api"
|
|
24
|
+
const AUTH = `${API_BASE}/auth`
|
|
25
|
+
/** Register this id on the server with redirectUris ["http://127.0.0.1/callback"]. */
|
|
26
|
+
export const CLIENT_ID = "__APP_ID__-desktop"
|
|
27
|
+
const TIMEOUT_MS = 5 * 60_000
|
|
28
|
+
|
|
29
|
+
export const session = createSession({
|
|
30
|
+
storage: tauriStorage(new LazyStore("auth.json")),
|
|
31
|
+
refresh: tokenEndpointRefresh(`${AUTH}/token`, CLIENT_ID),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
export const api = createApiClient({
|
|
35
|
+
baseUrl: API_BASE,
|
|
36
|
+
token: session.token,
|
|
37
|
+
refresh: session.refresh,
|
|
38
|
+
credentials: "omit",
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
export async function signIn(): Promise<void> {
|
|
42
|
+
const { verifier, challenge, state } = await createPkce()
|
|
43
|
+
let onCallback: (query: string) => void = () => {}
|
|
44
|
+
const callback = new Promise<string>((resolve) => {
|
|
45
|
+
onCallback = resolve
|
|
46
|
+
})
|
|
47
|
+
const unlisten = await listen<string>("oauth-callback", (e) => onCallback(e.payload))
|
|
48
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
49
|
+
try {
|
|
50
|
+
const port = await invoke<number>("listen_for_callback")
|
|
51
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`
|
|
52
|
+
const url = new URL(`${AUTH}/authorize`)
|
|
53
|
+
url.search = new URLSearchParams({
|
|
54
|
+
response_type: "code",
|
|
55
|
+
client_id: CLIENT_ID,
|
|
56
|
+
redirect_uri: redirectUri,
|
|
57
|
+
code_challenge: challenge,
|
|
58
|
+
code_challenge_method: "S256",
|
|
59
|
+
state,
|
|
60
|
+
}).toString()
|
|
61
|
+
await openUrl(url.toString())
|
|
62
|
+
|
|
63
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
64
|
+
timer = setTimeout(() => reject(new Error("Sign-in timed out")), TIMEOUT_MS)
|
|
65
|
+
})
|
|
66
|
+
const query = new URLSearchParams(await Promise.race([callback, timeout]))
|
|
67
|
+
if (query.get("state") !== state) throw new Error("Sign-in state mismatch")
|
|
68
|
+
const code = query.get("code")
|
|
69
|
+
if (!code)
|
|
70
|
+
throw new Error(query.get("error_description") ?? query.get("error") ?? "Sign-in failed")
|
|
71
|
+
|
|
72
|
+
const res = await fetch(`${AUTH}/token`, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
75
|
+
body: new URLSearchParams({
|
|
76
|
+
grant_type: "authorization_code",
|
|
77
|
+
code,
|
|
78
|
+
code_verifier: verifier,
|
|
79
|
+
redirect_uri: redirectUri,
|
|
80
|
+
client_id: CLIENT_ID,
|
|
81
|
+
}),
|
|
82
|
+
})
|
|
83
|
+
if (!res.ok) throw new Error(`Sign-in failed (HTTP ${res.status})`)
|
|
84
|
+
await session.set(fromTokenResponse(await res.json()))
|
|
85
|
+
} finally {
|
|
86
|
+
clearTimeout(timer)
|
|
87
|
+
unlisten()
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Revokes the session on the server (best effort), then forgets the tokens. */
|
|
92
|
+
export async function signOut(): Promise<void> {
|
|
93
|
+
const refreshToken = (await session.get())?.refreshToken
|
|
94
|
+
if (refreshToken) {
|
|
95
|
+
await fetch(`${AUTH}/revoke`, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
98
|
+
body: new URLSearchParams({ token: refreshToken }),
|
|
99
|
+
}).catch(() => {})
|
|
100
|
+
}
|
|
101
|
+
await session.clear()
|
|
102
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** PKCE (RFC 7636, S256) and a state value, from the webview's WebCrypto. */
|
|
2
|
+
|
|
3
|
+
const b64url = (bytes: Uint8Array) =>
|
|
4
|
+
btoa(String.fromCharCode(...bytes))
|
|
5
|
+
.replaceAll("+", "-")
|
|
6
|
+
.replaceAll("/", "_")
|
|
7
|
+
.replace(/=+$/, "")
|
|
8
|
+
|
|
9
|
+
/** 32 random bytes, base64url: 43 characters, inside the verifier's 43-128. */
|
|
10
|
+
export const randomToken = () => b64url(crypto.getRandomValues(new Uint8Array(32)))
|
|
11
|
+
|
|
12
|
+
/** base64url(SHA-256(verifier)), the `code_challenge` for `code_challenge_method=S256`. */
|
|
13
|
+
export async function pkceChallenge(verifier: string): Promise<string> {
|
|
14
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
|
|
15
|
+
return b64url(new Uint8Array(digest))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function createPkce() {
|
|
19
|
+
const verifier = randomToken()
|
|
20
|
+
return { verifier, challenge: await pkceChallenge(verifier), state: randomToken() }
|
|
21
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ThemeProvider } from "@dapplelight/signet-ui/components/theme-provider"
|
|
2
|
+
import { StrictMode } from "react"
|
|
3
|
+
import { createRoot } from "react-dom/client"
|
|
4
|
+
import { App } from "./App"
|
|
5
|
+
import "./app.css"
|
|
6
|
+
|
|
7
|
+
const rootElement = document.getElementById("root")
|
|
8
|
+
if (!rootElement) throw new Error("Root element #root not found in index.html")
|
|
9
|
+
|
|
10
|
+
createRoot(rootElement).render(
|
|
11
|
+
<StrictMode>
|
|
12
|
+
<ThemeProvider>
|
|
13
|
+
<App />
|
|
14
|
+
</ThemeProvider>
|
|
15
|
+
</StrictMode>,
|
|
16
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { createPkce, pkceChallenge } from "./lib/pkce"
|
|
3
|
+
|
|
4
|
+
test("S256 challenge matches the RFC 7636 appendix B vector", async () => {
|
|
5
|
+
expect(await pkceChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe(
|
|
6
|
+
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
|
|
7
|
+
)
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
test("verifier is 43 unreserved characters and state differs from it", async () => {
|
|
11
|
+
const { verifier, challenge, state } = await createPkce()
|
|
12
|
+
expect(verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)
|
|
13
|
+
expect(challenge).toMatch(/^[A-Za-z0-9_-]{43}$/)
|
|
14
|
+
expect(state).not.toBe(verifier)
|
|
15
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "__APP_ID__"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "__APP_NAME__"
|
|
5
|
+
edition = "2021"
|
|
6
|
+
|
|
7
|
+
[build-dependencies]
|
|
8
|
+
tauri-build = { version = "2", features = [] }
|
|
9
|
+
|
|
10
|
+
[dependencies]
|
|
11
|
+
tauri = { version = "2", features = ["tray-icon"] }
|
|
12
|
+
tauri-plugin-opener = "2"
|
|
13
|
+
tauri-plugin-store = "2"
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../gen/schemas/desktop-schema.json",
|
|
3
|
+
"identifier": "default",
|
|
4
|
+
"description": "What the main and tray windows may do. Nothing else is allowed.",
|
|
5
|
+
"windows": ["main", "tray"],
|
|
6
|
+
"permissions": [
|
|
7
|
+
"core:default",
|
|
8
|
+
{
|
|
9
|
+
"identifier": "opener:allow-open-url",
|
|
10
|
+
"allow": [{ "url": "https://*" }, { "url": "http://localhost:*" }]
|
|
11
|
+
},
|
|
12
|
+
"store:allow-load",
|
|
13
|
+
"store:allow-get",
|
|
14
|
+
"store:allow-set",
|
|
15
|
+
"store:allow-delete",
|
|
16
|
+
"store:allow-save"
|
|
17
|
+
]
|
|
18
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// No console window on Windows release builds.
|
|
2
|
+
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
3
|
+
|
|
4
|
+
use std::{
|
|
5
|
+
io::{ErrorKind, Read, Write},
|
|
6
|
+
net::TcpListener,
|
|
7
|
+
thread,
|
|
8
|
+
time::{Duration, Instant},
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
use tauri::{
|
|
12
|
+
menu::{Menu, MenuItem},
|
|
13
|
+
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
|
|
14
|
+
Emitter, Manager, WindowEvent,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const CALLBACK_PAGE: &str = "<!doctype html><meta charset=utf-8><title>Signed in</title>\
|
|
18
|
+
<p style=\"font-family:system-ui;margin:3rem\">Signed in. You can close this tab.</p>";
|
|
19
|
+
|
|
20
|
+
fn reply(stream: &mut std::net::TcpStream, status: &str, body: &str) {
|
|
21
|
+
let _ = write!(
|
|
22
|
+
stream,
|
|
23
|
+
"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
|
24
|
+
body.len()
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// Sign-in step: bind a loopback port for the OAuth redirect and return it. The
|
|
29
|
+
/// first `GET /callback?...` is emitted to the webview as `oauth-callback`
|
|
30
|
+
/// (the raw query string), then the listener closes; so does it after 5 minutes.
|
|
31
|
+
#[tauri::command]
|
|
32
|
+
fn listen_for_callback(app: tauri::AppHandle) -> Result<u16, String> {
|
|
33
|
+
let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
|
|
34
|
+
listener.set_nonblocking(true).map_err(|e| e.to_string())?;
|
|
35
|
+
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
|
36
|
+
thread::spawn(move || {
|
|
37
|
+
let deadline = Instant::now() + Duration::from_secs(300);
|
|
38
|
+
while Instant::now() < deadline {
|
|
39
|
+
match listener.accept() {
|
|
40
|
+
Ok((mut stream, _)) => {
|
|
41
|
+
let _ = stream.set_nonblocking(false);
|
|
42
|
+
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
|
|
43
|
+
let mut buf = [0u8; 4096];
|
|
44
|
+
let n = stream.read(&mut buf).unwrap_or(0);
|
|
45
|
+
let request = String::from_utf8_lossy(&buf[..n]);
|
|
46
|
+
let target = request.split_whitespace().nth(1).unwrap_or("");
|
|
47
|
+
if let Some(query) = target.strip_prefix("/callback?") {
|
|
48
|
+
let _ = app.emit("oauth-callback", query.to_string());
|
|
49
|
+
reply(&mut stream, "200 OK", CALLBACK_PAGE);
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
reply(&mut stream, "404 Not Found", "");
|
|
53
|
+
}
|
|
54
|
+
Err(e) if e.kind() == ErrorKind::WouldBlock => {
|
|
55
|
+
thread::sleep(Duration::from_millis(100))
|
|
56
|
+
}
|
|
57
|
+
Err(_) => break,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
Ok(port)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
fn show(app: &tauri::AppHandle, label: &str) {
|
|
65
|
+
if let Some(window) = app.get_webview_window(label) {
|
|
66
|
+
let _ = window.show();
|
|
67
|
+
let _ = window.set_focus();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
fn main() {
|
|
72
|
+
tauri::Builder::default()
|
|
73
|
+
.plugin(tauri_plugin_opener::init())
|
|
74
|
+
.plugin(tauri_plugin_store::Builder::new().build())
|
|
75
|
+
.invoke_handler(tauri::generate_handler![listen_for_callback])
|
|
76
|
+
.setup(|app| {
|
|
77
|
+
let open = MenuItem::with_id(app, "open", "Open", true, None::<&str>)?;
|
|
78
|
+
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
|
|
79
|
+
let menu = Menu::with_items(app, &[&open, &quit])?;
|
|
80
|
+
TrayIconBuilder::new()
|
|
81
|
+
.icon(app.default_window_icon().expect("bundle icon").clone())
|
|
82
|
+
.menu(&menu)
|
|
83
|
+
.show_menu_on_left_click(false)
|
|
84
|
+
.on_menu_event(|app, event| match event.id.as_ref() {
|
|
85
|
+
"open" => show(app, "main"),
|
|
86
|
+
"quit" => app.exit(0),
|
|
87
|
+
_ => {}
|
|
88
|
+
})
|
|
89
|
+
// Left click toggles the small window; right click opens the menu.
|
|
90
|
+
// ponytail: not positioned under the icon; add a positioner when it matters.
|
|
91
|
+
.on_tray_icon_event(|tray, event| {
|
|
92
|
+
if let TrayIconEvent::Click {
|
|
93
|
+
button: MouseButton::Left,
|
|
94
|
+
button_state: MouseButtonState::Up,
|
|
95
|
+
..
|
|
96
|
+
} = event
|
|
97
|
+
{
|
|
98
|
+
let app = tray.app_handle();
|
|
99
|
+
match app.get_webview_window("tray") {
|
|
100
|
+
Some(w) if w.is_visible().unwrap_or(false) => {
|
|
101
|
+
let _ = w.hide();
|
|
102
|
+
}
|
|
103
|
+
_ => show(app, "tray"),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
.build(app)?;
|
|
108
|
+
Ok(())
|
|
109
|
+
})
|
|
110
|
+
.on_window_event(|window, event| match (window.label(), event) {
|
|
111
|
+
// The tray window hides when it loses focus; closing the main window
|
|
112
|
+
// keeps the app running in the tray (Quit is in the tray menu).
|
|
113
|
+
("tray", WindowEvent::Focused(false)) => {
|
|
114
|
+
let _ = window.hide();
|
|
115
|
+
}
|
|
116
|
+
("main", WindowEvent::CloseRequested { api, .. }) => {
|
|
117
|
+
api.prevent_close();
|
|
118
|
+
let _ = window.hide();
|
|
119
|
+
}
|
|
120
|
+
_ => {}
|
|
121
|
+
})
|
|
122
|
+
.run(tauri::generate_context!())
|
|
123
|
+
.expect("error while running the application");
|
|
124
|
+
}
|