diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0181537..e4fd154 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,3 +18,14 @@ jobs: - uses: actions/setup-go@v5 with: { go-version: '1.27.x' } - run: make cross + - run: sudo apt-get install -y desktop-file-utils && desktop-file-validate packaging/linux/pasame.desktop + release-dry: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 0 } + - uses: actions/setup-go@v5 + with: { go-version: '1.27.x' } + - uses: goreleaser/goreleaser-action@v6 + with: { version: '~> v2', args: release --snapshot --clean --skip=sign,publish } + - run: RUNNER_TEMP=$RUNNER_TEMP packaging/macos/release-mac.sh 0.0.0-dev diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..1d9a5c2 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,22 @@ +name: pages +on: + push: + branches: [main] + paths: ['site/**'] + workflow_dispatch: +permissions: + contents: read + pages: write + id-token: write +concurrency: { group: pages, cancel-in-progress: true } +jobs: + deploy: + runs-on: ubuntu-latest + environment: { name: github-pages, url: '${{ steps.d.outputs.page_url }}' } + steps: + - uses: actions/checkout@v4 + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: { path: site } + - id: d + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..683eaf3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,37 @@ +name: release +on: + push: + tags: ['v*'] +permissions: + contents: write + id-token: write # cosign keyless (Sigstore) +jobs: + release: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 0 } + - uses: actions/setup-go@v5 + with: { go-version: '1.27.x' } + - uses: sigstore/cosign-installer@v3 + - uses: goreleaser/goreleaser-action@v6 + with: { version: '~> v2', args: release --clean } + env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' } + - name: .dmg (firmado y notarizado si hay certificado) + run: packaging/macos/release-mac.sh "$GITHUB_REF_NAME" + env: + MACOS_CERT_P12: ${{ secrets.MACOS_CERT_P12 }} + MACOS_CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }} + MACOS_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }} + MACOS_NOTARY_KEY: ${{ secrets.MACOS_NOTARY_KEY }} + MACOS_NOTARY_KEY_ID: ${{ secrets.MACOS_NOTARY_KEY_ID }} + MACOS_NOTARY_ISSUER_ID: ${{ secrets.MACOS_NOTARY_ISSUER_ID }} + - name: Subir .dmg y latest.json, agregarlos a los checksums y publicar + env: { GH_TOKEN: '${{ secrets.GITHUB_TOKEN }}' } + run: | + cd dist + shasum -a 256 Pasame-macOS.dmg >> checksums.txt + cosign sign-blob --yes --output-signature checksums.txt.sig --output-certificate checksums.txt.pem checksums.txt + gh release upload "$GITHUB_REF_NAME" Pasame-macOS.dmg latest.json checksums.txt checksums.txt.sig checksums.txt.pem --clobber + pre=true; grep -q '"macNotarized":true' latest.json && [[ "$GITHUB_REF_NAME" != *-* ]] && pre=false + gh release edit "$GITHUB_REF_NAME" --draft=false --prerelease=$pre diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..6d54358 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,83 @@ +version: 2 +project_name: pasame + +before: + hooks: + - go mod tidy + - go test ./... + +builds: + - id: unix + main: ./cmd/pasame + binary: pasame + env: [CGO_ENABLED=0] + flags: [-trimpath] + ldflags: ["-s -w -X main.version={{ .Version }}"] + goos: [linux, darwin] + goarch: [amd64, arm64, arm] + goarm: ["7"] + ignore: + - { goos: darwin, goarch: arm } + - id: windows + main: ./cmd/pasame + binary: pasame + env: [CGO_ENABLED=0] + flags: [-trimpath] + ldflags: ["-s -w -H=windowsgui -X main.version={{ .Version }}"] + goos: [windows] + goarch: [amd64, arm64] + +universal_binaries: + - id: macos + ids: [unix] + replace: true # queda un solo binario darwin (Intel + Apple Silicon) + +archives: + - id: linux + ids: [unix] + formats: [tar.gz] + builds_info: { mode: 0755 } + name_template: 'pasame-linux-{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' + files: + - src: packaging/linux/pasame.desktop + strip_parent: true + - src: packaging/linux/icon.png + strip_parent: true + - README.md + - LICENSE + - id: windows + ids: [windows] + formats: [binary] + name_template: 'Pasame-Windows{{ if eq .Arch "arm64" }}-arm64{{ end }}' + +nfpms: + - id: deb + ids: [unix] + package_name: pasame + file_name_template: 'pasame_{{ .Version }}_{{ if eq .Arch "arm" }}armhf{{ else }}{{ .Arch }}{{ end }}' + formats: [deb] + maintainer: Martin Coll <145708582+KonixDev@users.noreply.github.com> + homepage: https://github.com/KonixDev/pasame # pasame.com.ar cuando se registre el dominio + description: Pasá archivos a cualquier celular o computadora que esté cerca. + license: MIT + recommends: [zenity, xdg-utils] + contents: + - src: packaging/linux/pasame.desktop + dst: /usr/share/applications/pasame.desktop + - src: packaging/linux/icon.png + dst: /usr/share/icons/hicolor/256x256/apps/pasame.png + +checksum: + name_template: checksums.txt + +signs: + - cmd: cosign + artifacts: checksum + signature: '${artifact}.sig' + certificate: '${artifact}.pem' + args: [sign-blob, --yes, '--output-signature=${signature}', '--output-certificate=${certificate}', '${artifact}'] + +release: + github: { owner: KonixDev, name: pasame } + prerelease: auto + draft: true # release-mac.sh sube el .dmg y latest.json, y recién ahí la publica diff --git a/README.en.md b/README.en.md index 2316c79..212c90e 100644 --- a/README.en.md +++ b/README.en.md @@ -38,55 +38,67 @@ In 2026, moving a video from your phone to the laptop next to it is still a hass ## Download -Get the version for your computer from **[Releases](https://github.com/KonixDev/pasame/releases/latest)**: +Go to **[konixdev.github.io/pasame](https://konixdev.github.io/pasame/en/)**: the button picks the right version for your computer. They are all in **[Releases](https://github.com/KonixDev/pasame/releases)** too: | Your computer | File | |---|---| | Windows 10 or 11 | `Pasame-Windows.exe` (or `Pasame-Windows-arm64.exe` on ARM devices) | -| Mac (macOS 12 or newer, Intel or Apple silicon) | `Pasame-macOS.zip` | -| Linux (Raspberry Pi included) | `pasame-linux-amd64.tar.gz`, `-arm64` or `-armv7` | +| Mac (macOS 12 or newer, Intel or Apple silicon) | `Pasame-macOS.dmg` | +| Linux (Raspberry Pi included) | `pasame-linux-amd64.tar.gz`, `-arm64` or `-armv7`, or the `.deb` for Ubuntu and Debian | There is nothing to install: it is a single file you double-click. The receiving side **installs nothing at all**: any browser from 2017 onwards works, including iPhone, Android, smart TVs and e-readers. ### The first time you open it -Pasame is not yet signed by Microsoft or Apple, so your computer will warn you the first time. You only do this once. +Pasame is not yet signed by Microsoft or Apple, so your computer will warn you the first time. You only do this once ([step-by-step guide](https://konixdev.github.io/pasame/en/how-to-open.html)). - **Windows:** if you see "Windows protected your PC", click **More info** → **Run anyway**. If a "Windows Defender Firewall" window appears, click **Allow access**: this lets the phone see your computer. -- **Mac:** unzip the file, move **Pasame** to Applications and open it. If it says it can't be opened, go to **System Settings → Privacy & Security**, scroll to the bottom and click **Open Anyway**. -- **Linux:** extract it and run `./pasame`. To pick files with a window you need `zenity` or `kdialog` (GNOME and KDE ship them). +- **Mac:** open the `.dmg`, drag **Pasame** to Applications and open it. If it says it can't be opened, go to **System Settings → Privacy & Security**, scroll to the bottom and click **Open Anyway**. +- **Linux:** install the `.deb` (it shows up in your app menu) or extract the `.tar.gz` and run `./pasame`. To pick files with a window you need `zenity` or `kdialog` (GNOME and KDE ship them). ## Good to know - **Both devices need to be on the same WiFi network** (or one plugged into the same router). -- WiFi in cafés, hotels and airports often blocks devices from seeing each other. Sharing over the internet is coming in the next version. +- WiFi in cafés, hotels and airports often blocks devices from seeing each other: use **Share over the internet** (below). +- On a Mac you can drop files onto the Pasame icon to share them right away. - If you close the Pasame tab, the app quits by itself after 2 minutes (unless something is still downloading). - Files sent to you land in **Downloads → Pasame**. - Downloads resume on their own if the WiFi drops, and "Download all" builds a ZIP on the fly, with no waiting and no extra disk space. - Pasame speaks English and Spanish. It picks your browser's language, and you can switch it from the ⋯ menu. The receiving page follows the language of the person sharing, with a one-tap switch. +## Far away or on another network + +Click **Share over the internet**. A new code and a 4-digit key appear. The phone's code already includes the key; from a computer, type the address and then the key. + +While it's on, everyone needs the key, also on your WiFi. Files go through Cloudflare's servers (a free service that may be unavailable). When you click **Stop sharing**, or **Go back to sharing over WiFi only**, the internet link stops working. + ## What it doesn't promise -On your WiFi, anyone connected to that same network who has the link can see what you share while the app is open. Files never leave your network, but they are not encrypted inside it. Don't use Pasame on a network you don't trust. +- On your WiFi, anyone connected to that same network who has the link can see what you share while the app is open. +- Over the internet, files are encrypted up to Cloudflare, but Cloudflare could see them. +- Don't use Pasame on a network you don't trust. ## Status -**v0.1 · local network.** Working today: sharing files and folders, QR code and short address, several receivers at once, on-the-fly ZIP, resumable downloads, sending files back (including drag and drop onto the page), English and Spanish, single instance. +**v0.3 · local network and internet.** Working today: sharing files and folders, QR code and short address, several receivers at once, on-the-fly ZIP, resumable downloads, sending files back, sharing over the internet with a 4-digit key, dropping files onto the Mac icon, `.dmg` and `.deb`, English and Spanish. -Next (see the [plan](docs/superpowers/plans/2026-09-21-pasame-02-tunel-y-distribucion.md), in Spanish): sharing over the internet with a 4-digit code, a Mac app signed by Apple, installers, and the [pasame.com.ar](https://pasame.com.ar) website. +Next: a Mac app verified by Apple (it needs an Apple Developer account) and the [pasame.com.ar](https://pasame.com.ar) domain. ## For developers -Go 1.27, a single binary with no system dependencies (`CGO_ENABLED=0`) and two direct dependencies ([zenity](https://github.com/ncruces/zenity) for native dialogs and [go-qrcode](https://github.com/skip2/go-qrcode)). The interface is plain HTML, CSS and JavaScript with no framework, embedded in the binary; the receiving page even works with JavaScript turned off. +Go 1.27, a single binary with no system dependencies (`CGO_ENABLED=0`) and two direct dependencies ([zenity](https://github.com/ncruces/zenity) for native dialogs and [go-qrcode](https://github.com/skip2/go-qrcode)), plus [mdns](https://github.com/hashicorp/mdns) only in builds with `-tags mdns`. To share over the internet it downloads [cloudflared](https://github.com/cloudflare/cloudflared) the first time, with a pinned version and SHA-256. The interface is plain HTML, CSS and JavaScript with no framework, embedded in the binary; the receiving page even works with JavaScript turned off. ```bash make test # unit and integration tests (go test -race) make build # ./pasame make cross # builds all 7 targets (Windows, macOS, Linux; x64 and ARM) ./pasame photo.jpg video.mp4 # opens already sharing those files -scripts/release.sh 0.1.0 # builds the release files into dist/ (on macOS) +go build -tags mdns ./cmd/pasame # with pasame.local +goreleaser release --snapshot --clean --skip=sign # a release's files, in dist/ ``` +Releases: pushing a `vX.Y.Z` tag runs `.github/workflows/release.yml` (GoReleaser + `.dmg`). For an Apple-verified Mac build, add the `MACOS_*` secrets (see Task 8 of [plan 2](docs/superpowers/plans/2026-09-21-pasame-02-tunel-y-distribucion.md), in Spanish); without them the release ships as a pre-release. Before a stable version: `test/manual/matriz.md` and `test/manual/tunel.md` complete. + | Folder | What's inside | |---|---| | `cmd/pasame` | The binary: wires everything together, opens the browser, handles shutdown. | @@ -94,6 +106,9 @@ scripts/release.sh 0.1.0 # builds the release files into dist/ (on macOS) | `internal/control` | The sender's interface, only on `127.0.0.1` and protected by a token. | | `internal/core` | Orchestrates the session, the addresses and the auto-quit rule. | | `internal/addr` | Picks the right network (ignores VPNs, Docker and the like). | +| `internal/tunnel` | Downloads, verifies and runs `cloudflared` to share over the internet. | +| `site/` | The download website (GitHub Pages). | +| `packaging/` | Icons, the Mac `.app`, `.exe` metadata and the Linux launcher. | | `internal/i18n` | Every string on the receiving page, in Spanish and English. | | `web/` | HTML, CSS and JS for both screens. | | `docs/marca` | [Brand guidelines](docs/marca/manual-de-marca.html) (in Spanish), logos and colors. | diff --git a/README.md b/README.md index b23ce79..9e201cb 100644 --- a/README.md +++ b/README.md @@ -36,54 +36,67 @@ En 2026, pasar un video del celular a la compu de al lado sigue siendo un lío: ## Descargar -Bajá la versión para tu computadora desde **[Releases](https://github.com/KonixDev/pasame/releases/latest)**: +Entrá a **[konixdev.github.io/pasame](https://konixdev.github.io/pasame/)**: el botón elige la versión para tu computadora. También están todas en **[Releases](https://github.com/KonixDev/pasame/releases)**: | Tu computadora | Archivo | |---|---| | Windows 10 u 11 | `Pasame-Windows.exe` (o `Pasame-Windows-arm64.exe` en equipos ARM) | -| Mac (macOS 12 o más nuevo, Intel o Apple) | `Pasame-macOS.zip` | -| Linux (incluida Raspberry Pi) | `pasame-linux-amd64.tar.gz`, `-arm64` o `-armv7` | +| Mac (macOS 12 o más nuevo, Intel o Apple) | `Pasame-macOS.dmg` | +| Linux (incluida Raspberry Pi) | `pasame-linux-amd64.tar.gz`, `-arm64` o `-armv7`, o el `.deb` para Ubuntu y Debian | No hace falta instalar nada: es un solo archivo que se abre con doble clic. Del lado de quien recibe **no se instala nada**: sirve cualquier navegador de 2017 en adelante, incluidos iPhone, Android, Smart TVs y e-readers. ### La primera vez que lo abrís -Pasame todavía no está firmado por Microsoft ni por Apple, así que la primera vez tu computadora avisa. Se hace una sola vez. +Pasame todavía no está firmado por Microsoft ni por Apple, así que la primera vez tu computadora avisa. Se hace una sola vez ([guía paso a paso](https://konixdev.github.io/pasame/como-abrir.html)). - **Windows:** si aparece "Windows protegió tu PC", tocá **Más información** → **Ejecutar de todas formas**. Si aparece una ventana del "Firewall de Windows Defender", tocá **Permitir acceso**: es para que el celular pueda ver tu computadora. -- **Mac:** descomprimí el `.zip`, mové **Pasame** a Aplicaciones y abrilo. Si dice que no se puede abrir, andá a **Ajustes del Sistema → Privacidad y seguridad**, bajá hasta el final y tocá **Abrir de todos modos**. -- **Linux:** descomprimí y ejecutá `./pasame`. Para elegir archivos con una ventana hace falta `zenity` o `kdialog` (vienen en GNOME y KDE). +- **Mac:** abrí el `.dmg`, arrastrá **Pasame** a Aplicaciones y abrilo. Si dice que no se puede abrir, andá a **Ajustes del Sistema → Privacidad y seguridad**, bajá hasta el final y tocá **Abrir de todos modos**. +- **Linux:** instalá el `.deb` (queda en el menú de aplicaciones) o descomprimí el `.tar.gz` y ejecutá `./pasame`. Para elegir archivos con una ventana hace falta `zenity` o `kdialog` (vienen en GNOME y KDE). ## Lo que conviene saber - **Los dos dispositivos tienen que estar en la misma red WiFi** (o uno por cable al mismo router). -- Si están en el WiFi de un bar, un hotel o un aeropuerto, esas redes suelen bloquear esto. Compartir por internet llega en la próxima versión. +- Si están en el WiFi de un bar, un hotel o un aeropuerto, esas redes suelen bloquear esto: usá **Compartir por internet** (abajo). +- En la Mac podés soltar archivos sobre el ícono de Pasame para compartirlos directo. - Si cerrás la pestaña de Pasame, la app se cierra sola a los 2 minutos (si no hay nada bajando). - Lo que te mandan queda en **Descargas → Pasame**. - Las descargas se retoman solas si se corta el WiFi, y "Descargar todo" arma un ZIP al vuelo, sin esperar ni ocupar espacio extra. - Pasame habla español e inglés: toma el idioma de tu navegador y lo cambiás desde el menú ⋯. La página de quien recibe sigue el idioma de quien comparte, con un cambio de un toque. +## Si están lejos o en otra red + +Tocá **Compartir por internet**. Aparece un código nuevo y una clave de 4 números. El código del celular ya trae la clave; desde una computadora, se escribe la dirección y después la clave. + +Mientras está activo, todos necesitan la clave, también en tu WiFi. Los archivos pasan por los servidores de Cloudflare (un servicio gratuito que puede no estar disponible). Al tocar **Terminar**, o **Volver a compartir solo por WiFi**, el link de internet deja de funcionar. + ## Qué no promete -En tu WiFi, cualquiera conectado a esa misma red que tenga el link puede ver lo que compartís mientras la app está abierta. Los archivos no salen de tu red, pero no viajan cifrados dentro de ella. No uses Pasame en una red en la que no confíes. +- En tu WiFi, cualquiera conectado a esa misma red que tenga el link puede ver lo que compartís mientras la app está abierta. +- Por internet, los archivos van cifrados hasta Cloudflare, pero Cloudflare podría verlos. +- No uses Pasame en una red en la que no confíes. ## Estado -**v0.1 · red local.** Funciona: compartir archivos y carpetas, código QR y dirección corta, varios receptores a la vez, ZIP al vuelo, descargas reanudables, mandar archivos de vuelta (también arrastrándolos a la página), toda la app en español e inglés, instancia única. +**v0.3 · red local e internet.** Funciona: compartir archivos y carpetas, código QR y dirección corta, varios receptores a la vez, ZIP al vuelo, descargas reanudables, mandar archivos de vuelta, compartir por internet con clave de 4 números, soltar archivos sobre el ícono en la Mac, `.dmg` y `.deb`, toda la app en español e inglés. -Próximo (ver [plan](docs/superpowers/plans/2026-09-21-pasame-02-tunel-y-distribucion.md)): compartir por internet con clave de 4 números, app de Mac firmada por Apple, instaladores y el sitio [pasame.com.ar](https://pasame.com.ar). +Próximo: la app de Mac verificada por Apple (hace falta una cuenta de Apple Developer) y el dominio [pasame.com.ar](https://pasame.com.ar). ## Para desarrolladores -Go 1.27, un solo binario sin dependencias del sistema (`CGO_ENABLED=0`), dos dependencias directas ([zenity](https://github.com/ncruces/zenity) para los diálogos nativos y [go-qrcode](https://github.com/skip2/go-qrcode)). La interfaz es HTML, CSS y JavaScript sin frameworks, embebida en el binario; la página de quien recibe funciona incluso sin JavaScript. +Go 1.27, un solo binario sin dependencias del sistema (`CGO_ENABLED=0`), dos dependencias directas ([zenity](https://github.com/ncruces/zenity) para los diálogos nativos y [go-qrcode](https://github.com/skip2/go-qrcode)), más [mdns](https://github.com/hashicorp/mdns) solo en los builds con `-tags mdns`. Para compartir por internet baja [cloudflared](https://github.com/cloudflare/cloudflared) la primera vez que se usa, con versión y SHA-256 fijados. La interfaz es HTML, CSS y JavaScript sin frameworks, embebida en el binario; la página de quien recibe funciona incluso sin JavaScript. ```bash make test # tests unitarios y de integración (go test -race) make build # ./pasame make cross # compila los 7 targets (Windows, macOS, Linux; x64 y ARM) ./pasame foto.jpg video.mp4 # abre compartiendo esos archivos +go build -tags mdns ./cmd/pasame # con pasame.local +goreleaser release --snapshot --clean --skip=sign # los archivos de una release, en dist/ ``` +Releases: pushear un tag `vX.Y.Z` corre `.github/workflows/release.yml` (GoReleaser + `.dmg`). Para que Mac salga verificada por Apple, cargar los secrets `MACOS_*` (ver la Tarea 8 del [plan 2](docs/superpowers/plans/2026-09-21-pasame-02-tunel-y-distribucion.md)); sin ellos, la release sale como pre-release. Antes de una versión estable: `test/manual/matriz.md` y `test/manual/tunel.md` completos. + | Carpeta | Qué hay | |---|---| | `cmd/pasame` | El binario: arma todo, abre el navegador, maneja el cierre. | @@ -91,6 +104,9 @@ make cross # compila los 7 targets (Windows, macOS, Linux; x64 y ARM) | `internal/control` | La interfaz de quien comparte, solo en `127.0.0.1` y protegida con un token. | | `internal/core` | Orquesta la sesión, las direcciones y la regla de cierre automático. | | `internal/addr` | Elige la red correcta (ignora VPN, Docker y similares). | +| `internal/tunnel` | Baja, verifica y corre `cloudflared` para compartir por internet. | +| `site/` | El sitio de descarga (GitHub Pages). | +| `packaging/` | Íconos, `.app` de Mac, metadatos del `.exe` y lanzador de Linux. | | `web/` | HTML, CSS y JS de las dos pantallas. | | `docs/marca` | [Manual de marca](docs/marca/manual-de-marca.html), logos y colores. | | `docs/superpowers` | Diseño técnico y planes de implementación. | diff --git a/cmd/pasame/gen.go b/cmd/pasame/gen.go new file mode 100644 index 0000000..669df20 --- /dev/null +++ b/cmd/pasame/gen.go @@ -0,0 +1,5 @@ +package main + +// Genera el icono y los metadatos del .exe para ambas arquitecturas de Windows. +//go:generate go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo@v1.4.1 -64 -o resource_windows_amd64.syso ../../packaging/windows/versioninfo.json +//go:generate go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo@v1.4.1 -arm -64 -o resource_windows_arm64.syso ../../packaging/windows/versioninfo.json diff --git a/cmd/pasame/main.go b/cmd/pasame/main.go index 19975a0..bd9add7 100644 --- a/cmd/pasame/main.go +++ b/cmd/pasame/main.go @@ -84,6 +84,10 @@ func run() error { lan := addr.NewLAN(sharePort) book := addr.NewBook() book.Register(lan) + if m, err := addr.NewMDNS(lan, sharePort); err == nil { // solo en builds con -tags mdns + book.Register(m) + defer m.Close() + } c := core.New(core.Options{ SharePort: sharePort, Quarantine: quarantine, ConfigDir: cfgDir, Config: cfg, FirstRun: firstRun, LAN: lan, Book: book, Version: version, @@ -91,6 +95,7 @@ func run() error { shareH, err := share.New(share.Deps{ Current: c.Current, Stats: c.Stats, Quarantine: quarantine, Sender: c.Sender, Strict: c.Strict, Lang: c.Lang, + PINKey: c.PINKey, }) if err != nil { return err @@ -128,6 +133,7 @@ func run() error { c.RequestQuit() // avisa a las pestañas abiertas (evento SSE "quit") sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() + c.DisableTunnel() // no dejar cloudflared andando ctlSrv.Shutdown(sctx) shareSrv.Shutdown(sctx) if shareH.Received() { diff --git a/cmd/pasame/resource_windows_amd64.syso b/cmd/pasame/resource_windows_amd64.syso new file mode 100644 index 0000000..b3a69f9 Binary files /dev/null and b/cmd/pasame/resource_windows_amd64.syso differ diff --git a/cmd/pasame/resource_windows_arm64.syso b/cmd/pasame/resource_windows_arm64.syso new file mode 100644 index 0000000..25eeada Binary files /dev/null and b/cmd/pasame/resource_windows_arm64.syso differ diff --git a/go.mod b/go.mod index 363cd41..853bbda 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/KonixDev/pasame go 1.27 require ( + github.com/hashicorp/mdns v1.0.7 github.com/makiuchi-d/gozxing v0.1.1 github.com/ncruces/zenity v0.10.15 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e @@ -13,8 +14,13 @@ require ( github.com/akavel/rsrc v0.10.2 // indirect github.com/dchest/jsmin v1.0.0 // indirect github.com/josephspurrier/goversioninfo v1.7.0 // indirect + github.com/miekg/dns v1.1.72 // indirect github.com/randall77/makefat v0.0.0-20260406194835-1b91746796b7 // indirect golang.org/x/image v0.44.0 // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/sync v0.22.0 // indirect golang.org/x/text v0.40.0 // indirect + golang.org/x/tools v0.47.0 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect ) diff --git a/go.sum b/go.sum index 2bc0a61..0771304 100644 --- a/go.sum +++ b/go.sum @@ -4,10 +4,16 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dchest/jsmin v1.0.0 h1:Y2hWXmGZiRxtl+VcTksyucgTlYxnhPzTozCwx9gy9zI= github.com/dchest/jsmin v1.0.0/go.mod h1:AVBIund7Mr7lKXT70hKT2YgL3XEXUaUk5iw9DZ8b0Uc= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hashicorp/mdns v1.0.7 h1:yWoQVMW5JOiDxQnIUcm3IDt0kCjf3TuXHDbdEKPsbAY= +github.com/hashicorp/mdns v1.0.7/go.mod h1:yjuhYhZyPDqXXL48xC7cdpGwGUMwu7OViDmsuT5COvg= github.com/josephspurrier/goversioninfo v1.7.0 h1:LQzXOlVm/CtbwJ9/UHl5a2HT0BjcLAwid5gqGd7ZUJ8= github.com/josephspurrier/goversioninfo v1.7.0/go.mod h1:z9y0r2G6g5jwSJaFE0cxW9to0aeIibK7UYeLx53aQRU= github.com/makiuchi-d/gozxing v0.1.1 h1:xxqijhoedi+/lZlhINteGbywIrewVdVv2wl9r5O9S1I= github.com/makiuchi-d/gozxing v0.1.1/go.mod h1:eRIHbOjX7QWxLIDJoQuMLhuXg9LAuw6znsUtRkNw9DU= +github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= +github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/ncruces/zenity v0.10.15 h1:UaHekkxwt7QjoZmMWtzhqSEtQT97/Cux6FDBWwfyuqk= github.com/ncruces/zenity v0.10.15/go.mod h1:45d81tt+vF/UjBjlWE/vvE0oD0hWuHUQld4vPbA4VxE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -22,10 +28,18 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I= golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/addr/mdns.go b/internal/addr/mdns.go new file mode 100644 index 0000000..739ba9d --- /dev/null +++ b/internal/addr/mdns.go @@ -0,0 +1,83 @@ +//go:build mdns + +package addr + +import ( + "context" + "errors" + "io" + "log" + "net" + "strconv" + "sync" + + "github.com/hashicorp/mdns" +) + +var ErrMDNSDisabled = errors.New("addr: compilado sin mdns") + +const mdnsHost = "pasame.local" + +type MDNS struct { + lan *LAN + port int + announce func(ip string) (func(), error) // devuelve cómo dejar de anunciar + + mu sync.Mutex + ip string + stop func() + ok bool +} + +func NewMDNS(lan *LAN, port int) (*MDNS, error) { + return &MDNS{lan: lan, port: port, announce: realAnnounce(port)}, nil +} + +func realAnnounce(port int) func(string) (func(), error) { + return func(ip string) (func(), error) { + svc, err := mdns.NewMDNSService("Pasame", "_http._tcp", "", mdnsHost+".", port, []net.IP{net.ParseIP(ip)}, nil) + if err != nil { + return nil, err + } + srv, err := mdns.NewServer(&mdns.Config{Zone: svc, Logger: log.New(io.Discard, "", 0)}) + if err != nil { + return nil, err + } + return func() { srv.Shutdown() }, nil + } +} + +func (m *MDNS) Kind() string { return "mdns" } + +func (m *MDNS) Addresses(_ context.Context, sessionPath string) ([]Address, error) { + cs := m.lan.Candidates() + if len(cs) == 0 { + return nil, nil + } + m.mu.Lock() + defer m.mu.Unlock() + if cs[0].IP != m.ip { + if m.stop != nil { + m.stop() + } + m.ip, m.stop, m.ok = cs[0].IP, nil, false + if stop, err := m.announce(cs[0].IP); err == nil { + m.stop, m.ok = stop, true + } else { + log.Printf("mdns: %v (no se muestra pasame.local)", err) + } + } + if !m.ok { + return nil, nil + } + hp := mdnsHost + ":" + strconv.Itoa(m.port) + return []Address{{Kind: "mdns", URL: "http://" + hp + sessionPath, Display: hp, Label: "Nombre fácil (puede no funcionar)"}}, nil +} + +func (m *MDNS) Close() { + m.mu.Lock() + defer m.mu.Unlock() + if m.stop != nil { + m.stop() + } +} diff --git a/internal/addr/mdns_stub.go b/internal/addr/mdns_stub.go new file mode 100644 index 0000000..b23b41f --- /dev/null +++ b/internal/addr/mdns_stub.go @@ -0,0 +1,17 @@ +//go:build !mdns + +package addr + +import ( + "context" + "errors" +) + +var ErrMDNSDisabled = errors.New("addr: compilado sin mdns") + +type MDNS struct{} + +func NewMDNS(*LAN, int) (*MDNS, error) { return nil, ErrMDNSDisabled } +func (*MDNS) Kind() string { return "mdns" } +func (*MDNS) Addresses(context.Context, string) ([]Address, error) { return nil, nil } +func (*MDNS) Close() {} diff --git a/internal/addr/mdns_test.go b/internal/addr/mdns_test.go new file mode 100644 index 0000000..4a91668 --- /dev/null +++ b/internal/addr/mdns_test.go @@ -0,0 +1,44 @@ +//go:build mdns + +package addr + +import ( + "context" + "errors" + "net" + "testing" +) + +func TestMDNSAddressAndReannounce(t *testing.T) { + ip := "192.168.1.42" + lan := NewLAN(8080) + lan.List = func() ([]Iface, error) { return []Iface{{Name: "en0", Up: true, IPs: []net.IP{net.ParseIP(ip)}}}, nil } + lan.Route = func() net.IP { return nil } + var announced []string + m := &MDNS{lan: lan, port: 8080, announce: func(ip string) (func(), error) { + announced = append(announced, ip) + return func() {}, nil + }} + as, _ := m.Addresses(context.Background(), "/s/abcde") + if len(as) != 1 || as[0].Display != "pasame.local:8080" || as[0].Kind != "mdns" || as[0].URL != "http://pasame.local:8080/s/abcde" { + t.Fatalf("%+v", as) + } + m.Addresses(context.Background(), "/s/abcde") + ip = "10.0.0.7" + m.Addresses(context.Background(), "/s/abcde") + if len(announced) != 2 || announced[1] != "10.0.0.7" { + t.Fatalf("anuncios: %v", announced) + } +} + +func TestMDNSFailureIsSilent(t *testing.T) { + lan := NewLAN(8080) + lan.List = func() ([]Iface, error) { + return []Iface{{Name: "en0", Up: true, IPs: []net.IP{net.ParseIP("192.168.1.42")}}}, nil + } + lan.Route = func() net.IP { return nil } + m := &MDNS{lan: lan, port: 8080, announce: func(string) (func(), error) { return nil, errors.New("5353 ocupado") }} + if as, err := m.Addresses(context.Background(), "/s/x"); as != nil || err != nil { + t.Fatalf("%v %v", as, err) + } +} diff --git a/internal/addr/tunnel.go b/internal/addr/tunnel.go new file mode 100644 index 0000000..14ed363 --- /dev/null +++ b/internal/addr/tunnel.go @@ -0,0 +1,18 @@ +package addr + +import ( + "context" + "strings" +) + +// TunnelProvider publica la URL pública del túnel. No sabe nada de cloudflared: core le pasa la URL. +type TunnelProvider struct{ URL string } + +func (p *TunnelProvider) Kind() string { return "tunnel" } + +func (p *TunnelProvider) Addresses(_ context.Context, sessionPath string) ([]Address, error) { + return []Address{{ + Kind: "tunnel", URL: p.URL + sessionPath, + Display: strings.TrimPrefix(p.URL, "https://"), Label: "Por internet", + }}, nil +} diff --git a/internal/addr/tunnel_test.go b/internal/addr/tunnel_test.go new file mode 100644 index 0000000..ba90942 --- /dev/null +++ b/internal/addr/tunnel_test.go @@ -0,0 +1,19 @@ +package addr + +import ( + "context" + "testing" +) + +func TestTunnelProvider(t *testing.T) { + p := &TunnelProvider{URL: "https://amber-cat.trycloudflare.com"} + as, err := p.Addresses(context.Background(), "/s/k3x9m?pin=4813") + if err != nil || len(as) != 1 { + t.Fatal(err) + } + a := as[0] + if a.Kind != "tunnel" || a.URL != "https://amber-cat.trycloudflare.com/s/k3x9m?pin=4813" || + a.Display != "amber-cat.trycloudflare.com" || a.Label != "Por internet" { + t.Fatalf("%+v", a) + } +} diff --git a/internal/control/api.go b/internal/control/api.go index a4590d0..f192d13 100644 --- a/internal/control/api.go +++ b/internal/control/api.go @@ -100,3 +100,16 @@ func (s *server) lang(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusNoContent) } + +func (s *server) tunnel(w http.ResponseWriter, r *http.Request) { + var b struct{ On bool } + if !decode(w, r, &b) { + return + } + if b.On { + s.c.EnableTunnel() + } else { + s.c.DisableTunnel() + } + w.WriteHeader(http.StatusAccepted) +} diff --git a/internal/control/server.go b/internal/control/server.go index dc57de2..b5fa4a1 100644 --- a/internal/control/server.go +++ b/internal/control/server.go @@ -43,6 +43,7 @@ func New(c *core.Core, token string, port int) http.Handler { s.mux.HandleFunc("POST /api/name", s.auth(s.name)) s.mux.HandleFunc("POST /api/iface", s.auth(s.iface)) s.mux.HandleFunc("POST /api/lang", s.auth(s.lang)) + s.mux.HandleFunc("POST /api/tunnel", s.auth(s.tunnel)) s.mux.HandleFunc("POST /api/open-folder", s.auth(s.errOnly(c.OpenFolder))) s.mux.HandleFunc("POST /api/firewall", s.auth(s.errOnly(c.OpenFirewall))) return s diff --git a/internal/control/ui_test.go b/internal/control/ui_test.go index 1845600..67b457f 100644 --- a/internal/control/ui_test.go +++ b/internal/control/ui_test.go @@ -29,8 +29,10 @@ func TestUIVoice(t *testing.T) { es, en := block[:strings.Index(block, "\n en: {")], block[strings.Index(block, "\n en: {"):] clean := func(s string) string { s = strings.ToLower(s) - s = regexp.MustCompile(`(?m)^\s*//.*$`).ReplaceAllString(s, "") // comentarios de código - s = regexp.MustCompile(`(?m)^\s*\w+:`).ReplaceAllString(s, "") // nombres de clave (no se ven) + s = regexp.MustCompile(`(?m)^\s*//.*$`).ReplaceAllString(s, "") // comentarios de código + s = regexp.MustCompile(`(?m)^\s*\w+:`).ReplaceAllString(s, "") // nombres de clave (no se ven) + s = regexp.MustCompile(`[\w-]+="[^"]*"`).ReplaceAllString(s, "") // atributos HTML (data-act="tunnel-on") + s = strings.ReplaceAll(s, `\'`, "'") // comillas escapadas del JS // Títulos literales de ventanas del sistema que la persona va a ver: se permiten. s = strings.ReplaceAll(s, "firewall de windows defender", "") s = strings.ReplaceAll(s, "windows defender firewall", "") diff --git a/internal/core/core.go b/internal/core/core.go index 09cef64..0303a9d 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -18,6 +18,7 @@ import ( "github.com/KonixDev/pasame/internal/platform" "github.com/KonixDev/pasame/internal/qr" "github.com/KonixDev/pasame/internal/session" + "github.com/KonixDev/pasame/internal/tunnel" ) type Options struct { @@ -30,6 +31,9 @@ type Options struct { Book *addr.Book Pick func(kind string) ([]string, error) Version string + + Tunnel TunnelStarter // por defecto baja y corre cloudflared + TunnelAvailable func() bool // por defecto tunnel.Available } type Core struct { @@ -48,6 +52,10 @@ type Core struct { detectedLang string // del navegador de la pestaña de control; no se guarda (es una suposición) netChangedUntil time.Time lastPrimary string + pinKey []byte // clave HMAC de la cookie del PIN; rota al prender y apagar el túnel + tun TunnelState + tunStop func() + tunCancel context.CancelFunc // corta un túnel que todavía se está conectando subsMu sync.Mutex subs map[chan struct{}]bool @@ -72,6 +80,14 @@ func New(o Options) *Core { if o.Config.IfaceOverride != "" { o.LAN.SetOverride(o.Config.IfaceOverride) } + if c.o.Tunnel == nil { + c.o.Tunnel = defaultTunnel(o.ConfigDir, o.SharePort) + } + if c.o.TunnelAvailable == nil { + c.o.TunnelAvailable = tunnel.Available + } + c.pinKey = newPINKey() + c.tun = TunnelState{Status: "off"} return c } @@ -184,6 +200,7 @@ func (c *Core) Share(paths []string) { func (c *Core) ReceiveOnly() { c.Share(nil) } func (c *Core) Stop() { + c.DisableTunnel() // terminar de compartir también corta internet c.mu.Lock() c.sess, c.stats, c.unreadable, c.phase = nil, nil, nil, "idle" c.mu.Unlock() @@ -258,9 +275,11 @@ func (c *Core) State() State { FirewallHint: c.firewallHint, Lang: string(c.langLocked()), LangExplicit: c.cfg.Lang != "", } + pin := "" if sess != nil { - st.SharedAt = c.sharedAt.UnixMilli() + st.SharedAt, pin = c.sharedAt.UnixMilli(), sess.PIN } + st.Tunnel = c.tunnelView(pin) c.mu.Unlock() st.VPN = c.o.LAN.VPN() @@ -275,14 +294,27 @@ func (c *Core) State() State { } st.Stats = stats.Snapshot() st.Addresses = c.o.Book.Active(context.Background(), c.sessionPath(sess)) + if st.Strict { + // En modo estricto "/" no lleva a la sesión: lo que se dicta o se tipea tiene que traer la ruta. + // El PIN no va: se pide aparte ("y cuando te pida la clave:"). + for i := range st.Addresses { + st.Addresses[i].Display += sess.Path() + } + } if len(st.Addresses) > 0 { st.QR, _ = qr.SVG(st.Addresses[0].URL) } return st } -// sessionPath es lo que cada proveedor agrega a su base. En modo estricto (Plan 2) suma "?pin=". -func (c *Core) sessionPath(s *session.Session) string { return s.Path() } +// sessionPath es lo que cada proveedor agrega a su base. En modo estricto todas las direcciones llevan +// el PIN (también la de la red WiFi), porque el modo estricto lo pide en todas las rutas. +func (c *Core) sessionPath(s *session.Session) string { + if c.Strict() { + return s.Path() + "?pin=" + s.PIN + } + return s.Path() +} func (c *Core) nameLocked() string { if c.cfg.Name != "" { diff --git a/internal/core/state.go b/internal/core/state.go index a19be70..78a3af3 100644 --- a/internal/core/state.go +++ b/internal/core/state.go @@ -32,4 +32,5 @@ type State struct { Version string `json:"version"` Lang string `json:"lang"` // "es" | "en": idioma de la UI del emisor LangExplicit bool `json:"langExplicit"` // lo eligió la persona (no volver a detectar) + Tunnel TunnelState `json:"tunnel"` } diff --git a/internal/core/tunnel.go b/internal/core/tunnel.go new file mode 100644 index 0000000..6a3ec3b --- /dev/null +++ b/internal/core/tunnel.go @@ -0,0 +1,143 @@ +package core + +import ( + "context" + "crypto/rand" + "strings" + + "github.com/KonixDev/pasame/internal/addr" + "github.com/KonixDev/pasame/internal/tunnel" +) + +type TunnelState struct { + Status string `json:"status"` // "off" | "downloading" | "connecting" | "on" | "error" | "unavailable" + Progress int `json:"progress"` // 0–100 durante "downloading" + Host string `json:"host"` + PIN string `json:"pin"` // "4 8 1 3": con espacios, para dictarlo + Detail string `json:"detail"` // para "Ver detalle" + Dropped bool `json:"dropped"` // se cortó sin que la persona lo apagara +} + +// TunnelStarter prende el túnel. Tiene que cortar (y no dejar procesos) si se cancela ctx. +type TunnelStarter func(ctx context.Context, progress func(pct int)) (url string, done <-chan struct{}, stop func(), err error) + +// defaultTunnel baja cloudflared si hace falta y lo arranca apuntando al listener share. +func defaultTunnel(configDir string, sharePort int) TunnelStarter { + return func(ctx context.Context, progress func(int)) (string, <-chan struct{}, func(), error) { + bin, err := tunnel.Ensure(ctx, configDir, func(done, total int64) { + if total > 0 { + progress(int(done * 100 / total)) + } + }) + if err != nil { + return "", nil, nil, err + } + progress(100) + t, err := tunnel.Start(ctx, tunnel.Options{Bin: bin, Port: sharePort}) + if err != nil { + return "", nil, nil, err + } + return t.URL, t.Done(), t.Stop, nil + } +} + +func newPINKey() []byte { + k := make([]byte, 32) + if _, err := rand.Read(k); err != nil { + panic(err) + } + return k +} + +func (c *Core) PINKey() []byte { c.mu.Lock(); defer c.mu.Unlock(); return c.pinKey } + +func (c *Core) EnableTunnel() { + c.mu.Lock() + if !c.o.TunnelAvailable() || c.tun.Status == "downloading" || c.tun.Status == "connecting" || c.tun.Status == "on" { + c.mu.Unlock() + return + } + ctx, cancel := context.WithCancel(context.Background()) + c.tun, c.tunCancel = TunnelState{Status: "downloading"}, cancel + c.mu.Unlock() + c.notify() + + go func() { + url, done, stop, err := c.o.Tunnel(ctx, func(pct int) { + c.mu.Lock() + if ctx.Err() == nil { + c.tun.Progress = pct + if pct >= 100 { + c.tun.Status = "connecting" + } + } + c.mu.Unlock() + c.notify() + }) + c.mu.Lock() + switch { + case ctx.Err() != nil: // lo apagaron mientras conectaba: DisableTunnel ya dejó el estado en "off" + c.mu.Unlock() + if stop != nil { + stop() + } + return + case err != nil: + c.tun = TunnelState{Status: "error", Detail: err.Error()} + c.mu.Unlock() + c.notify() + return + } + c.tun = TunnelState{Status: "on", Host: strings.TrimPrefix(url, "https://")} + c.tunStop, c.strict, c.pinKey = stop, true, newPINKey() + c.mu.Unlock() + c.o.Book.Register(&addr.TunnelProvider{URL: url}) + c.notify() + + <-done + c.mu.Lock() + dropped := c.tun.Status == "on" && ctx.Err() == nil // si lo apagó la persona, DisableTunnel ya cambió el estado + c.mu.Unlock() + if dropped { + c.turnOff(true) // el proceso ya terminó: no hay nada que parar + } + }() +} + +func (c *Core) DisableTunnel() { + c.mu.Lock() + cancel := c.tunCancel + c.mu.Unlock() + if cancel == nil { + return // no está prendido ni conectándose + } + cancel() // primero: un túnel que termina de conectarse ahora ve ctx cancelado y se para solo + if stop := c.turnOff(false); stop != nil { + stop() + } +} + +// turnOff marca "off" y devuelve el stop vigente, tomado bajo el mismo lock que lo guardó. Cuando se +// desbloquea <-done, el goroutine ve que no fue un corte y no pisa el estado con Dropped. +func (c *Core) turnOff(dropped bool) (stop func()) { + c.o.Book.Unregister("tunnel") + c.mu.Lock() + stop = c.tunStop + c.tun = TunnelState{Status: "off", Dropped: dropped} + c.tunStop, c.tunCancel, c.strict, c.pinKey = nil, nil, false, newPINKey() + c.mu.Unlock() + c.notify() + return stop +} + +// tunnelView completa lo que depende de la sesión (el PIN, con espacios para leerlo en voz alta). +func (c *Core) tunnelView(pin string) TunnelState { + t := c.tun + if !c.o.TunnelAvailable() { + t.Status = "unavailable" + } + if t.Status == "on" && pin != "" { + t.PIN = strings.Join(strings.Split(pin, ""), " ") + } + return t +} diff --git a/internal/core/tunnel_test.go b/internal/core/tunnel_test.go new file mode 100644 index 0000000..b78280a --- /dev/null +++ b/internal/core/tunnel_test.go @@ -0,0 +1,149 @@ +package core + +import ( + "bytes" + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" +) + +type fakeTunnel struct { + err error + done chan struct{} + stopped atomic.Bool +} + +func (f *fakeTunnel) start(_ context.Context, progress func(int)) (string, <-chan struct{}, func(), error) { + progress(50) + if f.err != nil { + return "", nil, nil, f.err + } + f.done = make(chan struct{}) + return "https://amber-cat.trycloudflare.com", f.done, func() { + if f.stopped.CompareAndSwap(false, true) { + close(f.done) + } + }, nil +} + +func withTunnel(t *testing.T, ft *fakeTunnel, available bool) *env { + e := newEnv(t) + e.c.o.Tunnel = ft.start + e.c.o.TunnelAvailable = func() bool { return available } + return e +} + +func TestEnableTunnel(t *testing.T) { + ft := &fakeTunnel{} + e := withTunnel(t, ft, true) + e.c.Share([]string{e.file(t, "a", 1)}) + keyBefore := append([]byte(nil), e.c.PINKey()...) + e.c.EnableTunnel() + waitFor(t, func() bool { return e.c.State().Tunnel.Status == "on" }) + s := e.c.State() + pin := e.c.Current().PIN + if !s.Strict || !e.c.Strict() || s.Tunnel.Host != "amber-cat.trycloudflare.com" { + t.Fatalf("%+v", s.Tunnel) + } + if s.Tunnel.PIN != strings.Join(strings.Split(pin, ""), " ") { + t.Fatalf("PIN mostrado %q", s.Tunnel.PIN) + } + if s.Addresses[0].Kind != "tunnel" || !strings.HasSuffix(s.Addresses[0].URL, "?pin="+pin) { + t.Fatalf("primaria %+v", s.Addresses[0]) + } + if s.Addresses[0].Display != "amber-cat.trycloudflare.com"+e.c.Current().Path() { + t.Fatalf("lo que se tipea tiene que llevar la ruta (sin PIN): %q", s.Addresses[0].Display) + } + if !strings.HasSuffix(s.Addresses[1].URL, "?pin="+pin) { + t.Fatal("la dirección LAN también necesita el PIN en modo estricto") + } + if bytes.Equal(keyBefore, e.c.PINKey()) { + t.Fatal("la clave no rotó al prender") + } +} + +func TestDisableTunnel(t *testing.T) { + ft := &fakeTunnel{} + e := withTunnel(t, ft, true) + e.c.Share([]string{e.file(t, "a", 1)}) + e.c.EnableTunnel() + waitFor(t, func() bool { return e.c.State().Tunnel.Status == "on" }) + key := append([]byte(nil), e.c.PINKey()...) + e.c.DisableTunnel() + s := e.c.State() + if s.Tunnel.Status != "off" || s.Strict || !ft.stopped.Load() || s.Addresses[0].Kind != "lan" { + t.Fatalf("%+v", s) + } + if strings.Contains(s.Addresses[0].URL, "?pin=") { + t.Fatal("quedó el PIN en la URL LAN") + } + if bytes.Equal(key, e.c.PINKey()) { + t.Fatal("la clave no rotó al apagar") + } +} + +func TestTunnelDropsOnItsOwn(t *testing.T) { + ft := &fakeTunnel{} + e := withTunnel(t, ft, true) + e.c.EnableTunnel() + waitFor(t, func() bool { return e.c.State().Tunnel.Status == "on" }) + close(ft.done) // Cloudflare cortó + ft.stopped.Store(true) + waitFor(t, func() bool { s := e.c.State(); return s.Tunnel.Status == "off" && s.Tunnel.Dropped && !s.Strict }) +} + +func TestTunnelError(t *testing.T) { + e := withTunnel(t, &fakeTunnel{err: errors.New("línea 1\nlínea 2")}, true) + e.c.EnableTunnel() + waitFor(t, func() bool { return e.c.State().Tunnel.Status == "error" }) + if s := e.c.State(); s.Strict || !strings.Contains(s.Tunnel.Detail, "línea 2") { + t.Fatalf("%+v", s.Tunnel) + } +} + +func TestTunnelUnavailable(t *testing.T) { + e := withTunnel(t, &fakeTunnel{}, false) + if s := e.c.State(); s.Tunnel.Status != "unavailable" { + t.Fatalf("%+v", s.Tunnel) + } + e.c.EnableTunnel() + if s := e.c.State(); s.Tunnel.Status != "unavailable" || s.Strict { + t.Fatalf("%+v", s.Tunnel) + } +} + +// Terminar o cerrar mientras se conecta: no puede quedar cloudflared andando ni el estado en "on". +func TestDisableWhileConnecting(t *testing.T) { + e := newEnv(t) + started := make(chan struct{}) + e.c.o.TunnelAvailable = func() bool { return true } + e.c.o.Tunnel = func(ctx context.Context, _ func(int)) (string, <-chan struct{}, func(), error) { + close(started) + <-ctx.Done() + return "", nil, nil, ctx.Err() + } + e.c.Share([]string{e.file(t, "a", 1)}) + e.c.EnableTunnel() + <-started + e.c.DisableTunnel() + time.Sleep(50 * time.Millisecond) + if s := e.c.State(); s.Tunnel.Status != "off" || s.Strict { + t.Fatalf("%+v", s.Tunnel) + } +} + +// Terminar de compartir también corta internet: la próxima vez se arranca solo por WiFi. +func TestStopTurnsTunnelOff(t *testing.T) { + ft := &fakeTunnel{} + e := withTunnel(t, ft, true) + e.c.Share([]string{e.file(t, "a", 1)}) + e.c.EnableTunnel() + waitFor(t, func() bool { return e.c.State().Tunnel.Status == "on" }) + e.c.Stop() + if s := e.c.State(); s.Tunnel.Status != "off" || s.Strict || !ft.stopped.Load() { + t.Fatalf("%+v", s.Tunnel) + } +} diff --git a/internal/share/helpers_test.go b/internal/share/helpers_test.go index 64de219..c0e47f5 100644 --- a/internal/share/helpers_test.go +++ b/internal/share/helpers_test.go @@ -18,12 +18,13 @@ type fixture struct { dir string // archivos compartidos quar string // cuarentena strict bool + key []byte // clave HMAC del PIN; un test la cambia para simular la rotación } // newFixture crea archivos con los tamaños dados y una sesión que los comparte. func newFixture(t *testing.T, sizes map[string]int) *fixture { t.Helper() - f := &fixture{dir: t.TempDir(), quar: t.TempDir(), stats: session.NewStats(nil)} + f := &fixture{dir: t.TempDir(), quar: t.TempDir(), stats: session.NewStats(nil), key: []byte("clave-de-prueba-32-bytes-000000")} var paths []string for name, n := range sizes { p := filepath.Join(f.dir, name) @@ -41,6 +42,7 @@ func newFixture(t *testing.T, sizes map[string]int) *fixture { Sender: func() string { return "Martín" }, Strict: func() bool { return f.strict }, Lang: func() i18n.Lang { return i18n.ES }, + PINKey: func() []byte { return f.key }, }) if err != nil { t.Fatal(err) diff --git a/internal/share/pin.go b/internal/share/pin.go new file mode 100644 index 0000000..7d399e2 --- /dev/null +++ b/internal/share/pin.go @@ -0,0 +1,133 @@ +package share + +import ( + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "net/http" + "strings" + "sync" + "time" + + "github.com/KonixDev/pasame/internal/i18n" + "github.com/KonixDev/pasame/internal/session" +) + +const ( + maxFails = 5 + lockoutTime = 60 * time.Second +) + +// limiter es global a propósito: por el túnel todas las IP llegan como 127.0.0.1. +type limiter struct { + mu sync.Mutex + fails int + lockedUntil time.Time +} + +func (l *limiter) locked(now time.Time) bool { + l.mu.Lock() + defer l.mu.Unlock() + if !l.lockedUntil.IsZero() && !now.Before(l.lockedUntil) { + l.lockedUntil, l.fails = time.Time{}, 0 + } + return now.Before(l.lockedUntil) +} + +func (l *limiter) fail(now time.Time) { + l.mu.Lock() + defer l.mu.Unlock() + if l.fails++; l.fails >= maxFails { + l.lockedUntil = now.Add(lockoutTime) + } +} + +func (l *limiter) reset() { l.mu.Lock(); l.fails = 0; l.mu.Unlock() } + +func pinCookieValue(key []byte, token string) string { + m := hmac.New(sha256.New, key) + m.Write([]byte(token)) + return hex.EncodeToString(m.Sum(nil)) +} + +func (s *Server) hasPINCookie(r *http.Request, sess *session.Session) bool { + c, err := r.Cookie("pasame_pin") + if err != nil { + return false + } + want := pinCookieValue(s.d.PINKey(), sess.Token) + return subtle.ConstantTimeCompare([]byte(c.Value), []byte(want)) == 1 +} + +// checkPIN valida un PIN recibido; si es correcto deja la cookie. Si falla, devuelve el código HTTP y el texto. +func (s *Server) checkPIN(w http.ResponseWriter, sess *session.Session, pin string) (ok bool, status int, msgKey string) { + now := time.Now() + if s.lim.locked(now) { + return false, http.StatusTooManyRequests, "pin_locked" + } + if subtle.ConstantTimeCompare([]byte(pin), []byte(sess.PIN)) != 1 { + s.lim.fail(now) // el 5.º fallo todavía responde "La clave no es esa"; el bloqueo se ve en el 6.º intento + return false, http.StatusUnauthorized, "pin_wrong" + } + s.lim.reset() + http.SetCookie(w, &http.Cookie{ + Name: "pasame_pin", Value: pinCookieValue(s.d.PINKey(), sess.Token), + Path: sess.Path(), HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) + return true, 0, "" +} + +// gated agrega el control de PIN a una ruta de sesión. En modo LAN no hace nada. +func (s *Server) gated(h sessHandler) sessHandler { + return func(w http.ResponseWriter, r *http.Request, sess *session.Session, st *session.Stats) { + if !s.d.Strict() || s.hasPINCookie(r, sess) { + h(w, r, sess, st) + return + } + if pin := r.URL.Query().Get("pin"); pin != "" && r.Method == http.MethodGet { + if ok, status, key := s.checkPIN(w, sess, pin); !ok { + s.pinPage(w, r, sess, status, key) + return + } + q := r.URL.Query() + q.Del("pin") + target := r.URL.Path + if len(q) > 0 { + target += "?" + q.Encode() + } + http.Redirect(w, r, target, http.StatusSeeOther) + return + } + s.pinPage(w, r, sess, http.StatusUnauthorized, "") + } +} + +func (s *Server) pinPost(w http.ResponseWriter, r *http.Request, sess *session.Session, _ *session.Stats) { + if ok, status, key := s.checkPIN(w, sess, strings.TrimSpace(r.PostFormValue("pin"))); !ok { + s.pinPage(w, r, sess, status, key) + return + } + http.Redirect(w, r, sess.Path(), http.StatusSeeOther) +} + +func (s *Server) pinPage(w http.ResponseWriter, r *http.Request, sess *session.Session, status int, msgKey string) { + v := s.view(r, sess) + if msgKey == "pin_wrong" { + v.Msg = i18n.T(v.Lang, msgKey, v.Sender) + } else if msgKey != "" { + v.Msg = i18n.T(v.Lang, msgKey) + } + if strings.Contains(r.Header.Get("Accept"), "application/json") { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + msg := v.Msg + if msg == "" { + msg = i18n.T(v.Lang, "pin_prompt", v.Sender) + } + json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": msg}) + return + } + s.render(w, status, "pin.html", v) +} diff --git a/internal/share/pin_test.go b/internal/share/pin_test.go new file mode 100644 index 0000000..14800c6 --- /dev/null +++ b/internal/share/pin_test.go @@ -0,0 +1,130 @@ +package share + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" +) + +func timeZero() time.Time { return time.Date(2026, 9, 21, 12, 0, 0, 0, time.UTC) } + +func withCookie(r *http.Request, c *http.Cookie) *http.Request { + if c != nil { + r.AddCookie(c) + } + return r +} + +func cookieFrom(w *httptest.ResponseRecorder) *http.Cookie { + for _, c := range w.Result().Cookies() { + if c.Name == "pasame_pin" { + return c + } + } + return nil +} + +func TestLANModeNeedsNoPIN(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + if w := f.do(httptest.NewRequest("GET", f.sess.Path(), nil)); w.Code != 200 { + t.Fatalf("%d", w.Code) + } +} + +func TestStrictBlocksEveryRoute(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + f.strict = true + for _, r := range []*http.Request{ + httptest.NewRequest("GET", f.sess.Path(), nil), + httptest.NewRequest("GET", f.sess.Path()+"/f/0", nil), + httptest.NewRequest("GET", f.sess.Path()+"/zip", nil), + httptest.NewRequest("POST", f.sess.Path()+"/up", strings.NewReader("")), + } { + w := f.do(r) + if w.Code != http.StatusUnauthorized { + t.Errorf("%s %s → %d", r.Method, r.URL.Path, w.Code) + } + } + w := f.do(httptest.NewRequest("GET", f.sess.Path(), nil)) + if !strings.Contains(w.Body.String(), "Escribí la clave de 4 números que aparece en la pantalla de Martín.") { + t.Fatalf("body: %s", w.Body) + } +} + +func TestPINFromQRSetsCookieAndCleansURL(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + f.strict = true + w := f.do(httptest.NewRequest("GET", f.sess.Path()+"?pin="+f.sess.PIN, nil)) + c := cookieFrom(w) + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != f.sess.Path() || c == nil { + t.Fatalf("%d %q %v", w.Code, w.Header().Get("Location"), c) + } + if !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != f.sess.Path() || c.Secure { + t.Fatalf("cookie %+v", c) + } + for _, p := range []string{"", "/f/0", "/zip"} { + if w := f.do(withCookie(httptest.NewRequest("GET", f.sess.Path()+p, nil), c)); w.Code != 200 { + t.Errorf("%s con cookie → %d", p, w.Code) + } + } +} + +func TestPINTyped(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + f.strict = true + form := url.Values{"pin": {f.sess.PIN}}.Encode() + r := httptest.NewRequest("POST", f.sess.Path()+"/pin", strings.NewReader(form)) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := f.do(r) + if w.Code != http.StatusSeeOther || cookieFrom(w) == nil { + t.Fatalf("%d", w.Code) + } +} + +func TestWrongPINAndLockout(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + f.strict = true + wrong := "0000" + if f.sess.PIN == wrong { + wrong = "1111" + } + for i := 0; i < 5; i++ { + w := f.do(httptest.NewRequest("GET", f.sess.Path()+"?pin="+wrong, nil)) + if w.Code != http.StatusUnauthorized || !strings.Contains(w.Body.String(), "La clave no es esa") { + t.Fatalf("intento %d → %d", i, w.Code) + } + } + // Bloqueado: ni siquiera el PIN correcto entra durante 60 s. + w := f.do(httptest.NewRequest("GET", f.sess.Path()+"?pin="+f.sess.PIN, nil)) + if w.Code != http.StatusTooManyRequests || !strings.Contains(w.Body.String(), "Demasiados intentos") { + t.Fatalf("%d", w.Code) + } +} + +func TestKeyRotationInvalidatesCookies(t *testing.T) { + f := newFixture(t, map[string]int{"a.txt": 1}) + f.strict = true + c := cookieFrom(f.do(httptest.NewRequest("GET", f.sess.Path()+"?pin="+f.sess.PIN, nil))) + f.key = []byte("otra-clave-distinta-32-bytes-000") + if w := f.do(withCookie(httptest.NewRequest("GET", f.sess.Path(), nil), c)); w.Code != http.StatusUnauthorized { + t.Fatalf("cookie vieja aceptada: %d", w.Code) + } +} + +func TestLimiter(t *testing.T) { + var l limiter + now := timeZero() + for i := 0; i < 4; i++ { + l.fail(now) + } + if l.locked(now) { + t.Fatal("bloqueó con 4") + } + l.fail(now) + if !l.locked(now) || !l.locked(now.Add(59e9)) || l.locked(now.Add(61e9)) { + t.Fatal("ventana de 60 s incorrecta") + } +} diff --git a/internal/share/server.go b/internal/share/server.go index 3e449b0..b068f79 100644 --- a/internal/share/server.go +++ b/internal/share/server.go @@ -23,6 +23,7 @@ type Deps struct { Sender func() string Strict func() bool Lang func() i18n.Lang // idioma de quien comparte: es el de la página salvo que el receptor lo cambie + PINKey func() []byte // clave HMAC vigente de la cookie del PIN; core la rota al prender o apagar el túnel } type Server struct { @@ -32,6 +33,7 @@ type Server struct { createPart func(path string) (io.WriteCloser, error) // inyectable en tests (disco lleno) prepare sync.Once // crear la cuarentena recién con la primera subida received atomic.Bool + lim limiter // intentos de PIN fallidos } // view es lo que reciben todas las plantillas. @@ -67,10 +69,11 @@ func New(d Deps) (*Server, error) { s := &Server{d: d, mux: http.NewServeMux(), tpl: tpl, createPart: defaultCreatePart} s.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) s.mux.HandleFunc("GET /{$}", s.root) - s.mux.HandleFunc("GET /s/{tok}", s.withSession(s.page)) - s.mux.HandleFunc("GET /s/{tok}/f/{i}", s.withSession(s.file)) - s.mux.HandleFunc("GET /s/{tok}/zip", s.withSession(s.zip)) - s.mux.HandleFunc("POST /s/{tok}/up", s.withSession(s.upload)) + s.mux.HandleFunc("GET /s/{tok}", s.withSession(s.gated(s.page))) + s.mux.HandleFunc("GET /s/{tok}/f/{i}", s.withSession(s.gated(s.file))) + s.mux.HandleFunc("GET /s/{tok}/zip", s.withSession(s.gated(s.zip))) + s.mux.HandleFunc("POST /s/{tok}/up", s.withSession(s.gated(s.upload))) + s.mux.HandleFunc("POST /s/{tok}/pin", s.withSession(s.pinPost)) return s, nil } diff --git a/internal/tunnel/download.go b/internal/tunnel/download.go new file mode 100644 index 0000000..7e2f0ff --- /dev/null +++ b/internal/tunnel/download.go @@ -0,0 +1,159 @@ +package tunnel + +import ( + "archive/tar" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" +) + +var ( + ErrUnavailable = errors.New("tunnel: no hay cloudflared para esta computadora") + ErrChecksum = errors.New("tunnel: el archivo descargado no coincide") +) + +const releaseBase = "https://github.com/cloudflare/cloudflared/releases/download/" + +type Progress func(done, total int64) + +func Available() bool { + _, ok := assets[runtime.GOOS+"/"+runtime.GOARCH] + return ok +} + +func Ensure(ctx context.Context, configDir string, p Progress) (string, error) { + return ensure(ctx, configDir, runtime.GOOS, runtime.GOARCH, releaseBase, assets, p) +} + +func binDir(configDir string) string { return filepath.Join(configDir, "cloudflared", Version) } + +func binPath(configDir, goos string) string { + name := "cloudflared" + if goos == "windows" { + name += ".exe" + } + return filepath.Join(binDir(configDir), name) +} + +func ensure(ctx context.Context, configDir, goos, goarch, base string, table map[string]Asset, p Progress) (string, error) { + a, ok := table[goos+"/"+goarch] + if !ok { + return "", ErrUnavailable + } + dst := binPath(configDir, goos) + if fi, err := os.Stat(dst); err == nil && fi.Size() > 0 { + return dst, nil + } + if err := os.MkdirAll(binDir(configDir), 0o755); err != nil { + return "", err + } + tmp, err := download(ctx, base+Version+"/"+a.Name, binDir(configDir), a.SHA256, p) + if err != nil { + return "", err + } + defer os.Remove(tmp) + if a.Tgz { + err = extract(tmp, dst+".tmp") + } else { + err = os.Rename(tmp, dst+".tmp") + } + if err == nil { + err = os.Chmod(dst+".tmp", 0o755) + } + if err == nil { + err = os.Rename(dst+".tmp", dst) + } + if err != nil { + os.Remove(dst + ".tmp") + return "", err + } + if goos == "darwin" { + exec.Command("xattr", "-d", "com.apple.quarantine", dst).Run() // normalmente no lo tiene; se intenta igual + } + return dst, nil +} + +// download baja url a un temporal en dir, calculando el SHA-256 mientras copia. +func download(ctx context.Context, url, dir, wantSHA string, p Progress) (string, error) { + req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("tunnel: descarga respondió %s", resp.Status) + } + f, err := os.CreateTemp(dir, "dl-*") + if err != nil { + return "", err + } + h := sha256.New() + pr := &progressReader{r: resp.Body, total: resp.ContentLength, fn: p} + _, err = io.Copy(io.MultiWriter(f, h), pr) + f.Close() + if err == nil && hex.EncodeToString(h.Sum(nil)) != wantSHA { + err = ErrChecksum + } + if err != nil { + os.Remove(f.Name()) + return "", err + } + return f.Name(), nil +} + +func extract(tgzPath, dst string) error { + f, err := os.Open(tgzPath) + if err != nil { + return err + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + return err + } + tr := tar.NewReader(gz) + for { + h, err := tr.Next() + if err != nil { + return fmt.Errorf("tunnel: el .tgz no trae cloudflared: %w", err) + } + if filepath.Base(h.Name) != "cloudflared" || h.Typeflag != tar.TypeReg { + continue + } + out, err := os.Create(dst) + if err != nil { + return err + } + _, err = io.Copy(out, io.LimitReader(tr, 200<<20)) + if cerr := out.Close(); err == nil { + err = cerr + } + return err + } +} + +type progressReader struct { + r io.Reader + done int64 + total int64 + fn Progress +} + +func (p *progressReader) Read(b []byte) (int, error) { + n, err := p.r.Read(b) + p.done += int64(n) + if p.fn != nil && n > 0 { + p.fn(p.done, p.total) + } + return n, err +} diff --git a/internal/tunnel/download_test.go b/internal/tunnel/download_test.go new file mode 100644 index 0000000..ab1657e --- /dev/null +++ b/internal/tunnel/download_test.go @@ -0,0 +1,133 @@ +package tunnel + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "net/http/httptest" + "os" + "regexp" + "runtime" + "strconv" + "sync/atomic" + "testing" +) + +func TestPinnedAssets(t *testing.T) { + hex64 := regexp.MustCompile(`^[0-9a-f]{64}$`) + // Los 7 targets de Pasame tienen túnel. + for _, k := range []string{"darwin/amd64", "darwin/arm64", "windows/amd64", "windows/arm64", "linux/amd64", "linux/arm64", "linux/arm"} { + a, ok := assets[k] + if !ok || !hex64.MatchString(a.SHA256) { + t.Errorf("%s: asset o SHA-256 faltante (%+v)", k, a) + } + } +} + +func sum(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } + +func tgz(t *testing.T, name string, content []byte) []byte { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + tw.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(content))}) + tw.Write(content) + tw.Close() + gz.Close() + return buf.Bytes() +} + +type fakeRelease struct { + srv *httptest.Server + hits atomic.Int32 +} + +func serve(t *testing.T, files map[string][]byte) *fakeRelease { + f := &fakeRelease{} + f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.hits.Add(1) + for name, b := range files { + if r.URL.Path == "/"+Version+"/"+name { + w.Header().Set("Content-Length", strconv.Itoa(len(b))) + w.Write(b) + return + } + } + http.NotFound(w, r) + })) + t.Cleanup(f.srv.Close) + return f +} + +func TestEnsurePlainBinary(t *testing.T) { + bin := []byte("#!/bin/sh\necho falso\n") + rel := serve(t, map[string][]byte{"cloudflared-linux-amd64": bin}) + tbl := map[string]Asset{"linux/amd64": {Name: "cloudflared-linux-amd64", SHA256: sum(bin)}} + dir := t.TempDir() + var calls int + p, err := ensure(context.Background(), dir, "linux", "amd64", rel.srv.URL+"/", tbl, func(d, tot int64) { calls++ }) + if err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(p) + fi, _ := os.Stat(p) + executable := runtime.GOOS == "windows" || fi.Mode()&0o111 != 0 // Windows no tiene bit de ejecución + if !bytes.Equal(got, bin) || !executable || calls == 0 { + t.Fatalf("contenido/permisos/progreso mal: exec=%v calls=%d", fi.Mode(), calls) + } + // Segunda vez: ya está, no descarga. + before := rel.hits.Load() + if _, err := ensure(context.Background(), dir, "linux", "amd64", rel.srv.URL+"/", tbl, nil); err != nil || rel.hits.Load() != before { + t.Fatal("volvió a descargar") + } +} + +func TestEnsureTgz(t *testing.T) { + bin := []byte("binario mac falso") + archive := tgz(t, "cloudflared", bin) + rel := serve(t, map[string][]byte{"cloudflared-darwin-arm64.tgz": archive}) + tbl := map[string]Asset{"darwin/arm64": {Name: "cloudflared-darwin-arm64.tgz", SHA256: sum(archive), Tgz: true}} + p, err := ensure(context.Background(), t.TempDir(), "darwin", "arm64", rel.srv.URL+"/", tbl, nil) + if err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(p); !bytes.Equal(got, bin) { + t.Fatal("no extrajo el binario del .tgz") + } +} + +func TestEnsureChecksumMismatch(t *testing.T) { + rel := serve(t, map[string][]byte{"cloudflared-linux-amd64": []byte("adulterado")}) + tbl := map[string]Asset{"linux/amd64": {Name: "cloudflared-linux-amd64", SHA256: sum([]byte("original"))}} + dir := t.TempDir() + _, err := ensure(context.Background(), dir, "linux", "amd64", rel.srv.URL+"/", tbl, nil) + if !errors.Is(err, ErrChecksum) { + t.Fatalf("err = %v", err) + } + if _, err := os.Stat(binPath(dir, "linux")); err == nil { + t.Fatal("dejó el binario adulterado") + } + if left, _ := os.ReadDir(binDir(dir)); len(left) != 0 { + t.Fatalf("dejó temporales: %v", left) + } +} + +func TestEnsureUnavailable(t *testing.T) { + _, err := ensure(context.Background(), t.TempDir(), "freebsd", "amd64", "http://x/", assets, nil) + if !errors.Is(err, ErrUnavailable) { + t.Fatalf("err = %v", err) + } +} + +func TestEnsureHTTPError(t *testing.T) { + rel := serve(t, nil) + tbl := map[string]Asset{"linux/amd64": {Name: "cloudflared-linux-amd64", SHA256: sum(nil)}} + if _, err := ensure(context.Background(), t.TempDir(), "linux", "amd64", rel.srv.URL+"/", tbl, nil); err == nil { + t.Fatal("un 404 no dio error") + } +} diff --git a/internal/tunnel/null_unix.go b/internal/tunnel/null_unix.go new file mode 100644 index 0000000..793b933 --- /dev/null +++ b/internal/tunnel/null_unix.go @@ -0,0 +1,19 @@ +//go:build !windows + +package tunnel + +import ( + "os" + "os/exec" + "time" +) + +func nullConfig() string { return "/dev/null" } + +func hideConsole(*exec.Cmd) {} + +func interrupt(cmd *exec.Cmd) { cmd.Process.Signal(os.Interrupt) } + +func kill(cmd *exec.Cmd) { cmd.Process.Kill() } + +var stopGrace = 5 * time.Second diff --git a/internal/tunnel/null_windows.go b/internal/tunnel/null_windows.go new file mode 100644 index 0000000..ed05e3e --- /dev/null +++ b/internal/tunnel/null_windows.go @@ -0,0 +1,35 @@ +//go:build windows + +package tunnel + +import ( + "os/exec" + "strconv" + "syscall" + "time" +) + +func nullConfig() string { return "NUL" } + +// Pasame corre sin consola (-H=windowsgui); cloudflared y taskkill son programas de consola y, sin esto, +// cada uno abriría una ventana negra. +const createNoWindow = 0x08000000 + +func hideConsole(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow} +} + +func taskkill(args ...string) { + c := exec.Command("taskkill", args...) + hideConsole(c) + c.Run() +} + +// En Windows no hay forma ordenada de pedirle a un programa de consola sin ventana que termine: taskkill +// sin /F manda WM_CLOSE, que cloudflared nunca recibe, y cada apagado esperaba los 5 s de stopGrace. +// Cortarlo de una es seguro: Cloudflare da de baja el túnel cuando se cae la conexión. +func interrupt(cmd *exec.Cmd) { kill(cmd) } + +func kill(cmd *exec.Cmd) { taskkill("/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)) } + +var stopGrace = 5 * time.Second diff --git a/internal/tunnel/run.go b/internal/tunnel/run.go new file mode 100644 index 0000000..6b3194d --- /dev/null +++ b/internal/tunnel/run.go @@ -0,0 +1,192 @@ +package tunnel + +import ( + "bufio" + "context" + "fmt" + "net" + "net/http" + "os" + "os/exec" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +var urlRe = regexp.MustCompile(`https://[a-z0-9-]+\.trycloudflare\.com\b`) + +// ParseURL busca la URL del quick tunnel en una línea de log. "api." es el endpoint de Cloudflare, no el túnel. +func ParseURL(line string) (string, bool) { + for _, u := range urlRe.FindAllString(line, -1) { + if end := strings.Index(line, u) + len(u); end < len(line) && line[end] == '.' { + continue // "…trycloudflare.com.evil.com" + } + if u != "https://api.trycloudflare.com" { + return u, true + } + } + return "", false +} + +type Options struct { + Bin string + Port int + Timeout time.Duration + Verify func(ctx context.Context, url string) error +} + +type Tunnel struct { + URL string + cmd *exec.Cmd + done chan struct{} + home string + + mu sync.Mutex + log []string +} + +func childEnv(home string) []string { + return append(os.Environ(), "HOME="+home, "USERPROFILE="+home) +} + +func Start(ctx context.Context, o Options) (*Tunnel, error) { + if o.Timeout == 0 { + o.Timeout = 30 * time.Second + } + if o.Verify == nil { + o.Verify = verifyHealthz + } + home, err := os.MkdirTemp("", "pasame-cf-") + if err != nil { + return nil, err + } + cmd := exec.Command(o.Bin, "tunnel", "--url", "http://127.0.0.1:"+strconv.Itoa(o.Port), + "--no-autoupdate", "--config", nullConfig(), "--loglevel", "info") + cmd.Env = childEnv(home) + hideConsole(cmd) + stderr, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + os.RemoveAll(home) + return nil, err + } + t := &Tunnel{cmd: cmd, done: make(chan struct{}), home: home} + found := make(chan string, 1) + go func() { + sc := bufio.NewScanner(stderr) + for sc.Scan() { + line := sc.Text() + t.addLog(line) + if u, ok := ParseURL(line); ok { + select { + case found <- u: + default: + } + } + } + }() + go func() { + cmd.Wait() + os.RemoveAll(home) + close(t.done) + }() + + deadline, cancel := context.WithTimeout(ctx, o.Timeout) + defer cancel() + select { + case t.URL = <-found: + case <-t.done: + return nil, fmt.Errorf("cloudflared terminó sin dar una dirección:\n%s", t.LastLog()) + case <-deadline.Done(): + t.Stop() + return nil, fmt.Errorf("cloudflared no dio una dirección a tiempo:\n%s", t.LastLog()) + } + // Los quick tunnels tardan unos segundos en propagarse: reintentar hasta el plazo. + for { + err := o.Verify(deadline, t.URL) + if err == nil { + return t, nil + } + select { + case <-deadline.Done(): + t.Stop() + return nil, fmt.Errorf("la dirección %s no respondió: %v", t.URL, err) + case <-t.done: + return nil, fmt.Errorf("cloudflared se cerró:\n%s", t.LastLog()) + case <-time.After(time.Second): + } + } +} + +// verifyHealthz pide /healthz resolviendo el nombre con DNS públicos y no con el de la red: la +// dirección recién creada tarda unos segundos en existir, y el "no existe" de la primera consulta queda +// guardado en el DNS del router, lo que haría fallar también a los celulares de esa misma red. +func verifyHealthz(ctx context.Context, url string) error { + req, _ := http.NewRequestWithContext(ctx, "GET", url+"/healthz", nil) + resp, err := verifyClient.Do(req) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("respondió %s", resp.Status) + } + return nil +} + +var publicDNS = []string{"1.1.1.1:53", "8.8.8.8:53"} + +var verifyClient = &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{ + DisableKeepAlives: true, + DialContext: (&net.Dialer{Timeout: 10 * time.Second, Resolver: &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, network, system string) (net.Conn, error) { + d := net.Dialer{Timeout: 2 * time.Second} + for _, addr := range publicDNS { + if c, err := d.DialContext(ctx, network, addr); err == nil { + return c, nil + } + } + return d.DialContext(ctx, network, system) // red que bloquea DNS externos: el de la red + }, + }}).DialContext, + }, +} + +func (t *Tunnel) Done() <-chan struct{} { return t.done } + +func (t *Tunnel) Stop() { + select { + case <-t.done: + return + default: + } + interrupt(t.cmd) + select { + case <-t.done: + case <-time.After(stopGrace): + kill(t.cmd) + <-t.done + } +} + +func (t *Tunnel) addLog(line string) { + t.mu.Lock() + defer t.mu.Unlock() + t.log = append(t.log, line) + if len(t.log) > 30 { + t.log = t.log[len(t.log)-30:] + } +} + +func (t *Tunnel) LastLog() string { + t.mu.Lock() + defer t.mu.Unlock() + return strings.Join(t.log, "\n") +} diff --git a/internal/tunnel/run_test.go b/internal/tunnel/run_test.go new file mode 100644 index 0000000..8b39e52 --- /dev/null +++ b/internal/tunnel/run_test.go @@ -0,0 +1,118 @@ +package tunnel + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +var fakeBin string + +func TestMain(m *testing.M) { + dir, _ := os.MkdirTemp("", "fakecf") + fakeBin = filepath.Join(dir, "cloudflared") + if runtime.GOOS == "windows" { + fakeBin += ".exe" + } + out, err := exec.Command("go", "build", "-o", fakeBin, "../../test/fixtures/fake-cloudflared").CombinedOutput() + if err != nil { + panic(string(out)) + } + code := m.Run() + os.RemoveAll(dir) + os.Exit(code) +} + +func okVerify(context.Context, string) error { return nil } + +func TestParseURL(t *testing.T) { + cases := map[string]string{ + "2026-09-21T12:00:00Z INF | https://amber-cat-dream-yellow.trycloudflare.com |": "https://amber-cat-dream-yellow.trycloudflare.com", + "INF Requesting new quick Tunnel on trycloudflare.com...": "", + "ERR failed to request quick Tunnel: Post \"https://api.trycloudflare.com/tunnel\"": "", + "https://evil.com/?x=https://a.trycloudflare.com.evil.com": "", + "https://a-b-3.trycloudflare.com": "https://a-b-3.trycloudflare.com", + } + for line, want := range cases { + got, ok := ParseURL(line) + if got != want || ok != (want != "") { + t.Errorf("ParseURL(%q) = %q,%v; want %q", line, got, ok, want) + } + } +} + +func TestStartOKAndStop(t *testing.T) { + argsFile := filepath.Join(t.TempDir(), "args") + t.Setenv("FAKE_ARGS_FILE", argsFile) + t.Setenv("FAKE_MODE", "ok") + tun, err := Start(context.Background(), Options{Bin: fakeBin, Port: 8080, Timeout: 5 * time.Second, Verify: okVerify}) + if err != nil { + t.Fatal(err) + } + if tun.URL != "https://amber-cat-dream-yellow.trycloudflare.com" { + t.Fatalf("URL = %q", tun.URL) + } + args, _ := os.ReadFile(argsFile) + want := "tunnel --url http://127.0.0.1:8080 --no-autoupdate --config " + nullConfig() + " --loglevel info" + if string(args) != want { + t.Fatalf("args = %q\nwant %q", args, want) + } + tun.Stop() + select { + case <-tun.Done(): + case <-time.After(7 * time.Second): + t.Fatal("Stop no terminó el proceso") + } +} + +func TestStartTimeoutWithoutURL(t *testing.T) { + t.Setenv("FAKE_MODE", "nourl") + start := time.Now() + _, err := Start(context.Background(), Options{Bin: fakeBin, Port: 8080, Timeout: time.Second, Verify: okVerify}) + if err == nil || time.Since(start) > 4*time.Second { + t.Fatalf("err=%v en %v", err, time.Since(start)) + } + if !strings.Contains(err.Error(), "Requesting new quick Tunnel") { + t.Fatalf("el error no trae el log para 'Ver detalle': %v", err) + } +} + +func TestStartVerifyFails(t *testing.T) { + t.Setenv("FAKE_MODE", "ok") + bad := func(context.Context, string) error { return errors.New("todavía no responde") } + if _, err := Start(context.Background(), Options{Bin: fakeBin, Port: 8080, Timeout: time.Second, Verify: bad}); err == nil { + t.Fatal("mostró una URL que no verificó") + } +} + +func TestChildDiesOnItsOwn(t *testing.T) { + t.Setenv("FAKE_MODE", "die") + tun, err := Start(context.Background(), Options{Bin: fakeBin, Port: 8080, Timeout: 5 * time.Second, Verify: okVerify}) + if err != nil { + t.Fatal(err) + } + select { + case <-tun.Done(): + case <-time.After(5 * time.Second): + t.Fatal("no se enteró de que el proceso murió") + } +} + +func TestIsolatedHome(t *testing.T) { + // Un ~/.cloudflared/config.yaml del usuario rompe los quick tunnels: el hijo corre con HOME vacío. + env := childEnv("/tmp/pasame-cf-home") + var home, profile bool + for _, e := range env { + home = home || e == "HOME=/tmp/pasame-cf-home" + profile = profile || e == "USERPROFILE=/tmp/pasame-cf-home" + } + if !home || !profile { + t.Fatalf("env sin HOME/USERPROFILE aislados") + } +} diff --git a/internal/tunnel/versions.go b/internal/tunnel/versions.go new file mode 100644 index 0000000..764c3f8 --- /dev/null +++ b/internal/tunnel/versions.go @@ -0,0 +1,24 @@ +// Package tunnel maneja cloudflared: bajarlo verificado, correrlo y leer su URL. +package tunnel + +// Version se actualiza a mano junto con los SHA-256 (scripts/cloudflared-sums.sh). +// Nunca "latest": el comportamiento del túnel tiene que ser reproducible y testeable. +const Version = "2026.9.1" + +type Asset struct { + Name string + SHA256 string + Tgz bool +} + +// SHA-256 verificados el 2026-09-21 contra el campo "digest" de la API de GitHub. +// windows/arm64 usa el binario x86 (Windows en ARM lo emula); linux/arm usa armhf (armv7). +var assets = map[string]Asset{ + "darwin/amd64": {Name: "cloudflared-darwin-amd64.tgz", SHA256: "ff0d3b51d5ff70eceef89d6b32145fee985018a2174596a5dbe405e2766e2ac4", Tgz: true}, + "darwin/arm64": {Name: "cloudflared-darwin-arm64.tgz", SHA256: "c27ab8fd0aa489449e3d201eb02f957ef460a13b613662928b1b23394bf1bcfe", Tgz: true}, + "windows/amd64": {Name: "cloudflared-windows-amd64.exe", SHA256: "2837888cc0f5d58f15b6dc478376de90b4d3ba5241c7947455d1e0a0df429712"}, + "windows/arm64": {Name: "cloudflared-windows-386.exe", SHA256: "11b6e4b2d306950bd87e7caa4deee8e80a32d71ffee555a96237a76651eeae4c"}, + "linux/amd64": {Name: "cloudflared-linux-amd64", SHA256: "03f1f25d1cc93b9ad6c60569d44060bc4f17ed97075760ed8cfca4b12dcd68cc"}, + "linux/arm64": {Name: "cloudflared-linux-arm64", SHA256: "3d97437c71848bd8df68041e12436b484a661d95073ea1937f01a845ce88faa3"}, + "linux/arm": {Name: "cloudflared-linux-armhf", SHA256: "95420507a720fb543122a5d69372fbde8f5c919790e95ddd4374a449e0a6f4dd"}, +} diff --git a/packaging/icon/pasame.svg b/packaging/icon/pasame.svg new file mode 100644 index 0000000..e33e359 --- /dev/null +++ b/packaging/icon/pasame.svg @@ -0,0 +1 @@ + diff --git a/packaging/icon/render.sh b/packaging/icon/render.sh new file mode 100755 index 0000000..839e2bf --- /dev/null +++ b/packaging/icon/render.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Genera .icns (macOS), .ico (Windows) y .png (Linux) desde el SVG. Requiere: brew install librsvg imagemagick +set -euo pipefail +cd "$(dirname "$0")" +set_dir=pasame.iconset +rm -rf "$set_dir" && mkdir "$set_dir" +for s in 16 32 64 128 256 512 1024; do + src=pasame.svg; [ $s -lt 24 ] && src=../../docs/marca/isotipo-reducido.svg + rsvg-convert -w $s -h $s "$src" -o "png-$s.png" +done +for s in 16 32 128 256 512; do + cp "png-$s.png" "$set_dir/icon_${s}x${s}.png" + cp "png-$((s*2)).png" "$set_dir/icon_${s}x${s}@2x.png" +done +iconutil -c icns "$set_dir" -o ../macos/icon.icns +magick png-16.png png-32.png png-64.png png-128.png png-256.png ../windows/icon.ico +mkdir -p ../linux && cp png-256.png ../linux/icon.png +rm -rf "$set_dir" png-*.png diff --git a/packaging/linux/icon.png b/packaging/linux/icon.png new file mode 100644 index 0000000..8b06b9e Binary files /dev/null and b/packaging/linux/icon.png differ diff --git a/packaging/linux/pasame.desktop b/packaging/linux/pasame.desktop new file mode 100644 index 0000000..6ed76ad --- /dev/null +++ b/packaging/linux/pasame.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Type=Application +Name=Pasame +GenericName=Pasar archivos +Comment=Pasá archivos a cualquier celular o computadora que esté cerca +Exec=pasame %F +Icon=pasame +Terminal=false +Categories=Network;FileTransfer; +MimeType=application/octet-stream;inode/directory; +StartupNotify=false diff --git a/packaging/macos/Info.plist b/packaging/macos/Info.plist index fd6de90..616467d 100644 --- a/packaging/macos/Info.plist +++ b/packaging/macos/Info.plist @@ -8,12 +8,22 @@ CFBundleVersion__VERSION__ CFBundleShortVersionString__VERSION__ CFBundlePackageTypeAPPL - CFBundleExecutablepasame - CFBundleIconFilePasame + + CFBundleExecutabledroplet + CFBundleIconFileicon LSMinimumSystemVersion12.0 LSUIElement NSHighResolutionCapable NSHumanReadableCopyrightMIT · Martin Coll · martincoll.dev + + CFBundleDocumentTypes + + + CFBundleTypeNameCualquier archivo + CFBundleTypeRoleViewer + LSItemContentTypespublic.item + + diff --git a/packaging/macos/Pasame.icns b/packaging/macos/Pasame.icns deleted file mode 100644 index c282a5f..0000000 Binary files a/packaging/macos/Pasame.icns and /dev/null differ diff --git a/packaging/macos/build-app.sh b/packaging/macos/build-app.sh new file mode 100755 index 0000000..547640c --- /dev/null +++ b/packaging/macos/build-app.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Uso: build-app.sh +set -euo pipefail +bin="$1"; ver="${2#v}"; out="$3" +here="$(cd "$(dirname "$0")" && pwd)" +app="$out/Pasame.app" +rm -rf "$app" +osacompile -o "$app" "$here/droplet.applescript" +# osacompile genera su propio Info.plist y ejecutable "droplet": se reemplaza el plist por el nuestro. +sed "s/__VERSION__/$ver/g" "$here/Info.plist" > "$app/Contents/Info.plist" +cp "$here/icon.icns" "$app/Contents/Resources/icon.icns" +rm -f "$app/Contents/Resources/droplet.icns" +cp "$bin" "$app/Contents/Resources/pasame" +chmod 755 "$app/Contents/Resources/pasame" +# osacompile firmó el applet; al cambiar el plist y agregar archivos esa firma quedó rota. Re-firmar ad hoc +# (sin certificado): una firma rota en Apple Silicon es "la app está dañada". release-mac.sh la reemplaza +# por la de Developer ID cuando hay certificado. +codesign --force --deep -s - "$app" >/dev/null +echo "$app" diff --git a/packaging/macos/droplet.applescript b/packaging/macos/droplet.applescript new file mode 100644 index 0000000..b323179 --- /dev/null +++ b/packaging/macos/droplet.applescript @@ -0,0 +1,18 @@ +-- Doble clic: abre Pasame. Soltar archivos encima: abre Pasame compartiéndolos +-- (si ya está abierto, el binario se los pasa a la instancia que corre). +on run + launchPasame({}) +end run + +on open droppedItems + launchPasame(droppedItems) +end open + +on launchPasame(theItems) + set bin to quoted form of (POSIX path of (path to me) & "Contents/Resources/pasame") + set args to "" + repeat with f in theItems + set args to args & " " & quoted form of (POSIX path of f) + end repeat + do shell script bin & args & " > /dev/null 2>&1 &" +end launchPasame diff --git a/packaging/macos/entitlements.plist b/packaging/macos/entitlements.plist new file mode 100644 index 0000000..899d535 --- /dev/null +++ b/packaging/macos/entitlements.plist @@ -0,0 +1,3 @@ + + + diff --git a/packaging/macos/icon.icns b/packaging/macos/icon.icns new file mode 100644 index 0000000..d44ed76 Binary files /dev/null and b/packaging/macos/icon.icns differ diff --git a/packaging/macos/make-dmg.sh b/packaging/macos/make-dmg.sh new file mode 100755 index 0000000..1b91baf --- /dev/null +++ b/packaging/macos/make-dmg.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Uso: make-dmg.sh +set -euo pipefail +app="$1"; out="$2" +stage="$(mktemp -d)" +cp -R "$app" "$stage/" +ln -s /Applications "$stage/Aplicaciones" +rm -f "$out" +hdiutil create -volname Pasame -srcfolder "$stage" -ov -format UDZO "$out" +rm -rf "$stage" diff --git a/packaging/macos/release-mac.sh b/packaging/macos/release-mac.sh new file mode 100755 index 0000000..f90e2c7 --- /dev/null +++ b/packaging/macos/release-mac.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Arma Pasame.app y el .dmg desde el binario universal de GoReleaser; firma y notariza si hay certificado. +# Uso: release-mac.sh (ej. 1.2.3). Corre en macOS. +set -euo pipefail +ver="${1#v}" +here="$(cd "$(dirname "$0")" && pwd)" +out=dist/mac +mkdir -p "$out" +"$here/build-app.sh" dist/macos_darwin_all/pasame "$ver" "$out" >/dev/null +app="$out/Pasame.app" +dmg=dist/Pasame-macOS.dmg +notarized=false + +if [[ -n "${MACOS_CERT_P12:-}" ]]; then + kc="$RUNNER_TEMP/pasame.keychain-db"; kcpass="$(uuidgen)" + security create-keychain -p "$kcpass" "$kc" + security set-keychain-settings -lut 3600 "$kc" + security unlock-keychain -p "$kcpass" "$kc" + echo "$MACOS_CERT_P12" | base64 --decode > "$RUNNER_TEMP/cert.p12" + security import "$RUNNER_TEMP/cert.p12" -k "$kc" -P "$MACOS_CERT_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple: -s -k "$kcpass" "$kc" + security list-keychains -d user -s "$kc" login.keychain-db + + sign() { codesign --force --options runtime --timestamp --entitlements "$here/entitlements.plist" --sign "$MACOS_SIGN_IDENTITY" "$1"; } + # De adentro hacia afuera: el binario Go, el ejecutable del droplet y por último el bundle. + sign "$app/Contents/Resources/pasame" + sign "$app/Contents/MacOS/droplet" + sign "$app" + codesign --verify --deep --strict --verbose=2 "$app" + + "$here/make-dmg.sh" "$app" "$dmg" + sign "$dmg" + echo "$MACOS_NOTARY_KEY" | base64 --decode > "$RUNNER_TEMP/notary.p8" + xcrun notarytool submit "$dmg" --key "$RUNNER_TEMP/notary.p8" \ + --key-id "$MACOS_NOTARY_KEY_ID" --issuer "$MACOS_NOTARY_ISSUER_ID" --wait + xcrun stapler staple "$dmg" + spctl -a -t open --context context:primary-signature -vv "$dmg" # Expected: accepted, source=Notarized Developer ID + notarized=true +else + echo "Sin certificado de Apple: el .dmg sale sin firmar (beta en Mac)." + "$here/make-dmg.sh" "$app" "$dmg" +fi + +printf '{"version":"%s","macNotarized":%s}\n' "$ver" "$notarized" > dist/latest.json diff --git a/packaging/windows/icon.ico b/packaging/windows/icon.ico new file mode 100644 index 0000000..ca5506f Binary files /dev/null and b/packaging/windows/icon.ico differ diff --git a/packaging/windows/versioninfo.json b/packaging/windows/versioninfo.json new file mode 100644 index 0000000..736ac03 --- /dev/null +++ b/packaging/windows/versioninfo.json @@ -0,0 +1,13 @@ +{ + "FixedFileInfo": { "FileVersion": { "Major": 1 }, "ProductVersion": { "Major": 1 } }, + "StringFileInfo": { + "CompanyName": "Pasame", + "FileDescription": "Pasame — pasá archivos a cualquier celular o computadora que esté cerca", + "InternalName": "pasame", + "LegalCopyright": "MIT — Martin Coll", + "OriginalFilename": "Pasame.exe", + "ProductName": "Pasame" + }, + "VarFileInfo": { "Translation": { "LangID": "0C0A", "CharsetID": "04B0" } }, + "IconPath": "../../packaging/windows/icon.ico" +} diff --git a/scripts/cloudflared-sums.sh b/scripts/cloudflared-sums.sh new file mode 100755 index 0000000..4ab5499 --- /dev/null +++ b/scripts/cloudflared-sums.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Descarga los assets de cloudflared de la versión fijada y escribe el bloque Go con sus SHA-256. +# Uso: scripts/cloudflared-sums.sh 2026.9.1 > /tmp/sums.go.txt +set -euo pipefail +v="${1:?versión}" +base="https://github.com/cloudflare/cloudflared/releases/download/$v" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +emit() { # clave-go asset tgz + curl -fsSL -o "$tmp/$2" "$base/$2" + sum="$(shasum -a 256 "$tmp/$2" | cut -d' ' -f1)" + printf '\t"%s": {Name: "%s", SHA256: "%s", Tgz: %s},\n' "$1" "$2" "$sum" "$3" +} +emit darwin/amd64 cloudflared-darwin-amd64.tgz true +emit darwin/arm64 cloudflared-darwin-arm64.tgz true +emit windows/amd64 cloudflared-windows-amd64.exe false +emit windows/arm64 cloudflared-windows-386.exe false +emit linux/amd64 cloudflared-linux-amd64 false +emit linux/arm64 cloudflared-linux-arm64 false +emit linux/arm cloudflared-linux-armhf false diff --git a/scripts/release.sh b/scripts/release.sh deleted file mode 100755 index 8a82eb5..0000000 --- a/scripts/release.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash -# Arma los archivos de una release en dist/. Uso: scripts/release.sh 0.1.0 -# Corre en macOS (necesita lipo y ditto para el .app universal). -set -euo pipefail -ver="${1:?versión, ej. 0.1.0}" -root="$(cd "$(dirname "$0")/.." && pwd)" -out="$root/dist" -rm -rf "$out" && mkdir -p "$out/tmp" -build() { # os arch salida [ldflags extra] - local extra="${4:-}" - CGO_ENABLED=0 GOOS="$1" GOARCH="$2" GOARM=7 go build -trimpath -ldflags="-s -w -X main.version=$ver $extra" -o "$3" "$root/cmd/pasame" -} -cd "$root" -go test ./... - -# Windows: sin consola (-H=windowsgui). -build windows amd64 "$out/Pasame-Windows.exe" "-H=windowsgui" -build windows arm64 "$out/Pasame-Windows-arm64.exe" "-H=windowsgui" - -# macOS: binario universal dentro de Pasame.app. -build darwin amd64 "$out/tmp/pasame-amd64" -build darwin arm64 "$out/tmp/pasame-arm64" -app="$out/tmp/Pasame.app" -mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" -lipo -create -output "$app/Contents/MacOS/pasame" "$out/tmp/pasame-amd64" "$out/tmp/pasame-arm64" -sed "s/__VERSION__/$ver/g" packaging/macos/Info.plist > "$app/Contents/Info.plist" -cp packaging/macos/Pasame.icns "$app/Contents/Resources/Pasame.icns" -(cd "$out/tmp" && ditto -c -k --keepParent Pasame.app "$out/Pasame-macOS.zip") - -# Linux: x64, arm64 y armv7 (Raspberry Pi de 32 bits). -for a in amd64 arm64 arm; do - name="pasame-linux-$a"; [ "$a" = arm ] && name="pasame-linux-armv7" - mkdir -p "$out/tmp/$name" - build linux "$a" "$out/tmp/$name/pasame" - cp README.md LICENSE "$out/tmp/$name/" - tar -C "$out/tmp" -czf "$out/$name.tar.gz" "$name" -done - -rm -rf "$out/tmp" -(cd "$out" && shasum -a 256 * > checksums.txt) -ls -la "$out" diff --git a/site/como-abrir.html b/site/como-abrir.html new file mode 100644 index 0000000..2383d70 --- /dev/null +++ b/site/como-abrir.html @@ -0,0 +1,34 @@ + + + + + +Cómo abrir Pasame + + +
+

