Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,27 @@ on:

jobs:
docs:
runs-on: ubuntu-latest
runs-on: ubuntu-26.04
steps:
- uses: actions/checkout@v7
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
- uses: pnpm/action-setup@v6.1.0
- uses: actions/setup-node@v7
with:
node-version: '22'
node-version: '24'
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm docs:build
env:
DOCS_BASE: /LocalShare

server:
runs-on: ubuntu-latest
runs-on: ubuntu-26.04
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version: '1.23'
cache-dependency-path: server/go.mod
- name: 测试 LocalShare Server
working-directory: server
run: |
Expand All @@ -49,6 +50,7 @@ jobs:
- uses: actions/setup-go@v7
with:
go-version: '1.23'
cache-dependency-path: server/go.mod

- name: 编译 debug(首次会拉取 Swifter / Sparkle)
run: swift build
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ concurrency:

jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-26.04
steps:
- uses: actions/checkout@v7

- uses: pnpm/action-setup@v6
- uses: pnpm/action-setup@v6.1.0

- uses: actions/setup-node@v7
with:
Expand Down Expand Up @@ -50,7 +50,7 @@ jobs:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
needs: build
runs-on: ubuntu-latest
runs-on: ubuntu-26.04
steps:
- name: Deploy to GitHub Pages
id: deployment
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ jobs:
if: ${{ hashFiles('server/go.mod') != '' }}
with:
go-version-file: server/go.mod
cache-dependency-path: server/go.mod

