diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 5d2f37afb4..6676ad94d8 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -13,14 +13,53 @@ refused. Five files a phone fetches before anyone has signed in are public, matched exactly: `/manifest.webmanifest` and the four icons under `/icons/`. -| Section | What you can do | What runs | -| ------------- | ----------------------------------------------------------------------------------- | --------------------------------------- | -| Overview | Queue counts, ready pull requests, agents, failed units | the calls below, together | -| Queue | List queued, claimed, blocked and parked tasks; unblock or cancel one with a reason | the queue store (read), `fleet queue` | -| Priorities | Ranked issues, most urgent first; change a rank; comment; file new work | `fleet gh` | -| Agents | Send an idea, message or command to one agent, a group or everyone; recent messages | `fleet bridge` | -| Services | State of the stack's units; start, stop, restart; read logs | `systemctl --user`, `journalctl --user` | -| Pull requests | Open pull requests; check one; merge it | `fleet gh` | +## The app + +`/console/` is one page with five tabs. The first four are what the +owner does every day; everything else is under More. + +| Tab | What it is for | +| -------- | ---------------------------------------------------------------------------------------------------------------- | +| Now | Tasks in progress with their next step, sessions that are moving, and what the owner did lately | +| Next | The queue in the order it will be claimed; move a task first, sooner or later; why tasks are blocked | +| Needs me | Open questions (one tap to answer, undo for a few seconds), things only hands can do, reviews | +| Ask | Say what you want in your own words (typed or dictated). It becomes an issue and a top-of-queue task in one pass | +| More | Queue by state, pull requests, ranked issues, agents, services, notifications, phones, and the dashboard's pages | + +The page never waits on a live fan-out. The server keeps three documents +ready (`core`, `questions`, `ops`), each built from sections that are +read in the background and served from memory with the time they were +read (`GET /console/api/doc/`, ETag, gzip). Every change goes +through one endpoint, `POST /console/api/act {kind, args}`; the kinds are +the table in `src/actions.ts`. + +| Source | Read by | Written by | +| ----------------------------------------- | --------------------------------------- | ----------------------------------------------------- | +| The queue store | `src/work.ts` (one round trip) | `fleet queue`; one priority update for "move" | +| GitHub issues and pull requests | `fleet gh` | `fleet gh` | +| The dashboard's questions and needs lists | the dashboard's own JSON and store file | the dashboard's submit endpoint, with the set's token | +| Agents and messages | `fleet agent`, `fleet bridge` | `fleet bridge` | +| The stack's units | `systemctl --user`, `journalctl --user` | `systemctl --user` | + +### Notifications + +Web Push, sent by this service (`src/push.ts`: RFC 8291 and RFC 8292 +with WebCrypto, keys in `~/.local/state/pm-console/push.json`). A device +subscribes under More, Notifications, and chooses what reaches it: a +reply to something asked, something new that needs the owner, new +questions, a failed unit. The Android app shows them as its own. + +### Phones + +The Android app's home-screen widget reads a short summary (three counts +and the top line of each list) with a token of its own, since it cannot +use the browser's sign-in. Linking passes no secret through an address: +the phone shows the signed-in owner a hash, the owner approves it under +More, Phones, and the phone then presents the value behind the hash to +`POST /console/device/link` and is given its token once. The store +(`devices.json`) keeps hashes of tokens. `GET /console/device/summary` +answers a linked phone and nobody else; both paths are limited, and they +are the only ones under `/console` that answer without the sign-in. Every operation is an argument vector, never a shell line, and text you type travels on stdin or as one argument. @@ -65,9 +104,10 @@ itself comes from this machine and it crossed no proxy (loopback Host, no forwarding headers). The connection's address is the test, since headers are the caller's to write; for the same reason the console only listens on loopback and refuses to start on any other address. Everything else -needs a token. Outside the install files above, two paths answer without -one: `/console/health` and `/.well-known/assetlinks.json` (the Android -app's link to this origin). +needs a token. Outside the install files above, these answer without +one: `/console/health`, `/.well-known/assetlinks.json` (the Android +app's link to this origin), and the two phone paths under +`/console/device/`, which check a linked phone's own token instead. ## Run @@ -96,6 +136,7 @@ the route if the console does not come up with its sign-in settings. | `PM_CONSOLE_UNITS`, `PM_CONSOLE_PROTECTED_UNITS` | the stack's units | Units the console manages; units it will not stop | | `PM_CONSOLE_ANDROID_PACKAGE`, `PM_CONSOLE_ANDROID_SHA256` | `today.developing.pmconsole`, none | The Android app's identity in the asset-links file | | `PM_CONSOLE_ANDROID_APK` | `~/.local/state/pm-console/android/pm-console.apk` | The signed build the console hands to the owner | +| `PM_CONSOLE_DEVICES_FILE` | `~/.local/state/pm-console/devices.json` | Linked phones (hashes of their tokens) | | `PM_CONSOLE_REPO`, `PM_CONSOLE_QUEUE` | `developing-today/code`, `repo-health-code-pilot` | What it operates on | A malformed port, a listen address or dashboard address that is not @@ -104,10 +145,13 @@ variable. ## Android -`pm-stack/console/android/` is a Trusted Web Activity: the same site in -Chrome without browser chrome, so sign-in is Chrome's own and nothing is -reimplemented. The `pm-console-android` workflow builds it and the host -signs it. Once the signed file is on the host, the console's header -shows "Android app": a download for the signed-in owner at +`pm-stack/console/android/` shows the same site in Chrome without browser +chrome (a Trusted Web Activity), so sign-in is Chrome's own and the app +never falls behind the site. Around that it uses what only an installed +app has: a home-screen widget, dictation from a shortcut or a +quick-settings tile, text shared or selected in any app, long-press +shortcuts, and notifications shown as its own. The `pm-console-android` +workflow builds it and the host signs it. Once the signed file is on the +host, More, Phones offers it to the signed-in owner at `/console/pm-console.apk`, so the phone gets the app from the site it opens. See its README. diff --git a/pm-stack/console/android/README.md b/pm-stack/console/android/README.md index 590614b880..76a9b4e705 100644 --- a/pm-stack/console/android/README.md +++ b/pm-stack/console/android/README.md @@ -1,10 +1,39 @@ # PM console for Android -A Trusted Web Activity: the app opens `https://pm.security.cab/console/` -in Chrome without browser chrome. It is the site, so it does everything -the site does, signs in the way the site does (Chrome's own session), and -never needs a release when the console changes. There is no code in the -module; the launcher activity comes from `androidbrowserhelper`. +The screens are the site itself: the app opens +`https://pm.security.cab/console/` in Chrome without browser chrome (a +Trusted Web Activity). So it does everything the site does, signs in the +way the site does (Chrome's own session), and needs no release when the +console changes. + +Around the site, the app uses what only an installed app has: + +| What | How it is used | Code | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | +| Home-screen widget | In progress, queued next, needs me, and the task being worked on. Each number opens its screen | `StatusWidget`, `Fleet` | +| Dictation | Long-press the icon and choose Dictate, or tap the "Ask the fleet" quick-settings tile: the words land in the Ask box | `DictateActivity`, `AskTileService` | +| Share and selection | Share text from any app, or select text and choose "Ask the fleet": it lands in the Ask box | `ShareActivity` | +| Long-press shortcuts | Dictate, Ask, Needs me, Now. They move the open app to that screen and do not reload it | `OpenActivity`, `res/xml/shortcuts` | +| Notifications | The site's notifications arrive as the app's own, with its mark in the status bar; the app asks for the permission itself | the helper library's activities | +| Links | `https://pm.security.cab/...` links open in the app | the launcher activity's intent filter | + +Words handed to the site (shared, selected or dictated) travel after the +`#` of the address, which a browser never sends to a server; they sit in +the Ask box until the owner presses Send. + +### The widget's own sign-in + +A widget cannot use the browser's session, so the phone is linked once: + +1. Add the "PM status" widget to the home screen and tap it. +2. The app opens at More, Phones, showing "Link this phone?". Approve. +3. The widget fills in. It reads again every half hour, when the app is + opened, and when its refresh mark is tapped. + +The phone makes a random value and shows the site only its hash; after +the approval it presents the value itself and is given a token that can +read the widget's summary and nothing else. The owner can remove a phone +under More, Phones, and the widget then goes back to "Tap to link". ## How the app and the site trust each other @@ -45,10 +74,15 @@ reinstall; nothing else depends on it. ## Install -On the phone, open `https://pm.security.cab/console/`, sign in, and tap -"Android app" in the header. That downloads the signed build from the -host (`/console/pm-console.apk`, owner only); open it to install. Later -builds install over it. +On the phone, open `https://pm.security.cab/console/`, sign in, and go to +More, Phones, "Download the app". That downloads the signed build from +the host (`/console/pm-console.apk`, owner only); open it to install. +Later builds install over it. + +The native parts are checked by compiling the build and reading its +merged manifest; the site's side of each (the Ask box taking handed-over +words, linking a phone, the summary) is tested in `test/`. They have not +been exercised by an automated run on a device. The console serves whatever signed build is at `~/.local/state/pm-console/android/pm-console.apk` on the host, so diff --git a/pm-stack/console/android/app/build.gradle b/pm-stack/console/android/app/build.gradle index 8b85ff4136..a483d9744f 100644 --- a/pm-stack/console/android/app/build.gradle +++ b/pm-stack/console/android/app/build.gradle @@ -1,7 +1,11 @@ -// The PM console for Android: a Trusted Web Activity. The app is the -// site itself, shown by Chrome without browser chrome, so sign-in is -// Chrome's and nothing is reimplemented here. There is no code in this -// module: the launcher activity comes from androidbrowserhelper. +// The PM console for Android. The screens are the site itself, shown by +// Chrome without browser chrome (a Trusted Web Activity), so sign-in is +// Chrome's and the app never falls behind the site. Around that, the +// app uses what only an installed app has: it receives shared and +// selected text, starts dictation with the phone's own recogniser from +// a shortcut or a quick-settings tile, offers its main screens on a long +// press of the icon, shows the site's notifications as its own, and puts +// a widget on the home screen that reads a short summary by itself. plugins { id 'com.android.application' } @@ -15,13 +19,15 @@ android { defaultConfig { applicationId 'today.developing.pmconsole' - minSdk 23 + minSdk 24 targetSdk 34 - versionCode 1 - versionName '0.1.0' + versionCode 3 + versionName '0.3.0' manifestPlaceholders = [hostName: 'pm.security.cab', defaultUrl: "${site}/console/"] // The app's half of the link to the site. The site's half is // /.well-known/assetlinks.json, served by pm-console. + resValue 'string', 'console_url', "${site}/console/" + resValue 'string', 'site_url', "${site}" resValue 'string', 'asset_statements', "[{\\\"relation\\\": [\\\"delegate_permission/common.handle_all_urls\\\"], \\\"target\\\": {\\\"namespace\\\": \\\"web\\\", \\\"site\\\": \\\"${site}\\\"}}]" } @@ -31,7 +37,7 @@ android { main { manifest.srcFile 'src/twa/AndroidManifest.xml' res.srcDirs = ['src/twa/res'] - java.srcDirs = [] + java.srcDirs = ['src/twa/java'] } } diff --git a/pm-stack/console/android/app/src/twa/AndroidManifest.xml b/pm-stack/console/android/app/src/twa/AndroidManifest.xml index 3ad0c32515..3c7d39d792 100644 --- a/pm-stack/console/android/app/src/twa/AndroidManifest.xml +++ b/pm-stack/console/android/app/src/twa/AndroidManifest.xml @@ -2,8 +2,18 @@ + + + + + + + + + + + @@ -45,11 +60,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/AskTileService.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/AskTileService.java new file mode 100644 index 0000000000..832af03f91 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/AskTileService.java @@ -0,0 +1,44 @@ +package today.developing.pmconsole; + +import android.app.PendingIntent; +import android.content.Intent; +import android.os.Build; +import android.service.quicksettings.Tile; +import android.service.quicksettings.TileService; +import org.json.JSONObject; + +/** + * A quick-settings tile: pull down the shade, tap, and say what you want. + * On a linked phone it also shows how many things need the owner. + */ +public class AskTileService extends TileService { + @Override + public void onStartListening() { + Tile tile = getQsTile(); + if (tile != null) { + tile.setState(Tile.STATE_INACTIVE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // Under the label, how many things are waiting, when this phone knows. + JSONObject summary = Fleet.cached(this); + JSONObject needs = summary == null ? null : summary.optJSONObject("needs"); + int n = needs == null ? 0 : needs.optInt("total", 0); + tile.setSubtitle(n > 0 ? getResources().getQuantityString(R.plurals.tile_needs, n, n) : null); + } + tile.updateTile(); + } + } + + @Override + @SuppressWarnings("deprecation") + public void onClick() { + Intent dictate = new Intent(this, DictateActivity.class); + dictate.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + startActivityAndCollapse( + PendingIntent.getActivity( + this, 0, dictate, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT)); + } else { + startActivityAndCollapse(dictate); + } + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/DictateActivity.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/DictateActivity.java new file mode 100644 index 0000000000..0d08540026 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/DictateActivity.java @@ -0,0 +1,47 @@ +package today.developing.pmconsole; + +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.Intent; +import android.os.Bundle; +import android.speech.RecognizerIntent; +import java.util.ArrayList; + +/** + * Say what you want: the phone's own speech recogniser listens, and the + * words land in the Ask box. Reached from the app's shortcuts and from + * the quick-settings tile, so it works with the app closed. + */ +public class DictateActivity extends Activity { + private static final int REQUEST_SPEECH = 7; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (savedInstanceState != null) { + return; // the recogniser is already on screen + } + Intent listen = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + listen.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + listen.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.dictate_prompt)); + try { + startActivityForResult(listen, REQUEST_SPEECH); + } catch (ActivityNotFoundException noRecogniser) { + // No speech recogniser on this phone: open Ask to type instead. + startActivity(Links.open(this, "ask")); + finish(); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_SPEECH && resultCode == RESULT_OK && data != null) { + ArrayList heard = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); + if (heard != null && !heard.isEmpty() && !heard.get(0).trim().isEmpty()) { + startActivity(Links.ask(this, heard.get(0))); + } + } + finish(); + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Fleet.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Fleet.java new file mode 100644 index 0000000000..56ac99342d --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Fleet.java @@ -0,0 +1,209 @@ +package today.developing.pmconsole; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Base64; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import org.json.JSONObject; + +/** + * What this phone knows of the fleet without opening the app: a short + * summary (counts, and the top line of each list) read with a token of + * the phone's own. The token reads that summary and nothing else. + * + *

Linking passes no secret through an address or another app. The + * phone makes a random verifier and shows the signed-in owner only its + * hash. Once the owner approves the hash, the phone presents the + * verifier and is given its token. + */ +final class Fleet { + static final int NONE = 0; + static final int LINKED = 1; + static final int WAITING = 2; + static final int FAILED = 3; + + private static final String PREFS = "fleet"; + private static final String KEY_TOKEN = "token"; + private static final String KEY_VERIFIER = "verifier"; + private static final String KEY_VERIFIER_AT = "verifierAt"; + private static final String KEY_SUMMARY = "summary"; + private static final String KEY_FETCHED = "fetchedAt"; + /** A link request the owner has not approved is forgotten after this long. */ + private static final long VERIFIER_MS = 30 * 60 * 1000L; + private static final int CONNECT_MS = 3000; + private static final int READ_MS = 5000; + private static final int MAX_BODY = 64 * 1024; + + private Fleet() {} + + private static SharedPreferences prefs(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + static boolean linked(Context context) { + return prefs(context).getString(KEY_TOKEN, null) != null; + } + + /** The verifier of a link that is waiting for approval, or null. */ + static String pendingVerifier(Context context) { + SharedPreferences prefs = prefs(context); + String verifier = prefs.getString(KEY_VERIFIER, null); + if (verifier == null) { + return null; + } + if (System.currentTimeMillis() - prefs.getLong(KEY_VERIFIER_AT, 0) > VERIFIER_MS) { + prefs.edit().remove(KEY_VERIFIER).remove(KEY_VERIFIER_AT).apply(); + return null; + } + return verifier; + } + + /** Start a link: a new random verifier, kept until it is used or grows old. */ + static String newVerifier(Context context) { + byte[] random = new byte[32]; + new SecureRandom().nextBytes(random); + String verifier = base64Url(random); + prefs(context) + .edit() + .putString(KEY_VERIFIER, verifier) + .putLong(KEY_VERIFIER_AT, System.currentTimeMillis()) + .apply(); + return verifier; + } + + /** What the owner is shown and approves: the SHA-256 of the verifier. */ + static String challenge(String verifier) throws Exception { + return base64Url(MessageDigest.getInstance("SHA-256").digest(verifier.getBytes(StandardCharsets.US_ASCII))); + } + + private static String base64Url(byte[] bytes) { + return Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP); + } + + /** Present the verifier. LINKED once the owner has approved it. Not for the main thread. */ + static int tryLink(Context context) { + String verifier = pendingVerifier(context); + if (verifier == null) { + return NONE; + } + try { + Answer answer = + request(context, "POST", "/console/device/link", null, new JSONObject().put("verifier", verifier).toString()); + if (answer.code == 200) { + String token = new JSONObject(answer.body).getString("token"); + prefs(context).edit().putString(KEY_TOKEN, token).remove(KEY_VERIFIER).remove(KEY_VERIFIER_AT).apply(); + return LINKED; + } + return answer.code == 404 ? WAITING : FAILED; + } catch (Exception failed) { + return FAILED; + } + } + + /** Read the summary again and keep it. True when a fresh one was stored. Not for the main thread. */ + static boolean refresh(Context context) { + String token = prefs(context).getString(KEY_TOKEN, null); + if (token == null) { + return false; + } + try { + Answer answer = request(context, "GET", "/console/device/summary", token, null); + if (answer.code == 200) { + new JSONObject(answer.body); // kept only if it reads as a summary + prefs(context) + .edit() + .putString(KEY_SUMMARY, answer.body) + .putLong(KEY_FETCHED, System.currentTimeMillis()) + .apply(); + return true; + } + // The owner removed this phone: forget the token and what it read. + if (answer.code == 401 && new JSONObject(answer.body).optBoolean("unlinked", false)) { + prefs(context).edit().remove(KEY_TOKEN).remove(KEY_SUMMARY).remove(KEY_FETCHED).apply(); + } + return false; + } catch (Exception failed) { + return false; + } + } + + /** The last summary read, or null. */ + static JSONObject cached(Context context) { + String stored = prefs(context).getString(KEY_SUMMARY, null); + if (stored == null) { + return null; + } + try { + return new JSONObject(stored); + } catch (Exception unreadable) { + return null; + } + } + + /** When the last summary was read, in milliseconds, or 0. */ + static long fetchedAt(Context context) { + return prefs(context).getLong(KEY_FETCHED, 0); + } + + private static final class Answer { + final int code; + final String body; + + Answer(int code, String body) { + this.code = code; + this.body = body; + } + } + + private static Answer request(Context context, String method, String path, String bearer, String json) + throws IOException { + HttpURLConnection connection = + (HttpURLConnection) new URL(context.getString(R.string.site_url) + path).openConnection(); + try { + connection.setRequestMethod(method); + connection.setConnectTimeout(CONNECT_MS); + connection.setReadTimeout(READ_MS); + // A redirect would be the sign-in page, which is no answer to this. + connection.setInstanceFollowRedirects(false); + connection.setUseCaches(false); + connection.setRequestProperty("Accept", "application/json"); + if (bearer != null) { + connection.setRequestProperty("Authorization", "Bearer " + bearer); + } + if (json != null) { + byte[] out = json.getBytes(StandardCharsets.UTF_8); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setFixedLengthStreamingMode(out.length); + try (OutputStream stream = connection.getOutputStream()) { + stream.write(out); + } + } + int code = connection.getResponseCode(); + InputStream stream = code >= 400 ? connection.getErrorStream() : connection.getInputStream(); + return new Answer(code, stream == null ? "" : read(stream)); + } finally { + connection.disconnect(); + } + } + + private static String read(InputStream stream) throws IOException { + try (InputStream in = stream) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int n; + while ((n = in.read(buffer)) > 0 && out.size() < MAX_BODY) { + out.write(buffer, 0, n); + } + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/LinkActivity.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/LinkActivity.java new file mode 100644 index 0000000000..521d7a1139 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/LinkActivity.java @@ -0,0 +1,76 @@ +package today.developing.pmconsole; + +import android.app.Activity; +import android.content.Context; +import android.net.Uri; +import android.os.Bundle; +import android.widget.Toast; + +/** + * Links this phone so its home-screen widget can read the summary. + * + *

Started from the widget, it opens the signed-in app at a screen that + * asks the owner to approve this phone, showing only a hash. Started + * again by that screen once the owner has approved (the address + * pmconsole://finish, which carries nothing), it collects the phone's + * token and fills the widget. + */ +public class LinkActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Uri data = getIntent().getData(); + boolean approved = data != null && "pmconsole".equals(data.getScheme()); + if (approved || Fleet.linked(this) || Fleet.pendingVerifier(this) != null) { + // A request may already be approved: collect first, ask only if it is not. + collect(!approved); + return; + } + ask(Fleet.newVerifier(this)); + StatusWidget.draw(this); + finish(); + } + + /** Open the signed-in app at the screen that approves this phone. */ + private void ask(String verifier) { + try { + startActivity(Links.open(this, "more/link=" + Fleet.challenge(verifier))); + } catch (Exception failed) { + Toast.makeText(this, R.string.link_failed, Toast.LENGTH_LONG).show(); + } + } + + /** Present the verifier and, once linked, read the first summary. */ + private void collect(final boolean askWhenWaiting) { + final Context app = getApplicationContext(); + new Thread( + () -> { + final int result = Fleet.linked(app) ? Fleet.LINKED : Fleet.tryLink(app); + if (result == Fleet.LINKED) { + Fleet.refresh(app); + } + StatusWidget.draw(app); + runOnUiThread( + () -> { + String waiting = Fleet.pendingVerifier(app); + if (result == Fleet.LINKED) { + Toast.makeText(app, R.string.link_done, Toast.LENGTH_LONG).show(); + } else if (result == Fleet.WAITING && askWhenWaiting && waiting != null) { + ask(waiting); + } else if (result == Fleet.NONE && askWhenWaiting) { + ask(Fleet.newVerifier(app)); + StatusWidget.draw(app); + } else { + Toast.makeText( + app, + result == Fleet.FAILED ? R.string.link_failed : R.string.link_waiting, + Toast.LENGTH_LONG) + .show(); + } + finish(); + }); + }, + "pm-link") + .start(); + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Links.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Links.java new file mode 100644 index 0000000000..e03fe60723 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/Links.java @@ -0,0 +1,36 @@ +package today.developing.pmconsole; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import com.google.androidbrowserhelper.trusted.LauncherActivity; + +/** Where things are in the app, and how to open them from outside it. */ +final class Links { + /** Longest text handed to the app in a link. */ + private static final int MAX_TEXT = 6000; + + private Links() {} + + /** Open one screen of the app: "ask", "needs", "now", "next". */ + static Intent open(Context context, String screen) { + Intent intent = new Intent(context, LauncherActivity.class); + intent.setAction(Intent.ACTION_VIEW); + intent.setData(Uri.parse(context.getString(R.string.console_url) + "#" + screen)); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + return intent; + } + + /** + * Open Ask with words already in the box. The words travel in the + * part of the address after "#", which a browser never sends to a + * server: they stay on the phone until the owner presses Send. + */ + static Intent ask(Context context, CharSequence words) { + String text = words.toString().trim(); + if (text.length() > MAX_TEXT) { + text = text.substring(0, MAX_TEXT); + } + return open(context, "ask/say=" + Uri.encode(text)); + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/OpenActivity.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/OpenActivity.java new file mode 100644 index 0000000000..1de5dc761c --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/OpenActivity.java @@ -0,0 +1,33 @@ +package today.developing.pmconsole; + +import android.app.Activity; +import android.os.Bundle; +import java.util.Locale; + +/** + * Opens one screen of the app from a long press on its icon. It runs in + * a short-lived task of its own, so the app that is already open is + * brought forward and moved to that screen instead of being thrown away + * and loaded again (a launcher clears the task a shortcut starts in). + */ +public class OpenActivity extends Activity { + private static final String PREFIX = "today.developing.pmconsole.OPEN_"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + startActivity(Links.open(this, screen(getIntent().getAction()))); + finish(); + } + + /** The screen an action names; anything unknown opens Now. */ + static String screen(String action) { + if (action != null && action.startsWith(PREFIX)) { + String name = action.substring(PREFIX.length()).toLowerCase(Locale.ROOT); + if (name.equals("ask") || name.equals("needs") || name.equals("next")) { + return name; + } + } + return "now"; + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/PmApp.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/PmApp.java new file mode 100644 index 0000000000..daeb9de3f3 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/PmApp.java @@ -0,0 +1,38 @@ +package today.developing.pmconsole; + +import android.app.Activity; +import android.app.Application; +import android.os.Bundle; + +/** Whenever the app is opened, the home-screen widget is brought up to date. */ +public class PmApp extends Application { + @Override + public void onCreate() { + super.onCreate(); + registerActivityLifecycleCallbacks( + new ActivityLifecycleCallbacks() { + @Override + public void onActivityCreated(Activity activity, Bundle savedInstanceState) { + StatusWidget.requestRefresh(PmApp.this); + } + + @Override + public void onActivityStarted(Activity activity) {} + + @Override + public void onActivityResumed(Activity activity) {} + + @Override + public void onActivityPaused(Activity activity) {} + + @Override + public void onActivityStopped(Activity activity) {} + + @Override + public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} + + @Override + public void onActivityDestroyed(Activity activity) {} + }); + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/ShareActivity.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/ShareActivity.java new file mode 100644 index 0000000000..287d6c951b --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/ShareActivity.java @@ -0,0 +1,34 @@ +package today.developing.pmconsole; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +/** + * Receives text from anywhere on the phone: "Share" in another app, or + * "Ask the fleet" in the menu that appears when text is selected. The + * text lands in the Ask box, ready to edit and send. + */ +public class ShareActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = getIntent(); + CharSequence text = null; + if (Intent.ACTION_SEND.equals(intent.getAction())) { + text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); + String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); + if (subject != null && !subject.isEmpty() && (text == null || !text.toString().contains(subject))) { + text = text == null ? subject : subject + "\n" + text; + } + } else if (Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) { + text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT); + } + if (text != null && text.toString().trim().length() > 0) { + startActivity(Links.ask(this, text)); + } else { + startActivity(Links.open(this, "ask")); + } + finish(); + } +} diff --git a/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/StatusWidget.java b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/StatusWidget.java new file mode 100644 index 0000000000..21db17e07f --- /dev/null +++ b/pm-stack/console/android/app/src/twa/java/today/developing/pmconsole/StatusWidget.java @@ -0,0 +1,203 @@ +package today.developing.pmconsole; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.RemoteViews; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * The home-screen widget: how many tasks are in progress, how many are + * queued, how many things need the owner, and what is being worked on + * now. Each number opens its screen; the microphone starts dictation. + * + *

It is drawn from the last summary read, then the summary is read + * again: every half hour, whenever the app is opened, and on a tap of + * the refresh mark. + */ +public class StatusWidget extends AppWidgetProvider { + static final String ACTION_REFRESH = "today.developing.pmconsole.REFRESH"; + /** A broadcast must be done well inside ten seconds. */ + private static final long BUDGET_MS = 8500; + private static final long REQUEST_EVERY_MS = 30_000; + private static volatile long lastRequest; + + @Override + public void onReceive(Context context, Intent intent) { + super.onReceive(context, intent); + String action = intent.getAction(); + if (ACTION_REFRESH.equals(action) || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { + if (placed(context)) { + read(context.getApplicationContext(), goAsync()); + } + } + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) { + draw(context); + } + + /** Ask for the summary to be read again, at most twice a minute. */ + static void requestRefresh(Context context) { + long now = System.currentTimeMillis(); + if (now - lastRequest < REQUEST_EVERY_MS || !placed(context)) { + return; + } + lastRequest = now; + context.sendBroadcast(new Intent(context, StatusWidget.class).setAction(ACTION_REFRESH)); + } + + private static boolean placed(Context context) { + try { + return AppWidgetManager.getInstance(context) + .getAppWidgetIds(new ComponentName(context, StatusWidget.class)) + .length + > 0; + } catch (RuntimeException unavailable) { + return false; + } + } + + /** Read off the main thread, and let go of the broadcast in time whatever the network does. */ + private static void read(final Context app, final PendingResult pending) { + final Thread worker = + new Thread( + () -> { + try { + if (!Fleet.linked(app)) { + Fleet.tryLink(app); + } + if (Fleet.linked(app)) { + Fleet.refresh(app); + } + draw(app); + } catch (RuntimeException failed) { + // The widget keeps what it last showed. + } + }, + "pm-widget"); + worker.start(); + new Thread( + () -> { + try { + worker.join(BUDGET_MS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + pending.finish(); + }, + "pm-widget-watch") + .start(); + } + + /** Draw every placed widget from what this phone last read. */ + static void draw(Context context) { + if (!placed(context)) { + return; + } + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_status); + JSONObject summary = Fleet.cached(context); + boolean linked = Fleet.linked(context); + int flags = PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT; + if (linked && summary != null) { + views.setViewVisibility(R.id.widget_counts, View.VISIBLE); + views.setTextViewText(R.id.widget_now_n, count(summary, "now", "count")); + views.setTextViewText(R.id.widget_next_n, count(summary, "next", "count")); + views.setTextViewText(R.id.widget_needs_n, count(summary, "needs", "total")); + views.setTextViewText(R.id.widget_line, line(context, summary)); + views.setTextViewText(R.id.widget_asof, asOf(context, summary)); + views.setOnClickPendingIntent(R.id.widget_now, PendingIntent.getActivity(context, 1, Links.open(context, "now"), flags)); + views.setOnClickPendingIntent(R.id.widget_next, PendingIntent.getActivity(context, 2, Links.open(context, "next"), flags)); + views.setOnClickPendingIntent(R.id.widget_needs, PendingIntent.getActivity(context, 3, Links.open(context, "needs"), flags)); + views.setOnClickPendingIntent(R.id.widget_root, PendingIntent.getActivity(context, 4, Links.open(context, "now"), flags)); + } else { + views.setViewVisibility(R.id.widget_counts, View.GONE); + views.setTextViewText( + R.id.widget_line, + context.getString( + linked + ? R.string.widget_loading + : Fleet.pendingVerifier(context) != null + ? R.string.widget_waiting + : R.string.widget_unlinked)); + views.setTextViewText(R.id.widget_asof, ""); + Intent link = new Intent(context, LinkActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + views.setOnClickPendingIntent(R.id.widget_root, PendingIntent.getActivity(context, 5, link, flags)); + } + Intent dictate = new Intent(context, DictateActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + views.setOnClickPendingIntent(R.id.widget_mic, PendingIntent.getActivity(context, 6, dictate, flags)); + Intent refresh = new Intent(context, StatusWidget.class).setAction(ACTION_REFRESH); + views.setOnClickPendingIntent(R.id.widget_refresh, PendingIntent.getBroadcast(context, 7, refresh, flags)); + try { + AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, StatusWidget.class), views); + } catch (RuntimeException unavailable) { + // No launcher to draw on right now. + } + } + + private static String count(JSONObject summary, String group, String field) { + JSONObject object = summary.optJSONObject(group); + int n = object == null ? 0 : object.optInt(field, 0); + return n > 999 ? "999+" : String.valueOf(n); + } + + /** What is being worked on now, or what comes next, in a line or two. */ + private static String line(Context context, JSONObject summary) { + StringBuilder text = new StringBuilder(); + JSONObject now = summary.optJSONObject("now"); + JSONArray top = now == null ? null : now.optJSONArray("top"); + if (top != null && top.length() > 0) { + JSONObject first = top.optJSONObject(0); + text.append(first == null ? "" : first.optString("title", "")); + String step = first == null ? "" : first.optString("step", ""); + if (!step.isEmpty()) { + text.append("\n").append(context.getString(R.string.widget_step, step)); + } + } else { + JSONObject next = summary.optJSONObject("next"); + JSONArray queued = next == null ? null : next.optJSONArray("top"); + if (queued != null && queued.length() > 0) { + text.append(context.getString(R.string.widget_next_up, queued.optString(0, ""))); + } else { + text.append(context.getString(R.string.widget_idle)); + } + } + JSONObject asks = summary.optJSONObject("asks"); + int answered = asks == null ? 0 : asks.optInt("answered", 0); + if (answered > 0) { + text.append("\n").append(context.getResources().getQuantityString(R.plurals.widget_replies, answered, answered)); + } + return text.toString(); + } + + /** The time the fleet's state was read, in the phone's own clock style. */ + private static String asOf(Context context, JSONObject summary) { + long at = 0; + String iso = summary.optString("at", ""); + if (!iso.isEmpty()) { + try { + SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); + parser.setTimeZone(TimeZone.getTimeZone("UTC")); + Date parsed = parser.parse(iso); + at = parsed == null ? 0 : parsed.getTime(); + } catch (Exception unparsed) { + at = 0; + } + } + if (at == 0) { + at = Fleet.fetchedAt(context); + } + return at == 0 ? "" : DateFormat.getTimeFormat(context).format(new Date(at)); + } +} diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_ask.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_ask.xml new file mode 100644 index 0000000000..dad8c20de0 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_ask.xml @@ -0,0 +1,14 @@ + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_mic.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_mic.xml new file mode 100644 index 0000000000..96618fb842 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_mic.xml @@ -0,0 +1,14 @@ + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_needs.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_needs.xml new file mode 100644 index 0000000000..7b419eab16 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_needs.xml @@ -0,0 +1,14 @@ + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_notification.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_notification.xml new file mode 100644 index 0000000000..ba43d4410e --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_notification.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_now.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_now.xml new file mode 100644 index 0000000000..2828743e76 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_now.xml @@ -0,0 +1,14 @@ + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/ic_refresh.xml b/pm-stack/console/android/app/src/twa/res/drawable/ic_refresh.xml new file mode 100644 index 0000000000..7a8c41e26b --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/ic_refresh.xml @@ -0,0 +1,14 @@ + + + + diff --git a/pm-stack/console/android/app/src/twa/res/drawable/widget_bg.xml b/pm-stack/console/android/app/src/twa/res/drawable/widget_bg.xml new file mode 100644 index 0000000000..a5672848f3 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/drawable/widget_bg.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/pm-stack/console/android/app/src/twa/res/layout/widget_status.xml b/pm-stack/console/android/app/src/twa/res/layout/widget_status.xml new file mode 100644 index 0000000000..51442f51fe --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/layout/widget_status.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pm-stack/console/android/app/src/twa/res/values/colors.xml b/pm-stack/console/android/app/src/twa/res/values/colors.xml index 70e5510db1..4efe3de603 100644 --- a/pm-stack/console/android/app/src/twa/res/values/colors.xml +++ b/pm-stack/console/android/app/src/twa/res/values/colors.xml @@ -1,4 +1,7 @@ #12151A + #E6EAF0 + #8B96A5 + #6CB6FF diff --git a/pm-stack/console/android/app/src/twa/res/values/strings.xml b/pm-stack/console/android/app/src/twa/res/values/strings.xml index 82bd6ffdc1..93dccfcf07 100644 --- a/pm-stack/console/android/app/src/twa/res/values/strings.xml +++ b/pm-stack/console/android/app/src/twa/res/values/strings.xml @@ -1,4 +1,37 @@ PM Console + Ask the fleet + Ask the fleet + + %d thing needs you + %d things need you + + Say what you want the fleet to do + Dictate + Say what you want + Ask + Ask the fleet + Needs me + What needs me + Now + What is in progress + PM + PM status + In progress, queued next and what needs you, with the task being worked on now. + Next + Read again + Tap to link this phone, so the counts can show here. + Waiting for you to approve this phone in the app. Tap to open it. + Linked. Reading the fleet… + Next step: %1$s + Nothing in progress. Next: %1$s + Nothing in progress or queued. + + %d reply to what you asked + %d replies to what you asked + + This phone is linked. The widget is up to date. + Not approved yet. Open the app and approve this phone. + Could not reach the fleet. Try again in a moment. diff --git a/pm-stack/console/android/app/src/twa/res/xml/shortcuts.xml b/pm-stack/console/android/app/src/twa/res/xml/shortcuts.xml new file mode 100644 index 0000000000..6252149c93 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/xml/shortcuts.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + diff --git a/pm-stack/console/android/app/src/twa/res/xml/widget_status_info.xml b/pm-stack/console/android/app/src/twa/res/xml/widget_status_info.xml new file mode 100644 index 0000000000..f0f7c4b0a8 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/xml/widget_status_info.xml @@ -0,0 +1,14 @@ + + diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index 22e9749a7d..2f1812258b 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -323,6 +323,30 @@ button { font-weight: 600; cursor: pointer; } +/* A link that is the main thing to do on its card. */ +a.button { + display: inline-flex; + align-items: center; + min-height: 42px; + padding: 8px 14px; + border-radius: 10px; + background: var(--accent); + color: var(--accent-ink); + font-weight: 600; + text-decoration: none; +} +ul.plain { + margin: 0; + padding: 0; + list-style: none; +} +ul.plain li { + padding: 6px 0; + color: var(--quiet); +} +ul.plain li b { + color: var(--text); +} button.ghost { background: transparent; color: var(--text); diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 974cb8b7d1..96e6bb7ff1 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -5,7 +5,8 @@ // The page draws from three documents the server keeps ready (core, // questions, ops), so moving between sections never waits on a fetch. const API = "/console/api/"; -const $ = (id) => document.getElementById(id); +// Without a page (the tests import the small functions) nothing is found. +const $ = (id) => (typeof document === "undefined" ? null : document.getElementById(id)); const view = $("view"); const tabsEl = $("tabs"); const toastEl = $("toast"); @@ -40,16 +41,17 @@ function icon(d) { return s; } -/** "12 min", "3 h", "2 d" since an ISO time (times without a zone are UTC). */ +/** "just now", "12 min ago", "3 h ago", "2 d ago" since an ISO time + * (times without a zone are UTC). */ export function ago(iso, now = Date.now()) { if (!iso) return ""; const t = Date.parse(/[zZ]$|[+-]\d\d:?\d\d$/.test(iso) ? iso : `${iso}Z`); if (Number.isNaN(t)) return ""; const s = Math.max(0, (now - t) / 1000); if (s < 90) return "just now"; - if (s < 5400) return `${Math.round(s / 60)} min`; - if (s < 129600) return `${Math.round(s / 3600)} h`; - return `${Math.round(s / 86400)} d`; + if (s < 5400) return `${Math.round(s / 60)} min ago`; + if (s < 129600) return `${Math.round(s / 3600)} h ago`; + return `${Math.round(s / 86400)} d ago`; } /** The queue's priority bands, in words. */ @@ -181,7 +183,7 @@ async function act(kind, args, done, button) { function taskCard(t, extra) { const who = [t.worker, t.lane, t.model].filter(Boolean).join(" · "); - const when = t.claimed ? `claimed ${ago(t.claimed)} ago` : `queued ${ago(t.created)} ago`; + const when = t.claimed ? `claimed ${ago(t.claimed)}` : `queued ${ago(t.created)}`; return card( h( "div", @@ -240,7 +242,7 @@ function viewNow() { h( "p", { class: "meta" }, - [m.agent, m.model, m.where, m.last ? `active ${ago(m.last)} ago` : "", m.tools ? `${m.tools} tool calls running` : ""] + [m.agent, m.model, m.where, m.last ? `active ${ago(m.last)}` : "", m.tools ? `${m.tools} tool calls running` : ""] .filter(Boolean) .join(" · "), ), @@ -265,7 +267,7 @@ function viewNow() { h( "p", { class: "meta" }, - `${ago(a.at)} ago · ${a.kind} · `, + `${ago(a.at)} · ${a.kind} · `, h("span", { class: a.status === "failed" ? "bad" : "" }, a.status + (a.note ? `: ${a.note}` : "")), ), ), @@ -585,7 +587,7 @@ function needCard(i, kind) { i.action ? h("h3", {}, i.action) : h("h3", {}, i.title), i.action ? h("p", { class: "meta" }, i.title) : null, i.why ? h("p", { class: "meta" }, i.why) : null, - i.updated ? h("p", { class: "meta" }, `updated ${ago(i.updated)} ago`) : null, + i.updated ? h("p", { class: "meta" }, `updated ${ago(i.updated)}`) : null, i.ref && /#\d+$/.test(i.ref) ? h( "div", @@ -658,7 +660,17 @@ const STATUS = { }; let draft = ""; -function viewAsk() { +function viewAsk(sub) { + // Words handed over by the Android app (shared or selected text, or + // dictation) arrive after the "#", which never leaves the phone. + if (sub?.startsWith("say=")) { + try { + draft = decodeURIComponent(sub.slice(4)); + } catch { + // not valid text: leave the box as it was + } + history.replaceState(null, "", "#ask"); + } const box = h("textarea", { rows: 3, placeholder: "Say what you want, in your own words. An agent picks it up, does it, and reports back here.", @@ -723,9 +735,9 @@ function viewAsk() { ? asks.map((a) => { const [label, tone] = STATUS[a.status] || [a.status, ""]; return card( - h("div", { class: "row" }, chip(label, tone), ext(a.url, `#${a.issue}`), h("span", { class: "meta" }, `${ago(a.updated)} ago`), a.worker ? h("span", { class: "meta" }, `· ${a.worker}`) : null), + h("div", { class: "row" }, chip(label, tone), ext(a.url, `#${a.issue}`), h("span", { class: "meta" }, `${ago(a.updated)}`), a.worker ? h("span", { class: "meta" }, `· ${a.worker}`) : null), h("div", { class: "bubble you" }, h("b", {}, "You"), a.text), - ...a.replies.map((r) => h("div", { class: `bubble${r.you ? " you" : ""}` }, h("b", {}, `${r.you ? "You" : "Fleet"} · ${ago(r.at)} ago`), r.text)), + ...a.replies.map((r) => h("div", { class: `bubble${r.you ? " you" : ""}` }, h("b", {}, `${r.you ? "You" : "Fleet"} · ${ago(r.at)}`), r.text)), h( "div", { class: "row end" }, @@ -767,6 +779,7 @@ function viewMore() { tile("more/agents", "Agents", ops.agents ? `${ops.agents.length} registered` : "message one or all"), tile("more/services", "Services", ops.services ? `${ops.services.filter((u) => u.active === "failed").length} failed of ${ops.services.length}` : "start, stop, logs"), tile("more/notify", "Notifications", "choose what reaches this device"), + tile("more/phone", "Phones", "the Android app and its home-screen widget"), ), ]; for (const g of ops.more || []) { @@ -788,6 +801,12 @@ const NOTICE = { trouble: "A unit failed", }; +/** What the browser says it runs on: "Linux; Android 10; K", "Windows NT 10.0; Win64; x64". */ +export function deviceLabel(agent = navigator.userAgent) { + const m = /\(([^)]*)\)/.exec(agent); + return (m ? m[1] : agent).trim().slice(0, 60); +} + function keyBytes(b64) { const text = atob((b64 + "=".repeat((4 - (b64.length % 4)) % 4)).replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(text, (c) => c.charCodeAt(0)); @@ -810,7 +829,7 @@ async function viewNotify() { const r = await navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }); await navigator.serviceWorker.ready; const s = await r.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(status.key) }); - await act("push.on", { subscription: s.toJSON(), label: navigator.userAgent.replace(/^.*\((.*?)\).*$/, "$1").slice(0, 60) }, "Notifications are on for this device"); + await act("push.on", { subscription: s.toJSON(), label: deviceLabel() }, "Notifications are on for this device"); } catch (error) { toast(error.message, true); e.target.disabled = false; @@ -848,6 +867,120 @@ async function viewNotify() { ]; } +// ---- phones ------------------------------------------------------------ + +/** A request from the Android app on this phone to be linked, until it is answered. */ +let linkRequest = null; +/** How many phones were linked when the request was approved, or null before that. */ +let linkApprovedAt = null; + +/** The address that tells the Android app to collect its token. It carries nothing. */ +function collectUrl() { + const back = encodeURIComponent(`${location.origin}/console/#more/phone`); + return `intent://finish#Intent;scheme=pmconsole;package=${me.androidPackage || "today.developing.pmconsole"};S.browser_fallback_url=${back};end`; +} + +async function viewPhone(sub) { + if (sub?.startsWith("link=")) { + const request = sub.slice(5); + linkRequest = /^[A-Za-z0-9_-]{43}$/.test(request) ? request : null; + linkApprovedAt = null; + history.replaceState(null, "", "#more/phone"); + } + const devices = await api("devices"); + // The phone has collected its token: the request is finished. + if (linkApprovedAt !== null && devices.length > linkApprovedAt) { + linkRequest = null; + linkApprovedAt = null; + } + const approve = async (e) => { + const done = await act("device.approve", { challenge: linkRequest }, "Approved", e.target); + if (!done) return; + linkApprovedAt = devices.length; + draw(); + // Hand back to the app, which collects its token and fills the widget. + location.href = collectUrl(); + }; + const out = []; + if (linkRequest && linkApprovedAt === null) { + out.push( + card( + h("h3", {}, "Link this phone?"), + h( + "p", + { class: "meta" }, + "The app's home-screen widget asked to be linked. It will be able to read three counts (in progress, queued, needs you) and the titles at the top of each list, and nothing else. It cannot change anything, and you can remove it here at any time.", + ), + h("p", { class: "why" }, "Approve only if you just tapped the PM widget on this phone. If this appeared after following a link from somewhere else, choose Not now."), + h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: () => { + linkRequest = null; + draw(); + }, + }, + "Not now", + ), + h("button", { onclick: approve }, "Link this phone"), + ), + ), + ); + } else if (linkRequest) { + out.push( + card( + h("h3", {}, "Approved"), + h("p", { class: "meta" }, "The widget fills in a moment. If it does not, tap below, or tap the widget."), + h("div", { class: "row end" }, h("a", { class: "button", href: collectUrl() }, "Finish on this phone")), + ), + ); + } + out.push( + h("h2", {}, `Linked phones (${devices.length})`), + ...(devices.length + ? devices.map((d) => + card( + h("h3", {}, d.name), + h("p", { class: "meta" }, `Linked ${ago(d.createdAt)} · ${d.seenAt ? `last read ${ago(d.seenAt)}` : "has not read yet"}`), + h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const sure = await ask({ title: "Remove this phone?", text: `${d.name} will stop showing the counts on its home screen.`, okLabel: "Remove", danger: true }); + if (sure !== null) act("device.remove", { id: d.id }, "Removed", e.target); + }, + }, + "Remove", + ), + ), + ), + ) + : [empty("No phone is linked. On a phone with the app, add the PM widget to the home screen and tap it.")]), + h("h2", {}, "The Android app"), + card( + h( + "ul", + { class: "plain" }, + h("li", {}, h("b", {}, "Home-screen widget. "), "In progress, queued next and needs you, with the task being worked on. Each number opens its screen."), + h("li", {}, h("b", {}, "Say it. "), "Long-press the icon and choose Dictate, or add the “Ask the fleet” tile to quick settings: speak, check the words, send."), + h("li", {}, h("b", {}, "Share or select. "), "Share text from any app to PM Console, or select text anywhere and choose “Ask the fleet”: it lands in the Ask box."), + h("li", {}, h("b", {}, "Shortcuts. "), "Long-press the icon for Ask, Needs me and Now."), + h("li", {}, h("b", {}, "Notifications. "), "Turn them on under Notifications; they arrive as the app's own."), + ), + me.androidApp ? h("div", { class: "row end" }, h("a", { class: "button", href: "/console/pm-console.apk" }, "Download the app")) : null, + ), + ); + return out; +} + const QUEUE_STATES = ["blocked", "queued", "claimed", "parked"]; let queueState = { status: "blocked", q: "" }; async function viewQueue() { @@ -924,7 +1057,7 @@ function viewPrs() { const detail = h("div", {}); return card( h("h3", {}, ext(p.url, `#${p.number}`), ` ${p.title}`), - h("p", { class: "meta" }, `${p.draft ? "draft · " : ""}${p.author} · ${p.branch} · opened ${ago(p.created)} ago`), + h("p", { class: "meta" }, `${p.draft ? "draft · " : ""}${p.author} · ${p.branch} · opened ${ago(p.created)}`), detail, h( "div", @@ -1015,11 +1148,11 @@ async function viewAgents() { compose, h("h2", {}, `Agents (${agents.length})`), ...agents.map((a) => - card(h("h3", {}, a.name), h("p", { class: "meta" }, `${(a.groups || []).join(", ")} · seen ${ago(a.last_seen) || "never"} ago · ${a.unread_commands ?? 0} commands and ${a.unread_messages ?? 0} messages unread`)), + card(h("h3", {}, a.name), h("p", { class: "meta" }, `${(a.groups || []).join(", ")} · seen ${ago(a.last_seen) || "never"} · ${a.unread_commands ?? 0} commands and ${a.unread_messages ?? 0} messages unread`)), ), h("h2", {}, "Recent messages"), ...(recent.length - ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} ago · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) + ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) : [empty("No messages.")]), ]; } @@ -1098,6 +1231,7 @@ const VIEWS = { "more/agents": ["Agents", viewAgents, "ops"], "more/services": ["Services", viewServices, "ops"], "more/notify": ["Notifications", viewNotify], + "more/phone": ["Phones", viewPhone], }; let route = "now"; let drawSeq = 0; @@ -1105,6 +1239,8 @@ let drawSeq = 0; function parse(hash) { const r = hash.replace(/^#/, ""); if (VIEWS[r]) return [r, undefined]; + // The Android app asking for its phone to be linked: #more/link=. + if (r.startsWith("more/link=")) return ["more/phone", r.slice(5)]; const [top, sub] = r.split("/"); return VIEWS[top] ? [top, sub] : ["now", undefined]; } @@ -1135,7 +1271,7 @@ function drawFresh() { const t = asOf.core; const age = t ? (Date.now() - t) / 1000 : null; freshEl.className = `fresh${signedOut ? " down" : age !== null && age > 180 ? " stale" : ""}`; - freshEl.textContent = signedOut ? "signed out" : age === null ? "" : age < 45 ? "live" : `as of ${ago(new Date(t).toISOString())} ago`; + freshEl.textContent = signedOut ? "signed out" : age === null ? "" : age < 45 ? "live" : `as of ${ago(new Date(t).toISOString())}`; } /** Draw the current section from what is already loaded. Only the latest @@ -1191,7 +1327,11 @@ if (typeof document !== "undefined" && view) { }); document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") flushPending(); - else refresh(false); + else { + refresh(false); + // Back from the Android app after linking: show the phone it added. + if (route === "more/phone") draw(); + } }); addEventListener("pagehide", flushPending); setInterval(() => document.visibilityState === "visible" && refresh(false), 20_000); diff --git a/pm-stack/console/scripts/demo.ts b/pm-stack/console/scripts/demo.ts index a69414375a..20dd48cf56 100644 --- a/pm-stack/console/scripts/demo.ts +++ b/pm-stack/console/scripts/demo.ts @@ -4,7 +4,9 @@ // // The real server code answers; only the sources are canned, and every // action succeeds and is listed under "What you did". +import { actions as realActions } from "../src/actions.ts"; import { readConfig } from "../src/config.ts"; +import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; import { Ops } from "../src/ops.ts"; import { Push } from "../src/push.ts"; @@ -341,15 +343,26 @@ const docs = new Docs( Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), ); const done = (result: unknown) => ({ run: async () => result, touch: [] as string[], audit: () => ({}) }); +// Linking a phone is the real thing, kept in a file under /tmp. +const devices = new Devices("/tmp/pm-console-demo-devices.json"); +const phones = { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }; +const real = realActions( + new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), + undefined as never, + undefined, + devices, +); const table = new Proxy({} as Record>, { get: (_t, kind) => - done( - kind === "ask.send" - ? { issue: 12503, queued: true } - : kind === "questions.accept" - ? { applied: 2, refused: [] } - : { ok: true }, - ), + typeof kind === "string" && kind.startsWith("device.") + ? real[kind] + : done( + kind === "ask.send" + ? { issue: 12503, queued: true } + : kind === "questions.accept" + ? { applied: 2, refused: [] } + : { ok: true }, + ), has: () => true, getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }), }); @@ -367,6 +380,7 @@ Bun.serve({ cfg, ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), docs, + phones, push: new Push("/tmp/pm-console-demo-push.json", "mailto:you@example.com", async () => ({ status: 201 })), actions: table, identify: async () => ({ via: "demo", email: "you@example.com" }), diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 2c156d4179..2773ef7899 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -14,10 +14,12 @@ the owner's address. Sign-in methods are the one-time PIN, plus Google when the secrets `google.access-sso.client-id` and `google.access-sso.client-secret` exist. -2. Three public paths bypass sign-in at the edge, because a phone - fetches them before anyone has signed in: the asset-links file, the - install manifest and its icons. The console serves exactly those - files to an unsigned caller and nothing else. +2. Four paths bypass sign-in at the edge. Three are files a phone + fetches before anyone has signed in: the asset-links file, the + install manifest and its icons. The fourth, /console/device, is where + the Android app's home-screen widget presents a token of its own to + read a short summary. The console serves exactly those files to an + unsigned caller, checks that token itself, and answers nothing else. 3. The console's environment file names the Access issuer and the owner, and the console is running with it. 4. The tunnel routes the hostname to the console. @@ -57,7 +59,12 @@ "http_only_cookie_attribute": True, "session_duration": "720h", } -PUBLIC_PATHS = ("/.well-known/assetlinks.json", "/manifest.webmanifest", "/icons") +PUBLIC_PATHS = ( + "/.well-known/assetlinks.json", + "/manifest.webmanifest", + "/icons", + "/console/device", +) GOOGLE_ID = "google.access-sso.client-id" GOOGLE_SECRET = "google.access-sso.client-secret" diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 9b62a96d03..1966f7e22a 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -226,7 +226,18 @@ def test_check_reports_and_changes_nothing(self): account = Account() self.assertEqual(run(account, self.home, "--check"), 1) self.assertEqual(account.order, []) - self.assertEqual(len(account.changes), 7) + # One per public path, then the application, the console's + # settings, the route and the DNS record. + self.assertEqual( + expose.PUBLIC_PATHS, + ( + "/.well-known/assetlinks.json", + "/manifest.webmanifest", + "/icons", + "/console/device", + ), + ) + self.assertEqual(len(account.changes), len(expose.PUBLIC_PATHS) + 4) self.assertFalse( (pathlib.Path(self.home) / ".local/state/pm-console/.env").exists() ) diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index da6007338a..32cc7c455a 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -4,6 +4,7 @@ // changes, so the documents are read again before the answer goes back, // and what it leaves in the audit log, which never includes the text the // owner typed. +import type { Devices } from "./devices.ts"; import type { Docs } from "./docs.ts"; import { OpError, type Ops } from "./ops.ts"; import type { Push } from "./push.ts"; @@ -29,7 +30,14 @@ const asked = async (p: Promise): Promise => throw error instanceof OpError ? error : new OpError(400, error.message); }); -export function actions(ops: Ops, work: Work, push?: Push): Record { +export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): Record { + // A phone linked to read the summary its home-screen widget shows. + const phones: Record = devices + ? { + "device.approve": { run: (a) => devices.approve(a), touch: [], audit: ids("name") }, + "device.remove": { run: (a) => devices.remove(a), touch: [], audit: ids("id") }, + } + : {}; const notify: Record = push ? { "push.on": { run: (a) => asked(push.subscribe(a.subscription, a.label)), touch: [], audit: () => ({}) }, @@ -50,6 +58,7 @@ export function actions(ops: Ops, work: Work, push?: Push): Record work.ask(a), touch: ["asks", "board"], audit: () => ({}) }, "ask.reply": { run: (a) => work.askReply(a), touch: ["asks", "board"], audit: ids("issue") }, "ask.close": { run: (a) => work.askClose(a), touch: ["asks"], audit: ids("issue") }, diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts index d32daa07b0..e8178d5fe7 100644 --- a/pm-stack/console/src/config.ts +++ b/pm-stack/console/src/config.ts @@ -52,6 +52,8 @@ export interface Config { /** The signed APK the console hands to the signed-in owner, if the * file exists. */ androidApk: string; + /** Where linked phones are kept (hashes of their tokens, never the tokens). */ + devicesFile: string; /** The dashboard's decision-set store: the questions waiting on the * owner, and the per-set tokens that authorise an answer. */ decisionsFile: string; @@ -218,6 +220,7 @@ export function readConfig( androidPackage: env.PM_CONSOLE_ANDROID_PACKAGE ?? "today.developing.pmconsole", androidFingerprints: fingerprints, androidApk: env.PM_CONSOLE_ANDROID_APK ?? `${home}/.local/state/pm-console/android/pm-console.apk`, + devicesFile: env.PM_CONSOLE_DEVICES_FILE ?? `${home}/.local/state/pm-console/devices.json`, decisionsFile: env.PM_CONSOLE_DECISIONS_FILE ?? `${home}/.local/state/pm-aggregator/decisions.json`, promptLabel: env.PM_CONSOLE_PROMPT_LABEL ?? "owner/prompt", needsRepos: list(env, "PM_CONSOLE_NEEDS_REPOS", [ diff --git a/pm-stack/console/src/devices.ts b/pm-stack/console/src/devices.ts new file mode 100644 index 0000000000..837204dea6 --- /dev/null +++ b/pm-stack/console/src/devices.ts @@ -0,0 +1,237 @@ +// Phones that may read a short summary without the browser's sign-in. +// +// The Android app's home-screen widget cannot use the sign-in the +// browser holds, so it gets a token of its own that reads one thing: the +// counts and the top line of each list. Nothing can be changed with it. +// +// Linking never passes a secret through an address or another app. The +// phone makes a random verifier and shows the owner only its hash (the +// challenge) inside the signed-in app. The owner approves the challenge; +// the phone then presents the verifier, which only it knows, and is +// given its token. The store keeps hashes of tokens, never the tokens. +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import { OpError } from "./ops.ts"; + +export interface Device { + id: string; + name: string; + /** SHA-256 of the token, in hex. */ + hash: string; + createdAt: string; + seenAt: string | null; +} + +interface Pending { + challenge: string; + name: string; + expiresAt: number; +} + +interface Store { + devices: Device[]; + pending: Pending[]; +} + +const CHALLENGE = /^[A-Za-z0-9_-]{43}$/; +const VERIFIER = /^[A-Za-z0-9_-]{43,128}$/; +const TOKEN = /^[A-Za-z0-9_-]{43}$/; +const APPROVAL_MS = 10 * 60_000; +const MAX_DEVICES = 8; +const MAX_PENDING = 4; +/** `seenAt` is written at most this often, so reading does not mean writing. */ +const SEEN_EVERY_MS = 10 * 60_000; + +const sha = (text: string) => createHash("sha256").update(text).digest(); + +/** The challenge a verifier answers: its SHA-256, in base64url. */ +export function challengeOf(verifier: string): string { + return sha(verifier).toString("base64url"); +} + +function same(a: string, b: string): boolean { + const x = Buffer.from(a); + const y = Buffer.from(b); + return x.length === y.length && timingSafeEqual(x, y); +} + +/** So many tries in a window and no more: for the two paths that are + * reachable without sign-in. */ +export class Limiter { + private start = 0; + private used = 0; + constructor( + private max: number, + private windowMs: number, + private now: () => number = Date.now, + ) {} + + allow(): boolean { + const t = this.now(); + if (t - this.start >= this.windowMs) { + this.start = t; + this.used = 0; + } + this.used++; + return this.used <= this.max; + } +} + +export class Devices { + private store: Store | null = null; + private writing: Promise = Promise.resolve(); + + constructor( + private file: string, + private now: () => number = Date.now, + private random: (bytes: number) => Buffer = randomBytes, + ) {} + + private async load(): Promise { + if (this.store) return this.store; + let store: Store = { devices: [], pending: [] }; + try { + const parsed = JSON.parse(await readFile(this.file, "utf8")); + if (parsed && Array.isArray(parsed.devices) && Array.isArray(parsed.pending)) store = parsed; + } catch { + // no file yet, or one that cannot be read: start with no devices + } + this.store ??= store; + return this.store; + } + + /** Written whole to a new file and moved into place, one write at a time. */ + private save(): Promise { + const next = this.writing.then(async () => { + await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); + const tmp = `${this.file}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify(this.store), { mode: 0o600 }); + await rename(tmp, this.file); + }); + this.writing = next.catch(() => {}); + return next; + } + + /** The owner, signed in, approves a phone that is asking to be linked. */ + async approve(args: { challenge?: unknown; name?: unknown }): Promise<{ expires: string }> { + const challenge = String(args.challenge ?? ""); + if (!CHALLENGE.test(challenge)) throw new OpError(400, "that is not a link request from the app"); + const name = + String(args.name ?? "") + .trim() + .slice(0, 60) || "Android phone"; + const store = await this.load(); + const t = this.now(); + if (store.devices.length >= MAX_DEVICES) { + throw new OpError(409, `${MAX_DEVICES} phones are linked already: remove one first`); + } + const expiresAt = t + APPROVAL_MS; + store.pending = [ + ...store.pending.filter((p) => p.expiresAt > t && p.challenge !== challenge), + { challenge, name, expiresAt }, + ].slice(-MAX_PENDING); + await this.save(); + return { expires: new Date(expiresAt).toISOString() }; + } + + /** The phone presents its verifier. If the owner approved the matching + * challenge, the phone is given its token, once. */ + async link(verifier: unknown): Promise<{ id: string; token: string } | null> { + if (typeof verifier !== "string" || !VERIFIER.test(verifier)) return null; + const challenge = challengeOf(verifier); + const store = await this.load(); + const t = this.now(); + const found = store.pending.find((p) => p.expiresAt > t && same(p.challenge, challenge)); + if (!found || store.devices.length >= MAX_DEVICES) return null; + const token = this.random(32).toString("base64url"); + const device: Device = { + id: this.random(6).toString("base64url"), + name: found.name, + hash: sha(token).toString("hex"), + createdAt: new Date(t).toISOString(), + seenAt: null, + }; + store.pending = store.pending.filter((p) => p !== found && p.expiresAt > t); + store.devices.push(device); + await this.save(); + return { id: device.id, token }; + } + + /** The device a token belongs to, or null. */ + async check(token: unknown): Promise { + if (typeof token !== "string" || !TOKEN.test(token)) return null; + const hash = sha(token).toString("hex"); + const store = await this.load(); + const device = store.devices.find((d) => same(d.hash, hash)) ?? null; + if (device) { + const t = this.now(); + if (!device.seenAt || t - Date.parse(device.seenAt) > SEEN_EVERY_MS) { + device.seenAt = new Date(t).toISOString(); + // A read is answered whether or not this could be written down. + this.save().catch(() => {}); + } + } + return device; + } + + /** What the owner is shown: never a token or its hash. */ + async list(): Promise<{ id: string; name: string; createdAt: string; seenAt: string | null }[]> { + const store = await this.load(); + return store.devices.map(({ id, name, createdAt, seenAt }) => ({ id, name, createdAt, seenAt })); + } + + async remove(args: { id?: unknown }): Promise<{ removed: string }> { + const id = String(args.id ?? ""); + const store = await this.load(); + const device = store.devices.find((d) => d.id === id); + if (!device) throw new OpError(404, "that phone is not linked"); + store.devices = store.devices.filter((d) => d !== device); + await this.save(); + return { removed: device.name }; + } +} + +const clip = (text: unknown, max: number): string => { + const s = String(text ?? "") + .replace(/\s+/g, " ") + .trim(); + return s.length > max ? `${s.slice(0, max - 1)}…` : s; +}; +const list = (value: unknown): Record[] => + Array.isArray(value) ? (value as Record[]) : []; +const count = (value: unknown): number => (Number.isFinite(Number(value)) ? Number(value) : 0); + +/** What a linked phone is shown: counts, and the top line of each list. + * Built from sections the app already keeps; `at` is the oldest of them. */ +export function summary(sections: Record, at: number): Record { + const board = (sections.board ?? {}) as { counts?: Record; now?: unknown; next?: unknown }; + const census = (sections.census ?? {}) as { hands?: unknown; reviews?: unknown }; + const waiting = list((sections.sessions as { waiting?: unknown } | null)?.waiting).length; + const asks = list(sections.asks); + const questions = count((sections.questionCount as { total?: unknown } | null)?.total); + // The same sum as the app's own "Needs me" badge. + const hands = list(census.hands).length + waiting; + const reviews = list(census.reviews).length; + return { + v: 1, + at: at > 0 ? new Date(at).toISOString() : null, + now: { + count: count(board.counts?.claimed), + top: list(board.now) + .slice(0, 3) + .map((t) => ({ title: clip(t.title, 90), step: clip(t.step ?? t.goal ?? "", 120) })), + }, + next: { + count: count(board.counts?.queued), + top: list(board.next) + .slice(0, 3) + .map((t) => clip(t.title, 90)), + }, + needs: { total: questions + hands + reviews, questions, hands, reviews }, + asks: { + answered: asks.filter((a) => a.status === "answered").length, + waiting: asks.filter((a) => a.status !== "answered" && a.status !== "done").length, + }, + }; +} diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index 56cb9cd2be..131a2ef6a0 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -126,6 +126,38 @@ export class Docs { return s && s.goodAt > 0 ? s.data : null; } + /** Sections brought up to date for a caller that asks rarely (a + * phone's widget): stale ones are read again and waited for, up to + * `waitMs`. It does not count as someone looking, so it does not keep + * the background loop running. `missing` names the sections that have + * never been read; `at` is the oldest good read among the rest. */ + async current( + names: string[], + waitMs: number, + ): Promise<{ data: Record; at: number; missing: string[] }> { + const stale = names.filter((n) => { + const s = this.sections.get(n); + return s !== undefined && this.stale(s); + }); + if (stale.length > 0) { + let timer: ReturnType | undefined; + await Promise.race([ + Promise.all(stale.map((n) => this.refresh(n))), + new Promise((resolve) => { + timer = setTimeout(resolve, waitMs); + }), + ]); + clearTimeout(timer); + } + const read = names.map((n) => this.sections.get(n)?.goodAt ?? 0); + const good = read.filter((t) => t > 0); + return { + data: Object.fromEntries(names.map((n) => [n, this.good(n)])), + at: good.length > 0 ? Math.min(...good) : 0, + missing: names.filter((_, i) => read[i] === 0), + }; + } + logAct(act: Act): void { this.acts = [act, ...this.acts.filter((a) => a.id !== act.id)].slice(0, ACTS_KEPT); } diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 3270bd6651..af2c203424 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -7,12 +7,15 @@ // the check happens at this origin and does not rest on how the edge // reads a path. Three files a phone fetches before anyone has signed in // (the install manifest, its icons, the Android asset links) are public. +// Two more paths carry their own check instead of the sign-in: a linked +// phone's widget presents its own token there to read a short summary. import { mkdirSync, readFileSync } from "node:fs"; import { appendFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { actions, perform } from "./actions.ts"; import { AuthError, type Identity, identify } from "./auth.ts"; import { type Config, readConfig } from "./config.ts"; +import { Devices, Limiter, summary } from "./devices.ts"; import { DOC_NAMES, type DocName, Docs } from "./docs.ts"; import { Notifier } from "./notify.ts"; import { OpError, Ops } from "./ops.ts"; @@ -129,6 +132,69 @@ export interface Deps { actions?: ReturnType; work?: Work; push?: Push; + /** Phones linked to read the summary, with the limits on the two + * paths they use: those paths are reachable without sign-in, so they + * exist only when their limits do. */ + phones?: Phones; +} + +export interface Phones { + devices: Devices; + /** Tries at linking, and reads refused for a wrong token. */ + link: Limiter; + refused: Limiter; +} + +/** Sections the summary is built from, and how long a phone waits for + * them to be read again. */ +const SUMMARY_SECTIONS = ["board", "sessions", "census", "asks", "questionCount"]; +/** Under the five seconds the phone gives a read. */ +const SUMMARY_WAIT_MS = 3_500; +const DEVICE_BODY_LIMIT = 1024; + +/** A phone presents the verifier for a link the owner approved. */ +async function deviceLink(req: Request, deps: Deps, phones: Phones): Promise { + if (!phones.link.allow()) return json({ error: "too many tries: wait a minute" }, 429); + if (Number(req.headers.get("content-length") ?? "0") > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); + let verifier: unknown; + try { + const text = await req.text(); + if (text.length > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); + verifier = (JSON.parse(text) as { verifier?: unknown } | null)?.verifier; + } catch { + return json({ error: "body: expected a JSON object" }, 400); + } + const linked = await phones.devices.link(verifier); + if (!linked) return json({ error: "not approved" }, 404); + await deps + .audit({ + at: new Date().toISOString(), + who: `device:${linked.id}`, + via: "device", + action: "device.link", + phase: "done", + ok: true, + }) + .catch((error) => console.error(`pm-console: audit: ${(error as Error).message}`)); + return json(linked); +} + +/** A linked phone reads the counts and the top line of each list. */ +async function deviceSummary(req: Request, docs: Docs, phones: Phones): Promise { + const header = req.headers.get("authorization") ?? ""; + const device = header.startsWith("Bearer ") ? await phones.devices.check(header.slice(7)) : null; + if (!device) { + // Wrong tokens are counted; a linked phone is never slowed by them. + if (!phones.refused.allow()) return json({ error: "too many tries: wait a minute" }, 429); + // `unlinked` tells the app to forget its token; a refusal from + // anything else in front of this service does not carry it. + return json({ error: "this phone is not linked", unlinked: true }, 401); + } + const { data, at, missing } = await docs.current(SUMMARY_SECTIONS, SUMMARY_WAIT_MS); + // Before the queue has been read once there is nothing true to show: + // the phone keeps what it has and asks again. + if (missing.includes("board")) return json({ error: "not ready yet" }, 503); + return json(summary(data, at)); } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -243,6 +309,11 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-cache", ...SECURITY }, }); } + // Not behind the sign-in, and checked here instead: a linked phone. + if (deps.phones && deps.docs) { + if (path === `${BASE}/device/link` && method === "POST") return deviceLink(req, deps, deps.phones); + if (path === `${BASE}/device/summary` && method === "GET") return deviceSummary(req, deps.docs, deps.phones); + } const ours = path === BASE || path.startsWith(`${BASE}/`); if (!ours) { if (deps.cfg.dashboardUrl === null) return json({ error: "not found" }, 404); @@ -306,6 +377,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul repo: deps.cfg.repo, queue: deps.cfg.queue, androidApp: await Bun.file(deps.cfg.androidApk).exists(), + androidPackage: deps.cfg.androidPackage, }); case "overview": return json(await ops.overview()); @@ -339,6 +411,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul return gzipped(req, new TextEncoder().encode(doc.body), headers) ?? new Response(doc.body, { headers }); } if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status()); + if (seg.length === 1 && seg[0] === "devices" && deps.phones) return json(await deps.phones.devices.list()); if (seg.length === 1 && seg[0] === "question" && deps.work) { return json(await deps.work.question(query.get("set"), query.get("ledger"), query.get("qid"))); } @@ -522,13 +595,15 @@ if (import.meta.main) { const state = dirname(cfg.auditFile); const push = new Push(join(state, "push.json"), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`); new Notifier(docs, push, join(state, "notified.json")).start(); + const devices = new Devices(cfg.devicesFile); const deps: Deps = { cfg, ops, docs, work, push, - actions: actions(ops, work, push), + phones: { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }, + actions: actions(ops, work, push, devices), identify: (req, peer) => identify(req, cfg, { peer }), audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }), }; diff --git a/pm-stack/console/src/work.ts b/pm-stack/console/src/work.ts index a55b9839c4..2d13b0a651 100644 --- a/pm-stack/console/src/work.ts +++ b/pm-stack/console/src/work.ts @@ -27,6 +27,9 @@ const SET_ID = /^[A-Za-z0-9._:-]{1,160}$/; const REF = /^([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)#([1-9][0-9]{0,8})$/; const LEANS = ["none", "skeptical", "approve"] as const; const SUBMIT_BATCH = 200; +/** Replies shown in a prompt's thread, and how many pages back are read to find them. */ +const REPLIES_SHOWN = 6; +const REPLY_PAGES = 3; function clip(value: unknown, max: number): string { const s = typeof value === "string" ? value : ""; @@ -454,17 +457,21 @@ export class Work { if (i.comments > 0 && thread?.updated !== i.updated_at) { // The newest comments are on the last page. Bots that only link the // issue elsewhere (the board sync) are not the fleet answering. - const page = Math.max(1, Math.ceil(i.comments / 100)); - const comments = ( - (await this.ops.gh([`repos/${this.repo}/issues/${i.number}/comments?per_page=100&page=${page}`])) as { - body: string | null; - created_at: string; - user?: { type?: string } | null; - }[] - ).filter((c) => c.user?.type !== "Bot"); + // Read back from the last page until the replies shown are in + // hand: a page boundary, or a tail of bot comments, must not hide + // the answer. + type Comment = { body: string | null; created_at: string; user?: { type?: string } | null }; + const last = Math.max(1, Math.ceil(i.comments / 100)); + let comments: Comment[] = []; + for (let page = last; page >= 1 && last - page < REPLY_PAGES && comments.length < REPLIES_SHOWN; page--) { + const got = (await this.ops.gh([ + `repos/${this.repo}/issues/${i.number}/comments?per_page=100&page=${page}`, + ])) as Comment[]; + comments = [...got.filter((c) => c.user?.type !== "Bot"), ...comments]; + } thread = { updated: i.updated_at, - replies: comments.slice(-6).map((c) => ({ + replies: comments.slice(-REPLIES_SHOWN).map((c) => ({ you: (c.body ?? "").includes(OWNER_REPLY_MARK), at: c.created_at.slice(0, 19), text: clip((c.body ?? "").replace(OWNER_REPLY_MARK, "").trim(), 1500), diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts new file mode 100644 index 0000000000..2c55e5a36f --- /dev/null +++ b/pm-stack/console/test/app.test.ts @@ -0,0 +1,41 @@ +// The page's own small functions, run as the browser runs them. +// +// Oracles: the elapsed-time phrases and the device labels are written +// out here by hand for real inputs (two real browser names). +import { expect, test } from "bun:test"; +import { ago, band, deviceLabel } from "../public/app.js"; + +test("elapsed time reads as a phrase on its own, never 'just now ago'", () => { + const now = Date.parse("2026-11-22T12:00:00Z"); + const at = (seconds: number) => new Date(now - seconds * 1000).toISOString(); + expect(ago(at(0), now)).toBe("just now"); + expect(ago(at(89), now)).toBe("just now"); + expect(ago(at(90), now)).toBe("2 min ago"); + expect(ago(at(45 * 60), now)).toBe("45 min ago"); + expect(ago(at(5400), now)).toBe("2 h ago"); + expect(ago(at(26 * 3600), now)).toBe("26 h ago"); + expect(ago(at(3 * 86400), now)).toBe("3 d ago"); + // The queue store writes times without a zone: they are UTC. + expect(ago("2026-11-22T11:00:00", now)).toBe("60 min ago"); + // A time in the future (clock skew) is now, and no time is nothing. + expect(ago(at(-500), now)).toBe("just now"); + expect([ago("", now), ago(null, now), ago("not a time", now)]).toEqual(["", "", ""]); +}); + +test("a device is labelled by what it runs on, not by the engine's name", () => { + expect( + deviceLabel( + "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36", + ), + ).toBe("Linux; Android 10; K"); + expect(deviceLabel("Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0")).toBe( + "X11; Linux x86_64; rv:140.0", + ); + expect(deviceLabel("curl/8.5.0")).toBe("curl/8.5.0"); + expect(deviceLabel(`(${"x".repeat(100)})`)).toHaveLength(60); +}); + +test("priority bands in words", () => { + expect([10, 20, 30, 40, 50, 70, 90].map(band)).toEqual(["Top", "High", "Normal", "Low", "Low", "Later", "Later"]); + expect([band(null), band(undefined), band("")]).toEqual(["Normal", "Normal", "Normal"]); +}); diff --git a/pm-stack/console/test/devices.test.ts b/pm-stack/console/test/devices.test.ts new file mode 100644 index 0000000000..6663015610 --- /dev/null +++ b/pm-stack/console/test/devices.test.ts @@ -0,0 +1,499 @@ +// A phone linked to read the summary its home-screen widget shows. +// +// Oracles: the challenge is computed here with node's own SHA-256, not by +// the code under test; the store is a real file read back by the test, so +// "never keeps a token" is checked against the bytes on disk; and the +// HTTP checks run through the same `handle` the service uses, with a +// sign-in that always refuses, so anything answered was answered without +// it. +import { describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { actions, perform } from "../src/actions.ts"; +import { AuthError } from "../src/auth.ts"; +import { readConfig } from "../src/config.ts"; +import { challengeOf, Devices, Limiter, summary } from "../src/devices.ts"; +import { Docs } from "../src/docs.ts"; +import { OpError, Ops } from "../src/ops.ts"; +import { type Deps, handle } from "../src/server.ts"; +import { Work } from "../src/work.ts"; + +const CFG = readConfig({ HOME: "/h" }); +const VERIFIER = "v".repeat(43); +const OTHER = "w".repeat(43); +const hashOf = (text: string) => createHash("sha256").update(text).digest("base64url"); + +function store(now = { t: 1_800_000_000_000 }) { + const dir = mkdtempSync(join(tmpdir(), "pm-devices-")); + const file = join(dir, "devices.json"); + return { + now, + file, + devices: new Devices(file, () => now.t), + again: () => new Devices(file, () => now.t), + bytes: () => readFileSync(file, "utf8"), + done: () => rmSync(dir, { recursive: true, force: true }), + }; +} + +describe("linking a phone", () => { + test("the challenge is the SHA-256 of the verifier", () => { + expect(challengeOf(VERIFIER)).toBe(hashOf(VERIFIER)); + expect(challengeOf(VERIFIER)).toHaveLength(43); + }); + + test("an approved phone gets a token once, and only for its own verifier", async () => { + const s = store(); + try { + // Nothing approved: no verifier is worth anything. + expect(await s.devices.link(VERIFIER)).toBeNull(); + const { expires } = await s.devices.approve({ challenge: hashOf(VERIFIER), name: " Pocket " }); + expect(Date.parse(expires) - s.now.t).toBe(10 * 60_000); + // Another phone's verifier does not match the approved challenge. + expect(await s.devices.link(OTHER)).toBeNull(); + const linked = await s.devices.link(VERIFIER); + expect(linked?.token).toMatch(/^[A-Za-z0-9_-]{43}$/); + // The approval is spent. + expect(await s.devices.link(VERIFIER)).toBeNull(); + expect(await s.devices.list()).toEqual([ + { id: linked?.id as string, name: "Pocket", createdAt: new Date(s.now.t).toISOString(), seenAt: null }, + ]); + // The token is the phone's alone: the file holds neither it nor the verifier. + const onDisk = s.bytes(); + expect(onDisk).not.toContain(linked?.token as string); + expect(onDisk).not.toContain(VERIFIER); + expect(onDisk).toContain( + createHash("sha256") + .update(linked?.token as string) + .digest("hex"), + ); + // A restart reads the same store: the token still works. + expect((await s.again().check(linked?.token))?.id).toBe(linked?.id as string); + } finally { + s.done(); + } + }); + + test("an approval runs out, and malformed requests are refused", async () => { + const s = store(); + try { + await s.devices.approve({ challenge: hashOf(VERIFIER) }); + s.now.t += 10 * 60_000 + 1; + expect(await s.devices.link(VERIFIER)).toBeNull(); + for (const challenge of ["", "short", `${hashOf(VERIFIER)}x`, "!".repeat(43), 42, null]) { + await expect(s.devices.approve({ challenge })).rejects.toBeInstanceOf(OpError); + } + for (const verifier of ["", "x".repeat(42), "x".repeat(129), "é".repeat(43), 7, null, {}]) { + expect(await s.devices.link(verifier)).toBeNull(); + } + } finally { + s.done(); + } + }); + + test("a token is checked by its hash, seen times are kept, and removing a phone ends it", async () => { + const s = store(); + try { + await s.devices.approve({ challenge: hashOf(VERIFIER) }); + const linked = await s.devices.link(VERIFIER); + const token = linked?.token as string; + for (const wrong of ["", "x".repeat(43), `${token}x`, token.slice(1), 5, null]) { + expect(await s.devices.check(wrong)).toBeNull(); + } + expect((await s.devices.check(token))?.seenAt).toBe(new Date(s.now.t).toISOString()); + // Seen again soon after: the time is not rewritten. + const first = s.now.t; + s.now.t += 60_000; + expect((await s.devices.check(token))?.seenAt).toBe(new Date(first).toISOString()); + s.now.t += 10 * 60_000; + expect((await s.devices.check(token))?.seenAt).toBe(new Date(s.now.t).toISOString()); + await expect(s.devices.remove({ id: "nope" })).rejects.toThrow(/not linked/); + expect(await s.devices.remove({ id: linked?.id })).toEqual({ removed: "Android phone" }); + expect(await s.devices.check(token)).toBeNull(); + expect(await s.again().check(token)).toBeNull(); + } finally { + s.done(); + } + }); + + test("no more than eight phones, and no more than four requests waiting", async () => { + const s = store(); + try { + for (let n = 0; n < 8; n++) { + const verifier = String(n).repeat(43); + await s.devices.approve({ challenge: hashOf(verifier) }); + expect(await s.devices.link(verifier)).not.toBeNull(); + } + await expect(s.devices.approve({ challenge: hashOf(VERIFIER) })).rejects.toThrow(/8 phones/); + const fresh = store(); + try { + // Five requests approved: the oldest falls off, the newest four stand. + const verifiers = ["a", "b", "c", "d", "e"].map((c) => c.repeat(43)); + for (const verifier of verifiers) await fresh.devices.approve({ challenge: hashOf(verifier) }); + expect(await fresh.devices.link(verifiers[0])).toBeNull(); + expect(await fresh.devices.link(verifiers[4])).not.toBeNull(); + } finally { + fresh.done(); + } + } finally { + s.done(); + } + }); +}); + +describe("the limiter", () => { + test("so many in a window, then none until the window turns", () => { + const now = { t: 0 }; + const limit = new Limiter(3, 1000, () => now.t); + expect([limit.allow(), limit.allow(), limit.allow(), limit.allow()]).toEqual([true, true, true, false]); + now.t = 999; + expect(limit.allow()).toBe(false); + now.t = 1000; + expect(limit.allow()).toBe(true); + }); +}); + +describe("the summary", () => { + const sections = { + board: { + counts: { claimed: 4, queued: 2, blocked: 400 }, + now: [ + { title: "Fix the broker\nreconnect", step: "Run the soak test" }, + { title: "Two", goal: "It passes" }, + { title: "Three" }, + { title: "Four" }, + ], + next: [{ title: "N1" }, { title: "N2" }], + }, + sessions: { moving: [{}, {}], waiting: [{}, {}] }, + census: { hands: [{}, {}, {}], reviews: [{}], other: [{}, {}, {}, {}, {}] }, + asks: [{ status: "answered" }, { status: "working" }, { status: "done" }, { status: "queued" }], + questionCount: { total: 7, sets: 2 }, + }; + + test("counts and the top lines, with the same needs sum as the app's badge", () => { + expect(summary(sections, 1_800_000_000_000)).toEqual({ + v: 1, + at: "2027-01-15T08:00:00.000Z", + now: { + count: 4, + top: [ + { title: "Fix the broker reconnect", step: "Run the soak test" }, + { title: "Two", step: "It passes" }, + { title: "Three", step: "" }, + ], + }, + next: { count: 2, top: ["N1", "N2"] }, + // 7 questions + (3 hands + 2 sessions waiting) + 1 review; "other" is the fleet's to decide. + needs: { total: 13, questions: 7, hands: 5, reviews: 1 }, + asks: { answered: 1, waiting: 2 }, + }); + }); + + test("sections that have never been read count as nothing, and long lines are cut", () => { + expect(summary({}, 0)).toEqual({ + v: 1, + at: null, + now: { count: 0, top: [] }, + next: { count: 0, top: [] }, + needs: { total: 0, questions: 0, hands: 0, reviews: 0 }, + asks: { answered: 0, waiting: 0 }, + }); + const long = summary({ board: { counts: {}, now: [{ title: "x".repeat(300), step: "y".repeat(300) }] } }, 1) as { + now: { top: { title: string; step: string }[] }; + }; + expect(long.now.top[0].title).toHaveLength(90); + expect(long.now.top[0].title.endsWith("…")).toBe(true); + expect(long.now.top[0].step).toHaveLength(120); + }); +}); + +describe("over HTTP, without the sign-in", () => { + function setup(failing: string[] = []) { + const s = store(); + const reads: string[] = []; + const docs = new Docs( + Object.fromEntries( + [ + "board", + "sessions", + "census", + "asks", + "questionCount", + "questions", + "prs", + "priorities", + "agents", + "services", + "more", + ].map((name) => [ + name, + { + ttlMs: 10_000, + load: async () => { + reads.push(name); + if (failing.includes(name)) throw new Error(`${name} is down`); + return name === "board" + ? { counts: { claimed: 2, queued: 1 }, now: [{ title: "T" }], next: [] } + : name === "questionCount" + ? { total: 3 } + : []; + }, + }, + ]), + ), + () => s.now.t, + ); + const audited: Record[] = []; + const ops = new Ops(CFG, async () => ({ code: 0, stdout: "", stderr: "" })); + const deps: Deps = { + cfg: CFG, + ops, + docs, + phones: { + devices: s.devices, + link: new Limiter(3, 60_000, () => s.now.t), + refused: new Limiter(2, 60_000, () => s.now.t), + }, + actions: actions(ops, new Work(ops), undefined, s.devices), + // Sign-in always refuses: whatever answers below answered without it. + identify: async () => { + throw new AuthError(401, "sign-in required"); + }, + audit: async (e) => { + audited.push(e); + }, + }; + const link = (verifier: unknown, method = "POST") => + handle( + new Request("https://pm.security.cab/console/device/link", { + method, + body: method === "POST" ? JSON.stringify({ verifier }) : undefined, + headers: { host: "pm.security.cab", "content-type": "application/json" }, + }), + deps, + ); + const read = (token?: string, path = "/console/device/summary") => + handle( + new Request(`https://pm.security.cab${path}`, { + headers: { host: "pm.security.cab", ...(token === undefined ? {} : { authorization: `Bearer ${token}` }) }, + }), + deps, + ); + return { ...s, deps, docs, reads, audited, link, read }; + } + + test("a phone links with its verifier and then reads the summary with its token", async () => { + const w = setup(); + try { + expect((await w.link(VERIFIER)).status).toBe(404); + await perform(w.deps.actions as NonNullable, w.docs, "device.approve", { + challenge: hashOf(VERIFIER), + name: "Pocket", + }); + const res = await w.link(VERIFIER); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + const { token, id } = (await res.json()) as { token: string; id: string }; + // The record of the link names the device and carries no token. + expect(w.audited).toEqual([expect.objectContaining({ action: "device.link", who: `device:${id}`, ok: true })]); + expect(JSON.stringify(w.audited)).not.toContain(token); + + const got = await w.read(token); + expect(got.status).toBe(200); + expect(await got.json()).toEqual({ + v: 1, + at: new Date(w.now.t).toISOString(), + now: { count: 2, top: [{ title: "T", step: "" }] }, + next: { count: 1, top: [] }, + needs: { total: 3, questions: 3, hands: 0, reviews: 0 }, + asks: { answered: 0, waiting: 0 }, + }); + // Only the sections the summary is built from were read. + expect([...w.reads].sort()).toEqual(["asks", "board", "census", "questionCount", "sessions"]); + // Read again at once: served from memory. + await w.read(token); + expect(w.reads).toHaveLength(5); + // A widget's read does not count as someone looking: the loop stays idle. + w.now.t += 60_000; + w.docs.tick(); + expect(w.reads).toHaveLength(5); + // The next read, after the sections have aged, reads them again and waits for them. + expect(((await (await w.read(token)).json()) as { at: string }).at).toBe(new Date(w.now.t).toISOString()); + expect(w.reads).toHaveLength(10); + } finally { + w.done(); + } + }); + + test("without a linked token nothing is said, and only these two paths skip the sign-in", async () => { + const w = setup(); + try { + expect((await w.read()).status).toBe(401); + expect(await (await w.read("x".repeat(43))).json()).toEqual({ + error: "this phone is not linked", + unlinked: true, + }); + expect(w.reads).toEqual([]); + // Everything beside them is behind the sign-in, which refuses here. + for (const path of [ + "/console/device", + "/console/device/", + "/console/device/summary/", + "/console/device/other", + "/console/devices", + "/console/api/devices", + ]) { + expect(await (await w.read(undefined, path)).json()).toEqual({ error: "sign-in required" }); + } + expect(await (await w.link(VERIFIER, "GET")).json()).toEqual({ error: "sign-in required" }); + const post = await handle( + new Request("https://pm.security.cab/console/device/summary", { + method: "POST", + body: "{}", + headers: { host: "pm.security.cab" }, + }), + w.deps, + ); + expect(await post.json()).toEqual({ error: "sign-in required" }); + } finally { + w.done(); + } + }); + + test("tries are limited, and wrong tokens never slow a linked phone", async () => { + const w = setup(); + try { + await perform(w.deps.actions as NonNullable, w.docs, "device.approve", { + challenge: hashOf(VERIFIER), + }); + const { token } = (await (await w.link(VERIFIER)).json()) as { token: string }; + // Two wrong tokens are answered; the third is turned away unread. + expect([ + (await w.read("a".repeat(43))).status, + (await w.read("b".repeat(43))).status, + (await w.read("c".repeat(43))).status, + ]).toEqual([401, 401, 429]); + expect((await w.read(token)).status).toBe(200); + // The link path took one try above; two more are answered, then none. + expect([(await w.link(OTHER)).status, (await w.link(OTHER)).status, (await w.link(OTHER)).status]).toEqual([ + 404, 404, 429, + ]); + w.now.t += 60_000; + expect((await w.link(OTHER)).status).toBe(404); + // A body that is too large or not JSON is refused before anything is hashed. + const big = await handle( + new Request("https://pm.security.cab/console/device/link", { + method: "POST", + body: JSON.stringify({ verifier: "x".repeat(2000) }), + headers: { host: "pm.security.cab" }, + }), + w.deps, + ); + expect(big.status).toBe(413); + const junk = await handle( + new Request("https://pm.security.cab/console/device/link", { + method: "POST", + body: "not json", + headers: { host: "pm.security.cab" }, + }), + w.deps, + ); + expect(junk.status).toBe(400); + } finally { + w.done(); + } + }); + + test("before the queue has been read there is nothing to show; a missing side list does not stop the rest", async () => { + const down = setup(["board"]); + try { + await perform(down.deps.actions as NonNullable, down.docs, "device.approve", { + challenge: hashOf(VERIFIER), + }); + const { token } = (await (await down.link(VERIFIER)).json()) as { token: string }; + const res = await down.read(token); + expect(res.status).toBe(503); + expect(await res.json()).toEqual({ error: "not ready yet" }); + } finally { + down.done(); + } + const partial = setup(["census", "asks"]); + try { + await perform(partial.deps.actions as NonNullable, partial.docs, "device.approve", { + challenge: hashOf(VERIFIER), + }); + const { token } = (await (await partial.link(VERIFIER)).json()) as { token: string }; + const res = await partial.read(token); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ + at: new Date(partial.now.t).toISOString(), + now: { count: 2 }, + needs: { total: 3, questions: 3, hands: 0 }, + }); + expect(await partial.docs.current(["board", "census", "asks", "nope"], 10)).toMatchObject({ + at: partial.now.t, + missing: ["census", "asks", "nope"], + }); + } finally { + partial.done(); + } + }); + + test("with no limits set there are no open paths at all", async () => { + const w = setup(); + try { + const bare = { ...w.deps, phones: undefined }; + const link = await handle( + new Request("https://pm.security.cab/console/device/link", { + method: "POST", + body: JSON.stringify({ verifier: VERIFIER }), + headers: { host: "pm.security.cab" }, + }), + bare, + ); + expect(await link.json()).toEqual({ error: "sign-in required" }); + const read = await handle( + new Request("https://pm.security.cab/console/device/summary", { + headers: { host: "pm.security.cab", authorization: `Bearer ${"x".repeat(43)}` }, + }), + bare, + ); + expect(await read.json()).toEqual({ error: "sign-in required" }); + } finally { + w.done(); + } + }); + + test("the owner sees linked phones by name and can remove one; removing is recorded by id", async () => { + const w = setup(); + try { + const table = w.deps.actions as NonNullable; + await perform(table, w.docs, "device.approve", { challenge: hashOf(VERIFIER), name: "Pocket" }); + const { token, id } = (await (await w.link(VERIFIER)).json()) as { token: string; id: string }; + const asOwner = { + ...w.deps, + identify: async () => ({ via: "cloudflare-access", email: "drewrypope@gmail.com" }), + }; + const listed = await handle( + new Request("https://pm.security.cab/console/api/devices", { headers: { host: "pm.security.cab" } }), + asOwner, + ); + const body = await listed.text(); + expect(JSON.parse(body)).toEqual([ + { id, name: "Pocket", createdAt: new Date(w.now.t).toISOString(), seenAt: null }, + ]); + expect(body).not.toContain(token); + expect(table["device.remove"].audit({ id, extra: "x" })).toEqual({ id }); + expect(table["device.approve"].audit({ challenge: hashOf(VERIFIER), name: "Pocket" })).toEqual({ + name: "Pocket", + }); + await perform(table, w.docs, "device.remove", { id }); + expect((await w.read(token)).status).toBe(401); + } finally { + w.done(); + } + }); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index e0fac4bcf9..65ae0c90cd 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -556,25 +556,49 @@ describe("what the owner asks for in his own words", () => { [5, "waiting", null, "words 5", []], ]); expect(asks[3].replies[1].text).toBe("and I say"); - // A long thread is read from its last page, and a bot that only links - // the issue somewhere else is not the fleet answering. + // A long thread is read from its last page backwards until six replies + // are in hand, and a bot that only links the issue somewhere else is + // not the fleet answering. + const real = (n: number) => ({ body: `reply ${n}`, created_at: "2026-11-22T02:00:00Z", user: { type: "User" } }); + const bot = { + body: "[CODE-1](https://kaneo.example/task/1)", + created_at: "2026-11-22T02:01:00Z", + user: { type: "Bot" }, + }; + const pages: Record = { + // 250 comments: the last page holds one answer and a bot's link, the page before it the rest. + "7:3": [real(201), bot], + "7:2": [real(101), real(102), real(103), real(104), real(105), real(106), real(107)], + "7:1": [real(1)], + // 101 comments: the answer is the last comment of page 1, and page 2 is only the bot. + "8:2": [bot], + "8:1": [real(99), real(100)], + }; const long = world({ - commands: (argv) => - argv[3].includes("/issues?labels=") - ? JSON.stringify([found(7, "open", 250)]) - : JSON.stringify([ - { body: "the real answer", created_at: "2026-11-22T02:00:00Z", user: { type: "User" } }, - { - body: "[CODE-1](https://kaneo.example/task/1)", - created_at: "2026-11-22T02:01:00Z", - user: { type: "Bot" }, - }, - ]), + commands: (argv) => { + if (argv[3].includes("/issues?labels=")) return JSON.stringify([found(7, "open", 250), found(8, "open", 101)]); + const m = /issues\/(\d+)\/comments\?per_page=100&page=(\d+)$/.exec(argv[3]); + return JSON.stringify(m ? (pages[`${m[1]}:${m[2]}`] ?? []) : []); + }, }); - const [thread] = await new Work(long.ops).asks(); - expect(long.gh()[1]).toEqual([`repos/${REPO}/issues/7/comments?per_page=100&page=3`]); - expect(thread.replies.map((r) => r.text)).toEqual(["the real answer"]); - expect(thread.status).toBe("answered"); + const [deep, boundary] = await new Work(long.ops).asks(); + expect(long.gh().slice(1)).toEqual([ + [`repos/${REPO}/issues/7/comments?per_page=100&page=3`], + [`repos/${REPO}/issues/7/comments?per_page=100&page=2`], + [`repos/${REPO}/issues/8/comments?per_page=100&page=2`], + [`repos/${REPO}/issues/8/comments?per_page=100&page=1`], + ]); + // Six replies, oldest first, across the page boundary; the bot's link is not one of them. + expect(deep.replies.map((r) => r.text)).toEqual([ + "reply 103", + "reply 104", + "reply 105", + "reply 106", + "reply 107", + "reply 201", + ]); + expect(boundary.replies.map((r) => r.text)).toEqual(["reply 99", "reply 100"]); + expect([deep.status, boundary.status]).toEqual(["answered", "answered"]); // Threads are read again only when the issue has changed. await work.asks(); expect(commentReads).toBe(3);