← PasameEnglish

+

Cómo abrir Pasame

+

La primera vez, tu computadora puede avisarte porque Pasame es nueva y gratuita. Es normal: se hace una sola vez.

+ +

En Windows

+
    +
  1. Hacé doble clic en Pasame-Windows.exe (está en Descargas).
  2. +
  3. Si aparece “Windows protegió tu PC”, tocá Más información.
  4. +
  5. Tocá Ejecutar de todas formas.
  6. +
  7. Si aparece una ventana del “Firewall de Windows Defender”, tocá Permitir acceso. Es para que el celular pueda ver tu computadora.
  8. +
+ +

En Mac

+
    +
  1. Abrí Pasame-macOS.dmg y arrastrá Pasame a Aplicaciones.
  2. +
  3. Abrí Pasame desde Aplicaciones. Si dice que no se puede abrir, tocá Aceptar (o Listo).
  4. +
  5. Abrí Ajustes del Sistema → Privacidad y seguridad, bajá hasta el final y tocá Abrir de todos modos. Ese botón aparece solo durante un rato: si no lo ves, volvé a intentar el paso 2.
  6. +
  7. Confirmá con tu contraseña o huella.
  8. +
+

Cuando Pasame esté verificada por Apple, en Mac no vas a ver ningún aviso.