- name: 编译 LocalShare Server(Linux amd64 / arm64)
if: ${{ hashFiles('server/go.mod') != '' }}
Expand Down
4 changes: 3 additions & 1 deletion Sources/LocalShare/FileServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ final class FileServer {

// MARK: - 请求处理

private func handle(_ req: HttpRequest) -> HttpResponse {
func handle(_ req: HttpRequest, afterAuthentication: () -> Void = {}) -> HttpResponse {
// Tailscale 开关是网络边界,必须先于访问码和 token 鉴权;即使拿着有效链接,关闭后也立即拒绝。
guard Self.allowsClient(address: req.address, tailscaleAccessEnabled: tailscaleAccessEnabled) else {
return htmlResponse(403, "Forbidden", Self.forbiddenPage(
Expand Down Expand Up @@ -381,6 +381,8 @@ final class FileServer {

// 鉴权通过的每个请求都刷新该 IP 的活跃时间(含心跳与下载中的请求)。
touchPresence(clientAddress, lookupName: !remoteMode)
// Allow tests to rotate the share at the authenticated request boundary.
afterAuthentication()

// 已经有有效 Cookie 却打开 /ls/join 时直接回当前分享入口,不再重复要求输入短码。
if req.method == "GET", req.path == "/ls/join" {
Expand Down
3 changes: 2 additions & 1 deletion Tests/LocalShareTests/RemoteSharingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ final class RemoteSharingTests: XCTestCase {
XCTAssertEqual(String(data: frame.dropFirst(4).dropFirst(5), encoding: .utf8), "hello")
}

@MainActor func testRemotePairStatusUsesUserDefaultsMarker() {
// Keep MainActor-owned objects inside XCTest's async task context during teardown.
@MainActor func testRemotePairStatusUsesUserDefaultsMarker() async {
let key = "remotePairedServerAddresses"
let previous = UserDefaults.standard.object(forKey: key)
defer {
Expand Down
98 changes: 48 additions & 50 deletions Tests/LocalShareTests/ShareRotationTests.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import XCTest
import Darwin
import Swifter
@testable import LocalShare

final class ShareRotationTests: XCTestCase {
func testInFlightRequestsStayWithinAuthenticatedShare() async throws {
func testInFlightRequestsStayWithinAuthenticatedShare() throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
Expand All @@ -17,64 +16,63 @@ final class ShareRotationTests: XCTestCase {
for upload in [false, true] {
let server = FileServer(share: upload ? .directory(oldRoot) : .file(oldFile), token: "old-token")
server.uploadEnabled = upload
let port = try server.start(preferredPorts: [in_port_t.random(in: 30000...50000)])
defer { server.stop() }
let fd = Darwin.socket(AF_INET, SOCK_STREAM, 0)
XCTAssertGreaterThanOrEqual(fd, 0)
var noSignal: Int32 = 1
_ = setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSignal, socklen_t(MemoryLayout<Int32>.size))
var timeout = timeval(tv_sec: 5, tv_usec: 0)
_ = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
address.sin_port = port.bigEndian
_ = "127.0.0.1".withCString { inet_pton(AF_INET, $0, &address.sin_addr) }
let connected = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) }
}
XCTAssertEqual(connected, 0)
let socket = Swifter.Socket(socketFileDescriptor: fd)
defer { socket.close() }
// Presence is recorded after auth, before this long path is decoded and routed.
// Single-file reads ignore the filename; repeated encoded slashes upload at the folder root.
let path = "/" + String(repeating: upload ? "%2f" : "%61", count: 500_000)
let body = upload ? "--rotation\r\nContent-Disposition: form-data; name=\"file\"; filename=\"upload.txt\"\r\nContent-Type: text/plain\r\n\r\nupload\r\n--rotation--\r\n" : ""
let headers = upload ? "Content-Type: multipart/form-data; boundary=rotation\r\nContent-Length: \(body.utf8.count)\r\n" : ""
try socket.writeUTF8("\(upload ? "POST" : "GET") \(path)?t=old-token HTTP/1.1\r\nHost: localhost\r\n\(headers)\r\n\(body)")
// The intentionally large request line must finish parsing before the rotation.
let deadline = Date().addingTimeInterval(15)
while server.activeViewers() == 0 && Date() < deadline {
try await Task.sleep(nanoseconds: 100_000)
let request = HttpRequest()
request.method = upload ? "POST" : "GET"
request.path = upload ? "/" : "/old.txt"
request.queryParams = [("t", "old-token")]
request.address = "127.0.0.1"
if upload {
request.headers["content-type"] = "multipart/form-data; boundary=rotation"
request.body = Array("--rotation\r\nContent-Disposition: form-data; name=\"file\"; filename=\"upload.txt\"\r\nContent-Type: text/plain\r\n\r\nupload\r\n--rotation--\r\n".utf8)
}
guard server.activeViewers() == 1 else {
XCTFail("request did not reach authenticated routing")
return
var rotated = false
// Rotate after authentication and before content routing, independent of socket timing.
let response = server.handle(request) {
XCTAssertEqual(server.activeViewers(), 1)
server.token = "new-token"
server.share = upload ? .directory(newRoot) : .file(newFile)
rotated = true
}
server.token = "new-token"
server.share = upload ? .directory(newRoot) : .file(newFile)
let status = try socket.readLine()
XCTAssertTrue(status.contains("200"))
while !(try socket.readLine()).isEmpty {}
XCTAssertTrue(rotated)
XCTAssertEqual(response.statusCode, 200)
XCTAssertTrue(response.headers()["Set-Cookie"]?.contains("old-token") == true)
if upload {
XCTAssertEqual(try String(contentsOf: oldRoot.appendingPathComponent("upload.txt")), "upload")
XCTAssertFalse(FileManager.default.fileExists(atPath: newRoot.appendingPathComponent("upload.txt").path))
} else {
XCTAssertEqual(String(decoding: try socket.read(length: 3), as: UTF8.self), "old")
XCTAssertEqual(try responseText(response), "old")
}
let base = "http://127.0.0.1:\(port)"
let configuration = URLSessionConfiguration.ephemeral
configuration.httpCookieStorage = nil
let session = URLSession(configuration: configuration)
defer { session.invalidateAndCancel() }
let (_, rejected) = try await session.data(from: URL(string: base + "/?t=old-token")!)
XCTAssertEqual((rejected as? HTTPURLResponse)?.statusCode, 403)
let (newContent, accepted) = try await session.data(from: URL(string: base + "/new.txt?t=new-token")!)
XCTAssertEqual((accepted as? HTTPURLResponse)?.statusCode, 200)
XCTAssertEqual(String(decoding: newContent, as: UTF8.self), "new")
request.method = "GET"
request.path = "/new.txt"
request.body = []
request.headers = [:]
XCTAssertEqual(server.handle(request).statusCode, 403)
request.queryParams = [("t", "new-token")]
let accepted = server.handle(request)
XCTAssertEqual(accepted.statusCode, 200)
XCTAssertEqual(try responseText(accepted), "new")
}
}

private func responseText(_ response: HttpResponse) throws -> String {
guard case .raw(_, _, _, let write) = response else {
XCTFail("expected a raw file response")
return ""
}
let writer = BodyWriter()
try write?(writer)
return String(decoding: writer.data, as: UTF8.self)
}

private final class BodyWriter: HttpResponseBodyWriter {
var data = Data()
func write(_ file: String.File) throws { XCTFail("unexpected file writer") }
func write(_ bytes: [UInt8]) throws { data.append(contentsOf: bytes) }
func write(_ bytes: ArraySlice<UInt8>) throws { data.append(contentsOf: bytes) }
func write(_ bytes: NSData) throws { data.append(bytes as Data) }
func write(_ bytes: Data) throws { data.append(bytes) }
}

func testTextBreadcrumbReturnsToMountedShareRoot() {
let crumbs = DirectoryListing.breadcrumb(requestPath: "/文本", rootName: "Folder", navigationPath: "/ls/text")
XCTAssertTrue(crumbs.contains("href=\"../\""))
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"vitepress": "1.6.4"
},
"pnpm": {
"overrides": {
"vite": "6.4.4"
},
"onlyBuiltDependencies": [
"esbuild"
]
Expand Down
Loading
Loading