源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
@@ -0,0 +1,73 @@
|
||||
# @tutti-os/auth-bridge
|
||||
|
||||
High-level Tutti auth helpers for browser apps and Node/Electron clients.
|
||||
|
||||
## Shared contract
|
||||
|
||||
Clients that implement their own platform-specific account UI can reuse the
|
||||
canonical account defaults without importing Browser or Node runtime behavior:
|
||||
|
||||
```ts
|
||||
import {
|
||||
DEFAULT_ACCOUNT_BASE_URL,
|
||||
DEFAULT_APP_ID
|
||||
} from "@tutti-os/auth-bridge/shared";
|
||||
```
|
||||
|
||||
Keep compatibility identifiers in this shared contract rather than copying
|
||||
their literal values into product clients.
|
||||
|
||||
## Browser
|
||||
|
||||
```ts
|
||||
import { createTuttiBrowserAuthClient } from "@tutti-os/auth-bridge/browser";
|
||||
|
||||
const auth = createTuttiBrowserAuthClient();
|
||||
|
||||
auth.login();
|
||||
const user = await auth.getUserInfo();
|
||||
await auth.logout();
|
||||
```
|
||||
|
||||
## Node
|
||||
|
||||
```ts
|
||||
import { createTuttiNodeAuthClient } from "@tutti-os/auth-bridge/node";
|
||||
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath,
|
||||
appCallbackUrl,
|
||||
accountHeaders: { "x-environment-lane": "example" }
|
||||
});
|
||||
|
||||
const { session, user } = await auth.login();
|
||||
```
|
||||
|
||||
`accountHeaders` adds host-owned headers to Account API requests. The bridge
|
||||
always owns and overwrites its JSON content negotiation and Desktop session
|
||||
cookie headers.
|
||||
|
||||
## Local Desktop Callback
|
||||
|
||||
The Node bridge starts a loopback HTTP server for desktop sign-in. New desktop OAuth completions use:
|
||||
|
||||
- `GET /oauth/callback?state=<base64url>&transfer_code=<code>`
|
||||
- `GET /oauth/callback?state=<base64url>&error=<providerError>`
|
||||
- `GET /oauth/callback?state=<base64url>&error=user_cancelled`
|
||||
|
||||
The callback validates the signed login state, redeems the desktop transfer code through the account service, writes `auth.json`, fetches user info, and redirects the browser back to the web result page:
|
||||
|
||||
```text
|
||||
/auth/login/callback?desktopBridgeStatus=success&openAppUrl=<safe-deeplink>
|
||||
/auth/login/callback?desktopBridgeStatus=error&desktopBridgeError=<safeCode>&openAppUrl=<safe-deeplink>
|
||||
```
|
||||
|
||||
`openAppUrl` is only used to focus or reopen Tutti. It is sanitized to the allowed app schemes and must not carry `transfer_code`, sessions, or tokens.
|
||||
|
||||
An explicit `user_cancelled` callback is preserved as a typed cancellation for
|
||||
Node/Go consumers and returns the safe Web result code `userCancelled`.
|
||||
Cancellation results intentionally omit `openAppUrl`, so the Web result page
|
||||
can keep the user in the browser. Other callback errors continue to use the
|
||||
safe `providerError` result code.
|
||||
|
||||
`/oauth/health` and `POST /oauth/complete` remain available for compatibility with older web clients, but the current web flow redirects the browser to `/oauth/callback` instead of fetching the local bridge.
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "@tutti-os/auth-bridge",
|
||||
"version": "0.0.0-test.20260630000000.local",
|
||||
"private": false,
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tutti-os/tutti.git",
|
||||
"directory": "packages/auth/bridge"
|
||||
},
|
||||
"type": "module",
|
||||
"types": "./src/browser.ts",
|
||||
"exports": {
|
||||
"./browser": "./src/browser.ts",
|
||||
"./node": "./src/node.ts",
|
||||
"./shared": "./src/shared.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup --config tsup.config.ts",
|
||||
"type-check": "tsc --noEmit",
|
||||
"test": "pnpm exec tsx --test src/*.test.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"exports": {
|
||||
"./browser": {
|
||||
"types": "./dist/browser.d.ts",
|
||||
"import": "./dist/browser.js"
|
||||
},
|
||||
"./node": {
|
||||
"types": "./dist/node.d.ts",
|
||||
"import": "./dist/node.js"
|
||||
},
|
||||
"./shared": {
|
||||
"types": "./dist/shared.d.ts",
|
||||
"import": "./dist/shared.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/browser.d.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createTuttiBrowserAuthClient } from "./browser";
|
||||
import { DEFAULT_APP_ID } from "./shared";
|
||||
|
||||
test("browser login redirects in-place by default", () => {
|
||||
const assigned: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: {
|
||||
location: {
|
||||
pathname: "/room/1",
|
||||
search: "?tab=tasks",
|
||||
hash: "#top",
|
||||
assign: (url: string) => assigned.push(url)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
createTuttiBrowserAuthClient().login();
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: previousWindow
|
||||
});
|
||||
}
|
||||
|
||||
const url = new URL(assigned[0]);
|
||||
assert.equal(url.toString().startsWith("https://tutti.sh/auth/login?"), true);
|
||||
assert.equal(url.searchParams.get("redirect_uri"), "/room/1?tab=tasks#top");
|
||||
});
|
||||
|
||||
test("browser getUserInfo returns user and nulls unauthorized sessions", async () => {
|
||||
const previousFetch = globalThis.fetch;
|
||||
const requests: string[] = [];
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
requests.push(url);
|
||||
if (requests.length === 1) {
|
||||
return new Response(
|
||||
JSON.stringify({ code: 0, data: { user_id: "user-1", name: "Alice" } }),
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 401, errmsg: "Unauthorized" }), {
|
||||
status: 401
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const auth = createTuttiBrowserAuthClient();
|
||||
assert.deepEqual(await auth.getUserInfo(), {
|
||||
userId: "user-1",
|
||||
name: "Alice",
|
||||
email: undefined,
|
||||
avatar: undefined
|
||||
});
|
||||
assert.equal(await auth.getUserInfo(), null);
|
||||
} finally {
|
||||
globalThis.fetch = previousFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("browser logout calls account logout endpoint", async () => {
|
||||
const previousFetch = globalThis.fetch;
|
||||
let requestBody = "";
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
assert.equal(
|
||||
String(input),
|
||||
"https://tutti.sh/api/account/auth/v1/logout-web-session"
|
||||
);
|
||||
requestBody = String(init?.body ?? "");
|
||||
return new Response("", { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
await createTuttiBrowserAuthClient().logout();
|
||||
} finally {
|
||||
globalThis.fetch = previousFetch;
|
||||
}
|
||||
|
||||
assert.deepEqual(JSON.parse(requestBody), { appId: DEFAULT_APP_ID });
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import {
|
||||
type AccountEnvelope,
|
||||
buildAccountUrl,
|
||||
DEFAULT_ACCOUNT_BASE_URL,
|
||||
DEFAULT_APP_ID,
|
||||
DEFAULT_AUTH_LOGIN_URL,
|
||||
mapUserInfo,
|
||||
readEnvelopeError,
|
||||
type TuttiUserInfo
|
||||
} from "./shared";
|
||||
|
||||
export interface TuttiBrowserAuthClientOptions {
|
||||
openUrl?: (url: string) => void;
|
||||
appId?: string;
|
||||
accountBaseUrl?: string;
|
||||
authLoginUrl?: string;
|
||||
}
|
||||
|
||||
export interface TuttiBrowserLoginOptions {
|
||||
redirectUri?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export interface TuttiBrowserAuthClient {
|
||||
login: (options?: TuttiBrowserLoginOptions) => void;
|
||||
getUserInfo: () => Promise<TuttiUserInfo | null>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
function defaultOpenUrl(url: string): void {
|
||||
window.location.assign(url);
|
||||
}
|
||||
|
||||
function resolveCurrentRedirectUri(): string {
|
||||
return (
|
||||
`${window.location.pathname}${window.location.search}${window.location.hash}` ||
|
||||
"/"
|
||||
);
|
||||
}
|
||||
|
||||
async function readJsonEnvelope<T>(
|
||||
response: Response
|
||||
): Promise<AccountEnvelope<T> | null> {
|
||||
return (await response.json().catch(() => null)) as AccountEnvelope<T> | null;
|
||||
}
|
||||
|
||||
export function createTuttiBrowserAuthClient(
|
||||
options: TuttiBrowserAuthClientOptions = {}
|
||||
): TuttiBrowserAuthClient {
|
||||
const appId = options.appId?.trim() || DEFAULT_APP_ID;
|
||||
const accountBaseUrl =
|
||||
options.accountBaseUrl?.trim() || DEFAULT_ACCOUNT_BASE_URL;
|
||||
const authLoginUrl = options.authLoginUrl?.trim() || DEFAULT_AUTH_LOGIN_URL;
|
||||
const openUrl = options.openUrl ?? defaultOpenUrl;
|
||||
|
||||
return {
|
||||
login(loginOptions: TuttiBrowserLoginOptions = {}): void {
|
||||
const url = new URL(authLoginUrl);
|
||||
url.searchParams.set(
|
||||
"redirect_uri",
|
||||
loginOptions.redirectUri ?? resolveCurrentRedirectUri()
|
||||
);
|
||||
if (loginOptions.locale) {
|
||||
url.searchParams.set("locale", loginOptions.locale);
|
||||
}
|
||||
openUrl(url.toString());
|
||||
},
|
||||
|
||||
async getUserInfo(): Promise<TuttiUserInfo | null> {
|
||||
const response = await fetch(
|
||||
buildAccountUrl(accountBaseUrl, "/user/v1/user_info"),
|
||||
{
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({})
|
||||
}
|
||||
);
|
||||
const payload = await readJsonEnvelope<Record<string, unknown>>(response);
|
||||
if (response.status === 401 || payload?.code === 401) {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok || payload?.code !== 0) {
|
||||
throw readEnvelopeError(response, payload);
|
||||
}
|
||||
return mapUserInfo(payload.data);
|
||||
},
|
||||
|
||||
async logout(): Promise<void> {
|
||||
const response = await fetch(
|
||||
buildAccountUrl(accountBaseUrl, "/auth/v1/logout-web-session"),
|
||||
{
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ appId })
|
||||
}
|
||||
);
|
||||
const payload = await readJsonEnvelope<Record<string, never>>(response);
|
||||
if (!response.ok || (payload?.code ?? 0) !== 0) {
|
||||
throw readEnvelopeError(response, payload);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export type { TuttiUserInfo } from "./shared";
|
||||
@@ -0,0 +1,91 @@
|
||||
import { DEFAULT_APP_ID } from "./shared";
|
||||
|
||||
const USER_CANCELLED_CALLBACK_ERROR = "user_cancelled";
|
||||
const USER_CANCELLED_RESULT_ERROR = "userCancelled";
|
||||
|
||||
export type TuttiAuthErrorCode = "user_cancelled";
|
||||
|
||||
export class TuttiAuthError extends Error {
|
||||
readonly code: TuttiAuthErrorCode;
|
||||
|
||||
constructor(code: TuttiAuthErrorCode, message = code) {
|
||||
super(message);
|
||||
this.name = "TuttiAuthError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function isTuttiAuthUserCancelledError(
|
||||
error: unknown
|
||||
): error is TuttiAuthError {
|
||||
return (
|
||||
error instanceof TuttiAuthError &&
|
||||
error.code === USER_CANCELLED_CALLBACK_ERROR
|
||||
);
|
||||
}
|
||||
|
||||
export function callbackErrorToError(callbackError: string): Error {
|
||||
return callbackError === USER_CANCELLED_CALLBACK_ERROR
|
||||
? new TuttiAuthError(USER_CANCELLED_CALLBACK_ERROR)
|
||||
: new Error(callbackError);
|
||||
}
|
||||
|
||||
export function callbackErrorToSafeResultCode(callbackError: string): string {
|
||||
return callbackError === USER_CANCELLED_CALLBACK_ERROR
|
||||
? USER_CANCELLED_RESULT_ERROR
|
||||
: "providerError";
|
||||
}
|
||||
|
||||
export function buildBridgeResultUrl(
|
||||
input: { appCallbackUrl: string; authOrigin: string },
|
||||
status: string,
|
||||
safeErrorCode?: string
|
||||
): string {
|
||||
const url = new URL("/auth/login/callback", input.authOrigin);
|
||||
url.searchParams.set("desktopBridgeStatus", status);
|
||||
if (safeErrorCode) {
|
||||
url.searchParams.set("desktopBridgeError", safeErrorCode);
|
||||
}
|
||||
const openAppUrl =
|
||||
safeErrorCode === USER_CANCELLED_RESULT_ERROR
|
||||
? null
|
||||
: buildSafeOpenAppUrl(input.appCallbackUrl, status, safeErrorCode);
|
||||
if (openAppUrl) {
|
||||
url.searchParams.set("openAppUrl", openAppUrl);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function buildSafeOpenAppUrl(
|
||||
rawUrl: string,
|
||||
status: string,
|
||||
safeErrorCode?: string
|
||||
): string | null {
|
||||
try {
|
||||
const url = new URL(rawUrl.trim());
|
||||
if (!isAllowedAppCallbackProtocol(url.protocol)) {
|
||||
return null;
|
||||
}
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
url.searchParams.set("desktopBridgeStatus", status);
|
||||
if (safeErrorCode) {
|
||||
url.searchParams.set("desktopBridgeError", safeErrorCode);
|
||||
}
|
||||
return url.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isAllowedAppCallbackProtocol(protocol: string): boolean {
|
||||
const legacyProtocol = `${DEFAULT_APP_ID}:`;
|
||||
const legacyDevProtocol = `${DEFAULT_APP_ID}-dev:`;
|
||||
|
||||
return (
|
||||
protocol === "tutti:" ||
|
||||
protocol === "tutti-dev:" ||
|
||||
protocol === legacyProtocol ||
|
||||
protocol === legacyDevProtocol
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse
|
||||
} from "node:http";
|
||||
import { createConnection, type AddressInfo, type Socket } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createTuttiNodeAuthClient,
|
||||
isTuttiAuthUserCancelledError,
|
||||
readAuthJson,
|
||||
writeAuthJson
|
||||
} from "./node";
|
||||
import { DEFAULT_APP_ID } from "./shared";
|
||||
|
||||
test("auth json read/write keeps desktop-compatible shape", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
try {
|
||||
await writeAuthJson(file, {
|
||||
sessionId: "session-1",
|
||||
cookie: "session_id=session-1",
|
||||
userId: "user-1",
|
||||
name: "Alice",
|
||||
avatar: "https://example.com/a.png",
|
||||
email: "alice@example.com",
|
||||
updatedAt: 123
|
||||
});
|
||||
assert.deepEqual(JSON.parse(await readFile(file, "utf8")), {
|
||||
session_id: "session-1",
|
||||
cookie: "session_id=session-1",
|
||||
user_id: "user-1",
|
||||
name: "Alice",
|
||||
avatar: "https://example.com/a.png",
|
||||
email: "alice@example.com",
|
||||
updatedAt: 123
|
||||
});
|
||||
assert.equal((await readAuthJson(file))?.sessionId, "session-1");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node login completes bridge, redeems transfer code, writes auth json", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: authBase,
|
||||
accountHeaders: {
|
||||
"x-zk-ppe-lane": "lane-1",
|
||||
accept: "text/plain",
|
||||
"Content-TYPE": "text/plain",
|
||||
cookie: "session_id=attacker"
|
||||
},
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const decoded = decodeState(state);
|
||||
const healthUrl = new URL("/oauth/health", decoded.localServerOrigin);
|
||||
healthUrl.searchParams.set("attempt_id", decoded.attemptId);
|
||||
healthUrl.searchParams.set("token", decoded.bridgeToken);
|
||||
const healthResponse = await fetch(healthUrl);
|
||||
assert.equal(healthResponse.ok, true);
|
||||
assert.equal(
|
||||
healthResponse.headers.get("Access-Control-Allow-Private-Network"),
|
||||
"true"
|
||||
);
|
||||
const completeResponse = await fetch(
|
||||
new URL("/oauth/complete", decoded.localServerOrigin),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: authBase
|
||||
},
|
||||
body: JSON.stringify({ state, transfer_code: "transfer-1" })
|
||||
}
|
||||
);
|
||||
assert.equal(completeResponse.ok, true);
|
||||
}
|
||||
});
|
||||
|
||||
const result = await auth.login();
|
||||
assert.equal(result.session.sessionId, "desktop-session-1");
|
||||
assert.deepEqual(result.user, {
|
||||
userId: "user-1",
|
||||
name: "Alice",
|
||||
email: "alice@example.com",
|
||||
avatar: undefined
|
||||
});
|
||||
assert.equal(
|
||||
(await readAuthJson(file))?.cookie,
|
||||
"session_id=desktop-session-1"
|
||||
);
|
||||
assert.deepEqual(accountServer.requests.redeem, {
|
||||
transfer_code: "transfer-1",
|
||||
attempt_id: accountServer.requests.redeem?.attempt_id,
|
||||
bridge_token: accountServer.requests.redeem?.bridge_token,
|
||||
app_id: DEFAULT_APP_ID,
|
||||
device_id: accountServer.requests.redeem?.device_id
|
||||
});
|
||||
assert.equal(accountServer.requests.headers.redeem, "lane-1");
|
||||
assert.equal(accountServer.requests.headers.userInfo, "lane-1");
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node login callback redirects to web result after writing auth json", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login?transfer_code=bad",
|
||||
accountBaseUrl: authBase,
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const decoded = decodeState(state);
|
||||
const callbackUrl = new URL(
|
||||
"/oauth/callback",
|
||||
decoded.localServerOrigin
|
||||
);
|
||||
callbackUrl.searchParams.set("state", state);
|
||||
callbackUrl.searchParams.set("transfer_code", "transfer-1");
|
||||
const callbackResponse = await fetch(callbackUrl, {
|
||||
redirect: "manual"
|
||||
});
|
||||
assert.equal(callbackResponse.status, 302);
|
||||
const location = callbackResponse.headers.get("location") ?? "";
|
||||
assert.equal(location.includes("transfer-1"), false);
|
||||
const resultUrl = new URL(location);
|
||||
assert.equal(
|
||||
resultUrl.searchParams.get("desktopBridgeStatus"),
|
||||
"success"
|
||||
);
|
||||
const openAppUrl = resultUrl.searchParams.get("openAppUrl") ?? "";
|
||||
assert.equal(openAppUrl.includes("transfer_code"), false);
|
||||
assert.equal(new URL(openAppUrl).protocol, "tutti:");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await auth.login();
|
||||
assert.equal(result.session.sessionId, "desktop-session-1");
|
||||
assert.equal(
|
||||
(await readAuthJson(file))?.cookie,
|
||||
"session_id=desktop-session-1"
|
||||
);
|
||||
assert.deepEqual(accountServer.requests.redeem, {
|
||||
transfer_code: "transfer-1",
|
||||
attempt_id: accountServer.requests.redeem?.attempt_id,
|
||||
bridge_token: accountServer.requests.redeem?.bridge_token,
|
||||
app_id: DEFAULT_APP_ID,
|
||||
device_id: accountServer.requests.redeem?.device_id
|
||||
});
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node login preserves a typed cancellation without reopening the app", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
await writeAuthJson(file, {
|
||||
sessionId: "existing-session",
|
||||
cookie: "session_id=existing-session",
|
||||
userId: "existing-user",
|
||||
name: "Existing User",
|
||||
avatar: "",
|
||||
email: "",
|
||||
updatedAt: 123
|
||||
});
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: authBase,
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const decoded = decodeState(state);
|
||||
const callbackUrl = new URL(
|
||||
"/oauth/callback",
|
||||
decoded.localServerOrigin
|
||||
);
|
||||
callbackUrl.searchParams.set("state", state);
|
||||
callbackUrl.searchParams.set("error", "user_cancelled");
|
||||
const callbackResponse = await fetch(callbackUrl, {
|
||||
redirect: "manual"
|
||||
});
|
||||
assert.equal(callbackResponse.status, 302);
|
||||
const location = callbackResponse.headers.get("location") ?? "";
|
||||
const resultUrl = new URL(location);
|
||||
assert.equal(
|
||||
resultUrl.searchParams.get("desktopBridgeStatus"),
|
||||
"error"
|
||||
);
|
||||
assert.equal(
|
||||
resultUrl.searchParams.get("desktopBridgeError"),
|
||||
"userCancelled"
|
||||
);
|
||||
assert.equal(resultUrl.searchParams.get("openAppUrl"), null);
|
||||
assert.equal(location.includes("user_cancelled"), false);
|
||||
}
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => auth.login(),
|
||||
(error: unknown) => isTuttiAuthUserCancelledError(error)
|
||||
);
|
||||
assert.equal((await readAuthJson(file))?.sessionId, "existing-session");
|
||||
assert.equal(accountServer.requests.redeem, undefined);
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node compatibility completion preserves a typed cancellation", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: authBase,
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const decoded = decodeState(state);
|
||||
const response = await fetch(
|
||||
new URL("/oauth/complete", decoded.localServerOrigin),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: authBase
|
||||
},
|
||||
body: JSON.stringify({ state, error: "user_cancelled" })
|
||||
}
|
||||
);
|
||||
assert.equal(response.status, 400);
|
||||
assert.deepEqual(await response.json(), {
|
||||
ok: false,
|
||||
error: { code: "USER_CANCELLED", message: "user_cancelled" }
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => auth.login(),
|
||||
(error: unknown) => isTuttiAuthUserCancelledError(error)
|
||||
);
|
||||
assert.equal(await readAuthJson(file), null);
|
||||
assert.equal(accountServer.requests.redeem, undefined);
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node login completes when another bridge connection is stalled", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
let stalledSocket: Socket | undefined;
|
||||
let stalledSocketClosed: Promise<void> | undefined;
|
||||
try {
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: authBase,
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const bridgeUrl = new URL(decodeState(state).localServerOrigin ?? "");
|
||||
stalledSocket = createConnection({
|
||||
host: bridgeUrl.hostname,
|
||||
port: Number(bridgeUrl.port)
|
||||
});
|
||||
stalledSocketClosed = new Promise<void>((resolve) => {
|
||||
stalledSocket?.once("close", resolve);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
stalledSocket?.once("connect", resolve);
|
||||
stalledSocket?.once("error", reject);
|
||||
});
|
||||
stalledSocket.write(
|
||||
`GET /oauth/health HTTP/1.1\r\nHost: ${bridgeUrl.host}\r\n`
|
||||
);
|
||||
|
||||
const callbackUrl = new URL("/oauth/callback", bridgeUrl);
|
||||
callbackUrl.searchParams.set("state", state);
|
||||
callbackUrl.searchParams.set("transfer_code", "transfer-1");
|
||||
const callbackResponse = await fetch(callbackUrl, {
|
||||
redirect: "manual"
|
||||
});
|
||||
assert.equal(callbackResponse.status, 302);
|
||||
assert.equal(callbackResponse.headers.get("connection"), "close");
|
||||
}
|
||||
});
|
||||
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
const result = await Promise.race([
|
||||
auth.login(),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeout = setTimeout(
|
||||
() => reject(new Error("login did not close the bridge in time")),
|
||||
2_500
|
||||
);
|
||||
})
|
||||
]).finally(() => clearTimeout(timeout));
|
||||
assert.equal(result.session.sessionId, "desktop-session-1");
|
||||
let socketCloseTimeout: NodeJS.Timeout | undefined;
|
||||
await Promise.race([
|
||||
stalledSocketClosed,
|
||||
new Promise<never>((_, reject) => {
|
||||
socketCloseTimeout = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error("stalled bridge connection did not close in time")
|
||||
),
|
||||
2_500
|
||||
);
|
||||
})
|
||||
]).finally(() => clearTimeout(socketCloseTimeout));
|
||||
} finally {
|
||||
stalledSocket?.destroy();
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node bridge rejects invalid callback state", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
const authBase = `http://127.0.0.1:${accountServer.port}`;
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: authBase,
|
||||
authLoginUrl: `${authBase}/auth/login`,
|
||||
loginMaxTimeoutMs: 20,
|
||||
openUrl: async (loginUrl) => {
|
||||
const state = new URL(loginUrl).searchParams.get("state") ?? "";
|
||||
const decoded = decodeState(state);
|
||||
const response = await fetch(
|
||||
new URL("/oauth/complete", decoded.localServerOrigin),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: authBase
|
||||
},
|
||||
body: JSON.stringify({
|
||||
state: mutateState(state),
|
||||
transfer_code: "transfer-1"
|
||||
})
|
||||
}
|
||||
);
|
||||
assert.equal(response.status, 400);
|
||||
}
|
||||
});
|
||||
|
||||
await assert.rejects(auth.login(), /Invalid state|Login timed out/u);
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("node getUserInfo refreshes auth json and logout clears it", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "tutti-auth-bridge-"));
|
||||
const file = join(dir, "auth.json");
|
||||
const accountServer = await startAccountStub();
|
||||
try {
|
||||
await writeAuthJson(file, {
|
||||
sessionId: "desktop-session-1",
|
||||
cookie: "session_id=desktop-session-1",
|
||||
userId: "old-user",
|
||||
name: "",
|
||||
avatar: "",
|
||||
email: "",
|
||||
updatedAt: 1
|
||||
});
|
||||
const auth = createTuttiNodeAuthClient({
|
||||
authJsonPath: file,
|
||||
appCallbackUrl: "tutti://auth/login",
|
||||
accountBaseUrl: `http://127.0.0.1:${accountServer.port}`,
|
||||
accountHeaders: {
|
||||
"x-zk-ppe-lane": "lane-1",
|
||||
accept: "text/plain",
|
||||
"Content-TYPE": "text/plain",
|
||||
cookie: "session_id=attacker"
|
||||
}
|
||||
});
|
||||
assert.deepEqual(await auth.getUserInfo(), {
|
||||
userId: "user-1",
|
||||
name: "Alice",
|
||||
email: "alice@example.com",
|
||||
avatar: undefined
|
||||
});
|
||||
assert.equal((await readAuthJson(file))?.userId, "user-1");
|
||||
await auth.logout();
|
||||
assert.equal(await readAuthJson(file), null);
|
||||
assert.equal(accountServer.requests.logout?.app_id, DEFAULT_APP_ID);
|
||||
assert.equal(accountServer.requests.headers.userInfo, "lane-1");
|
||||
assert.equal(accountServer.requests.headers.logout, "lane-1");
|
||||
} finally {
|
||||
await accountServer.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function decodeState(state: string): Record<string, string> {
|
||||
return JSON.parse(Buffer.from(state, "base64url").toString("utf8")) as Record<
|
||||
string,
|
||||
string
|
||||
>;
|
||||
}
|
||||
|
||||
function mutateState(state: string): string {
|
||||
const decoded = decodeState(state);
|
||||
decoded.attemptId = "wrong-attempt";
|
||||
return Buffer.from(JSON.stringify(decoded), "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
async function startAccountStub(): Promise<{
|
||||
port: number;
|
||||
requests: {
|
||||
redeem?: Record<string, string>;
|
||||
logout?: Record<string, string>;
|
||||
headers: {
|
||||
redeem?: string;
|
||||
userInfo?: string;
|
||||
logout?: string;
|
||||
};
|
||||
};
|
||||
close: () => Promise<void>;
|
||||
}> {
|
||||
const requests: {
|
||||
redeem?: Record<string, string>;
|
||||
logout?: Record<string, string>;
|
||||
headers: {
|
||||
redeem?: string;
|
||||
userInfo?: string;
|
||||
logout?: string;
|
||||
};
|
||||
} = { headers: {} };
|
||||
const server = createServer(async (req, res) => {
|
||||
if (req.url === "/auth/v1/redeem_desktop_transfer_code") {
|
||||
assert.equal(req.headers.accept, "application/json");
|
||||
assert.equal(req.headers["content-type"], "application/json");
|
||||
assert.equal(req.headers.cookie, undefined);
|
||||
requests.headers.redeem = req.headers["x-zk-ppe-lane"] as
|
||||
| string
|
||||
| undefined;
|
||||
requests.redeem = (await readBody(req)) as Record<string, string>;
|
||||
sendJson(res, { code: 0, data: { session_id: "desktop-session-1" } });
|
||||
return;
|
||||
}
|
||||
if (req.url === "/user/v1/user_info") {
|
||||
assert.equal(req.headers.accept, "application/json");
|
||||
assert.equal(req.headers["content-type"], "application/json");
|
||||
requests.headers.userInfo = req.headers["x-zk-ppe-lane"] as
|
||||
| string
|
||||
| undefined;
|
||||
assert.equal(req.headers.cookie, "session_id=desktop-session-1");
|
||||
sendJson(res, {
|
||||
code: 0,
|
||||
data: { user_id: "user-1", name: "Alice", email: "alice@example.com" }
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.url === "/auth/v1/logout-web-session") {
|
||||
assert.equal(req.headers.accept, "application/json");
|
||||
assert.equal(req.headers["content-type"], "application/json");
|
||||
requests.headers.logout = req.headers["x-zk-ppe-lane"] as
|
||||
| string
|
||||
| undefined;
|
||||
requests.logout = (await readBody(req)) as Record<string, string>;
|
||||
assert.equal(req.headers.cookie, "session_id=desktop-session-1");
|
||||
sendJson(res, { code: 0 });
|
||||
return;
|
||||
}
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
});
|
||||
await listen(server);
|
||||
const address = server.address() as AddressInfo | null;
|
||||
assert.ok(address);
|
||||
return {
|
||||
port: address.port,
|
||||
requests,
|
||||
close: () => new Promise((resolve) => server.close(() => resolve()))
|
||||
};
|
||||
}
|
||||
|
||||
function listen(server: Server): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
async function readBody(req: IncomingMessage): Promise<unknown> {
|
||||
let raw = "";
|
||||
for await (const chunk of req) {
|
||||
raw += chunk;
|
||||
}
|
||||
return raw ? JSON.parse(raw) : {};
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, payload: unknown): void {
|
||||
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
@@ -0,0 +1,792 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse
|
||||
} from "node:http";
|
||||
import { createServer as createNetServer } from "node:net";
|
||||
import { hostname } from "node:os";
|
||||
import { dirname } from "node:path";
|
||||
import {
|
||||
buildBridgeResultUrl,
|
||||
callbackErrorToError,
|
||||
callbackErrorToSafeResultCode,
|
||||
isTuttiAuthUserCancelledError
|
||||
} from "./node-login-result";
|
||||
import {
|
||||
type AccountEnvelope,
|
||||
AUTH_SERVER_BASE_PORT,
|
||||
AUTH_SERVER_HOST,
|
||||
AUTH_SERVER_MAX_PORT,
|
||||
buildAccountUrl,
|
||||
buildSessionCookie,
|
||||
DEFAULT_ACCOUNT_BASE_URL,
|
||||
DEFAULT_APP_ID,
|
||||
DEFAULT_AUTH_LOGIN_URL,
|
||||
DEFAULT_LOGIN_IDLE_TIMEOUT_MS,
|
||||
DEFAULT_LOGIN_MAX_TIMEOUT_MS,
|
||||
mapUserInfo,
|
||||
readEnvelopeError,
|
||||
type TuttiAuthSession,
|
||||
type TuttiUserInfo,
|
||||
trimString
|
||||
} from "./shared";
|
||||
|
||||
const BRIDGE_SERVER_FORCE_CLOSE_TIMEOUT_MS = 1_000;
|
||||
|
||||
export interface TuttiNodeAuthClientOptions {
|
||||
authJsonPath: string;
|
||||
appCallbackUrl: string;
|
||||
openUrl?: (url: string) => Promise<void> | void;
|
||||
appId?: string;
|
||||
accountBaseUrl?: string;
|
||||
authLoginUrl?: string;
|
||||
deviceId?: string;
|
||||
deviceName?: string;
|
||||
clientVersion?: string;
|
||||
hostname?: string;
|
||||
loginIdleTimeoutMs?: number;
|
||||
loginMaxTimeoutMs?: number;
|
||||
accountHeaders?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface TuttiNodeAuthClient {
|
||||
login: () => Promise<{ session: TuttiAuthSession; user: TuttiUserInfo }>;
|
||||
getUserInfo: () => Promise<TuttiUserInfo | null>;
|
||||
logout: () => Promise<void>;
|
||||
readSession: () => Promise<TuttiAuthSession | null>;
|
||||
clearSession: () => Promise<void>;
|
||||
}
|
||||
|
||||
type BridgeState = {
|
||||
v: number;
|
||||
flow: "desktop_bridge";
|
||||
attemptId: string;
|
||||
localServerOrigin: string;
|
||||
bridgeToken: string;
|
||||
appId: string;
|
||||
appCallbackUrl: string;
|
||||
deviceId?: string;
|
||||
deviceName?: string;
|
||||
clientVersion?: string;
|
||||
hostname?: string;
|
||||
provider?: string;
|
||||
nonce?: string;
|
||||
};
|
||||
|
||||
type PendingLogin = {
|
||||
accountHeaders: Readonly<Record<string, string>>;
|
||||
accountBaseUrl: string;
|
||||
appId: string;
|
||||
appCallbackUrl: string;
|
||||
authJsonPath: string;
|
||||
attemptId: string;
|
||||
authOrigin: string;
|
||||
bridgeToken: string;
|
||||
completedResult?: { session: TuttiAuthSession; user: TuttiUserInfo };
|
||||
deviceId: string;
|
||||
localServerOrigin: string;
|
||||
state: string;
|
||||
expiresAt: number;
|
||||
maxExpiresAt: number;
|
||||
idleTimeoutMs: number;
|
||||
completed: boolean;
|
||||
};
|
||||
|
||||
type BridgeServer = {
|
||||
server: Server;
|
||||
waitForCompletion: Promise<string>;
|
||||
};
|
||||
|
||||
export function createTuttiNodeAuthClient(
|
||||
options: TuttiNodeAuthClientOptions
|
||||
): TuttiNodeAuthClient {
|
||||
const authJsonPath = options.authJsonPath.trim();
|
||||
const appCallbackUrl = options.appCallbackUrl.trim();
|
||||
if (!authJsonPath) {
|
||||
throw new Error("authJsonPath is required");
|
||||
}
|
||||
if (!appCallbackUrl) {
|
||||
throw new Error("appCallbackUrl is required");
|
||||
}
|
||||
new URL(appCallbackUrl);
|
||||
|
||||
const appId = options.appId?.trim() || DEFAULT_APP_ID;
|
||||
const accountBaseUrl =
|
||||
options.accountBaseUrl?.trim() || DEFAULT_ACCOUNT_BASE_URL;
|
||||
const authLoginUrl = options.authLoginUrl?.trim() || DEFAULT_AUTH_LOGIN_URL;
|
||||
const openUrl = options.openUrl ?? openUrlWithDefaultBrowser;
|
||||
const idleTimeoutMs = positiveMs(
|
||||
options.loginIdleTimeoutMs,
|
||||
DEFAULT_LOGIN_IDLE_TIMEOUT_MS
|
||||
);
|
||||
const maxTimeoutMs = Math.max(
|
||||
idleTimeoutMs,
|
||||
positiveMs(options.loginMaxTimeoutMs, DEFAULT_LOGIN_MAX_TIMEOUT_MS)
|
||||
);
|
||||
const accountHeaders = { ...options.accountHeaders };
|
||||
|
||||
async function readSession(): Promise<TuttiAuthSession | null> {
|
||||
return await readAuthJson(authJsonPath);
|
||||
}
|
||||
|
||||
async function clearSession(): Promise<void> {
|
||||
await rm(authJsonPath, { force: true });
|
||||
}
|
||||
|
||||
async function getUserInfo(): Promise<TuttiUserInfo | null> {
|
||||
const session = await readSession();
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
const user = await fetchUserInfo(
|
||||
accountBaseUrl,
|
||||
session.cookie,
|
||||
accountHeaders
|
||||
);
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
await writeAuthJson(authJsonPath, sessionFromUser(session.sessionId, user));
|
||||
return user;
|
||||
}
|
||||
|
||||
return {
|
||||
async login(): Promise<{ session: TuttiAuthSession; user: TuttiUserInfo }> {
|
||||
const port = await findAvailablePort();
|
||||
const localServerOrigin = `http://${AUTH_SERVER_HOST}:${port}`;
|
||||
const attemptId = randomUUID();
|
||||
const bridgeToken = randomUUID();
|
||||
const deviceId = options.deviceId?.trim() || randomUUID();
|
||||
const now = Date.now();
|
||||
const state = encodeBridgeState({
|
||||
v: 1,
|
||||
flow: "desktop_bridge",
|
||||
attemptId,
|
||||
localServerOrigin,
|
||||
bridgeToken,
|
||||
appId,
|
||||
appCallbackUrl,
|
||||
deviceId,
|
||||
deviceName: options.deviceName?.trim() || hostname() || "Desktop",
|
||||
clientVersion: options.clientVersion?.trim() || undefined,
|
||||
hostname: options.hostname?.trim() || hostname()
|
||||
});
|
||||
const pending: PendingLogin = {
|
||||
accountHeaders,
|
||||
accountBaseUrl,
|
||||
appId,
|
||||
appCallbackUrl,
|
||||
authJsonPath,
|
||||
attemptId,
|
||||
authOrigin: new URL(authLoginUrl).origin,
|
||||
bridgeToken,
|
||||
completed: false,
|
||||
deviceId,
|
||||
expiresAt: now + maxTimeoutMs,
|
||||
idleTimeoutMs,
|
||||
localServerOrigin,
|
||||
maxExpiresAt: now + maxTimeoutMs,
|
||||
state
|
||||
};
|
||||
const bridge = await createLoginBridgeServer(pending, port);
|
||||
const loginUrl = buildLoginUrl(authLoginUrl, state);
|
||||
const completion = waitForCompletion(pending, bridge.waitForCompletion);
|
||||
void completion.catch(() => undefined);
|
||||
|
||||
try {
|
||||
await openUrl(loginUrl);
|
||||
const transferCode = await completion;
|
||||
if (pending.completedResult) {
|
||||
return pending.completedResult;
|
||||
}
|
||||
return await completePendingLogin(pending, transferCode);
|
||||
} finally {
|
||||
await closeServer(bridge.server);
|
||||
}
|
||||
},
|
||||
getUserInfo,
|
||||
logout: async (): Promise<void> => {
|
||||
const session = await readSession();
|
||||
if (session) {
|
||||
await logoutSession(
|
||||
accountBaseUrl,
|
||||
appId,
|
||||
session.cookie,
|
||||
accountHeaders
|
||||
);
|
||||
}
|
||||
await clearSession();
|
||||
},
|
||||
readSession,
|
||||
clearSession
|
||||
};
|
||||
}
|
||||
|
||||
export async function readAuthJson(
|
||||
authJsonPath: string
|
||||
): Promise<TuttiAuthSession | null> {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(authJsonPath, "utf8")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const sessionId =
|
||||
trimString(parsed.sessionId) || trimString(parsed.session_id);
|
||||
if (!sessionId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
sessionId,
|
||||
cookie: trimString(parsed.cookie) || buildSessionCookie(sessionId),
|
||||
userId: trimString(parsed.userId) || trimString(parsed.user_id),
|
||||
name: trimString(parsed.name),
|
||||
avatar: trimString(parsed.avatar),
|
||||
email: trimString(parsed.email),
|
||||
updatedAt:
|
||||
typeof parsed.updatedAt === "number" &&
|
||||
Number.isFinite(parsed.updatedAt)
|
||||
? parsed.updatedAt
|
||||
: Date.now()
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeAuthJson(
|
||||
authJsonPath: string,
|
||||
session: TuttiAuthSession
|
||||
): Promise<void> {
|
||||
await mkdir(dirname(authJsonPath), { recursive: true });
|
||||
const payload = {
|
||||
session_id: session.sessionId,
|
||||
cookie: session.cookie,
|
||||
user_id: session.userId,
|
||||
name: session.name,
|
||||
avatar: session.avatar,
|
||||
email: session.email,
|
||||
updatedAt: session.updatedAt
|
||||
};
|
||||
const tempPath = `${authJsonPath}.tmp-${process.pid}-${Date.now()}-${randomUUID()}`;
|
||||
try {
|
||||
await writeFile(tempPath, JSON.stringify(payload, null, 2), {
|
||||
encoding: "utf8",
|
||||
mode: 0o600
|
||||
});
|
||||
await rename(tempPath, authJsonPath);
|
||||
} catch (error) {
|
||||
await rm(tempPath, { force: true }).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function encodeBridgeState(state: BridgeState): string {
|
||||
return Buffer.from(JSON.stringify(state), "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function decodeBridgeState(rawState: string): BridgeState | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
Buffer.from(rawState, "base64url").toString("utf8")
|
||||
) as Partial<BridgeState>;
|
||||
if (
|
||||
parsed.v !== 1 ||
|
||||
parsed.flow !== "desktop_bridge" ||
|
||||
!trimString(parsed.attemptId) ||
|
||||
!trimString(parsed.localServerOrigin) ||
|
||||
!trimString(parsed.bridgeToken)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return parsed as BridgeState;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildLoginUrl(authLoginUrl: string, state: string): string {
|
||||
const url = new URL(authLoginUrl);
|
||||
url.pathname = "/auth/login";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
url.searchParams.set("state", state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function stateMatches(input: PendingLogin, rawState: string): boolean {
|
||||
const state = decodeBridgeState(rawState);
|
||||
return (
|
||||
!input.completed &&
|
||||
Date.now() <= input.maxExpiresAt &&
|
||||
state?.attemptId === input.attemptId &&
|
||||
state.bridgeToken === input.bridgeToken &&
|
||||
state.localServerOrigin === input.localServerOrigin &&
|
||||
(state.appId ?? "") === input.appId
|
||||
);
|
||||
}
|
||||
|
||||
async function createLoginBridgeServer(
|
||||
input: PendingLogin,
|
||||
port: number
|
||||
): Promise<BridgeServer> {
|
||||
let resolveCompletion!: (code: string) => void;
|
||||
let rejectCompletion!: (error: unknown) => void;
|
||||
let completed = false;
|
||||
const waitForCompletion = new Promise<string>((resolve, reject) => {
|
||||
resolveCompletion = resolve;
|
||||
rejectCompletion = reject;
|
||||
});
|
||||
const complete = (fn: () => void): void => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
fn();
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? "/", input.localServerOrigin);
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
if (
|
||||
!isAllowedBridgeOrigin(req, input) ||
|
||||
!isAllowedLoopbackHost(req, port)
|
||||
) {
|
||||
res.writeHead(403);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
sendCors(res, 204);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/oauth/health") {
|
||||
const matched =
|
||||
!input.completed &&
|
||||
Date.now() <= input.expiresAt &&
|
||||
Date.now() <= input.maxExpiresAt &&
|
||||
url.searchParams.get("attempt_id") === input.attemptId &&
|
||||
url.searchParams.get("token") === input.bridgeToken;
|
||||
if (!matched) {
|
||||
sendJson(res, 401, {
|
||||
ok: false,
|
||||
error: {
|
||||
code: "INVALID_BRIDGE_ATTEMPT",
|
||||
message: "Desktop login attempt is unavailable."
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
input.expiresAt = Math.min(
|
||||
input.maxExpiresAt,
|
||||
Date.now() + input.idleTimeoutMs
|
||||
);
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
data: {
|
||||
attemptId: input.attemptId,
|
||||
status: "ready",
|
||||
expiresAt: input.expiresAt
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/oauth/callback") {
|
||||
if (!isAllowedLoopbackHost(req, port)) {
|
||||
res.writeHead(403);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const callbackError = trimString(url.searchParams.get("error"));
|
||||
const callbackState = trimString(url.searchParams.get("state"));
|
||||
const transferCode = trimString(url.searchParams.get("transfer_code"));
|
||||
if (!stateMatches(input, callbackState)) {
|
||||
const error = new Error("Invalid state");
|
||||
complete(() => rejectCompletion(error));
|
||||
sendRedirect(res, buildBridgeResultUrl(input, "error", "invalidState"));
|
||||
return;
|
||||
}
|
||||
if (callbackError) {
|
||||
const error = callbackErrorToError(callbackError);
|
||||
complete(() => rejectCompletion(error));
|
||||
sendRedirect(
|
||||
res,
|
||||
buildBridgeResultUrl(
|
||||
input,
|
||||
"error",
|
||||
callbackErrorToSafeResultCode(callbackError)
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!transferCode) {
|
||||
const error = new Error("Missing transfer_code");
|
||||
complete(() => rejectCompletion(error));
|
||||
sendRedirect(
|
||||
res,
|
||||
buildBridgeResultUrl(input, "error", "missingTransferCode")
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
input.completedResult = await completePendingLogin(input, transferCode);
|
||||
input.completed = true;
|
||||
complete(() => resolveCompletion(transferCode));
|
||||
sendRedirect(res, buildBridgeResultUrl(input, "success"));
|
||||
} catch (error) {
|
||||
complete(() => rejectCompletion(error));
|
||||
sendRedirect(res, buildBridgeResultUrl(input, "error", "redeemFailed"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/oauth/complete") {
|
||||
if (
|
||||
!isAllowedBridgeOrigin(req, input) ||
|
||||
!isAllowedLoopbackHost(req, port)
|
||||
) {
|
||||
sendJson(res, 403, {
|
||||
ok: false,
|
||||
error: {
|
||||
code: "FORBIDDEN_BRIDGE_ORIGIN",
|
||||
message: "Bridge origin is not allowed."
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
const payload = (await readJsonBody(req).catch(() => ({}))) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const callbackError = trimString(payload.error);
|
||||
const callbackState = trimString(payload.state);
|
||||
const transferCode =
|
||||
trimString(payload.transfer_code) || trimString(payload.transferCode);
|
||||
if (!stateMatches(input, callbackState)) {
|
||||
const error = new Error("Invalid state");
|
||||
sendJson(res, 400, {
|
||||
ok: false,
|
||||
error: { code: "INVALID_STATE", message: error.message }
|
||||
});
|
||||
complete(() => rejectCompletion(error));
|
||||
return;
|
||||
}
|
||||
if (callbackError) {
|
||||
const error = callbackErrorToError(callbackError);
|
||||
sendJson(res, 400, {
|
||||
ok: false,
|
||||
error: {
|
||||
code: isTuttiAuthUserCancelledError(error)
|
||||
? "USER_CANCELLED"
|
||||
: "PROVIDER_CALLBACK_ERROR",
|
||||
message: error.message
|
||||
}
|
||||
});
|
||||
complete(() => rejectCompletion(error));
|
||||
return;
|
||||
}
|
||||
if (!transferCode) {
|
||||
const error = new Error("Missing transfer_code");
|
||||
sendJson(res, 400, {
|
||||
ok: false,
|
||||
error: { code: "MISSING_TRANSFER_CODE", message: error.message }
|
||||
});
|
||||
complete(() => rejectCompletion(error));
|
||||
return;
|
||||
}
|
||||
input.completed = true;
|
||||
sendJson(res, 200, { ok: true, data: { status: "completed" } });
|
||||
complete(() => resolveCompletion(transferCode));
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(res, 404, {
|
||||
ok: false,
|
||||
error: { code: "NOT_FOUND", message: "Not found" }
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, AUTH_SERVER_HOST, () => resolve());
|
||||
});
|
||||
|
||||
return { server, waitForCompletion };
|
||||
}
|
||||
|
||||
async function completePendingLogin(
|
||||
input: PendingLogin,
|
||||
transferCode: string
|
||||
): Promise<{ session: TuttiAuthSession; user: TuttiUserInfo }> {
|
||||
const sessionId = await redeemDesktopTransferCode(input, transferCode);
|
||||
const user = await fetchUserInfo(
|
||||
input.accountBaseUrl,
|
||||
buildSessionCookie(sessionId),
|
||||
input.accountHeaders
|
||||
);
|
||||
if (!user) {
|
||||
throw new Error("Failed to load user info after login");
|
||||
}
|
||||
const session = sessionFromUser(sessionId, user);
|
||||
await writeAuthJson(input.authJsonPath, session);
|
||||
return { session, user };
|
||||
}
|
||||
|
||||
async function waitForCompletion(
|
||||
input: PendingLogin,
|
||||
completion: Promise<string>
|
||||
): Promise<string> {
|
||||
while (true) {
|
||||
const remainingMs =
|
||||
Math.min(input.expiresAt, input.maxExpiresAt) - Date.now();
|
||||
if (remainingMs <= 0) {
|
||||
throw new Error("Login timed out");
|
||||
}
|
||||
const result = await Promise.race([
|
||||
completion.then((transferCode) => ({ transferCode })),
|
||||
delay(Math.min(remainingMs, 500)).then(() => null)
|
||||
]);
|
||||
if (result) {
|
||||
return result.transferCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchUserInfo(
|
||||
accountBaseUrl: string,
|
||||
cookie: string,
|
||||
accountHeaders: Readonly<Record<string, string>>
|
||||
): Promise<TuttiUserInfo | null> {
|
||||
const response = await fetch(
|
||||
buildAccountUrl(accountBaseUrl, "/user/v1/user_info"),
|
||||
{
|
||||
method: "POST",
|
||||
headers: buildAccountHeaders(accountHeaders, cookie),
|
||||
body: JSON.stringify({})
|
||||
}
|
||||
);
|
||||
const payload = (await response.json().catch(() => null)) as AccountEnvelope<
|
||||
Record<string, unknown>
|
||||
> | null;
|
||||
if (response.status === 401 || payload?.code === 401) {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok || payload?.code !== 0) {
|
||||
throw readEnvelopeError(response, payload);
|
||||
}
|
||||
return mapUserInfo(payload.data);
|
||||
}
|
||||
|
||||
async function redeemDesktopTransferCode(
|
||||
input: PendingLogin,
|
||||
transferCode: string
|
||||
): Promise<string> {
|
||||
const response = await fetch(
|
||||
buildAccountUrl(
|
||||
input.accountBaseUrl,
|
||||
"/auth/v1/redeem_desktop_transfer_code"
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: buildAccountHeaders(input.accountHeaders),
|
||||
body: JSON.stringify({
|
||||
transfer_code: transferCode,
|
||||
attempt_id: input.attemptId,
|
||||
bridge_token: input.bridgeToken,
|
||||
app_id: input.appId,
|
||||
device_id: input.deviceId
|
||||
})
|
||||
}
|
||||
);
|
||||
const payload = (await response.json().catch(() => null)) as AccountEnvelope<{
|
||||
session_id?: string;
|
||||
sessionId?: string;
|
||||
}> | null;
|
||||
const sessionId =
|
||||
trimString(payload?.data?.sessionId) ||
|
||||
trimString(payload?.data?.session_id);
|
||||
if (!response.ok || payload?.code !== 0 || !sessionId) {
|
||||
throw readEnvelopeError(response, payload);
|
||||
}
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
async function logoutSession(
|
||||
accountBaseUrl: string,
|
||||
appId: string,
|
||||
cookie: string,
|
||||
accountHeaders: Readonly<Record<string, string>>
|
||||
): Promise<void> {
|
||||
const response = await fetch(
|
||||
buildAccountUrl(accountBaseUrl, "/auth/v1/logout-web-session"),
|
||||
{
|
||||
method: "POST",
|
||||
headers: buildAccountHeaders(accountHeaders, cookie),
|
||||
body: JSON.stringify({ app_id: appId })
|
||||
}
|
||||
);
|
||||
const payload = (await response.json().catch(() => null)) as AccountEnvelope<
|
||||
Record<string, never>
|
||||
> | null;
|
||||
if (!response.ok || (payload?.code ?? 0) !== 0) {
|
||||
throw readEnvelopeError(response, payload);
|
||||
}
|
||||
}
|
||||
|
||||
function buildAccountHeaders(
|
||||
accountHeaders: Readonly<Record<string, string>>,
|
||||
cookie?: string
|
||||
): Headers {
|
||||
const headers = new Headers(accountHeaders);
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set("Content-Type", "application/json");
|
||||
if (cookie) {
|
||||
headers.set("Cookie", cookie);
|
||||
} else {
|
||||
headers.delete("Cookie");
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function findAvailablePort(): Promise<number> {
|
||||
for (
|
||||
let port = AUTH_SERVER_BASE_PORT;
|
||||
port <= AUTH_SERVER_MAX_PORT;
|
||||
port += 1
|
||||
) {
|
||||
const available = await new Promise<boolean>((resolve) => {
|
||||
const probe = createNetServer();
|
||||
probe.once("error", () => resolve(false));
|
||||
probe.listen(port, AUTH_SERVER_HOST, () => {
|
||||
probe.close(() => resolve(true));
|
||||
});
|
||||
});
|
||||
if (available) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
throw new Error("unable to allocate localhost auth port");
|
||||
}
|
||||
|
||||
function sessionFromUser(
|
||||
sessionId: string,
|
||||
user: TuttiUserInfo
|
||||
): TuttiAuthSession {
|
||||
return {
|
||||
sessionId,
|
||||
cookie: buildSessionCookie(sessionId),
|
||||
userId: user.userId,
|
||||
name: user.name ?? "",
|
||||
avatar: user.avatar ?? "",
|
||||
email: user.email ?? "",
|
||||
updatedAt: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
function positiveMs(value: number | undefined, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? value
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
||||
let raw = "";
|
||||
for await (const chunk of req) {
|
||||
raw += chunk;
|
||||
}
|
||||
return raw ? JSON.parse(raw) : {};
|
||||
}
|
||||
|
||||
function sendCors(res: ServerResponse, status: number): void {
|
||||
res.writeHead(status, {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
"Access-Control-Allow-Private-Network": "true",
|
||||
Connection: "close"
|
||||
});
|
||||
res.end();
|
||||
}
|
||||
|
||||
function isAllowedBridgeOrigin(
|
||||
req: IncomingMessage,
|
||||
input: PendingLogin
|
||||
): boolean {
|
||||
const origin = trimString(req.headers.origin);
|
||||
return !origin || origin === input.authOrigin;
|
||||
}
|
||||
|
||||
function isAllowedLoopbackHost(req: IncomingMessage, port: number): boolean {
|
||||
const host = trimString(req.headers.host).toLowerCase();
|
||||
return host === `${AUTH_SERVER_HOST}:${port}` || host === `localhost:${port}`;
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, payload: unknown): void {
|
||||
res.writeHead(status, {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
"Access-Control-Allow-Private-Network": "true",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
Connection: "close"
|
||||
});
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function sendRedirect(res: ServerResponse, location: string): void {
|
||||
res.writeHead(302, { Location: location, Connection: "close" });
|
||||
res.end();
|
||||
}
|
||||
|
||||
function closeServer(server: Server): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const forceCloseTimer = setTimeout(() => {
|
||||
server.closeAllConnections();
|
||||
resolve();
|
||||
}, BRIDGE_SERVER_FORCE_CLOSE_TIMEOUT_MS);
|
||||
forceCloseTimer.unref();
|
||||
|
||||
server.close(() => {
|
||||
clearTimeout(forceCloseTimer);
|
||||
resolve();
|
||||
});
|
||||
server.closeIdleConnections();
|
||||
});
|
||||
}
|
||||
|
||||
function openUrlWithDefaultBrowser(url: string): Promise<void> {
|
||||
const command =
|
||||
process.platform === "darwin"
|
||||
? { file: "open", args: [url] }
|
||||
: process.platform === "win32"
|
||||
? { file: "cmd", args: ["/c", "start", "", url] }
|
||||
: { file: "xdg-open", args: [url] };
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command.file, command.args, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true
|
||||
});
|
||||
child.once("error", reject);
|
||||
child.once("spawn", () => {
|
||||
child.unref();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
isTuttiAuthUserCancelledError,
|
||||
TuttiAuthError
|
||||
} from "./node-login-result";
|
||||
export type { TuttiAuthErrorCode } from "./node-login-result";
|
||||
export type { TuttiAuthSession, TuttiUserInfo } from "./shared";
|
||||
@@ -0,0 +1,86 @@
|
||||
export const DEFAULT_APP_ID = "nextop";
|
||||
export const DEFAULT_ACCOUNT_BASE_URL = "https://tutti.sh/api/account";
|
||||
export const DEFAULT_AUTH_LOGIN_URL = "https://tutti.sh/auth/login";
|
||||
export const AUTH_SERVER_HOST = "127.0.0.1";
|
||||
export const AUTH_SERVER_BASE_PORT = 38473;
|
||||
export const AUTH_SERVER_MAX_PORT = 38492;
|
||||
export const DEFAULT_LOGIN_IDLE_TIMEOUT_MS = 90_000;
|
||||
export const DEFAULT_LOGIN_MAX_TIMEOUT_MS = 5 * 60_000;
|
||||
|
||||
export interface TuttiUserInfo {
|
||||
userId: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export interface TuttiAuthSession {
|
||||
sessionId: string;
|
||||
cookie: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
avatar: string;
|
||||
email: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface AccountEnvelope<T> {
|
||||
code?: number;
|
||||
errmsg?: string;
|
||||
message?: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
export function trimString(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export function buildSessionCookie(sessionId: string): string {
|
||||
return `session_id=${sessionId.trim()}`;
|
||||
}
|
||||
|
||||
export function normalizeBaseUrl(value: string): string {
|
||||
return value.replace(/\/+$/u, "");
|
||||
}
|
||||
|
||||
export function buildAccountUrl(accountBaseUrl: string, path: string): string {
|
||||
return `${normalizeBaseUrl(accountBaseUrl)}/${path.replace(/^\/+/u, "")}`;
|
||||
}
|
||||
|
||||
export function readEnvelopeError<T>(
|
||||
response: Response,
|
||||
payload: AccountEnvelope<T> | null
|
||||
): Error {
|
||||
return new Error(
|
||||
payload?.errmsg ??
|
||||
payload?.message ??
|
||||
`Request failed with status ${response.status}`
|
||||
);
|
||||
}
|
||||
|
||||
export function mapUserInfo(
|
||||
data: Record<string, unknown> | undefined
|
||||
): TuttiUserInfo | null {
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
const userId = trimString(data.userId) || trimString(data.user_id);
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
userId,
|
||||
name: trimString(data.name) || undefined,
|
||||
email:
|
||||
trimString(data.email) ||
|
||||
trimString(data.userEmail) ||
|
||||
trimString(data.emailAddress) ||
|
||||
undefined,
|
||||
avatar:
|
||||
trimString(data.avatar) ||
|
||||
trimString(data.picture) ||
|
||||
trimString(data.avatarUrl) ||
|
||||
trimString(data.headImg) ||
|
||||
undefined
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./tsconfig.json"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"types": ["node"],
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: {
|
||||
browser: "src/browser.ts",
|
||||
node: "src/node.ts",
|
||||
shared: "src/shared.ts"
|
||||
},
|
||||
format: ["esm"],
|
||||
sourcemap: false,
|
||||
tsconfig: "tsconfig.build.json"
|
||||
});
|
||||
Reference in new issue
Block a user