+ +

En el celular

+

No hay que instalar nada. Apuntá la cámara al código que muestra la computadora y tocá el aviso que aparece.

+
+ diff --git a/site/doc.go b/site/doc.go new file mode 100644 index 0000000..041e786 --- /dev/null +++ b/site/doc.go @@ -0,0 +1 @@ +package site diff --git a/site/en/how-to-open.html b/site/en/how-to-open.html new file mode 100644 index 0000000..8d8779f --- /dev/null +++ b/site/en/how-to-open.html @@ -0,0 +1,34 @@ + + + + + +How to open Pasame + + +
+

← PasameEspañol

+

How to open Pasame

+

The first time, your computer may warn you because Pasame is new and free. That's normal, and you only do this once.

+ +

On Windows

+
    +
  1. Double-click Pasame-Windows.exe (it's in Downloads).
  2. +
  3. If you see “Windows protected your PC”, click More info.
  4. +
  5. Click Run anyway.
  6. +
  7. If a “Windows Defender Firewall” window appears, click Allow access. It lets the phone see your computer.
  8. +
+ +

On Mac

+
    +
  1. Open Pasame-macOS.dmg and drag Pasame to Applications.
  2. +
  3. Open Pasame from Applications. If it says it can't be opened, click OK (or Done).
  4. +
  5. Open System Settings → Privacy & Security, scroll to the bottom and click Open Anyway. That button only shows up for a while: if you don't see it, try step 2 again.
  6. +
  7. Confirm with your password or Touch ID.
  8. +
+

Once Pasame is verified by Apple, you won't see any warning on Mac.

+ +

On the phone

+

Nothing to install. Point the camera at the code shown on the computer and tap the notice that appears.

+
+ diff --git a/site/en/index.html b/site/en/index.html new file mode 100644 index 0000000..14926d3 --- /dev/null +++ b/site/en/index.html @@ -0,0 +1,69 @@ + + + + + +Pasame — send files to any phone or computer nearby + + + + +
+

Español

+

Pasame

+

Send files to any phone or computer nearby. No cable, no accounts.

+ +Download Pasame +

For Windows, Mac and Linux

+ + + +
+
    +
  1. Open Pasame on your computer and choose the files.
  2. +
  3. The other person points their phone camera at the code on the screen.
  4. +
  5. Done: the files download. And they can send files back to you.
  6. +
+
+

Does Windows or Mac show a warning when you open it? See how to open it.

+

All downloads · Source code · Free and open source

+ + +
+ diff --git a/site/img/isotipo-reducido.svg b/site/img/isotipo-reducido.svg new file mode 100644 index 0000000..990ef33 --- /dev/null +++ b/site/img/isotipo-reducido.svg @@ -0,0 +1 @@ + diff --git a/site/img/logo.svg b/site/img/logo.svg new file mode 100644 index 0000000..08d90a9 --- /dev/null +++ b/site/img/logo.svg @@ -0,0 +1 @@ + diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..525b191 --- /dev/null +++ b/site/index.html @@ -0,0 +1,69 @@ + + + + + +Pasame — pasá archivos a cualquier celular o computadora + + + + +
+

English

+

Pasame

+

Pasá archivos a cualquier celular o computadora que esté cerca. Sin cable, sin cuentas.

+ +Descargar Pasame +

Para Windows, Mac y Linux

+ + + +
+
    +
  1. Abrí Pasame en tu computadora y elegí los archivos.
  2. +
  3. La otra persona apunta la cámara del celular al código que aparece.
  4. +
  5. Listo: se descargan. Y te puede mandar archivos de vuelta.
  6. +
+
+

¿Windows o Mac te avisan algo al abrirla? Mirá cómo abrirla.

+

Todas las descargas · Código · Gratis y de código abierto

+ + +
+ diff --git a/site/site.css b/site/site.css new file mode 100644 index 0000000..798bf25 --- /dev/null +++ b/site/site.css @@ -0,0 +1,19 @@ +/* Marca Ronda (docs/marca). El sitio sí carga la tipografía de marca: no tiene la restricción offline de la app. */ +@import url("https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,800&family=Atkinson+Hyperlegible:wght@400;700&display=swap"); +body{margin:0;font-family:"Atkinson Hyperlegible",-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;font-size:19px;line-height:1.5;color:#1B2A1A;background:#FAFAF6} +main{max-width:760px;margin:0 auto;padding:32px 16px 64px} +h1,h2{font-family:"Bricolage Grotesque",-apple-system,"Segoe UI",sans-serif;font-weight:800;letter-spacing:-.02em} +h1{font-size:44px;margin:0 0 8px;color:#2F5D2E} +.lead{font-size:22px;color:#1B2A1A;margin:0 0 32px} +.dl{display:block;text-align:center;padding:22px;font-size:24px;font-weight:700;color:#1B2A1A;background:#A7C957;border-radius:16px;text-decoration:none} +.sub{text-align:center;color:#5E675F;font-size:16px;margin:10px 0 32px} +.box{background:#fff;border:1px solid #E1E4DA;border-radius:16px;padding:18px 20px;margin:20px 0} +.beta{background:#FBF3D5;border:1px solid #F2C94C} +ol li{margin:0 0 14px} +img{max-width:100%;border:1px solid #E1E4DA;border-radius:10px;margin:8px 0} +a{color:#2F5D2E} +.top{display:flex;justify-content:space-between;align-items:center;min-height:24px;margin:0 0 12px;font-size:16px} +.top .lang{margin-left:auto} +.dl:hover{background:#B4D366} +.dl:focus-visible,a:focus-visible{outline:3px solid #F2C94C;outline-offset:3px} +[hidden]{display:none!important} /* .dl{display:block} le ganaba al atributo hidden */ diff --git a/site/site_test.go b/site/site_test.go new file mode 100644 index 0000000..b26c7b7 --- /dev/null +++ b/site/site_test.go @@ -0,0 +1,71 @@ +package site + +import ( + "os" + "regexp" + "strings" + "testing" +) + +func read(t *testing.T, n string) string { + b, err := os.ReadFile(n) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +var assets = []string{ + "Pasame-Windows.exe", "Pasame-Windows-arm64.exe", "Pasame-macOS.dmg", + "pasame-linux-amd64.tar.gz", "pasame-linux-arm64.tar.gz", "pasame-linux-armv7.tar.gz", + "api.github.com/repos/KonixDev/pasame/releases?per_page=1", + "https://github.com/KonixDev/pasame/releases", // sin JS: link a todas las descargas +} + +func TestIndex(t *testing.T) { + for file, texts := range map[string][]string{ + "index.html": {"Descargar Pasame", "como-abrir.html", "Desde el celular no hace falta instalar nada", `href="en/"`}, + "en/index.html": {"Download Pasame", "how-to-open.html", "Nothing to install on the phone", `href="../"`}, + } { + h := read(t, file) + for _, must := range append(texts, assets...) { + if !strings.Contains(h, must) { + t.Errorf("%s sin %q", file, must) + } + } + if regexp.MustCompile(`(?i)]+src=`).MatchString(h) { + t.Errorf("%s carga scripts externos", file) + } + } +} + +func TestComoAbrir(t *testing.T) { + for file, texts := range map[string][]string{ + "como-abrir.html": {`id="windows"`, `id="mac"`, "Más información", "Ejecutar de todas formas", "Abrir de todos modos", "Privacidad y seguridad"}, + "en/how-to-open.html": {`id="windows"`, `id="mac"`, "More info", "Run anyway", "Open Anyway", "Privacy & Security"}, + } { + h := read(t, file) + for _, must := range texts { + if !strings.Contains(h, must) { + t.Errorf("%s sin %q", file, must) + } + } + dir := strings.TrimSuffix(file, "how-to-open.html") + dir = strings.TrimSuffix(dir, "como-abrir.html") + for _, img := range regexp.MustCompile(`src="([^"]+\.(?:png|svg))"`).FindAllStringSubmatch(h, -1) { + if _, err := os.Stat(dir + img[1]); err != nil { + t.Errorf("%s: falta la imagen %s", file, img[1]) + } + } + } +} + +// Sin dominio propio todavía: GitHub Pages sirve en konixdev.github.io/pasame/, así que todos los links +// son relativos. Con pasame.com.ar alcanza con agregar site/CNAME (ver test/manual/tunel.md). +func TestRelativeLinks(t *testing.T) { + for _, f := range []string{"index.html", "como-abrir.html", "en/index.html", "en/how-to-open.html"} { + if m := regexp.MustCompile(`(?:href|src)="/[^/]`).FindString(read(t, f)); m != "" { + t.Errorf("%s tiene una ruta absoluta (%s): se rompe en konixdev.github.io/pasame/", f, m) + } + } +} diff --git a/test/fixtures/fake-cloudflared/main.go b/test/fixtures/fake-cloudflared/main.go new file mode 100644 index 0000000..9efdb2b --- /dev/null +++ b/test/fixtures/fake-cloudflared/main.go @@ -0,0 +1,35 @@ +// cloudflared falso para tests: imprime logs parecidos a los reales y una URL. +// FAKE_MODE: "ok" (espera hasta que lo maten), "nourl" (nunca da URL), "die" (da URL y muere al segundo). +package main + +import ( + "fmt" + "os" + "os/signal" + "strings" + "time" +) + +func main() { + if os.Getenv("FAKE_ARGS_FILE") != "" { + os.WriteFile(os.Getenv("FAKE_ARGS_FILE"), []byte(strings.Join(os.Args[1:], " ")), 0o644) + } + log := func(s string) { fmt.Fprintf(os.Stderr, "2026-09-21T12:00:00Z INF %s\n", s) } + log("Thank you for trying Cloudflare Tunnel.") + log("Requesting new quick Tunnel on trycloudflare.com...") + fmt.Fprintln(os.Stderr, "2026-09-21T12:00:00Z WRN Cannot determine default configuration path. No file [config.yml config.yaml]") + mode := os.Getenv("FAKE_MODE") + if mode != "nourl" { + log("+--------------------------------------------------------------------------------------------+") + log("| Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): |") + log("| https://amber-cat-dream-yellow.trycloudflare.com |") + log("+--------------------------------------------------------------------------------------------+") + } + if mode == "die" { + time.Sleep(time.Second) + os.Exit(1) + } + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + <-c +} diff --git a/test/manual/matriz.md b/test/manual/matriz.md new file mode 100644 index 0000000..7af2579 --- /dev/null +++ b/test/manual/matriz.md @@ -0,0 +1,28 @@ +# Matriz manual por release + +Se completa con los archivos de la release, no con `make build`. Sin la matriz mínima completa no se publica una versión estable (spec §9.3). ✓ = funcionó · ✗ = falló (anotar qué pasó) · n/a = no aplica. + +## Compartir en la red local + +Emisor × receptor: Windows 11 + macOS actual + Ubuntu LTS como emisores; iPhone actual, iOS−2, Android actual, Android 9 y una PC como receptores. + +| Receptor ↓ / Emisor → | Windows 11 | macOS actual | Ubuntu LTS | +|---|---|---|---| +| iPhone (iOS actual) | | | | +| iPhone (iOS−2) | | | | +| Android actual | | | | +| Android 9 | | | | +| PC con Windows (navegador) | n/a | ✓ (v0.1: Mac por WiFi → PC por cable) | | + +## Instalación y primer arranque (con los assets de la release, no con `make build`) + +| Chequeo | Windows 11 x64 | Windows 11 ARM | macOS 15 | macOS 12 | Ubuntu LTS (.deb) | Raspberry Pi OS | +|---|---|---|---|---|---|---| +| El botón del sitio baja el archivo correcto | | | | | | | +| Los pasos de como-abrir.html coinciden con lo que se ve | | | | | | | +| Sin notarizar: "Abrir de todos modos" aparece y funciona | n/a | n/a | | | n/a | n/a | +| Notarizado: abre sin ningún aviso | n/a | n/a | | | n/a | n/a | +| Soltar archivos sobre el ícono los comparte | n/a | n/a | | | n/a | n/a | +| El icono se ve bien (Dock/Finder, Explorador, lanzador) | | | | | | | +| Antivirus (Defender) no lo marca | | | n/a | n/a | n/a | n/a | +| `pasame.local` (solo builds con `-tags mdns`) | | | | | | | diff --git a/test/manual/tunel.md b/test/manual/tunel.md new file mode 100644 index 0000000..76c6ee1 --- /dev/null +++ b/test/manual/tunel.md @@ -0,0 +1,29 @@ +# Checklist del túnel real (cloudflared 2026.9.1) + +Se completa con los archivos de la release, no con `make build`. ✓ = funcionó · ✗ = falló (anotar qué pasó) · vacío = falta probar. + +Primera pasada: 2026-09-22 · Emisor: Mac (Apple Silicon, macOS 26), build de la rama `plan-02` · Receptor: `curl` desde la misma Mac, pasando por Cloudflare. + +| # | Chequeo | Resultado | +|---|---|---| +| 1 | Con `~/.cloudflared/config.yaml` presente (crear uno de prueba), "Compartir por internet" igual funciona (HOME aislado + `--config`). | | +| 2 | Primera vez: se ve "Preparando…" con barra y termina en menos de 2 min con conexión normal. | ✓ (descarga + conexión en unos 30 s) | +| 3 | Segunda vez: no vuelve a descargar (pasa directo a "Conectando…"). | ✓ | +| 4 | La URL aparece en < 30 s y el QR cambia solo cuando `/healthz` responde. | ✓ 11–15 s en 4 intentos | +| 5 | Celular en datos móviles escanea el QR y entra sin tipear la clave. | parcial: el link del QR (`?pin=`) entra y deja la cookie (probado con `curl`); falta un celular real | +| 6 | Tipear la dirección en otra PC pide la clave; 5 errores → "Demasiados intentos"; al minuto se puede de nuevo. | ✓ pide la clave y bloquea; falta cronometrar el minuto | +| 7 | Descarga de un video de 2 GB por el túnel completa (anotar velocidad). | parcial: 3 MB idénticos byte a byte; falta el de 2 GB | +| 8 | Subida de 3 fotos desde el celular por el túnel llega a `Descargas/Pasame`. | | +| 9 | "Volver a compartir solo por WiFi": el link de internet deja de responder; en la LAN ya no pide clave. | ✓ (Cloudflare responde 530; LAN 200) | +| 10 | `pkill cloudflared` con el túnel activo → aviso "Se cortó la conexión por internet". | ✓ | +| 11 | Cerrar Pasame con el túnel activo no deja un `cloudflared` vivo (`ps aux | grep cloudflared`). | ✓ | +| 12 | Windows ARM: el túnel funciona con `cloudflared-windows-386.exe` por emulación. | | +| 13 | Raspberry Pi 32 bits: el túnel funciona con `cloudflared-linux-armhf`. | | +| 14 | Windows: al compartir por internet **no** se abre ninguna ventana negra de consola. | | +| 15 | Desde la LAN, tipear `192.168.x.x:8080` con el túnel activo → "Para entrar necesitás el código QR o el link de quien comparte."; la dirección que muestra el emisor (con `/s/…`) sí entra y pide la clave. | ✓ | + +## Pendientes que no puede hacer un agente + +- **Capturas para `site/como-abrir.html`** (y `site/en/how-to-open.html`), en máquinas reales con la próxima release: "Windows protegió tu PC" + "Más información", "Ejecutar de todas formas", la ventana del Firewall de Windows Defender, el aviso de macOS "no se puede abrir" y el botón "Abrir de todos modos". Recortar a la ventana, 1200 px de ancho máximo, guardar en `site/img/` y agregar los `` en cada paso. `TestComoAbrir` verifica que existan los archivos que se nombran. +- **`pasame.local`** (solo builds con `-tags mdns`): en la Mac de la primera pasada el firewall de macOS estaba apagado, así que la regla de corte (ningún diálogo de firewall extra) todavía no se evaluó. Probar con el firewall prendido y en Windows 11. +- **Dominio `pasame.com.ar`**: registrarlo en NIC.ar; en Cloudflare DNS, cuatro `A` a `185.199.108.153`, `185.199.109.153`, `185.199.110.153` y `185.199.111.153` más `CNAME www → konixdev.github.io`, con el proxy apagado (nube gris); después crear `site/CNAME` con `pasame.com.ar` y poner el dominio en GitHub → Settings → Pages. diff --git a/web/control/app.css b/web/control/app.css index d249caf..20d98a4 100644 --- a/web/control/app.css +++ b/web/control/app.css @@ -59,6 +59,14 @@ h1{font-size:28px;line-height:1.25;margin:0;font-weight:700} .side .step{margin-bottom:20px} /* La dirección nunca se corta: se achica. */ .addr{display:inline-block;max-width:100%;margin:6px 0 4px;padding:10px 18px;font:700 clamp(24px,2.9vw,40px)/1.15 var(--mono);letter-spacing:.01em;white-space:nowrap;background:var(--soft);border:2px solid var(--ink);border-radius:var(--radius-sm);user-select:all} +/* Por internet la dirección es larga (x.trycloudflare.com/s/abcde): fitAddr() la achica; si igual no entra, + se parte solo antes de "/s/" (white-space normal entre los dos .nw). */ +.addr.wrap{white-space:normal} +.addr .nw{white-space:nowrap} +.addr.pin{letter-spacing:.2em} +.tunnel{margin-top:24px} +.tunnel .secondary{margin-top:4px} +pre{white-space:pre-wrap;font:13px/1.4 var(--mono);max-height:200px;overflow:auto;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:10px;margin:10px 0 0} section{margin-top:28px} section h2{font-size:14px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);border-bottom:1px solid var(--line);padding-bottom:8px;margin:0 0 8px} ul.plain{list-style:none;padding:0;margin:0} diff --git a/web/control/app.js b/web/control/app.js index fcf87a3..7f88526 100644 --- a/web/control/app.js +++ b/web/control/app.js @@ -64,7 +64,19 @@ noNetwork: 'Esta computadora no está conectada a ninguna red. Conectate a un WiFi y esperá unos segundos.', editLabel: 'Cambiar nombre', askName: '¿Cómo te llamás? (lo ve quien recibe)', - cantEnterPlan2: '', // el Plan 2 agrega acá el paso "Tocá Compartir por internet" + cantEnterPlan2: '

Si están en un bar, hotel o aeropuerto, o en redes distintas:

', + far: '¿Están lejos o en otra red?', + tunnelOn: 'Compartir por internet', + tunnelOff: 'Volver a compartir solo por WiFi', + preparing: 'Preparando… (la primera vez baja un componente de 40 MB, tarda un minuto)', + connecting: 'Conectando…', + askKey: 'y cuando te pida la clave:', + privacy: 'Los archivos pasan por los servidores de Cloudflare (servicio gratuito, puede no estar disponible).', + strictNote: 'Ahora todos necesitan la clave, también en tu WiFi. El código QR ya la lleva.', + tunnelError: 'No se pudo conectar por internet. Volvé a intentar en un momento.', + detail: 'Ver detalle', + dropped: 'Se cortó la conexión por internet. Podés volver a activarla.', + noTunnel: 'Compartir por internet no está disponible en esta computadora.', more: 'Más opciones', menuStar: '★ Dar una estrella en GitHub', menuMadeBy: 'Creado por martincoll.dev', @@ -107,7 +119,19 @@ '
  • Both devices need to be on the same WiFi network (check the network name on the phone).
  • ' + '
  • WiFi in cafés, hotels and airports often blocks this.
  • ' + '
  • If you use a VPN, turn it off for a moment.
  • ', - cantEnterPlan2: '', + cantEnterPlan2: '

    If you are in a café, hotel or airport, or on different networks:

    ', + far: 'Far away or on another network?', + tunnelOn: 'Share over the internet', + tunnelOff: 'Go back to sharing over WiFi only', + preparing: 'Getting ready… (the first time it downloads a 40 MB component, it takes a minute)', + connecting: 'Connecting…', + askKey: 'and when it asks for the code:', + privacy: 'Files go through Cloudflare\'s servers (free service, may be unavailable).', + strictNote: 'Now everyone needs the code, also on your WiFi. The QR code already includes it.', + tunnelError: 'Could not connect over the internet. Try again in a moment.', + detail: 'Show details', + dropped: 'The internet connection dropped. You can turn it on again.', + noTunnel: 'Sharing over the internet is not available on this computer.', checkWindows: 'Check Windows permission', vpn: 'It looks like a VPN is on. If the phone cannot connect, turn it off for a moment or use Change network.', netChanged: 'The network changed. The code was updated.', @@ -235,12 +259,12 @@ h += '
    ' + s.qr + '
    ' + '

    ' + esc(T.qrHint) + '

    '; h += '

    ' + T.phone + '

    ' + T.pc + '

    '; - h += '
    ' + esc(main.display) + '
    '; + h += '
    ' + addrHTML(main.display) + '
    '; h += '

    '; addrs.slice(1).forEach(function (a) { if (a.kind === 'mdns') h += '

    ' + esc(T.alsoTry + a.display) + '

    '; }); - h += '
    '; + h += tunnelBlock(s) + ''; h += '

    ' + esc(T.activity) + '

    ' + activity(s); var st = s.stats || {}; @@ -328,11 +352,62 @@ // Re-render cada 5 s: no pisar un control que la persona está usando (se le cerraría el menú de red). var f = document.activeElement; if (f && (f.id === 'iface' || f.id === 'paste')) return; + var detail = document.getElementById('detail'); // el detalle abierto se cerraría a los 5 s + if (detail && !detail.hidden) return; renderWho(state); var app = document.getElementById('app'); var qrFull = document.querySelector('.qr.full') !== null; app.innerHTML = state.phase === 'sharing' ? renderSharing(state) : renderIdle(state); if (qrFull && document.getElementById('qr')) document.getElementById('qr').classList.add('full'); + fitAddr(); + } + + // Solo se puede partir antes de "/s/…": el nombre (con guiones) nunca se corta al medio. + function addrHTML(d) { + var i = d.indexOf('/s/'); + if (i < 0) return esc(d); + return '' + esc(d.slice(0, i)) + '' + esc(d.slice(i)) + ''; + } + + // La dirección nunca se corta: se achica hasta entrar (y recién ahí se parte en "/s/"). + function fitAddr() { + var el = document.getElementById('addr'); + if (!el) return; + el.style.fontSize = ''; + el.classList.remove('wrap'); + var px = parseFloat(getComputedStyle(el).fontSize); + while (el.scrollWidth > el.clientWidth && px > 16) { px -= 1; el.style.fontSize = px + 'px'; } + if (el.scrollWidth <= el.clientWidth) return; + el.classList.add('wrap'); + while (el.scrollWidth > el.clientWidth && px > 11) { px -= 1; el.style.fontSize = px + 'px'; } + } + + function tunnelBlock(s) { + var tn = s.tunnel || {}, h = '
    '; + switch (tn.status) { + case 'on': + h += '

    ' + esc(T.askKey) + '

    ' + esc(tn.pin) + '
    '; + h += '

    ' + esc(T.privacy) + '

    ' + esc(T.strictNote) + '

    '; + h += ''; + break; + case 'downloading': + h += '

    ' + esc(T.preparing) + '

    '; + break; + case 'connecting': + h += '

    ' + esc(T.connecting) + '

    '; + break; + case 'unavailable': + h += '

    ' + esc(T.noTunnel) + '

    '; + break; + case 'error': + h += '
    ' + esc(T.tunnelError) + '
    '; + /* falls through */ + default: + if (tn.dropped) h += '
    ' + esc(T.dropped) + '
    '; + h += '

    ' + esc(T.far) + '

    '; + } + return h + '
    '; } // Créditos: solo en la pantalla inicial y al cerrar. Nunca mientras se comparte (no distraer del QR). @@ -381,6 +456,13 @@ case 'copy': return copyLink(); case 'open-folder': return api('/api/open-folder'); case 'firewall': return api('/api/firewall'); + case 'tunnel-on': return api('/api/tunnel', { on: true }); + case 'tunnel-off': return api('/api/tunnel', { on: false }); + case 'detail': + var d = document.getElementById('detail'); + d.hidden = !d.hidden; + el.setAttribute('aria-expanded', d.hidden ? 'false' : 'true'); + return; case 'paste': var v = document.getElementById('paste').value.trim(); if (v) api('/api/add', { paths: [v] }); @@ -388,6 +470,8 @@ } }); + window.addEventListener('resize', fitAddr); + document.addEventListener('change', function (e) { if (e.target.id === 'iface') api('/api/iface', { ip: e.target.value }); }); diff --git a/web/share/pin.html b/web/share/pin.html new file mode 100644 index 0000000..fce34bc --- /dev/null +++ b/web/share/pin.html @@ -0,0 +1,10 @@ +{{define "pin.html"}} +{{template "head" .}} +
    +

    {{template "brand"}}

    +

    {{if .Msg}}{{.Msg}}{{else}}{{t .Lang "pin_prompt" .Sender}}{{end}}

    +
    + + +
    +
    {{end}}