oc-phone-link 2.3.3 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,11 +2,123 @@
2
2
 
3
3
  This file records the beacon's server-side changes. APK and app release notes
4
4
  live in `../../CHANGELOG.md`; the `version` fields in `whitelist.json` are APK
5
- release digests, not the server version.
5
+ release digests, not the server version. The app-side facts in the entries below
6
+ are attributed to the app repository's own changelog
7
+ (`nathwn12/my-opencode-app`, CHANGELOG.md), with the APK digest in
8
+ `whitelist.json` as the in-repo anchor.
6
9
 
7
10
  ## [Unreleased]
8
11
 
9
- ## [2.3.3] - 2026-11-29
12
+ ## [2.4.1] - 2026-11-29
13
+
14
+ Ships with the 2.4.0 app. The app and beacon must be upgraded together.
15
+
16
+ - Upgrading a state written by 2.2.0/2.3.x: a v5 PIN record with no recorded
17
+ digit length is cleared on load, along with its claim. Every device key and
18
+ the owner token survive byte-identically and `v` stays 5, so paired
19
+ devices stay paired. A four-digit PIN must be set again on the PC before a
20
+ new device can pair. The migration logs one line saying so and runs once;
21
+ new PIN records store `len` and the panel echoes it.
22
+ - The shared code is exactly four digits: `pinPattern` is `^\d{4}$` in
23
+ `beacon.mjs` and is used by `setPin`, `/setup` and `/auth`. The panel
24
+ input and its client-side check were updated to match. PBKDF2-SHA256 at
25
+ 600,000 iterations and the 16-byte salt are unchanged.
26
+ - Wrong-code rate limiting: `AUTH_FAIL_MAX = 5` wrong PINs per source in
27
+ `AUTH_WINDOW_MS = 5 * 60 * 1000`, then `AUTH_LOCKOUT_MS = 15 * 60 * 1000`
28
+ of lockout, logged once per episode. Only a wrong PIN counts; the old
29
+ double-counting guess path is gone.
30
+ - `GET /info?pair=1` returns LAN `urls` and `agentUrls`, `httpsPort`,
31
+ `proxyPort`, the existing `hosts`/`fingerprint` and `pinRequired`,
32
+ with no code, key, owner or password. Plain `/info` keeps its device-key
33
+ gate, so no auth was weakened beyond the code format.
34
+ - Device keys idle-expire after 180 days (`KEY_TTL`) with a matching 180-day
35
+ cookie `Max-Age`; rotation-on-use, per-device revoke and revoke-all stay as
36
+ they were. `STATE_VERSION` stays 5, so existing keys and the owner token
37
+ survive the upgrade.
38
+ - Discovery self-reports: a `discovery addresses` line at startup and one
39
+ `discovery request <ip> answer on <addresses>` line per PROBE; a source
40
+ outside those addresses is logged once per source as `discovery unexpected
41
+ source`. Diagnostics only; UDP replies are unchanged.
42
+ - Wire changes for a 2.2.0 app: an eight-digit code now gets `pin-invalid`,
43
+ and pre-pair discovery must use `/info?pair=1`. The added `/info` fields
44
+ are ignored by older callers. Key format, headers, ports, `/health`,
45
+ `/auth`, `/setup`, `/request`, `/revoke` and the proxy contract are
46
+ unchanged.
47
+ - `beacon.test.mjs` adds twelve cases: four-digit accept/reject (3, 5, 8),
48
+ rate limit and lockout expiry, the 180-day idle boundary, rotation and
49
+ revoke-fails-closed, both `/info` shapes and the once-per-source discovery
50
+ log.
51
+
52
+ Proof: `node --test beacon.test.mjs` EXIT 0 — 42 tests, 42 pass, 0 fail
53
+ (baseline 37/37 before this migration; all 37 still pass). `bun run check` was already EXIT 1 at baseline on the
54
+ unrelated `packages/janua` MCP conformance timeout; the `oc-phone-link`
55
+ workspace portion passes 37/37.
56
+
57
+ ## 2.3.3
58
+
59
+ - Tagged as `oc-phone-link@2.3.3` (commit `680ff40`) and published as npm
60
+ latest. The only package change restored `repository`, `homepage` and
61
+ `bugs` in `package.json` so provenance publishing passes; no beacon, APK
62
+ or wire change shipped.
63
+ - Scope: **server-only** packaging metadata. A 2.2.0 APK user does not need to
64
+ update; the PIN and key flow are unchanged.
65
+
66
+ ## 2.3.2
67
+
68
+ - Tagged as `oc-phone-link@2.3.2` (commit `9f2938c`, the lint sweep).
69
+ `json()` spreads `extra` directly and two test helpers drop redundant
70
+ `|| {}` defaults; no runtime behaviour, endpoint or APK changed. The npm
71
+ registry has no 2.3.2 tarball, so this entry records the tagged server tree.
72
+ - Scope: **server-only**, cosmetic. No APK update.
73
+
74
+ ## 2.3.1
75
+
76
+ - Tagged as `oc-phone-link@2.3.1` (commit `87bd029`). `beacon.test.mjs`
77
+ gained socket-close guards so the suite stops hanging after socket failures;
78
+ no beacon source changed. The npm registry has no 2.3.1 tarball.
79
+ - Scope: **server-only** test hygiene. No APK update.
80
+
81
+ ## 2.3.0
82
+
83
+ - Tagged as `oc-phone-link@2.3.0` (merge `5d4c748`) and published to npm.
84
+ The server tree entered this monorepo in `bc0a0c4` with the front-door
85
+ README added in `44cb104`: eight-digit PIN, 90-day idle keys rotating at
86
+ 45 days, UDP 41337 discovery, the HTTPS panel on 41338 and proxy on 41340,
87
+ and the loopback-only 41341 tunnel listener preview. The import itself made
88
+ no wire change.
89
+ - The release ships Android APK 2.2.0 (digest in `whitelist.json`, release
90
+ notes in `nathwn12/my-opencode-app`). The APK sets the first PIN from the
91
+ phone in one `/setup` request, with a private-network guard and claim
92
+ attribution; the tunnel client and APK tunnel mode were deferred from 2.2.0
93
+ to 2.3.0.
94
+ - Scope: **app-affecting**. A 2.2.0 APK already has the app side; an older APK
95
+ must update to pair with this beacon's eight-digit flow.
96
+
97
+ ## 2.2.0
98
+
99
+ - App release 2.2.0 (APK digest in `whitelist.json`). The first PIN may be set
100
+ from the phone once via `POST /setup {pin, device, name}`, which also mints
101
+ that phone's key: private peers only, 409 `pin-exists` afterwards, 404 on
102
+ the tunnel listener. The claim is attributed in the panel and `agent.log`.
103
+ Eight-digit/600k PIN rules, owner token, 90-day idle / 45-day rotation keys
104
+ and the panel are unchanged.
105
+ - Server 2.2.0 was staged in `bc0a0c4` and is the source of the 2.3.0 npm
106
+ release; its beacon carries the 41341 listener preview. App notes:
107
+ `nathwn12/my-opencode-app` CHANGELOG 2.2.0.
108
+ - Scope: **app-affecting** for first-PIN-from-phone. A 2.2.0 APK user already
109
+ has it; only the 2.4.0 pairing rewrite needs a new APK.
110
+
111
+ ## 2.1.0
112
+
113
+ - App release 2.1.0 (APK digest in `whitelist.json`, notes in
114
+ `nathwn12/my-opencode-app` CHANGELOG 2.1.0). No loopback auth bypass; no
115
+ password or token sent to the phone (upstream Basic auth is injected
116
+ in-process); auth-bound Android vault, re-lock and FLAG_SECURE; eight-digit
117
+ 600k PIN with capped async derivation; per-device keys with 90-day idle /
118
+ 45-day rotation; streaming and WebSocket proxy; cert SAN for active LAN IPs;
119
+ upstream port from the plugin context; minSdk 29.
120
+ - Scope: **app-affecting** (APK and beacon together). A 2.2.0 APK already
121
+ carries all of it; an older APK must update.
10
122
 
