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
72 changes: 72 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
name: iOS CI

on:
pull_request:
branches:
- main
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ios-ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
build-and-test:
name: Build and test
runs-on: macos-latest
timeout-minutes: 40

steps:
- name: Checkout repository
uses: actions/checkout@v7

- name: Show toolchain versions
run: |
sw_vers
xcodebuild -version
swift --version

- name: Verify MediaServerKit
run: test -f Packages/MediaServerKit/Package.swift

- name: Test MediaServerKit
working-directory: Packages/MediaServerKit
run: swift test

- name: Resolve Swift package dependencies
run: >-
xcodebuild -resolvePackageDependencies
-project VideoPlayer.xcodeproj
-scheme VideoPlayer

- name: Select iPhone Simulator
run: |
simulatorID="$(xcrun simctl list devices available | awk -F '[()]' '/^[[:space:]]+iPhone/ { print $2; exit }')"
if [[ -z "$simulatorID" ]]; then
echo "利用可能なiPhone Simulatorがありません." >&2
exit 1
fi
echo "SIMULATOR_ID=$simulatorID" >> "$GITHUB_ENV"
echo "Selected simulator: $simulatorID"

- name: Build iOS app
run: >-
xcodebuild build
-project VideoPlayer.xcodeproj
-scheme VideoPlayer
-destination 'generic/platform=iOS Simulator'
-derivedDataPath "$RUNNER_TEMP/VideoPlayerDerivedData"
CODE_SIGNING_ALLOWED=NO

- name: Test iOS app
run: >-
xcodebuild test
-project VideoPlayer.xcodeproj
-scheme VideoPlayer
-destination "platform=iOS Simulator,id=$SIMULATOR_ID"
-derivedDataPath "$RUNNER_TEMP/VideoPlayerDerivedData"
CODE_SIGNING_ALLOWED=NO
-only-testing:VideoPlayerTests
17 changes: 17 additions & 0 deletions Packages/MediaServerKit/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// swift-tools-version:5.9
import PackageDescription

let package = Package(
name: "MediaServerKit",
platforms: [
.iOS(.v16),
.macOS(.v13),
],
products: [
.library(name: "MediaServerKit", targets: ["MediaServerKit"]),
],
targets: [
.target(name: "MediaServerKit"),
.testTarget(name: "MediaServerKitTests", dependencies: ["MediaServerKit"]),
]
)
21 changes: 21 additions & 0 deletions Packages/MediaServerKit/Sources/MediaServerKit/PINSecurity.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation

/// PIN 認証の総当たり対策に使う純粋関数群。状態(IP 別の失敗回数)は呼び出し側が保持する。
public enum PINSecurity {
/// タイミング攻撃を避けるため、長さ・内容を定数時間で比較する。
public static func constantTimeEquals(_ a: String, _ b: String) -> Bool {
let ab = Array(a.utf8), bb = Array(b.utf8)
guard ab.count == bb.count else { return false }
var diff: UInt8 = 0
for i in 0..<ab.count { diff |= ab[i] ^ bb[i] }
return diff == 0
}

/// 連続失敗 `failCount` 回に対するロックアウト秒数。`maxAttempts` 未満なら nil(ロックしない)。
/// しきい値到達後は 30s → 60s → 120s … と倍増し、最大 1 時間でキャップする。
public static func lockoutDelay(failCount: Int, maxAttempts: Int = 5) -> TimeInterval? {
guard failCount >= maxAttempts else { return nil }
let over = failCount - maxAttempts
return min(3600.0, 30.0 * pow(2.0, Double(over)))
}
}
17 changes: 17 additions & 0 deletions Packages/MediaServerKit/Sources/MediaServerKit/RangeHeader.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Foundation

/// HTTP `Range` ヘッダの解析。動画シーク再生(206 Partial Content)で使う純粋関数。
public enum RangeHeader {
/// `"bytes=start-end"` 形式を解析し、両端を含む `(start, end)` バイト範囲を返す。
/// - end 省略時は末尾まで。end がサイズ超過なら末尾にクランプ。
/// - 不正・反転・サイズ 0 の場合は nil。
public static func parse(_ header: String, totalSize: UInt64) -> (UInt64, UInt64)? {
guard header.hasPrefix("bytes="), totalSize > 0 else { return nil }
let components = header.dropFirst(6).split(separator: "-")
guard let startStr = components.first, let start = UInt64(startStr) else { return nil }
let end = (components.count > 1 && !components[1].isEmpty)
? min(UInt64(components[1]) ?? 0, totalSize - 1)
: totalSize - 1
return start <= end ? (start, end) : nil
}
}
59 changes: 59 additions & 0 deletions Packages/MediaServerKit/Sources/MediaServerKit/RemoteModels.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import Foundation

// MARK: - サーバー ⇔ クライアント間の API 契約 (wire format)
//
// これらの型は Mac サーバー (AllServerForMac) と iOS クライアント (VideoPlayer) の
// 双方で共有される。以前は両アプリに別々に定義されており、フィールドのズレが
// そのまま API 破壊につながっていた。1 か所に集約することで契約を構造的に保証する。
//
// 日付は JSONEncoder/JSONDecoder の `.iso8601` 戦略でやり取りする(両側の取り決め)。

