diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 8b16e4c..85dac9e 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -16,6 +16,14 @@ "label": "Workshop planner (development environment in Codespaces)", "onAutoForward": "notify", "visibility": "private" + }, + "10270": { + "label": "DocumentDB Site A \u2014 do not forward", + "onAutoForward": "ignore" + }, + "10271": { + "label": "DocumentDB Site B \u2014 do not forward", + "onAutoForward": "ignore" } }, "onCreateCommand": "npm ci --ignore-scripts --no-audit --no-fund", @@ -27,5 +35,8 @@ "ms-azuretools.vscode-documentdb" ] } + }, + "otherPortsAttributes": { + "onAutoForward": "ignore" } } diff --git a/.devcontainer/organizer/devcontainer.json b/.devcontainer/organizer/devcontainer.json index 46bba90..54fe1f5 100644 --- a/.devcontainer/organizer/devcontainer.json +++ b/.devcontainer/organizer/devcontainer.json @@ -20,6 +20,14 @@ "label": "Organizer development planner", "onAutoForward": "notify", "visibility": "private" + }, + "10270": { + "label": "DocumentDB Site A \u2014 do not forward", + "onAutoForward": "ignore" + }, + "10271": { + "label": "DocumentDB Site B \u2014 do not forward", + "onAutoForward": "ignore" } }, "onCreateCommand": "npm ci --ignore-scripts --no-audit --no-fund", @@ -31,5 +39,8 @@ "ms-azuretools.vscode-documentdb" ] } + }, + "otherPortsAttributes": { + "onAutoForward": "ignore" } } diff --git a/.dockerignore b/.dockerignore index bceca0f..6883715 100644 --- a/.dockerignore +++ b/.dockerignore @@ -7,3 +7,6 @@ node_modules coverage playwright-report test-results + +# Secret-bearing local extension handoff; never build, commit, or share. +.workshop-private/ diff --git a/.env.example b/.env.example index 907d098..d6bb2b1 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,10 @@ WORKSHOP_MODE=starter WORKSHOP_LOCATION=laptop WORKSHOP_PUBLIC_HOST= WORKSHOP_PORT=3000 +# Host/outer-dev-container loopback ports for the VS Code extension, not app DNS. +# If occupied, choose two distinct unused ports; never stop someone else's services. +SITE_A_EXTENSION_PORT=10270 +SITE_B_EXTENSION_PORT=10271 # The attendee Compose file always starts at local (Site A). # ACTIVE_TARGET is used only by the explicit presenter override. ACTIVE_TARGET=local diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 78705a3..7d1cdbe 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -22,6 +22,8 @@ jobs: - run: npm run test:docs - name: Start and seed only the two self-hosted sites run: npm run workspace:start + - name: Verify remote-extension loopback endpoints and independent authentication + run: npm run extension:check - name: Exercise two independent database servers run: docker compose -f compose.yaml exec -T app npm run test:database - name: Verify complete-reference recovery diff --git a/.gitignore b/.gitignore index 6c6846d..349d33f 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ playwright-report/ test-results/ .DS_Store Thumbs.db + +# Secret-bearing local extension handoff; never build, commit, or share. +.workshop-private/ diff --git a/README.md b/README.md index 4b2904b..a71f337 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,11 @@ On the preceding main source, a fresh **two-core attendee Codespace** reached bo sites in **4m47s**, actual Site A/B checks passed **34/34 plus integration**, Google Calendar imported **3/3 events**, and a real **local Mac mini → managed Azure** round trip passed (temporary cloud resource cleaned up). See the -[acceptance record](docs/acceptance.md) for scope. **This reconnect/onboarding -revision also passed a restarted-Codespace attendee run: 47/47 tests, actual -browser exercises, and cold first-connection recovery in the same app process.** +[acceptance record](docs/acceptance.md) for scope. **The preceding reconnect/onboarding revision also passed a restarted-Codespace +attendee run: 47/47 tests, actual browser exercises, and cold first-connection +recovery in the same app process. This extension-integrated revision still needs +a fresh Codespace and actual extension GUI acceptance; those earlier counts do +not prove it.** Timed human classroom delivery and conference-laptop networking are not verified; automated checks are not substitutes. @@ -43,16 +45,31 @@ cross-listings, unresolved disagreements, and the excluded invalid break time. 3. When the terminal says **Site A and Site B are ready and both catalogs are seeded**, select **Ports** beside Terminal in the editor's bottom panel. Find row **3000** and use **Open in Browser** (globe). Keep visibility **Private**. -4. Follow the [attendee guide](docs/lab.md), also linked persistently in the planner. +4. Run `npm run extension:connections`, then follow the + [private connection steps](docs/extension.md#connect-the-two-existing-sites-privately) + to save **Workshop — Site A** and **Workshop — Site B** in the DocumentDB + extension's **Connections** tree. No Azure sign-in or **Set Up Local** wizard. + The helper never prints credentials; keep its generated file private. +5. Follow the [attendee guide](docs/lab.md), also linked persistently in the planner. The blue **Exercise 1** checkpoint is intentional, not a broken database. -5. Edit in Codespaces: **Explorer → exercises → starter → repository.js**, or +6. Edit in Codespaces: **Explorer → exercises → starter → repository.js**, or **Ctrl/Cmd+P**, then type `exercises/starter/repository.js`. A GitHub file link is a read-only source view, not the editable file in your running Codespace. Both Codespaces profiles include the official [DocumentDB for VS Code extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-documentdb) -(`ms-azuretools.vscode-documentdb`). It does not connect to or provision a database -automatically; the workshop's Compose setup still owns Site A and Site B. +(`ms-azuretools.vscode-documentdb`; guide targets version 1.0.0). Use it throughout +the lab: inspect catalog JSON before TODO 1, see favorite writes after TODO 2, +compare sites around the **app's** selected copy, and observe index/migration +changes. The extension does not implement your driver code or copy favorites +automatically. Compose still owns both containers; saved connections do not +turn them into extension-managed Local instances. + +Only the app's **3000** port is privately forwarded. Database ports **10270/10271** +are bound to outer-container loopback for the remote extension and ignored by +auto-forwarding; never forward them or make them public. Both host ports are +configurable without touching credentials/volumes. See the +[networking explanation and CLI fallback](docs/extension.md). Every workshop terminal command runs **inside Codespaces**, unless explicitly following the optional [laptop-local appendix](docs/local.md). diff --git a/compose.yaml b/compose.yaml index 62c42de..e06c78e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,6 +4,9 @@ services: environment: USERNAME: ${DOCUMENTDB_USERNAME:?Run the setup command first} PASSWORD: ${DOCUMENTDB_PASSWORD:?Run the setup command first} + # Reachable by the remote VS Code extension in the outer dev container only. + ports: + - "127.0.0.1:${SITE_A_EXTENSION_PORT:-10270}:10260" volumes: - documentdb-data:/data stop_grace_period: 30s @@ -13,6 +16,8 @@ services: environment: USERNAME: ${SITE_B_USERNAME:?Run the setup command first} PASSWORD: ${SITE_B_PASSWORD:?Run the setup command first} + ports: + - "127.0.0.1:${SITE_B_EXTENSION_PORT:-10271}:10260" volumes: - documentdb-site-b-data:/data stop_grace_period: 30s diff --git a/docs/acceptance.md b/docs/acceptance.md index a4ae1ce..7db1143 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -1,5 +1,74 @@ # Acceptance record and remaining gates +## Extension-integrated revision — pending live GUI acceptance + +Implementation verification recorded October 18, 2026, based on canonical main +`56e769c026cc709b857f28fc45bb3048dc53b675`. This revision integrates the official +DocumentDB for VS Code **1.0.0** explorer into the existing 105-minute developer +lab. The older counts and screenshots below **do not prove this extension path**. + +Executed locally on macOS with Node 24: + +- `npm ci --ignore-scripts --no-audit --no-fund` completed. +- Offline suite: **58 tests, 57 passed, one existing Linux-only organizer-file + test skipped**. New checks cover `.env` literal/quoted parsing, safe rejection + of duplicates/interpolation/partial credentials, credential-free URI handoff, + private file ownership/permissions and atomic repeatability, unchanged `.env`, + no cloud export, no secrets in console output, loopback/forwarding policy, + reconnect-project port isolation, and bounded read-only playground contracts. +- Local Markdown links checked; no network requests in the docs check. Public + extension docs/source were separately read to verify the connection wizard, + local TLS choice, Collection View/Indexes controls and **prebound** playground + model. This is source review, not an executed GUI result. +- No Docker stack, existing attendee Codespace, cloud resource, database notebook, + or shared extension storage was changed by this implementation check. + +**Required live checks still pending for this revision:** + +1. Create a **fresh** attendee Codespace from the final merged source. Record + cold-start timing, extension version/remote host and actual resource needs. + Verify only app port **3000 / Private** is forwarded, not database ports + **10270/10271** or custom database ports. Inspect actual loopback bindings. +2. Run `npm run extension:connections`; check ignored private directory `700` + and file `600`, unchanged `.env`, and no secrets in terminal output. Run + `npm run extension:check` from the outer container: both authenticated local + reads and cross-site credential rejection must pass. This is only endpoint + proof, not the next GUI checkpoint. +3. In the actual extension GUI, use **New Connection → Connection String**, the + credential-free URI, local **Allow invalid certificates** choice (TLS stays + on), and **Username and Password** prompts. Save/rename both **Workshop — + Site A** and **Workshop — Site B**. Show **both saved Connections tree nodes** + expanded to the actual database and `sessions`/`workshop_meta`. No Azure login + or third local instance. Do not require Compose containers to appear as + extension-managed Local instances. Close private files before screenshots. +4. Browse Site A session JSON before TODO 1; show `_id`, `startsAt` and the real + `catalogVersion`. Complete both TODOs in the editor, save favorites in the app, + then show actual favorite `_id`/`savedAt` in the extension. Restart persistence + and the existing browser checkpoints must still work. +5. Compare A/B favorite views before and after the **app's selected copy**. Retry + that direction and verify one destination document with unchanged destination + `savedAt`, then copy a new favorite back. No extension **Copy Collection**. +6. Create the index via CLI and inspect actual `{ startsAt: 1, _id: 1 }` keys in + the extension's **Indexes** tab. Observe the **same session `_id`** before/after + CLI migration, version 1/no attendanceMode → version 2/in-person, with unchanged + favorite timestamp. Rerun migration: zero changed. Never reset an old notebook + to manufacture a before state. +7. Optional prebound `.documentdb.js` templates: actual CodeLens Run from the + selected database, at most five sample sessions, and **17 groups / 74 Monday + entries** for the aggregation. Test a custom database name by creating a new + playground from that database node, not editing a hidden connection setting. +8. Re-run real two-server integration, isolated reconnect/interruption regression + and calendar download on this source. The reconnect override must publish **no + database ports**, avoiding collisions with the main attendee stack or parallel + harnesses. Existing first-connection recovery must retain the same app process. + +CI now includes the read-only host-side `extension:check` after startup, alongside +existing database integration and reconnect jobs. Added CI steps are not claimed +as executed here. If a GUI checkpoint is blocked, record the blocker and use +`inspect` to continue the lab; **do not mark the extension accepted from CLI-only +or offline tests**. Presenter Azure extension use remains optional and requires +separate approved access with fully validated TLS; no attendee subscription. + ## Executed evidence before the reconnect / attendee-polish revision Recorded October 17, 2026 against the preceding main source @@ -127,7 +196,9 @@ npm run test:reconnect Requires Docker Compose **2.24.4+** for its port override. It creates a fresh random `ato-reconnect-*` project, private temporary `.env`, independent volumes and a -random **loopback-only** app port. It ignores ambient workshop credentials and +random **loopback-only** app port. The override removes both database port +mappings, so parallel harness projects never reserve the attendee extension +ports. It ignores ambient workshop credentials and never adopts an existing project. It stops/starts only its Site B, captures sanitized pass/fail receipts, and removes **only its own ephemeral project and volumes** through a single idempotent cleanup path. **SIGINT / SIGTERM** abort diff --git a/docs/extension.md b/docs/extension.md new file mode 100644 index 0000000..19cb615 --- /dev/null +++ b/docs/extension.md @@ -0,0 +1,181 @@ +# DocumentDB explorer: the lab's second view + +Use the official **DocumentDB for VS Code** extension +[`ms-azuretools.vscode-documentdb`](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-documentdb), +with the **1.0.0** UI described here. Both Codespaces profiles preinstall it. +It is the required visual database explorer throughout the lab, not a separate +Azure demo. Your two TODOs still implement real MongoDB-driver application code; +connecting an editor does not implement them or switch the app's target. + +## Connect the two existing sites privately + +Wait for workshop setup to finish. Run in the **Codespaces terminal**, not inside +`app` and not on your laptop: + +```sh +npm run extension:connections +``` + +This reads the existing `.env` as data and generates +`.workshop-private/extension-connections.txt`. It prints only the path, labels, +ports and database names, never a URI or credential. The directory is mode `700` +and the file `600`; both Git and Docker exclude it. Re-running atomically updates +only this helper's generated file, never `.env`, database users or volumes. +It exports **only local** settings, even if an old `.env` contains Azure settings. + +1. Open that private file with **Ctrl/Cmd+P** in the Codespaces editor. Do not use + `cat`, put it in a screenshot, commit it, sync it, or share your screen while it + is visible. There are separate **Site A / Site B** sections, including your + actual database names (which may differ from `ato_workshop`). +2. Open the Command Palette (**F1**) and select **DocumentDB: New Connection…**, + then **Connection String**. This attaches an existing database. Do **not** use + **Set Up Local**: Compose already owns two instances; that wizard would create + an unrelated third one. No Azure sign-in or subscription is wanted. +3. From the Site A section, copy **only the credential-free connection string** + into the URI input. That field is **not masked**. Never paste a password-bearing + URI there. The generated URI points to `127.0.0.1`, selects your database, and + specifies TLS, `SCRAM-SHA-256`, `authSource=admin` and `directConnection=true`. +4. For this loopback connection only, choose **Allow invalid certificates** when + the TLS picker appears. TLS encryption stays **on**; this accepts the existing + local development server's self-signed certificate. It is not “disable TLS,” + not a global setting, and never applies to Azure or another remote service. +5. If asked for an authentication method, choose **Username and Password** + (native authentication). Enter the section's username and paste its password only + into the **masked password prompt**. Do not select Microsoft Entra/Azure login. +6. In the extension's **Connections** tree, the new connection may initially be + named by host/port. Right-click it → **Rename Connection**, and name it + **Workshop — Site A**. Repeat steps 2–6 with Site B's own values and name it + **Workshop — Site B**. These are separate credentials, not interchangeable. +7. Close the private file before sharing your screen. Expand each connection and + the database named in your private instructions. Do not browse `admin` or + another application's database. An empty `favorites` collection may not exist + until the first save; that is normal. + +Expected **saved Connections** tree (use your custom database names if applicable): + +```text +Workshop — Site A + ato_workshop + sessions + workshop_meta + favorites (appears after the first save) +Workshop — Site B + ato_workshop + sessions + workshop_meta + favorites (appears after a save/copy into B) +``` + +These connections make the two databases visible for exploration. They do **not** +adopt Compose containers into the extension's managed **Local** instances list: +that list owns only instances created by its own setup workflow. Use this +checkout's Compose commands (or a separately installed Container Tools view) for +container lifecycle, and DocumentDB **Connections** for data. Never create fake +extension ownership records or run a third-database wizard to make a list appear. + +The connection flow is based on the extension's public +[connection-string step](https://github.com/microsoft/vscode-documentdb/blob/main/src/commands/newConnection/PromptConnectionStringStep.ts), +[local TLS choice](https://github.com/microsoft/vscode-documentdb/blob/main/src/commands/newConnection/PromptTlsExceptionStep.ts), +and [authentication labels](https://github.com/microsoft/vscode-documentdb/blob/main/src/documentdb/auth/AuthMethod.ts). +The exact fresh-Codespace GUI acceptance is tracked separately in +[the acceptance record](acceptance.md#extension-integrated-revision--pending-live-gui-acceptance). + +The helper supports generated settings and ordinary single/double-quoted legacy +values. It rejects duplicate bindings, interpolation, multiline values and +ambiguous quoting rather than guessing. If it fails, have a helper review `.env` +**privately**; never source it as a shell script or regenerate credentials for an +existing volume. The workshop does not store connection strings in committed +VS Code settings, create credential-bearing deep links, or automate SecretStorage. +The extension itself retains the connection you deliberately add: use your own +Codespace/editor account, not a shared authenticated environment. + +## Why these ports are not web links + +In Codespaces the extension runs remotely in the **outer development container**. +The databases are inside its Docker-in-Docker Compose network. The extension uses +these loopback-only published endpoints: + +- Site A: `127.0.0.1:10270` → `documentdb:10260`. +- Site B: `127.0.0.1:10271` → `documentdb-site-b:10260`. + +The app still uses Compose DNS on port `10260`; do not replace its hostnames with +these editor endpoints. Your laptop's localhost is not the Codespace's localhost. +Never open database ports in a browser or forward them, publicly **or privately**. +Both dev-container profiles ignore automatic forwarding for `10270`/`10271` and +all other unlisted ports, including custom database ports. Only app port `3000` +is explicitly forwarded, with **Private** visibility. Do not alter that policy. + +If a port is occupied, Compose reports a bind/port-allocation error. Do not kill +another process or stack. In this checkout's private `.env`, choose two distinct +unused ports using `SITE_A_EXTENSION_PORT` and `SITE_B_EXTENSION_PORT`; defaults +are `10270` and `10271`. Do not export conflicting shell overrides. Reapply only +this same Compose project (the same directory/project name and volumes): + +```sh +docker compose -f compose.yaml up -d --wait --wait-timeout 240 +npm run extension:connections +``` + +Use the complete/presenter override as well if that is your intentional mode. +Reconnect the extension using the regenerated instructions. Never change database +credentials, delete volumes, or change projects to repair a port collision. + +A helper can test both published endpoints, TLS and independent authentication, +without printing secrets or changing data: + +```sh +npm run extension:check +``` + +This runs from the outer Codespace/host where the extension runs. It verifies a +bounded authenticated catalog read and rejects the other site's credentials on +each endpoint. It is **not** proof that the extension GUI connected successfully. + +## Browse, query and refresh + +Expand a collection and double-click its **Documents** child, or use the +collection's **leftmost inline icon** to open **Collection View**. Use the +**Filter**, **Project**, and **Sort** editors and the JSON document view. The +[official collection-query guide](https://microsoft.github.io/vscode-documentdb/user-manual/collection-view-querying) +describes these controls. + +- Read `workshop_meta` with Filter `{ _id: "catalog" }`: note its `fingerprint` + and `ready: true`. This identifies the current seeded catalog. +- Open `sessions`; filter `{ catalogVersion: "" }`, + project `{ _id: 1, title: 1, startsAt: 1, catalogVersion: 1, schemaVersion: 1, attendanceMode: 1 }`, + and sort `{ startsAt: 1, _id: 1 }`. Inspect one JSON document, not all 216. The + placeholder means **replace it with your actual value**, not a literal query. +- Keep that session `_id`. Filter `{ _id: "" }` to compare + the same record after migration. `startsAt` is an ISO UTC **string**, not a BSON + Date. `catalogVersion` is the fingerprint, not the human-readable version label. +- For favorites, filter a saved session's `_id`, project `{ _id: 1, savedAt: 1 }`. + If the collection is newly created, refresh the **Connections** tree first. +- After an app save/copy or CLI migration, **rerun the query**. If the open view + still shows old results, close it and reopen **Documents** from that exact + site's collection, then reapply the filter. A tree refresh alone is not proof + that an already-open result view fetched new data. +- In the `sessions` Collection View, open **Indexes**, select **Refresh**, and + expand `schedule_order` to inspect the actual ordered keys after the CLI creates + it. See the [official index guide](https://microsoft.github.io/vscode-documentdb/user-manual/collection-view-index-management). + +Treat the catalog as **read-only by workshop intent**, not enforced permissions: +these development credentials can write. Do not edit/delete catalog JSON, rename +collections, drop indexes, or use extension **Copy Collection**. The app's +**Copy selected favorites** performs selected, catalog-validated, additive upserts +with per-record outcomes and destination first-save timestamps. A generic +collection copy is a different operation and would defeat the exercise. + +## If the visual explorer is blocked + +Tell a helper; continue the core driver/copy lab with its existing CLI inspection +fallback rather than spending the workshop on editor troubleshooting: + +```sh +docker compose -f compose.yaml exec app npm run inspect -- --target local +docker compose -f compose.yaml exec app npm run inspect -- --target site-b +``` + +`inspect` returns one actual projected session, one favorite and actual index +definitions without credentials. The CLI target is always explicit; neither the +app's selected target nor a focused extension tab chooses it. A successful CLI +inspection is fallback evidence, **not** a claimed extension acceptance pass. diff --git a/docs/instructor.md b/docs/instructor.md index 2b49597..68af809 100644 --- a/docs/instructor.md +++ b/docs/instructor.md @@ -9,16 +9,21 @@ trip across two independent OSS DocumentDB instances—without Azure access. | Minutes | Activity | | --- | --- | -| 0–20 | One-minute finished-planner demo, architecture, Codespaces setup; triage at minute 12 | -| 20–50 | Two repository TODOs, favorites, overlaps, persistence | -| 50–70 | Site A/B switch, missing favorites, explicit copy, retry, return trip | +| 0–20 | One-minute demo, architecture, Codespaces setup + save both extension connections; triage at minute 12 | +| 20–50 | Browse Site A JSON → TODO 1; TODO 2 → inspect favorite JSON, overlaps and persistence | +| 50–70 | Compare Site A/B in explorer around app switch, selected copy, retry and return trip | | 70–85 | Presenter-only actual laptop-to-Azure demonstration or rehearsed recording | -| 85–95 | Repeatable indexes and migration extension | +| 85–95 | CLI index/migration; inspect actual index and same session before/after in extension | | 95–105 | Calendar export, safe stopping, upstream pointers, questions | -This is a planned allocation, not a measured rehearsal. Setup delays consume the -index/migration extension first. Protect the return trip, calendar export, and -cleanup. Keep cloud troubleshooting off the critical attendee path. +This remains **105 minutes**, not an extra extension demo appended to the agenda. +Explorer observations replace narration and duplicate CLI output at each existing +checkpoint. The two developer TODOs retain 30 minutes. The read-only playground +and aggregation are stretch work, not another required TODO. If setup slips, cut +those first and shorten the presenter capstone with the checked recording. Protect +the app copy/return trip, brief index/migration observation, export and cleanup. +This is a planned allocation, not a measured human rehearsal. Keep cloud/editor +troubleshooting off the critical path; use the explicit CLI fallback when needed. ## Opening explanation @@ -58,18 +63,37 @@ Azure tooling is optional and does not confer permissions. The browser editor supports the TODOs. The complete-reference override preserves exercises and data. Optional GitHub CLI/SSH diagnostics are helper tools, not attendee prerequisites. +The official DocumentDB extension is the required visual explorer throughout the +lab. Follow [its private connection guide](extension.md): attach the existing +loopback endpoints, use native username/password prompts, and save **Workshop — +Site A/B** in **Connections**. The helper emits no credentials to the terminal; +never project its private handoff file. Database ports 10270/10271 (or custom +`.env` ports) must not be forwarded; only private app port 3000 is forwarded. +Do not use **Set Up Local**, fabricate extension-owned containers, or replace the +app's selected favorite copy with **Copy Collection**. Compose owns lifecycle; +the saved extension connections expose data. The catalog is read-only by intent, +not by the supplied development role. + ## Observable checkpoints - Both sites ready and seeded; a blue Exercise 1 checkpoint explains the empty planner, points to the editable file, and links to progressively revealed hints. The persistent implementation label describes the chosen file, not completion. -- TODO 1: 216 entries. TODO 2: save two favorites and retain them across app restart. +- Both **saved** extension Connections nodes expand to the actual database and + `sessions`/`workshop_meta`; `favorites` appears after its first write. Installed + extension or a successful port probe alone is not this checkpoint. +- Before TODO 1: inspect an actual Site A session `_id`, `startsAt`, `catalogVersion` + and schema version. TODO 1: 216 app entries. TODO 2: save two favorites, inspect + their actual `_id`/`savedAt` in the extension and retain them across app restart. - Switch A → B: same catalog, no automatic favorite movement; A remains intact. -- Copy A → B; switch back to A before repeating that same direction; Already present. +- Compare extension favorite views before/after **app** copy A → B. Switch back + to A before repeating the same direction: Already present. Requery B's same + `_id` to verify one document and unchanged destination `savedAt`. - New favorite at B; copy B → A; original A choices survive. - Removal is local to its site, not propagated to copies. -- Inspect an actual session before/after migration and an unchanged favorite - timestamp; explain zero migrated on rerun as idempotency. Index definition is +- In the extension, inspect the same actual session `_id` before/after CLI + migration and an unchanged favorite timestamp; explain zero migrated on rerun + as idempotency. Expand the actual `schedule_order` index keys; its definition is visible, not a performance claim. Optional advanced aggregation: 17 Monday track groups / 74 published program entries, not attendee counts. - Export from the intended site, follow calendar-specific import instructions, @@ -185,7 +209,10 @@ replicate together. No extra cloud resources are authorized by this guide. | `DATABASE_UNAVAILABLE` | Confirm intended site, readiness and private logs; never silently use the other site | | `CATALOG_NOT_SEEDED` | Seed that explicit local target, or retry interrupted same-catalog seed | | `CATALOG_MISMATCH` | Preserve the old notebook, choose a fresh database name, or review migration | -| Site B favorites empty after switch | Expected: switching isn't copying | +| Site B favorites empty after switch | Expected: switching isn't copying; its collection may not exist until first write | +| Extension cannot connect but CLI can | Run host-side `npm run extension:check`; check remote extension host/loopback ports/native auth/local-only certificate exception | +| Extension shows old JSON | Rerun the collection query or close/reopen Documents on the same site; tree refresh alone may not rerun results | +| Loopback port occupied | Choose distinct unused `SITE_A_EXTENSION_PORT`/`SITE_B_EXTENSION_PORT` in private `.env`, reapply same project, regenerate handoff; never kill unrelated services | | Incomplete copy | Read per-record outcomes, resolve failure, retry same direction | | Browser fails after restart | Refresh to obtain the new request token; attendee restarts at Site A | | Changed credentials fail | Recreate app for config changes; `.env` edits do not rotate an existing volume's users | @@ -204,6 +231,11 @@ preceding source and what still needs proof on this revision. - Fresh attendee Codespace with both instances and measured resource/startup cost. - Setup upgrade from a legacy `.env` without changing old credentials/data. +- Actual extension 1.0.0 GUI: two saved/renamed Connections nodes, authenticated + JSON browsing, custom database names and private file closed before screenshots. + No database auto-forwarding, no third container, no Azure sign-in. +- Explorer observes actual favorite writes/retry timestamps, index keys, same-id + migration; optional prebound playground returns 17 groups/74 Monday entries. - Starter/reference switching and restart persistence at both sites. - Same catalog, independent favorites before copying, safe repeat/return trip. - Second-site outage: clear error, no fallback; recovery retains both notebooks. diff --git a/docs/lab.md b/docs/lab.md index a21adf1..29b523c 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -44,9 +44,29 @@ checkpoint is expected; `DATABASE_UNAVAILABLE` is not. The internal CLI name `local` means Site A; `site-b` means Site B. Neither means managed Azure. Both sites have separate credentials and volumes. +### Connect your visual database explorer + +Run `npm run extension:connections` and follow the +[private setup steps](extension.md#connect-the-two-existing-sites-privately). Save +**Workshop — Site A** and **Workshop — Site B** in DocumentDB **Connections**. +Expand each to its actual workshop database. This is required lab tooling, not an +Azure demo: no sign-in, no **Set Up Local** third database, no forwarded database +ports. Keep the credential file out of screen sharing. If the editor is blocked, +ask a helper and use [CLI inspection](extension.md#if-the-visual-explorer-is-blocked) +as a fallback, not as a claimed visual-explorer pass. + ## 2. Read the catalog -In the **Codespaces editor**, use the left **Explorer** panel: +**First see the data before writing code.** In DocumentDB **Connections**, expand +**Workshop — Site A → your database → sessions** and open its **Documents** +child (or the collection's leftmost inline icon). Follow +[Browse, query and refresh](extension.md#browse-query-and-refresh): read the catalog +fingerprint from `workshop_meta`, filter `sessions` by it, and inspect one actual +JSON document with `_id`, `startsAt`, `catalogVersion` and `schemaVersion`. +Notice that `_id` is a stable session identifier and `startsAt` an ISO UTC string. +Keep this `_id` to revisit in step 8. Do not edit the seeded catalog. + +**Now implement the application read.** In the **Codespaces editor**, use the left **Explorer** panel: **exercises → starter → repository.js**. Or press **Ctrl+P** (Windows/Linux) / **Cmd+P** (Mac), type `exercises/starter/repository.js`, and press Enter. @@ -173,6 +193,15 @@ Both are listed Monday, 9:00–10:45 a.m. Eastern, in different rooms. Their car and favorites should flag an overlap. Back-to-back sessions do not conflict. Interpret shared keynote/lightning-talk blocks using the official program. +**See the write in the extension.** Refresh the **Workshop — Site A** tree; +`favorites` now exists. Open **Documents**, use JSON view, and inspect a saved +session's `_id` and `savedAt` (project only those fields). This is the database +record your TODO wrote, not browser storage. Your stable `_id` plus +`$setOnInsert` explains why retrying the upsert cannot add a duplicate or change +its first-save timestamp. Do not edit the JSON to “test” it; step 5 exercises a +real retry through the app. [Rerun/reopen the query](extension.md#browse-query-and-refresh) +after changes rather than trusting stale results. + Restart the app and refresh: ```sh @@ -188,6 +217,11 @@ Stay connected to Codespaces: laptop-offline operation is not part of this lab. Select **Site B — self-hosted**, then **Switch connection**. The same 216-entry catalog is there, but Site A's favorites are absent. +In the extension, compare **Workshop — Site A** and **Workshop — Site B**. Open +each database's `favorites` Documents view (refresh the tree first). B may have +no `favorites` collection yet, or no records in it; A still has your actual JSON +records. Merely opening an extension tab does not switch the app. + Before “fixing” any code, explain: - Which database is active? @@ -214,6 +248,17 @@ While **Site A** is active: 5. **Switch back to Site A**, select the same favorites, and repeat **Site A → Site B**. Expect **Already present**, not new duplicates. +After the first copy, refresh/reopen **Site B → favorites** in the extension. +Filter one copied `_id`, note B's `savedAt`, then compare that same `_id` on A. +After repeating the copy, rerun B's query: still one record with the **same B +timestamp**. A remains unchanged. B records its own initial save time, so it need +not equal A's timestamp. If your notebook was used before, compare your actual +before/after records rather than assuming an empty destination. + +Use the **planner app's Copy selected favorites**, never extension **Copy +Collection**. The latter is a different operation without this exercise's +selected-record/catalog-validation/per-record-outcome semantics. + The source is always the active site; switching before copying changes direction. Read the confirmation instead of assuming the destination. @@ -226,7 +271,8 @@ are preserved. Each site records its own first-save time, not the other site's. Switch to **Site B**. Save a different session. Select that new favorite and confirm **Site B → Site A**. Switch back to **Site A**: the original choices remain -and the new one is added. Any resulting overlap is flagged. +and the new one is added. Any resulting overlap is flagged. Refresh both extension +views to see the newly added `_id` and each site's independent `savedAt`. Removing a favorite from one site does not remove its copy at the other. This is explicit additive copying, not bidirectional synchronization or conflict @@ -250,42 +296,82 @@ that as self-hosted-to-managed, not on-prem-to-cloud. ## 8. Make changes repeatable -If time permits, follow the instructor against **Site A (`local`)**. First inspect -one actual session and one actual favorite, then add the index and migrate: +Follow the instructor against **Site A (`local`)**. In the extension, reopen the +**same session `_id`** you inspected in step 2. On an unmigrated notebook, it has +`schemaVersion: 1` and **no** `attendanceMode`. Keep a favorite's `_id`/`savedAt` +visible too. These are actual documents, not canned JSON. Use a narrow projection +as in [the explorer guide](extension.md#browse-query-and-refresh). + +Create the repeatable index from the terminal (explicit target): ```sh -docker compose -f compose.yaml exec app npm run inspect -- --target local docker compose -f compose.yaml exec app npm run indexes -- --target local +``` + +In Site A's `sessions` Collection View, select **Indexes → Refresh**, then expand +`schedule_order`. Inspect the actual key definition **`{ startsAt: 1, _id: 1 }`**, +including field order, not just its name. This shows a reproducible index exists; +it does not prove that the engine chooses it or that this small catalog is faster. +Do not create a second index through the extension. + +Run the versioned migration, then rerun/reopen that session query in the extension: + +```sh docker compose -f compose.yaml exec app npm run migrate -- --target local -docker compose -f compose.yaml exec app npm run inspect -- --target local +``` + +The **same `_id`** now has `schemaVersion: 2` and `attendanceMode: "in-person"`; +the title and `startsAt` are unchanged. Refresh the favorite query too: its +`savedAt` is unchanged. You observed the CLI's real write through a separate +client. Do not manually edit documents or run a hidden playground migration. + +Run the migration again to test idempotency: + +```sh docker compose -f compose.yaml exec app npm run migrate -- --target local docker compose -f compose.yaml exec app npm run check -- --target local ``` -Compare the **same session `_id`** in the two `inspect` outputs. On an unmigrated -notebook, the first actual document has `schemaVersion: 1` and **no** -`attendanceMode` field. After migration it has `schemaVersion: 2` and -`attendanceMode: "in-person"`. The title/time are unchanged. These are projected -fields from a real query, not canned example JSON; only one session and one -favorite are printed. No credentials or system documents are printed. - -The favorite output shows its actual `_id` and `savedAt` timestamp. Neither -index creation nor this session migration changes that timestamp. If `favorite` -is `null`, save a session on **this target** and inspect again. Repeated saves -and copies preserve each destination's first-save timestamp (Exercise 2). - -The second migration should report **zero newly migrated records**: the filter -only matches version-1 records without `attendanceMode`, so already migrated -records are untouched. This is **idempotency**, not a failed migration. If your -notebook was migrated earlier, the first inspection will already show version 2 -and both runs can report zero. Do not reset it just to recreate the before state. -Re-seeding does not undo migration. To try on Site B, substitute `--target site-b` -in **every** command; the browser's active target does not select a CLI target. - -`inspect` also displays the actual `schedule_order` index definition after -creation; `check` lists index names and document versions. This makes the index -repeatable and visible, **not** proof that the engine chooses it or that a tiny -catalog gets faster. Skip this extension before sacrificing copy-back or export. +The second migration reports **zero newly migrated records** because only +version-1 records without `attendanceMode` match. If this notebook was migrated +earlier, it will already show version 2 and both runs may report zero. Do not +reset it to recreate a before state. Re-seeding does not undo migration. + +**CLI fallback at any checkpoint:** run this before and after the same commands +if the extension is unavailable. It prints one actual projected session, one +favorite and actual index definitions, never credentials: + +```sh +docker compose -f compose.yaml exec app npm run inspect -- --target local +``` + +A null favorite means save one on **this target** first. To repeat on B, use its +extension connection and `--target site-b` in **every** CLI command. Neither the +browser's selected site nor a focused extension tab changes the CLI target. + +### Optional extension playground — inspect without writes + +After the required checkpoints, right-click the intended **database** under +**Workshop — Site A → your actual database** → **New Query Playground**. Verify +its connection/database **CodeLens** header. Copy the single block from +[inspect.documentdb.js](../exercises/optional/inspect.documentdb.js) into that new +playground, then click the block's **Run** CodeLens. It reads this database's +catalog metadata and at most **five** projected sessions, with a five-second +server query limit. It contains no credentials or writes. + +Do **not** run the unbound repository template directly or add `use(...)`. +Version 1.0 playgrounds are bound to the cluster/database where they were created; +they do not have a switch-connection workflow. For B or a custom database name, +create another playground from **that exact database node** and copy the template. +The extension supplies `db`, so no database-name code edit is needed. + +Blank lines separate blocks. **Run** executes one block; **Run All** executes the +whole file after confirmation. Variables persist only within Run All, not between +separate block runs. Each supplied template is self-contained. Results include +the connection/database header; check it each time. See the +[official playground guide](https://microsoft.github.io/vscode-documentdb/user-manual/query-playground). +These templates are read-only by code and workshop intent; the credentials are +not a read-only database role. Do not add write stages or export private settings. ### Optional developer challenge — Monday program entries by track @@ -341,6 +427,13 @@ it without replacing your optional exercise: docker compose -f compose.yaml exec app npm run challenge -- --target local --reference ``` +For the equivalent **extension** result, create a new playground from the same +explicit database node as above and copy the single self-contained block from +[program-counts.documentdb.js](../exercises/optional/program-counts.documentdb.js). +Click **Run**. It reads the active catalog fingerprint, projects only group/count, +limits to 30 groups and applies a five-second server query budget. It does not +read or print all 216 session documents, change the planner, or write data. + The October 12 snapshot produces **17 track groups totaling 74 Monday entries**. The first three are `Inclusion & Diversity in Open Source: 10`, `Break: 9`, and `Open Source Accessibility Summit: 8`. The offline test derives these from the diff --git a/docs/local.md b/docs/local.md index 7f08238..8ffe69e 100644 --- a/docs/local.md +++ b/docs/local.md @@ -2,7 +2,8 @@ The attendee workshop is browser-first. Use this appendix only if Docker already works on your laptop; do not spend the timed workshop installing/repairing it. -You need Docker with Linux containers, Docker Compose, a browser and text editor. +You need Docker with Linux containers, Docker Compose, a browser, and VS Code +with the official `ms-azuretools.vscode-documentdb` extension (guide: version 1.0.0). No host Node.js, Azure CLI or Kubernetes installation is required. Download/extract or clone the repository and open a terminal in its directory. @@ -28,7 +29,32 @@ two-site simulation, not two physical sites or cloud providers. Setup creates independent private credentials. For an old `.env`, it preserves all old values and appends only missing Site B settings. It refuses partial/empty Site B credentials rather than guessing about an existing volume. Neither database -publishes a host port; the app binds to loopback. Do not expose them publicly. +is publicly exposed: Site A publishes **127.0.0.1:10270**, Site B +**127.0.0.1:10271**, and the app binds to loopback. The VS Code extension on this +laptop connects to those two distinct host ports; the app still uses Compose DNS. +Do not forward or expose database ports. See [port-conflict recovery](extension.md#why-these-ports-are-not-web-links). + +### Show both sites in DocumentDB for VS Code + +If host Node.js 24 is available, run `npm run extension:connections`. Otherwise +on macOS/Linux, use the already-downloaded setup container under your own UID/GID: + +```sh +docker compose -f compose.setup.yaml run --rm --user "$(id -u):$(id -g)" setup node scripts/extension-connections.mjs +``` + +This only reads your existing `.env` and writes the owner-only, Git/Docker-ignored +`.workshop-private/extension-connections.txt`; it does not create or change users. +Open it privately in **local VS Code** and follow the +[existing-connection steps](extension.md#connect-the-two-existing-sites-privately): +credential-free URI in the unmasked field, native username/password in their +separate prompts, local-only self-signed certificate exception with TLS still on. +Save **Workshop — Site A/B** in **Connections**, expand your database names, and +close the private file before sharing. Do not use **Set Up Local** (third database) +or expect Compose containers to be adopted into the extension-managed Local list. +On a platform without the shell UID/GID commands, use host Node or ask a helper; +do not loosen file permissions as a workaround. The CLI `inspect` fallback in +[the lab](lab.md#8-make-changes-repeatable) remains available without host Node. On a network requiring an approved anonymous npm mirror, set `NPM_REGISTRY` in your private `.env`. Never put tokens/passwords in build arguments or disable TLS. diff --git a/docs/presenter.md b/docs/presenter.md index fb6984c..b9ef399 100644 --- a/docs/presenter.md +++ b/docs/presenter.md @@ -5,9 +5,11 @@ instance**. It does not provision a cluster, create cloud subscriptions, install Kubernetes, or grant permissions. Attendees never receive the connection string and do not execute this runbook. Their Site A/B lab works independently. -**Acceptance status:** the repository's earlier managed data-plane round trip -was not completed. Rehearse this revised path on the actual laptop and approved -Azure endpoint; local tests and successful infrastructure deployment are not proof. +**Acceptance status:** a prior local Mac mini → managed Azure round trip passed, +as scoped in the [acceptance record](acceptance.md). That does not prove the +extension-integrated revision or conference laptop/network. Rehearse this path +on the actual laptop and approved Azure endpoint; local tests and successful +infrastructure deployment are not proof. Keep a verified recording for conference-network failure. Do not claim a live cloud result from a recording or the two-container simulation. @@ -95,6 +97,27 @@ Open **http://localhost:3000** (or the privately configured `WORKSHOP_PORT`). Verify **Complete reference**, **DocumentDB on this laptop**, and exactly the local/Azure target pair. Do not show `.env` or raw connection errors on screen. +### Optional presenter-only extension view + +The attendee extension Connections tree contains only their own **Site A/B**; +attendees need no Azure subscription, login or credential. The private handoff +helper deliberately never exports `CLOUD_DOCUMENTDB_URI`. + +If already authorized and rehearsed, the presenter may separately attach the +approved Azure database in their **own** extension and inspect its catalog and +favorites beside the laptop connection. Enter cloud credentials privately through +the service's supported authentication flow; the connection-string field is not +a safe place to project secrets. Use a clear presenter-only label, close private +configuration, and verify the actual database before screen sharing. **Keep +validated TLS and hostname validation enabled for Azure.** Never apply the +loopback self-signed certificate exception to cloud or disable global TLS. + +This optional visual observation uses the existing 15-minute capstone allocation, +not extra classroom time. Perform transfers with the **app's selected favorite +copy**, never extension **Copy Collection**. Saved Connections expose databases; +they do not change Compose container ownership. If extension/cloud networking +is blocked, use the rehearsed recording rather than changing attendee setup. + ## 3. Rehearse the 15-minute story 1. **0–2 min: identify the boundary.** Laptop runs app + self-hosted DocumentDB; diff --git a/exercises/optional/inspect.documentdb.js b/exercises/optional/inspect.documentdb.js new file mode 100644 index 0000000..b364539 --- /dev/null +++ b/exercises/optional/inspect.documentdb.js @@ -0,0 +1,10 @@ +// READ-ONLY TEMPLATE: do not run this unbound repository file directly. +// In DocumentDB Connections, right-click the intended Site A/B DATABASE > +// New Query Playground. Check its connection/database CodeLens, then copy this +// whole block into that new .documentdb.js file. The extension supplies db. +// No database switching, connection string, name editing, or writes are needed. +const inspectionCatalog = db.workshop_meta.find({ _id: "catalog", ready: true }).limit(1).maxTimeMS(5000).toArray(); +if (!inspectionCatalog[0]?.fingerprint) throw new Error("Stop: select the seeded workshop database."); +db.sessions.find({ catalogVersion: inspectionCatalog[0].fingerprint }, { + _id: 1, title: 1, startsAt: 1, catalogVersion: 1, schemaVersion: 1, attendanceMode: 1, +}).sort({ startsAt: 1, _id: 1 }).limit(5).maxTimeMS(5000).toArray(); diff --git a/exercises/optional/program-counts.documentdb.js b/exercises/optional/program-counts.documentdb.js new file mode 100644 index 0000000..8f166cd --- /dev/null +++ b/exercises/optional/program-counts.documentdb.js @@ -0,0 +1,18 @@ +// READ-ONLY REFERENCE: create New Query Playground from the intended Site A/B +// DATABASE first; check its connection/database CodeLens, then copy this block. +// The extension provides db, including a custom workshop database name. +// One self-contained block: no variables depend on a previous Run Block. +// Counts published Monday program entries, NOT attendees or unique speakers. +const countsCatalog = db.workshop_meta.find({ _id: "catalog", ready: true }).limit(1).maxTimeMS(5000).toArray(); +if (!countsCatalog[0]?.fingerprint) throw new Error("Stop: select the seeded workshop database."); +db.sessions.aggregate([ + { $match: { + catalogVersion: countsCatalog[0].fingerprint, + // startsAt is a normalized ISO UTC string. Monday in America/New_York: + startsAt: { $gte: "2026-10-19T04:00:00.000Z", $lt: "2026-10-20T04:00:00.000Z" }, + } }, + { $group: { _id: "$track", entries: { $sum: 1 } } }, + { $sort: { entries: -1, _id: 1 } }, + { $project: { _id: 1, entries: 1 } }, + { $limit: 30 }, +], { maxTimeMS: 5000 }).toArray(); diff --git a/package.json b/package.json index f0af064..800e6f8 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,9 @@ "test": "node --test test/*.test.js", "test:docs": "node scripts/check-doc-links.mjs", "test:database": "node --test test/database.integration.js", - "wait:database": "node scripts/database.mjs wait" + "wait:database": "node scripts/database.mjs wait", + "extension:connections": "node scripts/extension-connections.mjs", + "extension:check": "node scripts/extension-check.mjs" }, "dependencies": { "mongodb": "7.1.0" diff --git a/scripts/extension-check.mjs b/scripts/extension-check.mjs new file mode 100644 index 0000000..2cfe18b --- /dev/null +++ b/scripts/extension-check.mjs @@ -0,0 +1,42 @@ +// Opt-in host-side probe of exactly the URIs handed to the remote extension. +// No writes, cloud settings, raw errors, credentials, or document contents logged. +import { MongoClient } from "mongodb"; +import { readLocalExtensionConnections } from "./extension-connections.mjs"; +import { pathToFileURL } from "node:url"; + +export async function checkExtensionConnections(directory = process.cwd(), log = console.log, Client = MongoClient) { + const connections = await readLocalExtensionConnections(directory); + for (const { label, uri, database, port, username, password } of connections) { + const client = new Client(uri, { auth: { username, password }, tlsAllowInvalidCertificates: true, + serverSelectionTimeoutMS: 5000, connectTimeoutMS: 5000, timeoutMS: 10000 }); + try { + await client.connect(); + const db = client.db(database); + await db.command({ ping: 1 }); + const catalog = await db.collection("workshop_meta").findOne({ _id: "catalog", ready: true }); + if (!catalog?.fingerprint) throw new Error("Local catalog not ready"); + const session = await db.collection("sessions").findOne({ catalogVersion: catalog.fingerprint }, { projection: { _id: 1 } }); + if (!session) throw new Error("Local catalog empty"); + // Prove independent authentication at the published endpoint too, not + // just on the app's Compose network. Only this local counterpart is used. + const other = connections.find((connection) => connection.port !== port); + const foreign = new Client(uri, { auth: { username: other.username, password: other.password }, + tlsAllowInvalidCertificates: true, serverSelectionTimeoutMS: 5000, connectTimeoutMS: 5000, timeoutMS: 10000 }); + let rejected = false; + try { await foreign.connect(); } + catch (error) { rejected = error.code === 18; } + finally { await foreign.close(); } + if (!rejected) throw new Error("Independent local authentication was not verified"); + log(JSON.stringify({ label, port, database, authenticatedCatalogRead: true, foreignCredentialsRejected: true, tls: true, loopbackOnly: true })); + } catch { + throw new Error(`${label} probe failed on loopback port ${port}. Check readiness, .env credentials/database and published port; raw driver errors are suppressed. No data changed.`); + } finally { await client.close(); } + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + checkExtensionConnections().catch(() => { + console.error("Local extension endpoint check failed. Confirm both sites are ready, the .env ports match Compose, and the database/credentials belong to those volumes. Never delete data or change credentials as a generic fix. Raw errors are suppressed."); + process.exitCode = 1; + }); +} diff --git a/scripts/extension-connections.mjs b/scripts/extension-connections.mjs new file mode 100644 index 0000000..d16caff --- /dev/null +++ b/scripts/extension-connections.mjs @@ -0,0 +1,128 @@ +// Host-side private handoff for the extension. Never source/execute .env, read +// ambient credentials, change .env, or export the optional Azure connection. +import { constants } from "node:fs"; +import { readFile, mkdir, lstat, open, rename, unlink } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { resolve, join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const marker = "Workshop local extension connections — generated private file v1"; +const invalid = () => new Error("Unsupported or duplicate .env binding. Review quoting privately; no configuration was changed. Shell/Compose interpolation is not supported by this helper."); + +// Deliberately bounded Compose-compatible subset: one binding per line, optional +// export, literal single quotes, double-quote escapes, comments. Reject rather +// than silently alter interpolation, multiline values, or ambiguous escapes. +export function parsePrivateEnv(source) { + const values = Object.create(null); + for (const line of source.replace(/^\uFEFF/, "").split(/\r?\n/)) { + if (/^\s*(?:#.*)?$/.test(line)) continue; + const binding = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!binding || Object.hasOwn(values, binding[1])) throw invalid(); + const [, key, raw] = binding; + let value = ""; + if (/^["']/.test(raw)) { + const quote = raw[0]; + let i = 1; + let closed = false; + for (; i < raw.length; i++) { + const char = raw[i]; + if (char === quote) { closed = true; i++; break; } + if (char === "\\") { + const next = raw[i + 1]; + if (quote === "'" && next !== "'") { value += char; continue; } + const escapes = quote === "'" ? { "'": "'" } : { n: "\n", r: "\r", t: "\t", "\\": "\\", '"': '"' }; + if (!Object.hasOwn(escapes, next)) throw invalid(); + value += escapes[next]; i++; + } else { + if (quote === '"' && char === "$") throw invalid(); + value += char; + } + } + if (!closed || !/^\s*(?:#.*)?$/.test(raw.slice(i))) throw invalid(); + } else { + value = raw.replace(/\s+#.*$/, "").trimEnd(); + if (/[\s$"'\\`]/.test(value)) throw invalid(); + } + values[key] = value; + } + return values; +} + +function port(value, fallback) { + const text = value ?? fallback; + if (!/^[1-9][0-9]{0,4}$/.test(text) || Number(text) > 65535) { + throw new Error("Extension ports must be integers from 1 through 65535 in .env."); + } + return Number(text); +} + +export function localExtensionConnections(values) { + const connections = [ + { label: "Workshop — Site A", prefix: "DOCUMENTDB", databaseKey: "LOCAL_DATABASE_NAME", port: port(values.SITE_A_EXTENSION_PORT, "10270") }, + { label: "Workshop — Site B", prefix: "SITE_B", databaseKey: "SITE_B_DATABASE_NAME", port: port(values.SITE_B_EXTENSION_PORT, "10271") }, + ].map(({ label, prefix, databaseKey, port }) => { + const username = values[`${prefix}_USERNAME`]; + const password = values[`${prefix}_PASSWORD`]; + if (!username || !password || /[\x00-\x1f\x7f]/.test(username + password) || /[<>]/.test(username + password)) { + throw new Error("Both sites need complete, non-placeholder credentials in the existing .env. Run setup or review partial settings; never regenerate an existing volume's credentials."); + } + const database = values[databaseKey] ?? "ato_workshop"; + if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,62}$/.test(database)) throw new Error("Review the local database names in .env; use letters, digits, underscores or hyphens."); + return { label, port, database, username, password, + // The extension's URI box is NOT masked. Keep credentials separate for + // its native-auth prompts, and explicitly select the local TLS exception. + // Azure settings are intentionally never handed to the extension. + uri: `mongodb://127.0.0.1:${port}/${database}?tls=true&authMechanism=SCRAM-SHA-256&authSource=admin&directConnection=true&retryWrites=false`, + }; + }); + if (connections[0].port === connections[1].port) throw new Error("Site A and Site B extension ports must be distinct."); + if (values.DOCUMENTDB_PASSWORD === values.SITE_B_PASSWORD) throw new Error("Site A and Site B must keep independent credentials; review .env without rotating existing users."); + return connections; +} + +export async function readLocalExtensionConnections(directory = process.cwd()) { + return localExtensionConnections(parsePrivateEnv(await readFile(resolve(directory, ".env"), "utf8"))); +} + +function ownedPrivate(info, directory = false) { + return (directory ? info.isDirectory() : info.isFile() && info.nlink === 1) && + (info.mode & 0o077) === 0 && (process.getuid?.() === undefined || info.uid === process.getuid()); +} + +export async function writeExtensionConnections(directory = process.cwd(), log = console.log) { + const connections = await readLocalExtensionConnections(directory); + const privateDirectory = resolve(directory, ".workshop-private"); + await mkdir(privateDirectory, { mode: 0o700 }).catch((error) => { if (error.code !== "EEXIST") throw error; }); + if (!ownedPrivate(await lstat(privateDirectory), true)) throw new Error(".workshop-private must be a real, owner-only directory owned by this user; no files were changed."); + const filename = join(privateDirectory, "extension-connections.txt"); + try { + if (!ownedPrivate(await lstat(filename))) throw new Error("The existing handoff must be a real owner-only file owned by this user."); + const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + if (!(await file.readFile("utf8")).startsWith(marker + "\n")) throw new Error("Refusing to replace a file not generated by this helper."); + } finally { await file.close(); } + } catch (error) { if (error.code !== "ENOENT") throw error; } + const content = [marker, "SECRET: open privately; never share, commit, screenshot, or paste into a terminal.", + "Use DocumentDB: New Connection... > Connection String. No Azure sign-in or local setup wizard.", + "Paste only the credential-free URI into the unmasked URI box; username/password go in separate native-auth prompts.", + "Select Allow invalid certificates for these loopback connections only: TLS stays enabled with the local self-signed certificate.", "", + ...connections.flatMap(({ label, port, database, uri, username, password }) => [label, `Loopback port: ${port}; database: ${database}`, `Connection string (no credentials): ${uri}`, `Username: ${username}`, `Password (paste only in masked prompt): ${password}`, ""]), + ].join("\n"); + const temporary = join(privateDirectory, `.connections-${randomUUID()}.tmp`); + try { + const file = await open(temporary, "wx", 0o600); + try { await file.writeFile(content); } finally { await file.close(); } + await rename(temporary, filename); + } finally { await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; }); } + log(`Private connection instructions: ${filename}`); + for (const { label, port, database } of connections) log(`${label}: loopback port ${port}, database ${database}`); + log("Open the file privately in the editor; no URI or credential was printed. Close it before screen sharing."); + return filename; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + writeExtensionConnections().catch(() => { + console.error("Extension handoff failed. Check that .env has complete distinct local credentials, supported literal quoting and distinct valid ports; private output must be owner-only. Existing .env was not changed; no credentials were printed."); + process.exitCode = 1; + }); +} diff --git a/scripts/test-reconnect.mjs b/scripts/test-reconnect.mjs index 7bba454..7c99ae5 100644 --- a/scripts/test-reconnect.mjs +++ b/scripts/test-reconnect.mjs @@ -32,7 +32,7 @@ const override = join(directory, "compose.reconnect.yaml"); // inputs that could otherwise choose a host port, mode or private forwarding host. const env = { ...process.env }; for (const key of Object.keys(env)) { - if (/^(COMPOSE_|WORKSHOP_|DOCUMENTDB_|SITE_B_|LOCAL_|CLOUD_)/.test(key) || key === "ACTIVE_TARGET") delete env[key]; + if (/^(COMPOSE_|WORKSHOP_|DOCUMENTDB_|SITE_A_|SITE_B_|LOCAL_|CLOUD_)/.test(key) || key === "ACTIVE_TARGET") delete env[key]; } Object.assign(env, { COMPOSE_PROJECT_NAME: project, WORKSHOP_PORT: "3000", WORKSHOP_MODE: "complete", WORKSHOP_SCENARIO: "attendee", WORKSHOP_PUBLIC_HOST: "", @@ -95,7 +95,9 @@ try { } // setup ignores ambient credentials and generates independent private values. await setup(directory, {}, () => {}); - await writeFile(override, `services:\n app:\n init: false\n command: ["node", "src/server.js"]\n ports: !override\n - "127.0.0.1::3000"\n`, { mode: 0o600 }); + // No published database ports: parallel harnesses cannot collide with the + // attendee extension endpoints, and only the app needs host-side access. + await writeFile(override, `services:\n documentdb:\n ports: !override []\n documentdb-site-b:\n ports: !override []\n app:\n init: false\n command: ["node", "src/server.js"]\n ports: !override\n - "127.0.0.1::3000"\n`, { mode: 0o600 }); owned = true; await run(["up", "--build", "-d", "--wait", "--wait-timeout", "240"], { timeout: 600000 }); receipt("owned-ephemeral-project-ready", { project, privateDirectory: directory }); diff --git a/scripts/workspace-start.mjs b/scripts/workspace-start.mjs index 7389456..fa8438f 100644 --- a/scripts/workspace-start.mjs +++ b/scripts/workspace-start.mjs @@ -18,6 +18,7 @@ export function startWorkspace(run = spawnSync, log = console.log) { } log("Site A and Site B are ready and both catalogs are seeded. Open private port 3000 from the Ports tab."); log("The starter's TODO prompt is intentional. Both sites are local simulations; no Azure connection, sign-in or provisioning was performed."); + log("Next: npm run extension:connections, then docs/extension.md to save Workshop - Site A/B in the DocumentDB Connections tree. Never forward database ports."); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { diff --git a/test/extension.test.js b/test/extension.test.js new file mode 100644 index 0000000..5fc9bba --- /dev/null +++ b/test/extension.test.js @@ -0,0 +1,209 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, writeFile, stat, chmod, mkdir, rm, symlink, link } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { execFileSync } from "node:child_process"; +import vm from "node:vm"; +import { parsePrivateEnv, localExtensionConnections, writeExtensionConnections } from "../scripts/extension-connections.mjs"; +import { checkExtensionConnections } from "../scripts/extension-check.mjs"; +import { setup } from "../scripts/setup.mjs"; +import { readCatalog } from "../src/catalog.js"; +import { programCountsPipeline } from "../examples/complete/program-counts.js"; + +const settings = "DOCUMENTDB_USERNAME=workshop\nDOCUMENTDB_PASSWORD='site A: p@ss/#$literal'\nSITE_B_USERNAME=workshop_b\nSITE_B_PASSWORD=independent-secret\nLOCAL_DATABASE_NAME=custom_a\nSITE_B_DATABASE_NAME=custom_b\nCLOUD_DOCUMENTDB_URI='mongodb://cloud-user:never-export@cloud.invalid/'\n"; +async function temporary(t) { + const directory = await mkdtemp(join(tmpdir(), "ato-extension-test-")); + t.after(() => rm(directory, { recursive: true, force: true })); + return directory; +} + +test("private env parser handles generated and legacy literal quotes/comments without executing data", () => { + const env = parsePrivateEnv(settings + "export COMMENTED = \"a\\\"b\\\\c\" # comment\nSINGLE='it\\'s literal'\nHASH=value#hash\nSPACED=value # comment\nEMPTY=\n"); + assert.equal(env.DOCUMENTDB_PASSWORD, "site A: p@ss/#$literal"); + assert.equal(env.COMMENTED, 'a"b\\c'); + assert.equal(env.SINGLE, "it's literal"); + assert.equal(env.HASH, "value#hash"); + assert.equal(env.SPACED, "value"); + assert.equal(env.EMPTY, ""); + assert.equal(parsePrivateEnv("LITERAL='$(touch should-never-execute)'\n").LITERAL, "$(touch should-never-execute)"); + for (const source of ["A=one\nA=two", "A=one\nexport A=two", "A=${ENV}", 'A="$ENV"', "A=$(command)", + "A='unterminated", "A='one' extra", "A=two words", "A=one; command", 'A="bad\\q"', "A='first\nsecond'", "not-a-binding"]) { + assert.throws(() => parsePrivateEnv(source), /Unsupported or duplicate/, source); + } +}); + +test("connections keep all secrets OUT of the unmasked URI and use only separate loopback endpoints", () => { + const env = parsePrivateEnv(settings); + const connections = localExtensionConnections(env); + assert.deepEqual(connections.map(({ port, database }) => ({ port, database })), [{ port: 10270, database: "custom_a" }, { port: 10271, database: "custom_b" }]); + for (const connection of connections) { + const uri = new URL(connection.uri); + assert.equal(uri.hostname, "127.0.0.1"); + assert.equal(uri.username, ""); assert.equal(uri.password, ""); + assert.equal(uri.searchParams.get("tls"), "true"); + assert.equal(uri.searchParams.get("authSource"), "admin"); + assert.equal(uri.searchParams.get("authMechanism"), "SCRAM-SHA-256"); + assert.equal(uri.searchParams.get("directConnection"), "true"); + assert.equal(uri.searchParams.has("tlsAllowInvalidCertificates"), false, "local exception is explicitly chosen in the wizard"); + assert.doesNotMatch(connection.uri, /p@ss|independent-secret|cloud/); + } + assert.deepEqual(localExtensionConnections({ ...env, SITE_A_EXTENSION_PORT: "11270", SITE_B_EXTENSION_PORT: "11271" }).map(({ port }) => port), [11270, 11271]); + for (const change of [{ DOCUMENTDB_PASSWORD: "" }, { SITE_B_PASSWORD: "" }, { SITE_B_PASSWORD: env.DOCUMENTDB_PASSWORD }, + { DOCUMENTDB_USERNAME: "" }, { SITE_A_EXTENSION_PORT: "0" }, { SITE_B_EXTENSION_PORT: "65536" }, + { SITE_A_EXTENSION_PORT: "0.0.0.0:10270" }, { SITE_A_EXTENSION_PORT: "10271" }, { LOCAL_DATABASE_NAME: "bad/name" }]) { + assert.throws(() => localExtensionConnections({ ...env, ...change })); + } +}); + +test("private handoff is owner-only, atomically repeatable, excludes cloud and preserves every .env byte", async (t) => { + const directory = await temporary(t); + const filename = join(directory, ".env"); + await writeFile(filename, settings, { mode: 0o600 }); + const logs = []; + const output = await writeExtensionConnections(directory, (line) => logs.push(line)); + assert.equal((await stat(join(directory, ".workshop-private"))).mode & 0o777, 0o700); + assert.equal((await stat(output)).mode & 0o777, 0o600); + const content = await readFile(output, "utf8"); + assert.match(content, /Password \(paste only in masked prompt\): site A: p@ss\/#\$literal/); + assert.doesNotMatch(content, /never-export|cloud\.invalid/); + assert.doesNotMatch(logs.join("\n"), /mongodb:|p@ss|independent-secret|never-export/); + assert.equal(await writeExtensionConnections(directory, () => {}), output); + assert.equal(await readFile(output, "utf8"), content); + assert.equal(await readFile(filename, "utf8"), settings); + // Errors leave both the original .env and earlier handoff intact. + await writeFile(filename, settings + "SITE_B_PASSWORD=duplicate\n"); + await assert.rejects(writeExtensionConnections(directory, () => {})); + assert.equal(await readFile(output, "utf8"), content); + assert.equal(await readFile(filename, "utf8"), settings + "SITE_B_PASSWORD=duplicate\n"); +}); + +test("generated setup credentials work and partial credentials are never repaired by the handoff", async (t) => { + const directory = await temporary(t); + await setup(directory, {}, () => {}); + const before = await readFile(join(directory, ".env"), "utf8"); + await writeExtensionConnections(directory, () => {}); + assert.equal(await readFile(join(directory, ".env"), "utf8"), before); + await writeFile(join(directory, ".env"), "DOCUMENTDB_USERNAME=user\nDOCUMENTDB_PASSWORD=one\nSITE_B_USERNAME=second\n"); + await assert.rejects(writeExtensionConnections(directory, () => {})); +}); + +test("handoff refuses public directories/files, unknown files, symlinks and hardlinks without overwriting", async (t) => { + const directory = await temporary(t); + await writeFile(join(directory, ".env"), settings); + const privateDirectory = join(directory, ".workshop-private"); + const output = join(privateDirectory, "extension-connections.txt"); + await mkdir(privateDirectory, { mode: 0o755 }); + await chmod(privateDirectory, 0o755); + await assert.rejects(writeExtensionConnections(directory, () => {}), /owner-only/); + await chmod(privateDirectory, 0o700); + await writeFile(output, "Not generated by the helper", { mode: 0o600 }); + await assert.rejects(writeExtensionConnections(directory, () => {}), /not generated/); + assert.equal(await readFile(output, "utf8"), "Not generated by the helper"); + await chmod(output, 0o644); + await assert.rejects(writeExtensionConnections(directory, () => {}), /owner-only/); + await rm(output); + const victim = join(directory, "unrelated.txt"); + await writeFile(victim, "do not change", { mode: 0o600 }); + await symlink(victim, output); + await assert.rejects(writeExtensionConnections(directory, () => {}), /owner-only/); + assert.equal(await readFile(victim, "utf8"), "do not change"); + await rm(output); await link(victim, output); + await assert.rejects(writeExtensionConnections(directory, () => {}), /owner-only/); + await rm(privateDirectory, { recursive: true }); + await symlink(directory, privateDirectory); + await assert.rejects(writeExtensionConnections(directory, () => {}), /owner-only/); +}); + +test("handoff CLI suppresses secrets even for malformed input", async (t) => { + const directory = await temporary(t); + await writeFile(join(directory, ".env"), settings + "SENSITIVE=do-not-print-me $unsupported\n"); + try { + execFileSync(process.execPath, [new URL("../scripts/extension-connections.mjs", import.meta.url).pathname], { cwd: directory, stdio: "pipe" }); + assert.fail("expected failure"); + } catch (error) { + assert.equal(error.status, 1); + const logs = `${error.stdout}${error.stderr}`; + assert.doesNotMatch(logs, /do-not-print-me|p@ss|independent-secret|never-export|mongodb:/); + assert.match(logs, /handoff failed/); + } +}); + +test("published-port probe authenticates both sites with bounded TLS, rejects foreign credentials, prints no secrets", async (t) => { + const directory = await temporary(t); + await writeFile(join(directory, ".env"), settings); + const calls = []; + class Client { + constructor(uri, options) { Object.assign(this, { uri, options, closed: false }); calls.push(this); } + async connect() { + const expected = this.uri.includes(":10270/") ? "workshop" : "workshop_b"; + if (this.options.auth.username !== expected) throw Object.assign(new Error("not logged"), { code: 18 }); + } + db(name) { this.database = name; return { command: async () => ({ ok: 1 }), collection: (collection) => ({ + findOne: async () => collection === "workshop_meta" ? { fingerprint: "catalog" } : { _id: "one" }, + }) }; } + async close() { this.closed = true; } + } + const logs = []; + await checkExtensionConnections(directory, (line) => logs.push(JSON.parse(line)), Client); + assert.equal(calls.length, 4); + assert.ok(calls.every(({ closed, options, uri }) => closed && options.tlsAllowInvalidCertificates && options.timeoutMS === 10000 && uri.includes("tls=true"))); + assert.ok(logs.every(({ authenticatedCatalogRead, foreignCredentialsRejected }) => authenticatedCatalogRead && foreignCredentialsRejected)); + assert.doesNotMatch(JSON.stringify(logs), /p@ss|independent-secret|never-export|mongodb:/); +}); + +test("both profiles ignore database ports and unknown ports, retain private 3000 and safe Compose DNS", async () => { + for (const path of ["../.devcontainer/devcontainer.json", "../.devcontainer/organizer/devcontainer.json"]) { + const config = JSON.parse(await readFile(new URL(path, import.meta.url), "utf8")); + assert.deepEqual(config.forwardPorts, [3000]); + assert.equal(config.portsAttributes["3000"].visibility, "private"); + assert.equal(config.portsAttributes["3000"].onAutoForward, "notify"); + for (const port of [10270, 10271]) assert.equal(config.portsAttributes[port].onAutoForward, "ignore"); + assert.equal(config.otherPortsAttributes.onAutoForward, "ignore"); + } + const compose = (await readFile(new URL("../compose.yaml", import.meta.url), "utf8")).replaceAll("\r\n", "\n"); + assert.match(compose, /"127\.0\.0\.1:\$\{SITE_A_EXTENSION_PORT:-10270\}:10260"/); + assert.match(compose, /"127\.0\.0\.1:\$\{SITE_B_EXTENSION_PORT:-10271\}:10260"/); + assert.match(compose, /LOCAL_DOCUMENTDB_HOST: documentdb\n/); + assert.match(compose, /SITE_B_DOCUMENTDB_HOST: documentdb-site-b\n/); + const reconnect = await readFile(new URL("../scripts/test-reconnect.mjs", import.meta.url), "utf8"); + assert.match(reconnect, /documentdb:\\n ports: !override \[\]\\n documentdb-site-b:\\n ports: !override \[\]/); + for (const name of [".gitignore", ".dockerignore"]) { + assert.match(await readFile(new URL(`../${name}`, import.meta.url), "utf8"), /^\.workshop-private\/\r?$/m); + } +}); + +test("read-only playground templates use the selected database/catalog, bounded output and reference pipeline", async () => { + const catalog = await readCatalog(); + const calls = []; + const db = { + workshop_meta: { find(filter) { + assert.deepEqual(JSON.parse(JSON.stringify(filter)), { _id: "catalog", ready: true }); + return { limit(n) { assert.equal(n, 1); return this; }, maxTimeMS(n) { assert.equal(n, 5000); return this; }, toArray: () => [{ fingerprint: catalog.fingerprint }] }; + } }, + sessions: { + find(filter, projection) { + calls.push({ filter, projection }); + return { sort(order) { calls.at(-1).sort = order; return this; }, limit(n) { calls.at(-1).limit = n; return this; }, + maxTimeMS(n) { assert.equal(n, 5000); return this; }, toArray: () => [{ _id: "one" }] }; + }, + aggregate(pipeline, options) { + const clean = JSON.parse(JSON.stringify(pipeline)); + assert.deepEqual(clean.slice(0, 3), programCountsPipeline(catalog.fingerprint)); + assert.deepEqual(clean.at(-1), { $limit: 30 }); + assert.equal(options.maxTimeMS, 5000); + return { toArray: () => [] }; + }, + }, + }; + for (const name of ["inspect", "program-counts"]) { + const source = await readFile(new URL(`../exercises/optional/${name}.documentdb.js`, import.meta.url), "utf8"); + assert.doesNotMatch(source, /mongodb:\/\/|\buse\s*\(|\.(insert|update|delete|drop|create)|\$(out|merge)\b/); + vm.runInNewContext(source, { db }); // Syntax/contract only; NOT extension execution proof. + const empty = { ...db, workshop_meta: { find: () => ({ limit() { return this; }, maxTimeMS() { return this; }, toArray: () => [] }) } }; + assert.throws(() => vm.runInNewContext(source, { db: empty }), /seeded workshop database/); + } + assert.equal(calls[0].filter.catalogVersion, catalog.fingerprint); + assert.equal(calls[0].projection.catalogVersion, 1); + assert.equal(calls[0].limit, 5); +});