11
123
  ## 2.0.11
12
124
 
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nathan <137482711+nathwn12@users.noreply.github.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -10,34 +10,40 @@
10
10
 
11
11
  ## Install
12
12
 
13
- Use the published [PC plugin 2.3.0](https://www.npmjs.com/package/oc-phone-link/v/2.3.0). Add `oc-phone-link` to `~/.config/opencode/opencode.jsonc` and restart OpenCode:
13
+ Install the published [oc-phone-link plugin](https://www.npmjs.com/package/oc-phone-link) from npm, add `oc-phone-link` to `~/.config/opencode/opencode.jsonc` and restart OpenCode:
14
14
 
15
15
  ```json
16
16
  { "plugins": ["oc-phone-link"] }
17
17
  ```
18
18
 
19
- The PC plugin and Android app use separate version numbers. The plugin starts the beacon during setup and stops it when the session disposes. There is no tray app, no separate service and no QR code: the beacon is a keyed reverse proxy in front of the OpenCode server your PC already runs.
19
+ There is no version pin here on purpose: npm's published version changes on every release of this package, so the install line stays true after the next publish. The PC plugin and Android app use separate version numbers. The plugin starts the beacon during setup and stops it when the session disposes. There is no tray app, no separate service and no QR code: the beacon is a keyed reverse proxy in front of the OpenCode server your PC already runs.
20
20
 
21
- ## First use
21
+ ## Upgrading from 2.2.0 or 2.3.x
22
22
 
23
- 1. Connect the PC and Android phone to the same Wi-Fi.
24
- 2. Install the [Android 2.2.0 APK](https://github.com/nathwn12/oc-collections/releases/tag/oc-phone-link%402.3.0) (`oc-phone-link-v2.2.0.apk`) on the phone.
25
- 3. Open `https://localhost:41338` on the PC. That page is the beacon's own control panel. Set an 8-digit PIN there.
26
- 4. Open the phone app. It finds the beacon over UDP port 41337 on the local network and shows a short TLS fingerprint.
27
- 5. Compare that short fingerprint with the Verify line on the PC page. Enter the PIN only after the fingerprints match.
28
- 6. The phone receives a device key: valid for 90 days, rotated after 45, and one of at most 16 keys the beacon will hold.
23
+ An eight-digit PIN stored by an older beacon cannot work with the four-digit rule. On first start the beacon clears that PIN and its claim and logs one line in `agent.log`: set a four-digit PIN again on the PC. Device keys, paired phones and the owner token are kept, so paired devices stay paired and keep using their existing keys while the new PIN is set. The migration runs once; a state that already stores the PIN length is left untouched, including across restarts.
29
24
 
30
- The PC page also lists paired devices with issue date, last use and last IP, and can revoke one device, revoke all of them, or reset the PIN.
25
+ ## First use — one entry, then automatic
31
26
 
32
- Once paired, the phone sends its requests to the beacon on port 41340, which checks the device key and forwards to OpenCode on its own port (28894 by default). The beacon also keeps a loopback port on 41339 for the PC itself and an exposed port on 41341 for setup actions, which it refuses when the request did not come from the local machine.
27
+ 1. Connect the PC and Android phone to the same Wi-Fi (or use the tunnel transport with an app that supports it).
28
+ 2. Install the Android app that ships with this beacon. From 2.4.0 the app and beacon share the four-digit flow; a 2.2.0 app still expects eight digits and cannot pair with this build.
29
+ 3. Open `https://localhost:41338` on the PC. That page is the beacon's own control panel. Set a **four-digit** PIN there (or let the phone set the first one in step 5).
30
+ 4. Open the phone app. You can let discovery find the PC, or enter the beacon address once and call `GET /info?pair=1` on the HTTPS port (41338) instead. That endpoint returns the beacon's LAN `urls` and `agentUrls`, `httpsPort`, `proxyPort`, `hosts`, `fingerprint` and `pinRequired` (`true` when no code has been set yet). It returns no code, key, owner token or password; a plain `GET /info` still needs a device key or the owner cookie. This is the pairing-without-discovery path.
31
+ 5. The app shows a short TLS fingerprint. Compare it with the Verify line on the PC page. Enter the four digits **once** after the fingerprints match: the first code can be set from the phone through `/setup`, and a later device uses `/auth`. A successful call mints a device key. Five wrong codes from one source IP in five minutes arm a 15-minute lockout for that source; only a wrong code counts, and a correct one clears the record.
32
+ 6. Every later launch reuses that device key and asks for nothing. The key idle-expires after 180 days and rotates after 45 days of age on use; each use refreshes the idle clock, so weekly use never re-pairs. At most 16 keys are held.
33
33
 
34
- The phone drives the same server session the PC does. Nothing is uploaded anywhere: discovery, pairing and proxying all stay on your network.
34
+ Discovery order on the phone is: last proven address first, then a UDP broadcast probe on 41337, then a parallel HTTPS scan of the local /24 on 41338. Entering the address and using `/info?pair=1` skips all three probes.
35
+
36
+ The PC page also lists paired devices with issue date, last use and last IP, and can revoke one device, revoke all of them, or reset the PIN. A revoked key fails closed on its next request.
37
+
38
+ Once paired, the phone sends its requests to the beacon on port 41340, which checks the device key and forwards to OpenCode on its own port (28894 by default). The beacon keeps a loopback-only, plain-HTTP owner panel on 41339. When `OC_PHONE_LINK_TRANSPORT=tunnel` is set it also starts a plain-HTTP listener bound to `127.0.0.1:41341` for a tunnel client you provision. That listener serves the proxy plus `/health`, `/auth` and `/info` (plain `/info` still needs a device key or owner cookie, while `/info?pair=1` stays available for pairing) and answers 404 for `/setup`, `/reset` and `/revoke`. It does not exist in the default local-network mode.
39
+
40
+ By default nothing is uploaded anywhere: discovery, pairing and proxying all stay on your local network. Under `OC_PHONE_LINK_TRANSPORT=tunnel`, traffic through the 41341 listener is carried out of your network by the tunnel you provision, so that default claim no longer holds for those requests. The package itself ships no cloud relay, account or telemetry.
35
41
 
36
42
  ## Troubleshooting
37
43
 
38
- - **The phone cannot find the beacon.** Confirm both devices are on the same Wi-Fi and that UDP port 41337 can reach the PC. `OC_PHONE_LINK_NO_UDP=1` disables discovery for pair-by-address setups.
44
+ - **The phone cannot find the beacon.** The app tries the last proven address, then UDP broadcast on 41337, then a parallel HTTPS /24 sweep on 41338; a blocked UDP port still leaves the sweep. `OC_PHONE_LINK_NO_UDP=1` disables the beacon's UDP listener for pair-by-address setups; enter the beacon address and use `GET /info?pair=1` instead. The log writes a `discovery addresses` line at startup and a `discovery request ... answer on` line for each probe, naming the addresses the beacon answers on; a probe from any other source is logged once per source as `discovery unexpected source`. Check `agent.log` before assuming the Wi-Fi is at fault.
39
45
  - **The TLS fingerprints differ.** Do not enter the PIN. Confirm the phone is showing this PC's beacon and compare its short fingerprint with the Verify line on the PC page before trying again.
40
- - **The Android app cannot pair.** The old Android 1.4.1 APK is not compatible with this PC plugin. Install the 2.2.0 APK linked above.
46
+ - **The Android app cannot pair.** The old Android 1.4.1 and 2.2.0 apps expect eight digits and cannot pair with this beacon. Install the 2.4.0 app that ships with it.
41
47
  - **The control panel does not open.** Confirm the plugin loaded after the OpenCode restart. If a port is taken, set `OC_PHONE_LINK_PORT_BASE` to shift the fixed port block.
42
48
 
43
49
  ## Development
@@ -51,24 +57,25 @@ The test file covers PIN derivation, key revoke and rotation, discovery and the
51
57
 
52
58
  ## Security
53
59
 
54
- - **PIN**: exactly 8 digits, stretched with PBKDF2-SHA256 at 600,000 iterations and stored salted and hashed. Only the owner's own networks may claim the first PIN.
60
+ - **PIN**: exactly four digits (`^\d{4}$` in the panel, `/setup` and `/auth`), stretched with the same PBKDF2-SHA256 at 600,000 iterations and stored salted and hashed. Only the owner's own networks may claim the first PIN.
55
61
  - **TLS**: a self-signed certificate is generated on first start and pinned by the phone on first use. The PC page prints the full fingerprint and a short form for comparison.
56
- - **Keys**: per-device, tagged with the device that minted them. A targeted revoke fails closed and drops only that device's keys; revoke all drops every key.
57
- - **Lockout**: five failed PIN attempts from one address in ten minutes locks that address out for ten minutes.
62
+ - **Keys**: per-device, tagged with the device that minted them. A key idle-expires after 180 days (`KEY_TTL`) and rotates after 45 days of age on use; presenting it refreshes the idle clock, so wall-clock age alone never expires a key in use. The cookie carries a matching 180-day `Max-Age`. A targeted revoke fails closed and drops only that device's keys; revoke all drops every key.
63
+ - **Lockout**: at most five wrong codes from one source IP in five minutes; the fifth arms a 15-minute lockout that is logged once. Constants in `beacon.mjs`: `AUTH_FAIL_MAX = 5`, `AUTH_WINDOW_MS = 5 * 60 * 1000`, `AUTH_LOCKOUT_MS = 15 * 60 * 1000`.
64
+ - **Pre-pair info**: `GET /info?pair=1` exposes only endpoint discovery (LAN URLs, HTTPS port, `pinRequired`); no code, key, owner token or password. Plain `/info` stays gated.
58
65
  - **Limits**: ten requests per minute per address, request bodies capped at 4 KB, upstream calls time out after five seconds.
59
66
  - **Local only**: no telemetry, no cloud relay, no analytics.
60
67
 
61
68
  ## Configuration
62
69
 
63
- The beacon reads these environment variables and nothing else:
70
+ The beacon reads the environment variables below, plus `LOCALAPPDATA` (or the process working directory when that is unset) as the parent of its default data directory; it reads nothing else from the environment.
64
71
 
65
72
  - `OC_PHONE_LINK_PORT_BASE` - shift the fixed port block (41337 to 41341) by an offset, for when a port is taken.
66
73
  - `OC_PHONE_LINK_BIND_HOST` - address to bind, default all interfaces.
67
- - `OC_PHONE_LINK_DATA_DIR` - where state, TLS material and the agent log live.
74
+ - `OC_PHONE_LINK_DATA_DIR` - where state, TLS material and the agent log live; overrides the `LOCALAPPDATA`-based default.
68
75
  - `OC_PHONE_LINK_NO_UDP` - set to 1 to disable UDP discovery and pair by address instead.
69
76
  - `OC_PHONE_LINK_PASSWORD` (or `OPENCODE_SERVER_PASSWORD`) - upstream password the proxy presents when OpenCode asks for one.
70
77
  - `OC_PHONE_LINK_UPSTREAM` - upstream port override when OpenCode is not on 28894.
71
- - `OC_PHONE_LINK_TRANSPORT` - set to `tunnel` to use the tunnel transport instead of the local network.
78
+ - `OC_PHONE_LINK_TRANSPORT` - set to `tunnel` to start the plain-HTTP, loopback-bound listener on 41341 for a tunnel you provision.
72
79
 
73
80
  ## Requirements
74
81
 
package/beacon.mjs CHANGED
@@ -35,9 +35,9 @@ const REQ_WINDOW_MS = 60 * 1000;
35
35
  const REQ_MAX = 10;
36
36
  const BODY_CAP = 4096;
37
37
  const LOG_MAX = 5 * 1024 * 1024;
38
- const KEY_TTL = 90 * 24 * 60 * 60 * 1000;
38
+ const KEY_TTL = 180 * 24 * 60 * 60 * 1000; // idle expiry; weekly use never re-pairs
39
39
  const KEY_ROTATE_AFTER = 45 * 24 * 60 * 60 * 1000;
40
- const KEY_COOKIE_MAX_AGE = 90 * 24 * 60 * 60;
40
+ const KEY_COOKIE_MAX_AGE = 180 * 24 * 60 * 60; // matches KEY_TTL
41
41
  const KEY_PERSIST_MS = 60 * 1000;
42
42
  const KEY_CAP = 16;
43
43
  const UPSTREAM_TIMEOUT_MS = 5000;
@@ -48,11 +48,26 @@ const PASSWORD_NEG_TTL = 30000;
48
48
  const reqHits = new Map(); // ip -> [ts...] sliding window
49
49
  let now = () => Date.now();
50
50
 
51
- const AUTH_FAIL_MAX = 5;
52
- const AUTH_WINDOW_MS = 10 * 60 * 1000;
51
+ const AUTH_FAIL_MAX = 5; // wrong PINs per source before a lockout
52
+ const AUTH_WINDOW_MS = 5 * 60 * 1000; // window those wrong PINs are counted in
53
+ const AUTH_LOCKOUT_MS = 15 * 60 * 1000; // lockout after the fifth wrong PIN
53
54
  const AUTH_MAP_MAX = 1024;
54
55
  const authFails = new Map(); // ip -> { count, first, until }
55
56
 
57
+ function capAuthFails(t) {
58
+ if (authFails.size <= AUTH_MAP_MAX) return;
59
+ for (const [key, val] of authFails) if (t - val.first >= AUTH_WINDOW_MS && !val.until) authFails.delete(key);
60
+ if (authFails.size > AUTH_MAP_MAX) {
61
+ let oldestKey = null;
62
+ let oldest = Infinity;
63
+ for (const [key, val] of authFails) {
64
+ const age = val.until || val.first;
65
+ if (age < oldest) { oldest = age; oldestKey = key; }
66
+ }
67
+ if (oldestKey !== null) authFails.delete(oldestKey);
68
+ }
69
+ }
70
+
56
71
  function authBlocked(ip) {
57
72
  const e = authFails.get(ip);
58
73
  if (!e) return 0;
@@ -66,51 +81,30 @@ function authBlocked(ip) {
66
81
  return 0;
67
82
  }
68
83
 
84
+ // Only a wrong PIN counts as a guess. beginGuess is the in-flight lockout gate;
85
+ // noteAuthFail arms the lockout and logs it exactly once per episode.
69
86
  function noteAuthFail(ip) {
70
87
  const t = now();
71
88
  let e = authFails.get(ip);
72
89
  if (!e || (t - e.first >= AUTH_WINDOW_MS && !e.until)) e = { count: 0, first: t, until: 0 };
73
90
  e.count += 1;
74
- if (e.count >= AUTH_FAIL_MAX) e.until = t + AUTH_WINDOW_MS;
75
- authFails.set(ip, e);
76
- if (authFails.size > AUTH_MAP_MAX) {
77
- for (const [key, val] of authFails) if (t - val.first >= AUTH_WINDOW_MS) authFails.delete(key);
78
- if (authFails.size > AUTH_MAP_MAX) {
79
- let oldestKey = null;
80
- let oldest = Infinity;
81
- for (const [key, val] of authFails) {
82
- const age = val.until || val.first;
83
- if (age < oldest) { oldest = age; oldestKey = key; }
84
- }
85
- if (oldestKey !== null) authFails.delete(oldestKey);
86
- }
91
+ let armed = false;
92
+ if (e.count >= AUTH_FAIL_MAX && !e.until) {
93
+ e.until = t + AUTH_LOCKOUT_MS;
94
+ armed = true;
87
95
  }
88
- return e.count === AUTH_FAIL_MAX;
96
+ authFails.set(ip, e);
97
+ capAuthFails(t);
98
+ if (armed) log("auth lockout", ip, AUTH_FAIL_MAX, "wrong PINs in", (AUTH_WINDOW_MS / 60000) + "m; locked", (AUTH_LOCKOUT_MS / 60000) + "m");
99
+ return armed;
89
100
  }
90
101
 
91
102
  function beginGuess(ip) {
92
103
  const t = now();
93
- let e = authFails.get(ip);
104
+ const e = authFails.get(ip);
94
105
  if (e && e.until) {
95
106
  if (t < e.until) return false;
96
107
  authFails.delete(ip);
97
- e = null;
98
- }
99
- if (!e || t - e.first >= AUTH_WINDOW_MS) e = { count: 0, first: t, until: 0 };
100
- e.count += 1;
101
- if (e.count >= AUTH_FAIL_MAX) e.until = t + AUTH_WINDOW_MS;
102
- authFails.set(ip, e);
103
- if (authFails.size > AUTH_MAP_MAX) {
104
- for (const [key, val] of authFails) if (t - val.first >= AUTH_WINDOW_MS) authFails.delete(key);
105
- if (authFails.size > AUTH_MAP_MAX) {
106
- let oldestKey = null;
107
- let oldest = Infinity;
108
- for (const [key, val] of authFails) {
109
- const age = val.until || val.first;
110
- if (age < oldest) { oldest = age; oldestKey = key; }
111
- }
112
- if (oldestKey !== null) authFails.delete(oldestKey);
113
- }
114
108
  }
115
109
  return true;
116
110
  }
@@ -185,7 +179,7 @@ function log(...a) {
185
179
 
186
180
  const isHex = (s, bytes) => typeof s === "string" && s.length === bytes * 2 && /^[0-9a-f]+$/i.test(s);
187
181
  const validPin = (p) => !!p && typeof p === "object" && isHex(p.salt, 16) && isHex(p.hash, 32);
188
- const pinPattern = /^\d{8}$/;
182
+ const pinPattern = /^\d{4}$/;
189
183
  const validPinClaim = (c) => !!c && typeof c === "object" &&
190
184
  typeof c.ip === "string" && c.ip.length > 0 &&
191
185
  (typeof c.name === "string" || c.name === null) && Number.isFinite(c.at);
@@ -247,20 +241,33 @@ function loadState() {
247
241
  return { ok: false, error: "state is not an object" };
248
242
  }
249
243
 
250
- // Any pre-v5 state is discarded wholesale: its PIN may be shorter than 8
244
+ // Any pre-v5 state is discarded wholesale: its PIN may be longer than 4
251
245
  // digits and its key set may mix untagged keys with plaintext legacy tokens.
252
246
  // A fresh, fail-closed state is the only safe migration target.
253
247
  if (s.v !== STATE_VERSION) {
254
248
  const fresh = blankState();
255
- log("state migrated: PIN and keys cleared; set an 8-digit PIN on the PC, then pair the phone again");
249
+ log("state migrated: PIN and keys cleared; set a 4-digit PIN on the PC, then pair the phone again");
256
250
  if (!saveState(fresh)) return { ok: false, error: "state migration not persisted" };
257
251
  return { ok: true, state: fresh };
258
252
  }
259
253
 
260
254
  let changed = false;
255
+ let pinMigrationLog = null;
261
256
  const pinPresent = s.pin !== undefined && s.pin !== null;
262
257
  if (s.pin === undefined) { s.pin = null; changed = true; }
263
258
  else if (s.pin !== null && !validPin(s.pin)) return { ok: false, error: "state pin is invalid" };
259
+ // A v5 PIN record with no `len` was written before the four-digit rule: its
260
+ // hash belongs to a longer code that /auth now rejects, so the PIN is dead.
261
+ // Clear only the PIN and its claim. Keys and the owner stay: paired phones
262
+ // keep working. The marker lets this PIN-less state load again instead of
263
+ // tripping the "keys have no PIN" guard below.
264
+ if (pinPresent && !Number.isInteger(s.pin.len)) {
265
+ s.pin = null;
266
+ s.pinClaim = null;
267
+ s.pinResetNeeded = true;
268
+ pinMigrationLog = "state migrated: legacy PIN cleared; set a 4-digit PIN on the PC, paired devices stay paired";
269
+ changed = true;
270
+ }
264
271
  if (s.keys === undefined) {
265
272
  if (pinPresent) return { ok: false, error: "state keys are missing" };
266
273
  s.keys = [];
@@ -271,7 +278,7 @@ function loadState() {
271
278
  s.keys = s.keys.map(normalizeKey);
272
279
  changed = true;
273
280
  }
274
- if (!pinPresent && s.keys.length > 0) return { ok: false, error: "state keys have no PIN" };
281
+ if (!pinPresent && s.keys.length > 0 && !s.pinResetNeeded) return { ok: false, error: "state keys have no PIN" };
275
282
 
276
283
  const pruned = s.keys.filter((k) => now() - (k.lastUsed || 0) > KEY_TTL).length;
277
284
  if (pruned) {
@@ -299,7 +306,9 @@ function loadState() {
299
306
  if (changed) {
300
307
  if (pruned) log("state keys pruned", pruned);
301
308
  s.v = STATE_VERSION;
302
- if (!saveState(s)) log("state normalize not persisted");
309
+ if (saveState(s)) {
310
+ if (pinMigrationLog) log(pinMigrationLog);
311
+ } else log("state normalize not persisted");
303
312
  }
304
313
  return { ok: true, state: s };
305
314
  }
@@ -369,7 +378,7 @@ async function setPin(pin, opts) {
369
378
  // Another request may have claimed the PIN while this derivation was queued.
370
379
  if (state.pin !== before) return "pin-exists";
371
380
  const t = Date.now();
372
- state.pin = { salt: salt, hash: hash, at: t };
381
+ state.pin = { salt: salt, hash: hash, at: t, len: p.length };
373
382
  if (opts && opts.claim) state.pinClaim = { ip: opts.claim.ip, name: opts.claim.name, at: t };
374
383
  if (opts && opts.keyRecord) {
375
384
  if (!Array.isArray(state.keys)) state.keys = [];
@@ -383,6 +392,7 @@ async function setPin(pin, opts) {
383
392
  log("pin set not persisted: rolled back");
384
393
  return "save-failed";
385
394
  }
395
+ delete state.pinResetNeeded;
386
396
  log("pin set");
387
397
  if (opts && opts.claim) log("pin set by phone", opts.claim.ip, opts.claim.name || "unknown");
388
398
  return null;
@@ -484,8 +494,11 @@ function ownerToken(req) {
484
494
 
485
495
  // Gate: loopback is a source address, never an identity. No isLocal() here.
486
496
  function gate(req, opts) {
487
- if (!state.pin || !state.pin.hash) return "setup";
497
+ // A device key stays usable while the PIN is absent after the legacy-PIN
498
+ // migration: paired phones keep working until a new four-digit PIN is set.
499
+ // With no key and no PIN the state is still a first-time setup.
488
500
  if (keyOk(req)) return null;
501
+ if (!state.pin || !state.pin.hash) return "setup";
489
502
  if (opts && opts.owner && ownerToken(req)) return null;
490
503
  return "pin";
491
504
  }
@@ -518,6 +531,28 @@ function lanAddresses() {
518
531
  return out;
519
532
  }
520
533
 
534
+ const unexpectedDiscoverySources = new Set();
535
+ const DISCOVERY_SOURCE_CAP = 256;
536
+
537
+ function discoveryAddresses() { return lanAddresses().map((a) => a.address); }
538
+
539
+ // One line per PROBE names the interfaces we answer on; an address outside
540
+ // that set is logged once per source. This is a "check your Wi-Fi" diagnostic,
541
+ // never a change to who UDP replies to.
542
+ function discoveryRequest(rinfo) {
543
+ const addrs = discoveryAddresses();
544
+ const list = addrs.length ? addrs.join(",") : "none";
545
+ const src = String((rinfo && rinfo.address) || "?");
546
+ log("discovery request", src, "answer on", list);
547
+ if (src === "?" || src === "127.0.0.1" || src === "::1" || src === "::ffff:127.0.0.1" || addrs.includes(src)) return;
548
+ if (unexpectedDiscoverySources.has(src)) return;
549
+ unexpectedDiscoverySources.add(src);
550
+ if (unexpectedDiscoverySources.size > DISCOVERY_SOURCE_CAP) {
551
+ unexpectedDiscoverySources.delete(unexpectedDiscoverySources.values().next().value);
552
+ }
553
+ log("discovery unexpected source", src, "answer on", list);
554
+ }
555
+
521
556
  function fingerprintOf(pemCert) {
522
557
  const body = pemCert.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
523
558
  return createHash("sha256").update(Buffer.from(body, "base64")).digest("hex");
@@ -644,6 +679,22 @@ function publicInfo() {
644
679
  }
645
680
 
646
681
  function privateInfo() { return { ...publicInfo(), devices: state.keys.length }; }
682
+
683
+ // A phone with no device key can call /info?pair=1 to learn every endpoint it
684
+ // needs without UDP discovery. It never returns the PIN, its hash or any key.
685
+ function pairingInfo() {
686
+ const addrs = lanAddresses();
687
+ const proxyUrls = addrs.map((a) => "https://" + a.address + ":" + PROXY_PORT);
688
+ const agentUrls = addrs.map((a) => "https://" + a.address + ":" + HTTPS_PORT);
689
+ return {
690
+ ...publicInfo(),
691
+ urls: proxyUrls.length ? proxyUrls : ["https://127.0.0.1:" + PROXY_PORT],
692
+ agentUrls: agentUrls.length ? agentUrls : ["https://127.0.0.1:" + HTTPS_PORT],
693
+ httpsPort: HTTPS_PORT,
694
+ proxyPort: PROXY_PORT,
695
+ pinRequired: !(state.pin && state.pin.hash),
696
+ };
697
+ }
647
698
  function payload() { return Buffer.from(JSON.stringify(publicInfo())); }
648
699
 
649
700
  const LOOPBACK_ORIGIN = /^https?:\/\/(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/i;
@@ -722,9 +773,9 @@ function loopPage() {
722
773
  const ready = password() !== "";
723
774
  const hasPin = !!(state.pin && state.pin.hash);
724
775
  const pinBlock = hasPin
725
- ? '<p class="dim">PIN set. Enter it once on the phone.</p>'
776
+ ? '<p class="dim">PIN set (' + (Number.isInteger(state.pin.len) ? state.pin.len : 4) + ' digits). Enter it once on the phone.</p>'
726
777
  : '<p class="dim">No PIN yet. Set one here, then enter the same PIN on the phone.</p>\n' +
727
- '<p><input id="pin" type="password" inputmode="numeric" autocomplete="new-password" placeholder="8 digits" size="18">' +
778
+ '<p><input id="pin" type="password" inputmode="numeric" autocomplete="new-password" placeholder="4 digits" size="18">' +
728
779
  '<button data-set-pin="1">Set PIN</button></p>';
729
780
  const claim = state.pinClaim;
730
781
  const claimLine = claim
@@ -789,7 +840,7 @@ function loopPage() {
789
840
  ' b.onclick = () => {\n' +
790
841
  ' const el = document.getElementById("pin");\n' +
791
842
  ' const pin = el ? el.value.trim() : "";\n' +
792
- ' if (!/^\\d{8}$/.test(pin)) { alert("Exactly 8 digits"); return; }\n' +
843
+ ' if (!/^\\d{4}$/.test(pin)) { alert("Exactly 4 digits"); return; }\n' +
793
844
  ' if (confirm("Set this PIN? The phone enters it once.")) post("/setup", { pin });\n' +
794
845
  ' });\n' +
795
846
  ' document.querySelectorAll("[data-revoke-all]").forEach((b) =>\n' +
@@ -1049,6 +1100,7 @@ async function handleAgent(req, res, opts) {
1049
1100
  state.keys = beforeKeys;
1050
1101
  return json(req, res, 500, { ok: false, error: "save-failed" });
1051
1102
  }
1103
+ delete state.pinResetNeeded;
1052
1104
  authFails.clear();
1053
1105
  setupRefused.clear();
1054
1106
  log("pin and device keys reset; owner kept");
@@ -1094,8 +1146,8 @@ async function handleAgent(req, res, opts) {
1094
1146
  return json(req, res, 400, { ok: false, error: "pin-invalid" });
1095
1147
  }
1096
1148
  if (!await pinMatches(pin)) {
1097
- const armed = (authFails.get(ip) || {}).count >= AUTH_FAIL_MAX;
1098
- log("pin rejected", ip, armed ? "locked " + (AUTH_WINDOW_MS / 60000) + "m" : "");
1149
+ noteAuthFail(ip);
1150
+ log("pin rejected", ip);
1099
1151
  release();
1100
1152
  return json(req, res, 401, { ok: false, error: "bad-pin" });
1101
1153
  }
@@ -1121,6 +1173,9 @@ async function handleAgent(req, res, opts) {
1121
1173
  release();
1122
1174
  return json(req, res, 200, { ok: true, key: key });
1123
1175
  }
1176
+ if (url.pathname === "/info" && url.searchParams.has("pair")) {
1177
+ return json(req, res, 200, pairingInfo());
1178
+ }
1124
1179
  if (url.pathname === "/" || url.pathname === "/info") {
1125
1180
  const why = gate(req, { owner: true });
1126
1181
  if (why) return json(req, res, 401, { ok: false, error: why });
@@ -1211,6 +1266,7 @@ async function handleLoopback(req, res) {
1211
1266
  res.end('{"ok":false,"error":"save-failed"}');
1212
1267
  return;
1213
1268
  }
1269
+ delete state.pinResetNeeded;
1214
1270
  authFails.clear();
1215
1271
  setupRefused.clear();
1216
1272
  log("pin and device keys reset; owner kept");
@@ -1278,6 +1334,8 @@ export function startBeacon(opts) {
1278
1334
  }
1279
1335
  }
1280
1336
  log("state loaded", "keys:", state.keys.length);
1337
+ const startAddrs = discoveryAddresses();
1338
+ log("discovery addresses", startAddrs.length ? startAddrs.join(",") : "none");
1281
1339
 
1282
1340
  let udp = null;
1283
1341
  let udpOk = !NO_UDP;
@@ -1289,6 +1347,7 @@ export function startBeacon(opts) {
1289
1347
  udp.on("error", (e) => { udpOk = false; log("udp unavailable", e.code || e.message); });
1290
1348
  udp.on("message", (msg, rinfo) => {
1291
1349
  if (msg.toString().trim() !== PROBE) return;
1350
+ discoveryRequest(rinfo);
1292
1351
  try { udp.send(payload(), rinfo.port, rinfo.address); } catch (e) { log("reply fail", e.message); }
1293
1352
  });
1294
1353
  udp.bind(UDP_PORT, "0.0.0.0", () => { udp.setBroadcast(true); log("udp listening", UDP_PORT); });
@@ -1406,7 +1465,7 @@ export const __test = {
1406
1465
  setState: (s) => { state = s; },
1407
1466
  freshState: blankState,
1408
1467
  clearLimits: () => {
1409
- reqHits.clear(); authFails.clear(); setupRefused.clear();
1468
+ reqHits.clear(); authFails.clear(); setupRefused.clear(); unexpectedDiscoverySources.clear();
1410
1469
  authInFlight = 0; authInFlightByIp.clear();
1411
1470
  },
1412
1471
  setClock: (fn) => { now = typeof fn === "function" ? fn : () => Date.now(); },
@@ -1428,6 +1487,9 @@ export const __test = {
1428
1487
  ownerToken,
1429
1488
  ownerPost,
1430
1489
  isPrivatePeer,
1490
+ discoveryAddresses,
1491
+ discoveryRequest,
1492
+ pinPattern: pinPattern.source,
1431
1493
  shortFingerprint,
1432
1494
  selfPort,
1433
1495
  port,
@@ -1440,5 +1502,6 @@ export const __test = {
1440
1502
  constants: {
1441
1503
  STATE_VERSION, PIN_ITER, DERIVE_MAX, PASSWORD_NEG_TTL, KEY_TTL, KEY_ROTATE_AFTER,
1442
1504
  KEY_COOKIE_MAX_AGE, KEY_CAP, UPSTREAM_TIMEOUT_MS, UPSTREAM_PROBE_MS, EXPOSED_PORT,
1505
+ AUTH_FAIL_MAX, AUTH_WINDOW_MS, AUTH_LOCKOUT_MS, DISCOVERY_SOURCE_CAP, HTTPS_PORT, PROXY_PORT, UDP_PORT,
1443
1506
  },
1444
1507
  };
package/package.json CHANGED
@@ -1,7 +1,22 @@
1
1
  {
2
2
  "name": "oc-phone-link",
3
- "version": "2.3.3",
3
+ "version": "2.4.1",
4
4
  "description": "Drive OpenCode from an Android phone on the same Wi-Fi: in-server beacon, pinned TLS, one PIN, no tray, no QR.",
5
+ "license": "MIT",
6
+ "author": "nathwn12",
7
+ "keywords": [
8
+ "opencode",
9
+ "opencode-plugin",
10
+ "plugin",
11
+ "android",
12
+ "phone",
13
+ "remote",
14
+ "beacon",
15
+ "tls"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
5
20
  "type": "module",
6
21
  "main": "./index.js",
7
22
  "exports": {
@@ -18,6 +33,8 @@
18
33
  "index.js",
19
34
  "beacon.mjs",
20
35
  "whitelist.json",
36
+ "README.md",
37
+ "LICENSE",
21
38
  "CHANGELOG.md"
22
39
  ],
23
40
  "scripts": {
package/whitelist.json CHANGED
@@ -4,6 +4,11 @@
4
4
  "md5": "c5db10035ac6a3d99302b64fa01232bf"
5
5
  },
6
6
  "releases": [
7
+ {
8
+ "version": "2.4.0",
9
+ "sha256": "2550d7bea6b10966f52d9fa2b271a98cf2735c7f018e88b9a2c1c5120d3009ed",
10
+ "md5": "a0701e39e1546c8b772f4f826492511c"
11
+ },
7
12
  {
8
13
  "version": "2.2.0",
9
14
  "sha256": "65210da2853ada04b3f03dcd7833a316fa5ac8b7545aa8502e6ca416652daa6e",
@@ -23,11 +28,6 @@
23
28
  "version": "2.0.10",
24
29
  "sha256": "9c1b36b1c4b93dc2d3e8a424ab33ae4a71d2fe9baa33bee44d32fc06ec18da6d",
25
30
  "md5": "ee141e91dcd3617cb7dea53422ccc569"
26
- },
27
- {
28
- "version": "2.0.9",
29
- "sha256": "1fbc2a55540496633222417c992ffa89a0b5599a51f9a643be43f14b8f25f73b",
30
- "md5": "4590715bafb8c67caf8922463c3c224a"
31
31
  }
32
32
  ]
33
33
  }