/// アルバム一覧 (`GET /albums`) の 1 要素
public struct RemoteAlbumInfo: Codable, Identifiable, Hashable, Sendable {
public let id: String
public let name: String
public let videoCount: Int
public let type: String?
public let coverVideoID: String?

public init(id: String, name: String, videoCount: Int, type: String?, coverVideoID: String? = nil) {
self.id = id
self.name = name
self.videoCount = videoCount
self.type = type
self.coverVideoID = coverVideoID
}
}

/// アルバム内メディア一覧 (`GET /albums/:id/videos`) の 1 要素
public struct RemoteVideoInfo: Codable, Identifiable, Hashable, Sendable {
public let id: String
public let filename: String
public let duration: TimeInterval
public let importDate: Date
public let creationDate: Date?
public let mediaType: String?
public let parentAlbumID: String?
/// 実ファイルのサイズ(バイト)。並べ替え「サイズ」用。旧サーバーは送らないので Optional。
public let fileSize: Int64?
/// 実ファイルの更新日時。並べ替え「変更日」用。旧サーバーは送らないので Optional。
public let modificationDate: Date?
/// 実ファイルの最終アクセス日時。並べ替え「最後に開いた日」用。旧サーバーは送らないので Optional。
public let accessDate: Date?

public init(id: String, filename: String, duration: TimeInterval, importDate: Date, creationDate: Date?, mediaType: String?, parentAlbumID: String? = nil, fileSize: Int64? = nil, modificationDate: Date? = nil, accessDate: Date? = nil) {
self.id = id
self.filename = filename
self.duration = duration
self.importDate = importDate
self.creationDate = creationDate
self.mediaType = mediaType
self.parentAlbumID = parentAlbumID
self.fileSize = fileSize
self.modificationDate = modificationDate
self.accessDate = accessDate
}

/// `mediaType == "photo"` のとき写真。動画と写真で UI を分岐するために使う。
public var isPhoto: Bool { mediaType == "photo" }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import Foundation

/// アップロードファイル名の安全化。パストラバーサルと非メディアファイルの書き込みを防ぐ。
public enum UploadFilename {
/// アップロードを許可するメディア拡張子
public static let defaultAllowedExtensions: Set<String> = [
"mp4", "mov", "m4v", "avi", "jpg", "jpeg", "png", "heic", "webp", "gif", "tiff"
]

/// パス区切りを除去し、メディア拡張子のみ許可する。
/// 不正(空・"."/".." ・隠しファイル・非許可拡張子)の場合は nil を返す。
public static func sanitize(_ raw: String, allowedExtensions: Set<String> = defaultAllowedExtensions) -> String? {
var name = (raw as NSString).lastPathComponent
name = name.replacingOccurrences(of: "/", with: "")
.replacingOccurrences(of: "\\", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, name != ".", name != "..", !name.hasPrefix(".") else { return nil }
if name.count > 255 { name = String(name.suffix(255)) }
let ext = (name as NSString).pathExtension.lowercased()
guard allowedExtensions.contains(ext) else { return nil }
return name
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import XCTest
import MediaServerKit

final class PINSecurityTests: XCTestCase {

func testEqualPinsMatch() {
XCTAssertTrue(PINSecurity.constantTimeEquals("123456", "123456"))
}

func testDifferentPinsReject() {
XCTAssertFalse(PINSecurity.constantTimeEquals("123456", "123457"))
}

func testDifferentLengthRejects() {
XCTAssertFalse(PINSecurity.constantTimeEquals("123456", "12345"))
}

func testEmptyEqualsEmpty() {
XCTAssertTrue(PINSecurity.constantTimeEquals("", ""))
}

func testNoLockoutUnderThreshold() {
XCTAssertNil(PINSecurity.lockoutDelay(failCount: 4))
}

func testLockoutEscalation() {
XCTAssertEqual(PINSecurity.lockoutDelay(failCount: 5), 30)
XCTAssertEqual(PINSecurity.lockoutDelay(failCount: 6), 60)
XCTAssertEqual(PINSecurity.lockoutDelay(failCount: 7), 120)
}

func testLockoutCapsAtOneHour() {
XCTAssertEqual(PINSecurity.lockoutDelay(failCount: 100), 3600)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import XCTest
import MediaServerKit

final class RangeHeaderTests: XCTestCase {

func testFullRangeFromStart() {
let r = RangeHeader.parse("bytes=0-", totalSize: 1000)
XCTAssertEqual(r?.0, 0)
XCTAssertEqual(r?.1, 999)
}

func testExplicitRange() {
let r = RangeHeader.parse("bytes=100-199", totalSize: 1000)
XCTAssertEqual(r?.0, 100)
XCTAssertEqual(r?.1, 199)
}

func testEndClampedToTotalSize() {
let r = RangeHeader.parse("bytes=900-5000", totalSize: 1000)
XCTAssertEqual(r?.0, 900)
XCTAssertEqual(r?.1, 999)
}

func testRejectsNonBytesUnit() {
XCTAssertNil(RangeHeader.parse("items=0-1", totalSize: 1000))
}

func testRejectsZeroTotalSize() {
XCTAssertNil(RangeHeader.parse("bytes=0-", totalSize: 0))
}

func testRejectsInvertedRange() {
XCTAssertNil(RangeHeader.parse("bytes=500-100", totalSize: 1000))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import XCTest
import MediaServerKit

final class RemoteModelsTests: XCTestCase {

func testAlbumRoundTrip() throws {
let a = RemoteAlbumInfo(id: "abc", name: "Trip", videoCount: 3, type: "video")
let data = try JSONEncoder().encode(a)
let decoded = try JSONDecoder().decode(RemoteAlbumInfo.self, from: data)
XCTAssertEqual(a, decoded)
}

func testAlbumDecodesMissingType() throws {
let json = Data(#"{"id":"x","name":"N","videoCount":0}"#.utf8)
let decoded = try JSONDecoder().decode(RemoteAlbumInfo.self, from: json)
XCTAssertNil(decoded.type)
}

/// サーバーは .iso8601 でエンコードし、クライアントは .iso8601 でデコードする取り決め。
func testVideoISO8601Contract() throws {
let enc = JSONEncoder(); enc.dateEncodingStrategy = .iso8601
let dec = JSONDecoder(); dec.dateDecodingStrategy = .iso8601
let v = RemoteVideoInfo(id: "1", filename: "a.mp4", duration: 12.5,
importDate: Date(timeIntervalSince1970: 1_700_000_000),
creationDate: nil, mediaType: "video")
let data = try enc.encode(v)
let decoded = try dec.decode(RemoteVideoInfo.self, from: data)
XCTAssertEqual(v, decoded)
XCTAssertFalse(decoded.isPhoto)
}

func testIsPhoto() {
let photo = RemoteVideoInfo(id: "1", filename: "a.heic", duration: 0,
importDate: Date(), creationDate: nil, mediaType: "photo")
let video = RemoteVideoInfo(id: "2", filename: "b.mp4", duration: 1,
importDate: Date(), creationDate: nil, mediaType: "video")
XCTAssertTrue(photo.isPhoto)
XCTAssertFalse(video.isPhoto)
}

func testVideoDecodesMissingOptionalFields() throws {
let dec = JSONDecoder(); dec.dateDecodingStrategy = .iso8601
let json = Data(#"{"id":"1","filename":"a.mp4","duration":3.0,"importDate":"2024-01-01T00:00:00Z"}"#.utf8)
let decoded = try dec.decode(RemoteVideoInfo.self, from: json)
XCTAssertNil(decoded.creationDate)
XCTAssertNil(decoded.mediaType)
XCTAssertFalse(decoded.isPhoto)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import XCTest
import MediaServerKit

final class UploadFilenameTests: XCTestCase {

func testTraversalStripped() {
XCTAssertEqual(UploadFilename.sanitize("../../movie.mp4"), "movie.mp4")
}

func testAbsolutePathStripped() {
XCTAssertEqual(UploadFilename.sanitize("/abs/path/clip.MOV"), "clip.MOV")
}

func testRejectsNonMediaExtension() {
XCTAssertNil(UploadFilename.sanitize("../../etc/passwd"))
XCTAssertNil(UploadFilename.sanitize("malware.exe"))
}

func testRejectsHiddenDotAndEmpty() {
XCTAssertNil(UploadFilename.sanitize(".hidden.mp4"))
XCTAssertNil(UploadFilename.sanitize(""))
XCTAssertNil(UploadFilename.sanitize("."))
XCTAssertNil(UploadFilename.sanitize(".."))
}

func testTrimsSurroundingWhitespace() {
XCTAssertEqual(UploadFilename.sanitize(" spaced.png "), "spaced.png")
}

func testBackslashTraversalRejected() {
XCTAssertNil(UploadFilename.sanitize("evil.mp4\\..\\x"))
}

func testPlainMediaAccepted() {
XCTAssertEqual(UploadFilename.sanitize("photo.jpg"), "photo.jpg")
XCTAssertEqual(UploadFilename.sanitize("clip.mp4"), "clip.mp4")
}
}
6 changes: 3 additions & 3 deletions VideoPlayer.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -606,16 +606,16 @@
/* End XCConfigurationList section */

/* Begin XCLocalSwiftPackageReference section */
7934EB602DFF000000000010 /* XCLocalSwiftPackageReference "../MediaServerKit" */ = {
7934EB602DFF000000000010 /* XCLocalSwiftPackageReference "Packages/MediaServerKit" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../MediaServerKit;
relativePath = Packages/MediaServerKit;
};
/* End XCLocalSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
7934EB602DFF000000000011 /* MediaServerKit */ = {
isa = XCSwiftPackageProductDependency;
package = 7934EB602DFF000000000010 /* XCLocalSwiftPackageReference "../MediaServerKit" */;
package = 7934EB602DFF000000000010 /* XCLocalSwiftPackageReference "Packages/MediaServerKit" */;
productName = MediaServerKit;
};
/* End XCSwiftPackageProductDependency section */
Expand Down
Loading