源码快照 @ 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,871 @@
|
||||
package authbridge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultAppID = "nextop"
|
||||
DefaultAccountBaseURL = "https://tutti.sh/api/account"
|
||||
DefaultAuthLoginURL = "https://tutti.sh/auth/login"
|
||||
DefaultBridgeHost = "127.0.0.1"
|
||||
DefaultBridgeBasePort = 38473
|
||||
DefaultBridgeMaxPort = 38492
|
||||
DefaultLoginIdleTimeout = 90 * time.Second
|
||||
DefaultLoginMaxTimeout = 5 * time.Minute
|
||||
statusPending = "pending"
|
||||
statusCompleted = "completed"
|
||||
statusFailed = "failed"
|
||||
statusExpired = "expired"
|
||||
bridgeFlowDesktop = "desktop_bridge"
|
||||
bridgeStateVersion = 1
|
||||
authJSONFileMode = 0o600
|
||||
authJSONDirectoryFileMode = 0o755
|
||||
)
|
||||
|
||||
// ErrUserCancelled identifies a desktop login that the user explicitly cancelled.
|
||||
var ErrUserCancelled = errors.New("user cancelled")
|
||||
|
||||
// IsUserCancelled reports whether err represents an explicit user cancellation.
|
||||
func IsUserCancelled(err error) bool {
|
||||
return errors.Is(err, ErrUserCancelled)
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
AccountBaseURL string
|
||||
AccountHeaders http.Header
|
||||
AppCallbackURL string
|
||||
AppID string
|
||||
AuthJSONPath string
|
||||
AuthLoginURL string
|
||||
BridgeHost string
|
||||
BridgeBasePort int
|
||||
BridgeMaxPort int
|
||||
ClientVersion string
|
||||
DeviceID string
|
||||
DeviceName string
|
||||
Hostname string
|
||||
HTTPClient *http.Client
|
||||
LoginIdleTimeout time.Duration
|
||||
LoginMaxTimeout time.Duration
|
||||
OpenURL func(context.Context, string) error
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
config Config
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
type UserInfo struct {
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Avatar string `json:"avatar,omitempty"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Cookie string `json:"cookie"`
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Avatar string `json:"avatar"`
|
||||
Email string `json:"email"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
Session Session `json:"session"`
|
||||
User UserInfo `json:"user"`
|
||||
}
|
||||
|
||||
type LoginStatus struct {
|
||||
AttemptID string `json:"attempt_id"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Status string `json:"status"`
|
||||
User *UserInfo `json:"user,omitempty"`
|
||||
}
|
||||
|
||||
type LoginAttempt struct {
|
||||
ID string
|
||||
LoginURL string
|
||||
ExpiresAt time.Time
|
||||
|
||||
client *Client
|
||||
state string
|
||||
bridgeToken string
|
||||
deviceID string
|
||||
origin string
|
||||
server *http.Server
|
||||
listener net.Listener
|
||||
maxExpires time.Time
|
||||
idleTimeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
status string
|
||||
err error
|
||||
user *UserInfo
|
||||
done chan struct{}
|
||||
doneOnce sync.Once
|
||||
}
|
||||
|
||||
type bridgeState struct {
|
||||
Version int `json:"v"`
|
||||
Flow string `json:"flow"`
|
||||
AttemptID string `json:"attemptId"`
|
||||
LocalServerOrigin string `json:"localServerOrigin"`
|
||||
BridgeToken string `json:"bridgeToken"`
|
||||
AppID string `json:"appId"`
|
||||
AppCallbackURL string `json:"appCallbackUrl"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
DeviceName string `json:"deviceName,omitempty"`
|
||||
ClientVersion string `json:"clientVersion,omitempty"`
|
||||
Hostname string `json:"hostname,omitempty"`
|
||||
}
|
||||
|
||||
type accountEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
Message string `json:"message"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
func NewClient(config Config) (*Client, error) {
|
||||
normalized := normalizeConfig(config)
|
||||
if strings.TrimSpace(normalized.AuthJSONPath) == "" {
|
||||
return nil, errors.New("auth json path is required")
|
||||
}
|
||||
if strings.TrimSpace(normalized.AppCallbackURL) == "" {
|
||||
return nil, errors.New("app callback url is required")
|
||||
}
|
||||
if _, err := url.ParseRequestURI(normalized.AppCallbackURL); err != nil {
|
||||
return nil, fmt.Errorf("invalid app callback url: %w", err)
|
||||
}
|
||||
if _, err := url.ParseRequestURI(normalized.AuthLoginURL); err != nil {
|
||||
return nil, fmt.Errorf("invalid auth login url: %w", err)
|
||||
}
|
||||
httpClient := normalized.HTTPClient
|
||||
if httpClient == nil {
|
||||
// This package is a standalone module and intentionally preserves the
|
||||
// caller's process-wide default client customizations.
|
||||
httpClient = http.DefaultClient //nolint:forbidigo // standalone module preserves caller's process-wide client
|
||||
}
|
||||
return &Client{config: normalized, http: httpClient}, nil
|
||||
}
|
||||
|
||||
func (c *Client) StartLogin(ctx context.Context) (*LoginAttempt, error) {
|
||||
if c == nil {
|
||||
return nil, errors.New("auth client is nil")
|
||||
}
|
||||
listener, origin, err := listenBridge(c.config.BridgeHost, c.config.BridgeBasePort, c.config.BridgeMaxPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attemptID := randomID()
|
||||
bridgeToken := randomID()
|
||||
now := time.Now()
|
||||
maxExpires := now.Add(c.config.LoginMaxTimeout)
|
||||
state := bridgeState{
|
||||
Version: bridgeStateVersion,
|
||||
Flow: bridgeFlowDesktop,
|
||||
AttemptID: attemptID,
|
||||
LocalServerOrigin: origin,
|
||||
BridgeToken: bridgeToken,
|
||||
AppID: c.config.AppID,
|
||||
AppCallbackURL: c.config.AppCallbackURL,
|
||||
DeviceID: firstNonEmpty(c.config.DeviceID, randomID()),
|
||||
DeviceName: firstNonEmpty(c.config.DeviceName, c.config.Hostname, "Desktop"),
|
||||
ClientVersion: c.config.ClientVersion,
|
||||
Hostname: c.config.Hostname,
|
||||
}
|
||||
encodedState, err := encodeBridgeState(state)
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attempt := &LoginAttempt{
|
||||
ID: attemptID,
|
||||
LoginURL: buildLoginURL(c.config.AuthLoginURL, encodedState),
|
||||
ExpiresAt: maxExpires,
|
||||
bridgeToken: bridgeToken,
|
||||
client: c,
|
||||
deviceID: state.DeviceID,
|
||||
done: make(chan struct{}),
|
||||
idleTimeout: c.config.LoginIdleTimeout,
|
||||
listener: listener,
|
||||
maxExpires: maxExpires,
|
||||
origin: origin,
|
||||
state: encodedState,
|
||||
status: statusPending,
|
||||
}
|
||||
attempt.server = &http.Server{Handler: attempt}
|
||||
|
||||
go attempt.serve()
|
||||
go attempt.wait(ctx)
|
||||
|
||||
return attempt, nil
|
||||
}
|
||||
|
||||
func (c *Client) Login(ctx context.Context) (LoginResult, error) {
|
||||
attempt, err := c.StartLogin(ctx)
|
||||
if err != nil {
|
||||
return LoginResult{}, err
|
||||
}
|
||||
if c.config.OpenURL != nil {
|
||||
if err := c.config.OpenURL(ctx, attempt.LoginURL); err != nil {
|
||||
attempt.fail(err)
|
||||
return LoginResult{}, err
|
||||
}
|
||||
}
|
||||
<-attempt.done
|
||||
status := attempt.Status()
|
||||
if status.Status != statusCompleted {
|
||||
if attemptErr := attempt.resultError(); attemptErr != nil {
|
||||
return LoginResult{}, attemptErr
|
||||
}
|
||||
if status.Error != "" {
|
||||
return LoginResult{}, errors.New(status.Error)
|
||||
}
|
||||
return LoginResult{}, errors.New("login did not complete")
|
||||
}
|
||||
session, err := c.ReadSession()
|
||||
if err != nil {
|
||||
return LoginResult{}, err
|
||||
}
|
||||
if session == nil || status.User == nil {
|
||||
return LoginResult{}, errors.New("login session is missing")
|
||||
}
|
||||
return LoginResult{Session: *session, User: *status.User}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetUserInfo(ctx context.Context) (*UserInfo, error) {
|
||||
session, err := c.ReadSession()
|
||||
if err != nil || session == nil {
|
||||
return nil, err
|
||||
}
|
||||
user, err := c.fetchUserInfo(ctx, session.Cookie)
|
||||
if err != nil || user == nil {
|
||||
return user, err
|
||||
}
|
||||
if err := c.writeAuthJSON(sessionFromUser(session.SessionID, *user)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *Client) Logout(ctx context.Context) error {
|
||||
session, err := c.ReadSession()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if session != nil {
|
||||
_ = c.logoutSession(ctx, session.Cookie)
|
||||
}
|
||||
if err := os.Remove(c.config.AuthJSONPath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ReadSession() (*Session, error) {
|
||||
raw, err := os.ReadFile(c.config.AuthJSONPath)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Cookie string `json:"cookie"`
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Avatar string `json:"avatar"`
|
||||
Email string `json:"email"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(payload.SessionID) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
session := sessionFromUser(payload.SessionID, UserInfo{
|
||||
UserID: payload.UserID,
|
||||
Name: payload.Name,
|
||||
Email: payload.Email,
|
||||
Avatar: payload.Avatar,
|
||||
})
|
||||
if payload.Cookie != "" {
|
||||
session.Cookie = payload.Cookie
|
||||
}
|
||||
if payload.UpdatedAt > 0 {
|
||||
session.UpdatedAt = payload.UpdatedAt
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) Status() LoginStatus {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
status := a.status
|
||||
if status == statusPending && time.Now().After(a.ExpiresAt) {
|
||||
status = statusExpired
|
||||
}
|
||||
out := LoginStatus{
|
||||
AttemptID: a.ID,
|
||||
ExpiresAt: a.ExpiresAt,
|
||||
Status: status,
|
||||
User: a.user,
|
||||
}
|
||||
if a.err != nil {
|
||||
out.Error = a.err.Error()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) resultError() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.err
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodOptions {
|
||||
if !a.allowedOrigin(r) || !a.allowedHost(r) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
sendBridgeCORS(w, http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/oauth/health":
|
||||
a.handleHealth(w, r)
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/oauth/callback":
|
||||
a.handleCallback(w, r)
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/oauth/complete":
|
||||
a.handleComplete(w, r)
|
||||
default:
|
||||
sendBridgeJSON(w, http.StatusNotFound, map[string]any{"ok": false})
|
||||
}
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
a.mu.Lock()
|
||||
matched := a.status == statusPending &&
|
||||
time.Now().Before(a.ExpiresAt) &&
|
||||
time.Now().Before(a.maxExpires) &&
|
||||
r.URL.Query().Get("attempt_id") == a.ID &&
|
||||
r.URL.Query().Get("token") == a.bridgeToken
|
||||
if matched {
|
||||
a.ExpiresAt = minTime(a.maxExpires, time.Now().Add(a.idleTimeout))
|
||||
}
|
||||
expiresAt := a.ExpiresAt
|
||||
a.mu.Unlock()
|
||||
|
||||
if !matched {
|
||||
sendBridgeJSON(w, http.StatusUnauthorized, map[string]any{
|
||||
"ok": false,
|
||||
"error": map[string]string{
|
||||
"code": "INVALID_BRIDGE_ATTEMPT",
|
||||
"message": "Desktop login attempt is unavailable.",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
sendBridgeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"data": map[string]any{
|
||||
"attemptId": a.ID,
|
||||
"status": "ready",
|
||||
"expiresAt": expiresAt.UnixMilli(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) handleComplete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.allowedOrigin(r) || !a.allowedHost(r) {
|
||||
sendBridgeJSON(w, http.StatusForbidden, map[string]any{"ok": false})
|
||||
return
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := readJSON(r.Body, &payload); err != nil {
|
||||
sendBridgeJSON(w, http.StatusBadRequest, map[string]any{"ok": false})
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
callbackError := stringField(payload, "error")
|
||||
callbackState := stringField(payload, "state")
|
||||
transferCode := stringField(payload, "transfer_code", "transferCode")
|
||||
if !a.stateMatches(callbackState) {
|
||||
err := errors.New("invalid state")
|
||||
sendBridgeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": map[string]string{"code": "INVALID_STATE", "message": err.Error()}})
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(callbackError) != "" {
|
||||
err := callbackErrorValue(callbackError)
|
||||
errorCode := "PROVIDER_CALLBACK_ERROR"
|
||||
if IsUserCancelled(err) {
|
||||
errorCode = "USER_CANCELLED"
|
||||
}
|
||||
sendBridgeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": map[string]string{"code": errorCode, "message": err.Error()}})
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(transferCode) == "" {
|
||||
err := errors.New("missing transfer_code")
|
||||
sendBridgeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": map[string]string{"code": "MISSING_TRANSFER_CODE", "message": err.Error()}})
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
sendBridgeJSON(w, http.StatusOK, map[string]any{"ok": true, "data": map[string]string{"status": statusCompleted}})
|
||||
go a.complete(transferCode)
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) handleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.allowedHost(r) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
query := r.URL.Query()
|
||||
callbackError := strings.TrimSpace(query.Get("error"))
|
||||
callbackState := strings.TrimSpace(query.Get("state"))
|
||||
transferCode := strings.TrimSpace(query.Get("transfer_code"))
|
||||
if !a.stateMatches(callbackState) {
|
||||
err := errors.New("invalid state")
|
||||
redirectBridgeResult(w, r, a, "error", "invalidState")
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
if callbackError != "" {
|
||||
err := callbackErrorValue(callbackError)
|
||||
redirectBridgeResult(w, r, a, "error", callbackErrorSafeResultCode(callbackError))
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
if transferCode == "" {
|
||||
err := errors.New("missing transfer_code")
|
||||
redirectBridgeResult(w, r, a, "error", "missingTransferCode")
|
||||
a.markFailed(err)
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := a.completeWithContext(ctx, transferCode); err != nil {
|
||||
redirectBridgeResult(w, r, a, "error", "redeemFailed")
|
||||
a.closeGracefully()
|
||||
return
|
||||
}
|
||||
redirectBridgeResult(w, r, a, "success", "")
|
||||
a.closeGracefully()
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) complete(transferCode string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_ = a.completeWithContext(ctx, transferCode)
|
||||
a.close()
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) completeWithContext(ctx context.Context, transferCode string) error {
|
||||
sessionID, err := a.client.redeemTransferCode(ctx, a, transferCode)
|
||||
if err != nil {
|
||||
a.markFailed(err)
|
||||
return err
|
||||
}
|
||||
user, err := a.client.fetchUserInfo(ctx, buildSessionCookie(sessionID))
|
||||
if err != nil {
|
||||
a.markFailed(err)
|
||||
return err
|
||||
}
|
||||
if user == nil {
|
||||
err := errors.New("failed to load user info after login")
|
||||
a.markFailed(err)
|
||||
return err
|
||||
}
|
||||
if err := a.client.writeAuthJSON(sessionFromUser(sessionID, *user)); err != nil {
|
||||
a.markFailed(err)
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.status = statusCompleted
|
||||
a.user = user
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) wait(ctx context.Context) {
|
||||
t := time.NewTimer(time.Until(a.maxExpires))
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-a.done:
|
||||
case <-ctx.Done():
|
||||
a.fail(ctx.Err())
|
||||
case <-t.C:
|
||||
a.fail(errors.New("login timed out"))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) serve() {
|
||||
err := a.server.Serve(a.listener)
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
a.fail(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) fail(err error) {
|
||||
a.markFailed(err)
|
||||
a.close()
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) markFailed(err error) {
|
||||
a.mu.Lock()
|
||||
if a.status == statusCompleted {
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if time.Now().After(a.ExpiresAt) {
|
||||
a.status = statusExpired
|
||||
} else {
|
||||
a.status = statusFailed
|
||||
}
|
||||
a.err = err
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) close() {
|
||||
_ = a.server.Close()
|
||||
a.doneOnce.Do(func() {
|
||||
close(a.done)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) closeGracefully() {
|
||||
a.doneOnce.Do(func() {
|
||||
close(a.done)
|
||||
})
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_ = a.server.Shutdown(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) allowedOrigin(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
return true
|
||||
}
|
||||
authURL, err := url.Parse(a.client.config.AuthLoginURL)
|
||||
return err == nil && origin == authURL.Scheme+"://"+authURL.Host
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) allowedHost(r *http.Request) bool {
|
||||
host, _, err := net.SplitHostPort(r.Host)
|
||||
if err != nil {
|
||||
host = r.Host
|
||||
}
|
||||
return host == a.client.config.BridgeHost || host == "localhost"
|
||||
}
|
||||
|
||||
func (a *LoginAttempt) stateMatches(raw string) bool {
|
||||
state, err := decodeBridgeState(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.status == statusPending &&
|
||||
time.Now().Before(a.maxExpires) &&
|
||||
state.Flow == bridgeFlowDesktop &&
|
||||
state.AttemptID == a.ID &&
|
||||
state.BridgeToken == a.bridgeToken &&
|
||||
state.AppID == a.client.config.AppID &&
|
||||
state.AppCallbackURL == a.client.config.AppCallbackURL &&
|
||||
state.LocalServerOrigin == a.origin
|
||||
}
|
||||
|
||||
func (c *Client) redeemTransferCode(ctx context.Context, attempt *LoginAttempt, transferCode string) (string, error) {
|
||||
body := map[string]string{
|
||||
"transfer_code": transferCode,
|
||||
"attempt_id": attempt.ID,
|
||||
"bridge_token": attempt.bridgeToken,
|
||||
"app_id": c.config.AppID,
|
||||
"device_id": attempt.deviceID,
|
||||
}
|
||||
var data struct {
|
||||
SessionIDLegacy string `json:"session_id"`
|
||||
SessionID string `json:"sessionId"`
|
||||
}
|
||||
if err := c.postAccount(ctx, "/auth/v1/redeem_desktop_transfer_code", "", body, &data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sessionID := firstNonEmpty(data.SessionIDLegacy, data.SessionID)
|
||||
if strings.TrimSpace(sessionID) == "" {
|
||||
return "", errors.New("redeem response missing session_id")
|
||||
}
|
||||
return sessionID, nil
|
||||
}
|
||||
|
||||
func (c *Client) fetchUserInfo(ctx context.Context, cookie string) (*UserInfo, error) {
|
||||
var raw map[string]any
|
||||
if err := c.postAccount(ctx, "/user/v1/user_info", cookie, map[string]any{}, &raw); err != nil {
|
||||
if errors.Is(err, errUnauthorized) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
user := mapUserInfo(raw)
|
||||
if user.UserID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
func (c *Client) logoutSession(ctx context.Context, cookie string) error {
|
||||
return c.postAccount(ctx, "/auth/v1/logout-web-session", cookie, map[string]string{"app_id": c.config.AppID}, nil)
|
||||
}
|
||||
|
||||
func (c *Client) postAccount(ctx context.Context, path string, cookie string, body any, out any) error {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, buildAccountURL(c.config.AccountBaseURL, path), bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(c.config.AccountHeaders) != 0 {
|
||||
req.Header = c.config.AccountHeaders.Clone()
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if cookie != "" {
|
||||
req.Header.Set("Cookie", cookie)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var envelope accountEnvelope
|
||||
if err := readJSON(resp.Body, &envelope); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized || envelope.Code == http.StatusUnauthorized {
|
||||
return errUnauthorized
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 || envelope.Code != 0 {
|
||||
message := firstNonEmpty(envelope.ErrMsg, envelope.Message, fmt.Sprintf("request failed with status %d", resp.StatusCode))
|
||||
return errors.New(message)
|
||||
}
|
||||
if out != nil && len(envelope.Data) > 0 {
|
||||
return json.Unmarshal(envelope.Data, out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) writeAuthJSON(session Session) error {
|
||||
if err := os.MkdirAll(filepath.Dir(c.config.AuthJSONPath), authJSONDirectoryFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.MarshalIndent(session, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := fmt.Sprintf("%s.tmp-%d-%s", c.config.AuthJSONPath, os.Getpid(), randomID())
|
||||
if err := os.WriteFile(tmp, raw, authJSONFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, c.config.AuthJSONPath); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var errUnauthorized = errors.New("unauthorized")
|
||||
|
||||
func normalizeConfig(config Config) Config {
|
||||
config.AccountHeaders = config.AccountHeaders.Clone()
|
||||
config.AppID = firstNonEmpty(config.AppID, DefaultAppID)
|
||||
config.AccountBaseURL = firstNonEmpty(config.AccountBaseURL, DefaultAccountBaseURL)
|
||||
config.AuthLoginURL = firstNonEmpty(config.AuthLoginURL, DefaultAuthLoginURL)
|
||||
config.BridgeHost = firstNonEmpty(config.BridgeHost, DefaultBridgeHost)
|
||||
if config.BridgeBasePort == 0 {
|
||||
config.BridgeBasePort = DefaultBridgeBasePort
|
||||
}
|
||||
if config.BridgeMaxPort == 0 {
|
||||
config.BridgeMaxPort = DefaultBridgeMaxPort
|
||||
}
|
||||
if config.LoginIdleTimeout <= 0 {
|
||||
config.LoginIdleTimeout = DefaultLoginIdleTimeout
|
||||
}
|
||||
if config.LoginMaxTimeout <= 0 {
|
||||
config.LoginMaxTimeout = DefaultLoginMaxTimeout
|
||||
}
|
||||
if config.LoginMaxTimeout < config.LoginIdleTimeout {
|
||||
config.LoginMaxTimeout = config.LoginIdleTimeout
|
||||
}
|
||||
if config.Hostname == "" {
|
||||
if hostname, err := os.Hostname(); err == nil {
|
||||
config.Hostname = hostname
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
func listenBridge(host string, basePort int, maxPort int) (net.Listener, string, error) {
|
||||
if maxPort < basePort {
|
||||
maxPort = basePort
|
||||
}
|
||||
for port := basePort; port <= maxPort; port++ {
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
return listener, "http://" + addr, nil
|
||||
}
|
||||
return nil, "", fmt.Errorf("no available bridge port in %d-%d", basePort, maxPort)
|
||||
}
|
||||
|
||||
func encodeBridgeState(state bridgeState) (string, error) {
|
||||
raw, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func decodeBridgeState(raw string) (bridgeState, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return bridgeState{}, err
|
||||
}
|
||||
var state bridgeState
|
||||
if err := json.Unmarshal(decoded, &state); err != nil {
|
||||
return bridgeState{}, err
|
||||
}
|
||||
if state.Version != bridgeStateVersion || state.Flow != bridgeFlowDesktop || state.AttemptID == "" || state.BridgeToken == "" {
|
||||
return bridgeState{}, errors.New("invalid bridge state")
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func isAllowedAppCallbackScheme(scheme string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(scheme)) {
|
||||
case "tutti", "tutti-dev", "nextop", "nextop-dev":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func buildAccountURL(baseURL string, path string) string {
|
||||
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(path, "/")
|
||||
}
|
||||
|
||||
func buildSessionCookie(sessionID string) string {
|
||||
return "session_id=" + strings.TrimSpace(sessionID)
|
||||
}
|
||||
|
||||
func sessionFromUser(sessionID string, user UserInfo) Session {
|
||||
return Session{
|
||||
SessionID: strings.TrimSpace(sessionID),
|
||||
Cookie: buildSessionCookie(sessionID),
|
||||
UserID: user.UserID,
|
||||
Name: user.Name,
|
||||
Avatar: user.Avatar,
|
||||
Email: user.Email,
|
||||
UpdatedAt: time.Now().UnixMilli(),
|
||||
}
|
||||
}
|
||||
|
||||
func mapUserInfo(data map[string]any) UserInfo {
|
||||
return UserInfo{
|
||||
UserID: stringField(data, "userId", "user_id"),
|
||||
Name: stringField(data, "name"),
|
||||
Email: stringField(data, "email", "userEmail", "emailAddress"),
|
||||
Avatar: stringField(data, "avatar", "picture", "avatarUrl", "headImg"),
|
||||
}
|
||||
}
|
||||
|
||||
func stringField(data map[string]any, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if value, ok := data[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readJSON(reader io.Reader, out any) error {
|
||||
decoder := json.NewDecoder(reader)
|
||||
return decoder.Decode(out)
|
||||
}
|
||||
|
||||
func sendBridgeJSON(w http.ResponseWriter, status int, body any) {
|
||||
sendBridgeCORS(w, status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
func sendBridgeCORS(w http.ResponseWriter, status int) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "content-type")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Private-Network", "true")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
var bytes [16]byte
|
||||
if _, err := rand.Read(bytes[:]); err != nil {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(bytes[:])
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func minTime(a time.Time, b time.Time) time.Time {
|
||||
if a.Before(b) {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
package authbridge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCallbackCompletesWritesAuthJSONAndRedirectsToWebResult(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
callbackURL, err := url.Parse(state.LocalServerOrigin + "/oauth/callback")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := callbackURL.Query()
|
||||
query.Set("state", attempt.state)
|
||||
query.Set("transfer_code", "transfer-1")
|
||||
callbackURL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := noRedirectClient().Get(callbackURL.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("callback status = %d", resp.StatusCode)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
resultURL, err := url.Parse(location)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resultURL.String() == "" || resultURL.Scheme != "https" || resultURL.Host != "tutti.sh" || resultURL.Path != "/auth/login/callback" {
|
||||
t.Fatalf("redirect location = %q", location)
|
||||
}
|
||||
if got := resultURL.Query().Get("desktopBridgeStatus"); got != "success" {
|
||||
t.Fatalf("desktopBridgeStatus = %q", got)
|
||||
}
|
||||
if strings.Contains(location, "transfer-1") || strings.Contains(location, "desktop-session-1") {
|
||||
t.Fatalf("redirect leaked sensitive value: %s", location)
|
||||
}
|
||||
openAppURL := resultURL.Query().Get("openAppUrl")
|
||||
if openAppURL == "" {
|
||||
t.Fatal("openAppUrl is missing")
|
||||
}
|
||||
parsedOpenAppURL, err := url.Parse(openAppURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsedOpenAppURL.Scheme != "tutti" || parsedOpenAppURL.Query().Get("desktopBridgeStatus") != "success" {
|
||||
t.Fatalf("openAppUrl = %q", openAppURL)
|
||||
}
|
||||
|
||||
waitForStatus(t, attempt, statusCompleted)
|
||||
session, err := client.ReadSession()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session == nil || session.SessionID != "desktop-session-1" || session.UserID != "user-1" {
|
||||
t.Fatalf("session = %#v", session)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLoginCompletesAndWritesAuthJSON(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
if state.AttemptID != attempt.ID || state.AppID != DefaultAppID {
|
||||
t.Fatalf("state = %#v", state)
|
||||
}
|
||||
|
||||
healthURL := state.LocalServerOrigin + "/oauth/health?attempt_id=" + state.AttemptID + "&token=" + state.BridgeToken
|
||||
healthResp, err := http.Get(healthURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if healthResp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("health status = %d", healthResp.StatusCode)
|
||||
}
|
||||
if got := healthResp.Header.Get("Access-Control-Allow-Private-Network"); got != "true" {
|
||||
t.Fatalf("private network cors header = %q", got)
|
||||
}
|
||||
_ = healthResp.Body.Close()
|
||||
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"state": attempt.state,
|
||||
"transfer_code": "transfer-1",
|
||||
})
|
||||
completeResp, err := http.Post(state.LocalServerOrigin+"/oauth/complete", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if completeResp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("complete status = %d", completeResp.StatusCode)
|
||||
}
|
||||
_ = completeResp.Body.Close()
|
||||
|
||||
waitForStatus(t, attempt, statusCompleted)
|
||||
|
||||
session, err := client.ReadSession()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session == nil || session.SessionID != "desktop-session-1" || session.UserID != "user-1" {
|
||||
t.Fatalf("session = %#v", session)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteRejectsInvalidState(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"state": "bad",
|
||||
"transfer_code": "transfer-1",
|
||||
})
|
||||
resp, err := http.Post(state.LocalServerOrigin+"/oauth/complete", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("complete status = %d", resp.StatusCode)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
waitForStatus(t, attempt, statusFailed)
|
||||
}
|
||||
|
||||
func TestCompleteRejectsMismatchedStateOrigin(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
tampered := state
|
||||
tampered.LocalServerOrigin = "http://127.0.0.1:1"
|
||||
tamperedState, err := encodeBridgeState(tampered)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"state": tamperedState,
|
||||
"transfer_code": "transfer-1",
|
||||
})
|
||||
resp, err := http.Post(state.LocalServerOrigin+"/oauth/complete", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("complete status = %d", resp.StatusCode)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
waitForStatus(t, attempt, statusFailed)
|
||||
}
|
||||
|
||||
func TestCompletePreservesUserCancellation(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"state": attempt.state,
|
||||
"error": "user_cancelled",
|
||||
})
|
||||
resp, err := http.Post(state.LocalServerOrigin+"/oauth/complete", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("complete status = %d", resp.StatusCode)
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Error.Code != "USER_CANCELLED" {
|
||||
t.Fatalf("error code = %q, want USER_CANCELLED", payload.Error.Code)
|
||||
}
|
||||
waitForStatus(t, attempt, statusFailed)
|
||||
if !IsUserCancelled(attempt.resultError()) {
|
||||
t.Fatalf("attempt error = %v, want user cancellation", attempt.resultError())
|
||||
}
|
||||
session, err := client.ReadSession()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session != nil {
|
||||
t.Fatalf("session = %#v, want nil", session)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackRedirectsProviderErrorWithoutLeakingSecrets(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
callbackURL, err := url.Parse(state.LocalServerOrigin + "/oauth/callback")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := callbackURL.Query()
|
||||
query.Set("state", attempt.state)
|
||||
query.Set("error", "access_denied")
|
||||
query.Set("transfer_code", "transfer-1")
|
||||
callbackURL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := noRedirectClient().Get(callbackURL.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("callback status = %d", resp.StatusCode)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
resultURL, err := url.Parse(location)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := resultURL.Query().Get("desktopBridgeStatus"); got != "error" {
|
||||
t.Fatalf("desktopBridgeStatus = %q", got)
|
||||
}
|
||||
if got := resultURL.Query().Get("desktopBridgeError"); got != "providerError" {
|
||||
t.Fatalf("desktopBridgeError = %q", got)
|
||||
}
|
||||
if strings.Contains(location, "access_denied") || strings.Contains(location, "transfer-1") {
|
||||
t.Fatalf("redirect leaked sensitive value: %s", location)
|
||||
}
|
||||
waitForStatus(t, attempt, statusFailed)
|
||||
}
|
||||
|
||||
func TestCallbackPreservesUserCancellationWithoutOpenAppURL(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client := newTestClient(t, account.URL)
|
||||
if err := client.writeAuthJSON(sessionFromUser("existing-session", UserInfo{UserID: "existing-user"})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attempt, err := client.StartLogin(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := loginState(t, attempt.LoginURL)
|
||||
callbackURL, err := url.Parse(state.LocalServerOrigin + "/oauth/callback")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := callbackURL.Query()
|
||||
query.Set("state", attempt.state)
|
||||
query.Set("error", "user_cancelled")
|
||||
callbackURL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := noRedirectClient().Get(callbackURL.String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("callback status = %d", resp.StatusCode)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
resultURL, err := url.Parse(location)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := resultURL.Query().Get("desktopBridgeStatus"); got != "error" {
|
||||
t.Fatalf("desktopBridgeStatus = %q", got)
|
||||
}
|
||||
if got := resultURL.Query().Get("desktopBridgeError"); got != "userCancelled" {
|
||||
t.Fatalf("desktopBridgeError = %q", got)
|
||||
}
|
||||
if got := resultURL.Query().Get("openAppUrl"); got != "" {
|
||||
t.Fatalf("openAppUrl = %q, want empty", got)
|
||||
}
|
||||
if strings.Contains(location, "user_cancelled") {
|
||||
t.Fatalf("redirect leaked callback error: %s", location)
|
||||
}
|
||||
waitForStatus(t, attempt, statusFailed)
|
||||
if !IsUserCancelled(attempt.resultError()) {
|
||||
t.Fatalf("attempt error = %v, want user cancellation", attempt.resultError())
|
||||
}
|
||||
session, err := client.ReadSession()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session == nil || session.SessionID != "existing-session" {
|
||||
t.Fatalf("session = %#v, want existing session", session)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginReturnsUserCancelledSentinel(t *testing.T) {
|
||||
account := newAccountServer(t)
|
||||
defer account.Close()
|
||||
|
||||
client, err := NewClient(Config{
|
||||
AccountBaseURL: account.URL,
|
||||
AppCallbackURL: "tutti://login/callback",
|
||||
AuthJSONPath: filepath.Join(t.TempDir(), "account", "auth.json"),
|
||||
AuthLoginURL: "https://tutti.sh/auth/login",
|
||||
OpenURL: func(_ context.Context, loginURL string) error {
|
||||
state := loginState(t, loginURL)
|
||||
parsedLoginURL, parseErr := url.Parse(loginURL)
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
callbackURL, parseErr := url.Parse(state.LocalServerOrigin + "/oauth/callback")
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
query := callbackURL.Query()
|
||||
query.Set("state", parsedLoginURL.Query().Get("state"))
|
||||
query.Set("error", "user_cancelled")
|
||||
callbackURL.RawQuery = query.Encode()
|
||||
response, requestErr := noRedirectClient().Get(callbackURL.String())
|
||||
if requestErr != nil {
|
||||
return requestErr
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusFound {
|
||||
return fmt.Errorf("callback status = %d", response.StatusCode)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = client.Login(context.Background())
|
||||
if !IsUserCancelled(err) {
|
||||
t.Fatalf("Login error = %v, want user cancellation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBridgeResultOpenAppURLSchemeWhitelist(t *testing.T) {
|
||||
allowed := buildBridgeResultURL(Config{
|
||||
AuthLoginURL: "https://tutti.sh/auth/login",
|
||||
AppCallbackURL: "tutti-dev://login/callback?transfer_code=bad",
|
||||
}, "success", "")
|
||||
allowedURL, err := url.Parse(allowed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
openAppURL := allowedURL.Query().Get("openAppUrl")
|
||||
if openAppURL == "" {
|
||||
t.Fatal("allowed openAppUrl is missing")
|
||||
}
|
||||
if strings.Contains(openAppURL, "transfer_code") {
|
||||
t.Fatalf("openAppUrl leaked old query: %s", openAppURL)
|
||||
}
|
||||
parsedOpenAppURL, err := url.Parse(openAppURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsedOpenAppURL.Scheme != "tutti-dev" {
|
||||
t.Fatalf("openAppUrl = %q", openAppURL)
|
||||
}
|
||||
|
||||
blocked := buildBridgeResultURL(Config{
|
||||
AuthLoginURL: "https://tutti.sh/auth/login",
|
||||
AppCallbackURL: "https://evil.example/callback",
|
||||
}, "success", "")
|
||||
blockedURL, err := url.Parse(blocked)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := blockedURL.Query().Get("openAppUrl"); got != "" {
|
||||
t.Fatalf("blocked openAppUrl = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserInfoAndLogout(t *testing.T) {
|
||||
account := newAccountServerWithHeaders(t, http.Header{"x-zk-ppe-lane": {"ppe-connectors"}})
|
||||
defer account.Close()
|
||||
|
||||
client, err := NewClient(Config{
|
||||
AccountBaseURL: account.URL,
|
||||
AccountHeaders: http.Header{"x-zk-ppe-lane": {"ppe-connectors"}},
|
||||
AppCallbackURL: "tutti://login/callback",
|
||||
AuthJSONPath: filepath.Join(t.TempDir(), "account", "auth.json"),
|
||||
AuthLoginURL: "https://tutti.sh/auth/login",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = client.writeAuthJSON(sessionFromUser("desktop-session-1", UserInfo{UserID: "old"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user, err := client.GetUserInfo(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user == nil || user.UserID != "user-1" || user.Email != "user@example.com" {
|
||||
t.Fatalf("user = %#v", user)
|
||||
}
|
||||
if err := client.Logout(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(client.config.AuthJSONPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("auth json stat error = %v, want not exist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestClient(t *testing.T, accountBaseURL string) *Client {
|
||||
t.Helper()
|
||||
client, err := NewClient(Config{
|
||||
AccountBaseURL: accountBaseURL,
|
||||
AppCallbackURL: "tutti://login/callback",
|
||||
AuthJSONPath: filepath.Join(t.TempDir(), "account", "auth.json"),
|
||||
AuthLoginURL: "https://tutti.sh/auth/login",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func newAccountServer(t *testing.T) *httptest.Server {
|
||||
return newAccountServerWithHeaders(t, nil)
|
||||
}
|
||||
|
||||
func newAccountServerWithHeaders(t *testing.T, expectedHeaders http.Header) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for name, values := range expectedHeaders {
|
||||
if got, want := r.Header.Values(name), values; !slices.Equal(got, want) {
|
||||
t.Errorf("%s headers = %q, want %q", name, got, want)
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/auth/v1/redeem_desktop_transfer_code":
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode redeem body: %v", err)
|
||||
}
|
||||
if strings.TrimSpace(body["device_id"]) == "" {
|
||||
t.Errorf("redeem device_id is empty in body %#v", body)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"code": 0,
|
||||
"data": map[string]string{"sessionId": "desktop-session-1"},
|
||||
})
|
||||
case "/user/v1/user_info":
|
||||
if got := r.Header.Get("Cookie"); got != "session_id=desktop-session-1" {
|
||||
t.Errorf("user_info cookie = %q, want redeemed desktop session", got)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"code": 0,
|
||||
"data": map[string]string{
|
||||
"user_id": "user-1",
|
||||
"name": "Tutti User",
|
||||
"email": "user@example.com",
|
||||
"avatar": "https://example.com/avatar.png",
|
||||
},
|
||||
})
|
||||
case "/auth/v1/logout-web-session":
|
||||
if got := r.Header.Get("Cookie"); got != "session_id=desktop-session-1" {
|
||||
t.Errorf("logout cookie = %q, want redeemed desktop session", got)
|
||||
}
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode logout body: %v", err)
|
||||
}
|
||||
if strings.TrimSpace(body["app_id"]) == "" {
|
||||
t.Errorf("logout app_id is empty in body %#v", body)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{}})
|
||||
default:
|
||||
t.Fatalf("unexpected account path %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func loginState(t *testing.T, loginURL string) bridgeState {
|
||||
t.Helper()
|
||||
u, err := url.Parse(loginURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := decodeBridgeState(u.Query().Get("state"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func waitForStatus(t *testing.T, attempt *LoginAttempt, want string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if got := attempt.Status().Status; got == want {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("status = %s, want %s", attempt.Status().Status, want)
|
||||
}
|
||||
|
||||
func noRedirectClient() *http.Client {
|
||||
return &http.Client{
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module github.com/tutti-os/tutti/packages/auth/bridge-go
|
||||
|
||||
go 1.24.3
|
||||
@@ -0,0 +1,80 @@
|
||||
package authbridge
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func buildLoginURL(authLoginURL string, state string) string {
|
||||
u, _ := url.Parse(authLoginURL)
|
||||
u.Path = "/auth/login"
|
||||
u.RawQuery = ""
|
||||
u.Fragment = ""
|
||||
q := u.Query()
|
||||
q.Set("state", state)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func redirectBridgeResult(w http.ResponseWriter, r *http.Request, attempt *LoginAttempt, status string, safeErrorCode string) {
|
||||
http.Redirect(w, r, buildBridgeResultURL(attempt.client.config, status, safeErrorCode), http.StatusFound)
|
||||
}
|
||||
|
||||
func buildBridgeResultURL(config Config, status string, safeErrorCode string) string {
|
||||
u, err := url.Parse(config.AuthLoginURL)
|
||||
if err != nil {
|
||||
return "/auth/login/callback"
|
||||
}
|
||||
u.Path = "/auth/login/callback"
|
||||
u.RawQuery = ""
|
||||
u.Fragment = ""
|
||||
q := u.Query()
|
||||
q.Set("desktopBridgeStatus", status)
|
||||
if strings.TrimSpace(safeErrorCode) != "" {
|
||||
q.Set("desktopBridgeError", strings.TrimSpace(safeErrorCode))
|
||||
}
|
||||
if openAppURL := buildSafeOpenAppURLForResult(config.AppCallbackURL, status, safeErrorCode); openAppURL != "" {
|
||||
q.Set("openAppUrl", openAppURL)
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func callbackErrorValue(value string) error {
|
||||
if strings.TrimSpace(value) == "user_cancelled" {
|
||||
return ErrUserCancelled
|
||||
}
|
||||
return errors.New(strings.TrimSpace(value))
|
||||
}
|
||||
|
||||
func callbackErrorSafeResultCode(value string) string {
|
||||
if strings.TrimSpace(value) == "user_cancelled" {
|
||||
return "userCancelled"
|
||||
}
|
||||
return "providerError"
|
||||
}
|
||||
|
||||
func buildSafeOpenAppURLForResult(raw string, status string, safeErrorCode string) string {
|
||||
if safeErrorCode == "userCancelled" {
|
||||
return ""
|
||||
}
|
||||
return buildSafeOpenAppURL(raw, status, safeErrorCode)
|
||||
}
|
||||
|
||||
func buildSafeOpenAppURL(raw string, status string, safeErrorCode string) string {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || !isAllowedAppCallbackScheme(u.Scheme) {
|
||||
return ""
|
||||
}
|
||||
u.RawQuery = ""
|
||||
u.Fragment = ""
|
||||
q := u.Query()
|
||||
q.Set("desktopBridgeStatus", status)
|
||||
if strings.TrimSpace(safeErrorCode) != "" {
|
||||
q.Set("desktopBridgeError", strings.TrimSpace(safeErrorCode))
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
@@ -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