-
Notifications
You must be signed in to change notification settings - Fork 12
feat(auth): add --tunnel flag for OAuth login on headless machines #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
danikhan632
wants to merge
3
commits into
lox:main
Choose a base branch
from
danikhan632:feat/auth-tunnel-login
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| package tunnel | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // DefaultServer is the public localtunnel.me instance. | ||
| const DefaultServer = "https://localtunnel.me" | ||
|
|
||
| // Tunnel proxies connections from a public URL to a local port using the | ||
| // localtunnel protocol (https://github.com/localtunnel/server). | ||
| type Tunnel struct { | ||
| // URL is the public HTTPS URL assigned by the tunnel server. | ||
| URL string | ||
|
|
||
| localPort int | ||
| remoteHost string | ||
| remotePort int | ||
| maxConn int | ||
| ctx context.Context | ||
| cancel context.CancelFunc | ||
| wg sync.WaitGroup | ||
| } | ||
|
|
||
| type assignment struct { | ||
| ID string `json:"id"` | ||
| Port int `json:"port"` | ||
| URL string `json:"url"` | ||
| MaxConnCount int `json:"max_conn_count"` | ||
| } | ||
|
|
||
| // Start opens a tunnel from the default localtunnel.me server to localPort. | ||
| func Start(ctx context.Context, localPort int) (*Tunnel, error) { | ||
| return StartWithServer(ctx, localPort, DefaultServer) | ||
| } | ||
|
|
||
| // StartWithServer opens a tunnel using a localtunnel-compatible server. | ||
| func StartWithServer(ctx context.Context, localPort int, serverURL string) (*Tunnel, error) { | ||
| parsed, err := url.Parse(serverURL) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parse server URL: %w", err) | ||
| } | ||
|
|
||
| info, err := requestTunnel(ctx, serverURL) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if info.URL == "" || info.Port == 0 { | ||
| return nil, fmt.Errorf("invalid tunnel assignment: missing URL or port") | ||
| } | ||
|
|
||
| tctx, cancel := context.WithCancel(ctx) | ||
|
|
||
| t := &Tunnel{ | ||
| URL: info.URL, | ||
| localPort: localPort, | ||
| remoteHost: parsed.Hostname(), | ||
| remotePort: info.Port, | ||
| maxConn: info.MaxConnCount, | ||
| ctx: tctx, | ||
| cancel: cancel, | ||
| } | ||
|
|
||
| if t.maxConn <= 0 { | ||
| t.maxConn = 10 | ||
| } | ||
|
|
||
| for i := 0; i < t.maxConn; i++ { | ||
| t.wg.Add(1) | ||
| go t.worker() | ||
| } | ||
|
|
||
| return t, nil | ||
| } | ||
|
|
||
| func requestTunnel(ctx context.Context, serverURL string) (*assignment, error) { | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, serverURL+"/?new", nil) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("build tunnel request: %w", err) | ||
| } | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("request tunnel: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) | ||
| return nil, fmt.Errorf("tunnel server returned %d: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| var info assignment | ||
| if err := json.NewDecoder(resp.Body).Decode(&info); err != nil { | ||
| return nil, fmt.Errorf("decode tunnel assignment: %w", err) | ||
| } | ||
|
|
||
| return &info, nil | ||
| } | ||
|
|
||
| func (t *Tunnel) worker() { | ||
| defer t.wg.Done() | ||
| for { | ||
| select { | ||
| case <-t.ctx.Done(): | ||
| return | ||
| default: | ||
| if err := t.proxy(); err != nil { | ||
| // Brief pause before reconnecting on error. | ||
| select { | ||
| case <-t.ctx.Done(): | ||
| return | ||
| case <-time.After(time.Second): | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (t *Tunnel) proxy() error { | ||
| d := net.Dialer{Timeout: 10 * time.Second} | ||
| remote, err := d.DialContext(t.ctx, "tcp", fmt.Sprintf("%s:%d", t.remoteHost, t.remotePort)) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // Ensure the remote connection is closed when the context is cancelled, | ||
| // which unblocks the blocking ReadFull below. | ||
| proxyDone := make(chan struct{}) | ||
| defer close(proxyDone) | ||
| go func() { | ||
| select { | ||
| case <-t.ctx.Done(): | ||
| remote.Close() | ||
| case <-proxyDone: | ||
| } | ||
| }() | ||
| defer remote.Close() | ||
|
|
||
| // Block until the tunnel server forwards a request to this connection. | ||
| header := make([]byte, 1) | ||
| if _, err := io.ReadFull(remote, header); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| local, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", t.localPort), 5*time.Second) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer local.Close() | ||
|
|
||
| // Forward the byte we already consumed. | ||
| if _, err := local.Write(header); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // Bidirectional copy. | ||
| errc := make(chan error, 2) | ||
| go func() { _, err := io.Copy(local, remote); errc <- err }() | ||
| go func() { _, err := io.Copy(remote, local); errc <- err }() | ||
|
|
||
| select { | ||
| case <-errc: | ||
| case <-t.ctx.Done(): | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // Close shuts down the tunnel and waits for all proxy workers to exit. | ||
| func (t *Tunnel) Close() { | ||
| t.cancel() | ||
| t.wg.Wait() | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Starting the tunnel before
mcpClient.Initializemakesauth login --tunneldepend on localtunnel availability even when no OAuth flow is needed. If a user is already authenticated (theInitializecall would succeed), this path now fails early attunnel.Start(...)on offline/restricted networks instead of returningAlready authenticated!, which is a regression introduced by this ordering.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in a28e9d5 — added an
isAuthenticatedpre-check at the top ofRunOAuthFlowthat tries a quickInitializebefore starting any listener or tunnel. If credentials are already valid, it returns immediately without touching localtunnel.