diff --git a/.cdsrc.json b/.cdsrc.json index 37a8c597f..40bf22d11 100644 --- a/.cdsrc.json +++ b/.cdsrc.json @@ -62,6 +62,17 @@ ] } }, + { + "for": "nodejs", + "src": "srv-sage", + "dest": "srv-sage", + "options": { + "model": [ + "srv-sage", + "db" + ] + } + }, { "for": "cds-caching" } diff --git a/.gitignore b/.gitignore index bbe5e43c2..258fd606d 100644 --- a/.gitignore +++ b/.gitignore @@ -195,9 +195,11 @@ playwright-report/ srv/lib/_shared/ srv-mcp/lib/_shared/ srv-qa/lib/_shared/ +srv-sage/lib/_shared/ # BTP→BAIP audit run artifacts (export/report/changeset/applied) /btp-audit/ # Discovery sync working drafts — local only, never committed. .sync-draft/ +srv-sage/lib/parsers.bundle.mjs diff --git a/deploy/mta-sage-dev.mtaext b/deploy/mta-sage-dev.mtaext new file mode 100644 index 000000000..6206b659d --- /dev/null +++ b/deploy/mta-sage-dev.mtaext @@ -0,0 +1,14 @@ +_schema-version: 3.3.0 +# DEV extension for the SAGE backend MTA (mta-sage.yaml). +# No parameter overrides needed for DEV — tutorials-xsuaa is the correct +# XSUAA instance name in the dev space. This file exists as a parallel to +# mcp-dev.mtaext so the deploy command is symmetric: +# mbt build -f mta-sage.yaml -t mta_archives +# cf deploy mta_archives/*.mtar -e deploy/mta-sage-dev.mtaext -f +# +# Deploy DEV (from origin/DEV; cf target -s dev FIRST): +# git fetch origin && git checkout origin/DEV +# mbt build -f mta-sage.yaml -t mta_archives +# cf deploy mta_archives/*.mtar -e deploy/mta-sage-dev.mtaext -f +ID: tutorials-sage-dev +extends: tutorials-sage diff --git a/deploy/mta-sage-prod.mtaext b/deploy/mta-sage-prod.mtaext new file mode 100644 index 000000000..f35dc752e --- /dev/null +++ b/deploy/mta-sage-prod.mtaext @@ -0,0 +1,25 @@ +_schema-version: 3.3.0 +# PROD extension for the SAGE backend MTA (mta-sage.yaml). +# +# tutorials-xsuaa service-name → xsuaa-imsprod. DEV+PROD share one +# subaccount, so prod's XSUAA instance has a distinct name (xsuaa-imsprod, +# with xsappname 'tutorials-prod'); it is deployed and OWNED by the main +# tutorials-ims MTA (see deploy/prod.mtaext). srv-sage adopts it as an +# existing service for the XSUAA-fallback leg of its hybrid auth. The base +# mta-sage.yaml hardcodes service-name: tutorials-xsuaa (the DEV name), +# which does not exist in prod — without this override the SAGE MTA deploy +# fails to resolve the existing service. We only rename the binding target; +# we do NOT set config-path here (the main MTA owns + configures +# xsuaa-imsprod from xs-security-prod.json). +# +# Deploy PROD (from origin/main; cf target -s prod FIRST): +# git fetch origin && git checkout origin/main +# mbt build -f mta-sage.yaml -t mta_archives +# cf deploy mta_archives/*.mtar -e deploy/mta-sage-prod.mtaext -f +ID: tutorials-sage-prod +extends: tutorials-sage + +resources: + - name: tutorials-xsuaa + parameters: + service-name: xsuaa-imsprod diff --git a/docs/developers/operations/mta-deployment.md b/docs/developers/operations/mta-deployment.md index f7d9b9120..b91f2664c 100644 --- a/docs/developers/operations/mta-deployment.md +++ b/docs/developers/operations/mta-deployment.md @@ -4,7 +4,7 @@ Complete deployment procedure for standing up the tutorials-ims stack in a CF sp ## Architecture -The stack is **two separately-deployed MTAs** sharing one set of service instances: +The stack is **three separately-deployed MTAs** sharing one set of service instances: ```text tutorials-ims MTA (.deploy/mta.yaml — the main MTA; OWNS the service instances) @@ -17,21 +17,29 @@ tutorials-ims MTA (.deploy/mta.yaml — the main MTA; OWNS the service instance tutorials-mcp MTA (mta-mcp.yaml at repo root — the MCP microservice; ADOPTS the services above) └── tutorials-srv-mcp (type: nodejs — serves ONLY the authenticated /mcp-auth/* surface) -Resources (created/owned by the MAIN MTA; the MCP MTA references them as existing-service): -├── tutorials-hana (HDI container — com.sap.xs.hdi-container) -├── tutorials-xsuaa (XSUAA application — org.cloudfoundry.managed-service) -├── tutorials-identity (IAS — public PKCE client for the MCP app) -├── tutorials-destination (Destination lite — org.cloudfoundry.managed-service) -├── tutorials-credstore (Credential Store — holds deploy-time secrets) -├── tutorials-mail (optional — fails gracefully if plan unavailable) -├── tutorials-audit-log (optional) -└── tutorials-cloud-logging (optional) +tutorials-sage MTA (mta-sage.yaml at repo root — the SAGE isolated backend; ADOPTS the services above) +└── tutorials-srv-sage (type: nodejs — serves ONLY the SAGE author operations surface) + +Resources (created/owned by the MAIN MTA; the MCP and SAGE MTAs reference them as existing-service): +├── tutorials-hana (HDI container — com.sap.xs.hdi-container) +├── tutorials-xsuaa (XSUAA application — org.cloudfoundry.managed-service) +├── tutorials-identity (IAS — public PKCE client for the MCP app) +├── tutorials-destination (Destination lite — org.cloudfoundry.managed-service) +├── tutorials-credstore (Credential Store — holds deploy-time secrets) +├── tutorials-mail (optional — fails gracefully if plan unavailable) +├── tutorials-audit-log (optional) +└── tutorials-cloud-logging (optional) + +Resources (created/owned OUT-OF-BAND; the SAGE MTA references as existing-service): +└── tutorials-sage-identity (IAS — dedicated public PKCE client for the SAGE VS Code extension; + provisioned per docs/developers/operations/sage-ias-setup.md) ``` The approuter (main MTA) fronts both backends: `/mcp-auth/*` is proxied to the external `tutorials-srv-mcp` app via the `srv-mcp-api` destination (`${srv-mcp-url}`), everything else -to the local `srv-api`. The MCP MTA creates **no** service instances of its own — it declares -each resource as `org.cloudfoundry.existing-service` and adopts the main MTA's instances. +to the local `srv-api`. The MCP and SAGE MTAs create **no** service instances of their own — they declare +each resource as `org.cloudfoundry.existing-service` and adopt the main MTA's instances (plus +`tutorials-sage-identity` for the SAGE MTA, which is provisioned out-of-band). ## Prerequisites @@ -109,6 +117,37 @@ space so those instances exist before the MCP MTA tries to adopt them. The appro discovery/routing env (`srv-mcp-url`, `XSUAA_MCP_URL`, `MCP_ISSUER_KIND`) stays in the **main** MTA's `deploy/*.mtaext` (the approuter lives in the main MTA). +### SAGE MTA (`tutorials-sage`) + +The SAGE isolated backend (`/author/*` + `/preview/render`) ships as a **separate MTA** (`mta-sage.yaml` at +repo root, module `tutorials-srv-sage`). It is **not** part of the main MTA archive. +There is **no orchestrated path** — deploy it by hand: + +```bash +# From repo root (the descriptor's before-all runs from root, no `cd ..`) +mbt build -f mta-sage.yaml -t mta_archives +cf deploy mta_archives/*.mtar -e deploy/mta-sage-dev.mtaext -f # DEV +# PROD: cf deploy mta_archives/*.mtar -e deploy/mta-sage-prod.mtaext -f +``` + +| Env | SAGE MTA ext | MTA ID (ext) | Notes | +| --- | --- | --- | --- | +| dev | `deploy/mta-sage-dev.mtaext` | `tutorials-sage-dev` | No overrides needed — `tutorials-xsuaa` is the DEV XSUAA name | +| prod | `deploy/mta-sage-prod.mtaext` | `tutorials-sage-prod` | Overrides `tutorials-xsuaa` → `service-name: xsuaa-imsprod` (PROD XSUAA, xsappname `tutorials-prod`) | + +**Service adoption:** every `resources:` entry in `mta-sage.yaml` is +`org.cloudfoundry.existing-service` (`tutorials-sage-identity`, `tutorials-xsuaa`, +`tutorials-hana`). The SAGE MTA creates no instances — it adopts the ones the **main MTA +owns**, plus the dedicated IAS instance provisioned by the [sage-ias-setup.md](sage-ias-setup.md) +runbook. **Deploy the main MTA first** on a fresh space — `tutorials-hana`, `tutorials-xsuaa`, +and `tutorials-sage-identity` must all exist before `mta-sage.yaml` can adopt them. On an +existing space the instances are already present; deploy order does not matter. + +**Before deploying the SAGE MTA for the first time:** ensure `tutorials-sage-identity` has +been provisioned out-of-band per [sage-ias-setup.md](sage-ias-setup.md) Step 2. This is a +dedicated IAS public-client instance (PKCE-only, no `client_credentials`) separate from the +shared `tutorials-identity` used by the MCP surface. + ## Step 2: Populate Data (First Deploy Only) After a fresh HDI deploy, mission/group slugs are empty. The build pipeline needs slugs to generate pages. @@ -217,8 +256,10 @@ curl -s -o /dev/null -w "%{http_code}" "$APPROUTER/tutorials/abap-dev-get-starte |------|---------| | `.deploy/mta.yaml` | Main MTA (`tutorials-ims`) deployment descriptor | | `mta-mcp.yaml` | MCP MTA (`tutorials-mcp`) descriptor — the separate `/mcp-auth/*` app | +| `mta-sage.yaml` | SAGE MTA (`tutorials-sage`) descriptor — the isolated SAGE author backend | | `deploy/dev.mtaext` | Main-MTA DEV extension (debug logging, app name suffix, `srv-mcp-url`) | | `deploy/mcp-dev.mtaext` / `deploy/mcp-prod.mtaext` | MCP-MTA env extensions | +| `deploy/mta-sage-dev.mtaext` / `deploy/mta-sage-prod.mtaext` | SAGE-MTA env extensions | | `xs-security.json` | XSUAA scopes, role templates, role collections | | `approuter/xs-app.json` | AppRouter route definitions (incl. the `/mcp-auth/*` → `srv-mcp-api` route) | | `.cdsrc-private.json` | Local hybrid bindings (gitignored) | diff --git a/docs/developers/operations/sage-ias-setup.md b/docs/developers/operations/sage-ias-setup.md new file mode 100644 index 000000000..38d383e7b --- /dev/null +++ b/docs/developers/operations/sage-ias-setup.md @@ -0,0 +1,236 @@ +# SAGE IAS Public-Client Setup Runbook + +This runbook provisions a **dedicated IAS public-client instance** (`tutorials-sage-identity`) for the SAGE VS Code extension. SAGE authenticates to IAS via secret-less PKCE (which IAS supports; XSUAA cannot be a public client) and then calls the isolated `srv-sage` backend. + +This is a **Tom-run, out-of-band** provisioning step — no `cf` commands are scripted into version control. The resulting `clientid` and IAS tenant URL are needed for Task 6 (live sign-in verification) and for the SAGE extension's `imsAuth.ts` configuration. + +--- + +## Why a dedicated instance? + +SAGE gets its own `tutorials-sage-identity` instance rather than reusing the shared `tutorials-identity` for audience isolation: an IAS token minted for SAGE's `clientid` cannot be accepted by the MCP or browser surfaces, and vice versa. This mirrors how `tutorials-srv-mcp` is isolated from `tutorials-srv`. + +--- + +## Prerequisites + +- `cf login` targeting the correct space (re-check `cf target` before every mutating command — see [ias-setup.md § CF target drift](ias-setup.md)) +- The IAS service plan `application` must be entitled in the subaccount + +--- + +## Step 1 — Verify CF target before provisioning + +```bash +cf target +# Confirm: space = tutorials-system/dev (for DEV) +# space = tutorials-system/prod (for PROD) +# If wrong: cf target -o tutorials-system -s dev +``` + +--- + +## Step 2 — Create the SAGE IAS instance + +Run **once per space** (DEV and PROD are separate instances, yielding separate `clientid` values). + +### DEV + +```bash +cf target -o tutorials-system -s dev +cf create-service identity application tutorials-sage-identity -c '{ + "oauth2-configuration": { + "grant-types": [ + "authorization_code_pkce_s256", + "refresh_token" + ], + "public-client": true, + "redirect-uris": [ + "vscode://sap-tutorials.sage-tutorial-extension/**", + "http://localhost:*/oauth/callback", + "http://127.0.0.1:*/oauth/callback" + ] + } +}' +``` + +### PROD + +```bash +cf target -o tutorials-system -s prod +cf create-service identity application tutorials-sage-identity -c '{ + "oauth2-configuration": { + "grant-types": [ + "authorization_code_pkce_s256", + "refresh_token" + ], + "public-client": true, + "redirect-uris": [ + "vscode://sap-tutorials.sage-tutorial-extension/**", + "http://localhost:*/oauth/callback", + "http://127.0.0.1:*/oauth/callback" + ] + } +}' +``` + +**Configuration notes:** + +| Field | Value | Reason | +|---|---|---| +| `grant-types` | `authorization_code_pkce_s256`, `refresh_token` | PKCE-only; `client_credentials` intentionally omitted — SAGE is a user-facing client, not M2M. `authorization_code_pkce_s256` is the SAP IAS-specific PKCE grant name (confirmed in `mta-mcp.yaml:64` and [ias-setup.md § M2M](ias-setup.md)); if the broker returns `invalid_grant_type` check that the IAS plan is `application` and not `broker` | +| `public-client` | `true` | No client secret ever — matches the PKCE contract; XSUAA cannot do this, IAS can | +| `redirect-uris` | `vscode://sap-tutorials.sage-tutorial-extension/**` | VS Code custom-scheme callback (required for PKCE in-extension) | +| `redirect-uris` | `http://localhost:*/oauth/callback`, `http://127.0.0.1:*…` | Local dev / test runner loopback | + +> **Do NOT add `client_credentials` to this instance** — SAGE is a user-facing VS Code extension. The local `localhost` URIs are for development and test; they are harmless for a public client. + +--- + +## Step 3 — Read back the clientid and IAS tenant URL + +After creation, extract the credentials that the extension and backend need. + +```bash +# Create a temporary service key to read the credentials +cf create-service-key tutorials-sage-identity sk-read + +# Strip the CF header so jq can parse +cf service-key tutorials-sage-identity sk-read | sed -n '/{/,$p' > sage-sk.json + +# Print the values you need +jq -r '"clientid: " + .credentials.clientid' sage-sk.json +jq -r '"url: " + .credentials.url' sage-sk.json + +# Clean up — the key is not needed further; credentials are read once +cf delete-service-key tutorials-sage-identity sk-read -f +rm -f sage-sk.json +``` + +> **`sage-sk.json` is transient** — it must be removed immediately after use and never committed (the `rm -f` above covers the happy path). If this block exits early (e.g. `jq` not found, CF error), clean up manually: +> ```bash +> cf delete-service-key tutorials-sage-identity sk-read -f && rm -f sage-sk.json +> ``` + +The `url` field is the IAS tenant root (e.g. `https://atxgsg7zi.accounts.ondemand.com`). +The `clientid` is the OAuth2 client identifier SAGE presents in its PKCE flow. + +Record both values: + +| Value | Where used | +|---|---| +| `clientid` (DEV) | `imsAuth.ts` `clientId` field for the DEV/testing build of SAGE | +| `clientid` (PROD) | `imsAuth.ts` `clientId` field for the stable PROD build of SAGE | +| `url` (IAS tenant root) | `authUrl` → `/oauth2/authorize`, `tokenUrl` → `/oauth2/token` | + +> **Never commit these values to source** — they are runtime config in the extension's `package.json` contributes or environment-specific build constants, not in VCS. `sage-sk.json` is a transient file; remove it immediately after use. + +--- + +## Step 4 — Add or update redirect URIs (if updating an existing instance) + +If the instance already exists and you need to add or change redirect URIs (e.g. a new VS Code extension ID), use `cf update-service`. Always carry forward all existing URIs additively — omitting a URI removes it and breaks live sessions: + +```bash +cf update-service tutorials-sage-identity -c '{ + "oauth2-configuration": { + "grant-types": [ + "authorization_code_pkce_s256", + "refresh_token" + ], + "public-client": true, + "redirect-uris": [ + "vscode://sap-tutorials.sage-tutorial-extension/**", + "http://localhost:*/oauth/callback", + "http://127.0.0.1:*/oauth/callback" + ] + } +}' +``` + +> **Note:** `cf update-service -c` replaces the entire `oauth2-configuration` object. Always include the full desired config in a single call, not just the delta. + +--- + +## Step 5 — Adopt the instance in `mta-sage.yaml` + +The `srv-sage` MTA adopts `tutorials-sage-identity` as an `existing-service` (the same pattern used by the MCP MTA for `tutorials-identity`). The relevant stanza in `mta-sage.yaml` will look like: + +```yaml +resources: + - name: tutorials-sage-identity + type: org.cloudfoundry.existing-service + parameters: + service-name: tutorials-sage-identity +``` + +And the `tutorials-srv-sage` module binds it: + +```yaml +modules: + - name: tutorials-srv-sage + ... + requires: + - name: tutorials-sage-identity + - name: tutorials-hana + - name: tutorials-xsuaa # hybrid fallback — DEV name +``` + +> **PROD XSUAA name differs.** On DEV the XSUAA instance is `tutorials-xsuaa`; on PROD it is `xsuaa-imsprod`. The `mta-sage.yaml` PROD variant (or `.mtaext` override) must reference `xsuaa-imsprod` as the `existing-service` name — using `tutorials-xsuaa` on PROD will fail the deploy with a "service not found" error: +> +> ```yaml +> # deploy/mta-sage-prod.mtaext (or prod resource block) +> resources: +> - name: tutorials-xsuaa +> parameters: +> service-name: xsuaa-imsprod # override for PROD space +> ``` + +**Deploy the main MTA before the SAGE MTA** on a fresh space — `tutorials-sage-identity` must exist before `mta-sage.yaml` can adopt it. On an existing space the instances are already there; order does not matter. + +--- + +## Step 6 — Verify the instance is a public client + +Confirm the IAS metadata endpoint shows `none` as a supported `token_endpoint_auth_method` (the public-client signal): + +```bash +cf create-service-key tutorials-sage-identity sk-verify +cf service-key tutorials-sage-identity sk-verify | sed -n '/{/,$p' > sage-sk-v.json +TENANT_URL=$(jq -r .credentials.url sage-sk-v.json) + +curl -s "$TENANT_URL/.well-known/openid-configuration" \ + | jq '.token_endpoint_auth_methods_supported' +# Expected to include "none" — confirms public-client mode +# XSUAA does NOT include "none" (that's the root cause we're working around) + +cf delete-service-key tutorials-sage-identity sk-verify -f +rm -f sage-sk-v.json +``` + +> **`sage-sk-v.json` is transient** — remove it immediately after use, never commit it. If this block exits early (e.g. `curl` or `jq` not found), clean up manually: +> ```bash +> cf delete-service-key tutorials-sage-identity sk-verify -f && rm -f sage-sk-v.json +> ``` + +If `none` is absent, the instance was created without `"public-client": true` or the update did not take. Re-run Step 2 (`cf update-service ...`) with the correct config. + +--- + +## Rollback / decommission + +```bash +# Delete the instance (removes all service keys and bindings first) +cf delete-service tutorials-sage-identity -f +``` + +The main `tutorials-srv` and `tutorials-srv-mcp` are unaffected — they bind `tutorials-identity`, not `tutorials-sage-identity`. + +--- + +## References + +- Design spec: [`docs/superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md`](../../superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md) +- Shared IAS + M2M runbook: [`docs/developers/operations/ias-setup.md`](ias-setup.md) — covers `tutorials-identity`, M2M service keys, CF-target-drift warning +- MTA deployment guide: [`docs/developers/operations/mta-deployment.md`](mta-deployment.md) — covers `existing-service` adoption and deploy order +- IAS PKCE public-client constraint: `mta-mcp.yaml:64` comment + design spec §"Root cause" diff --git a/docs/superpowers/plans/2026-11-19-sage-ias-isolated-backend.md b/docs/superpowers/plans/2026-11-19-sage-ias-isolated-backend.md new file mode 100644 index 000000000..5685b9bc7 --- /dev/null +++ b/docs/superpowers/plans/2026-11-19-sage-ias-isolated-backend.md @@ -0,0 +1,120 @@ +# SAGE IAS Isolated Backend (`srv-sage`) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Restore SAGE IMS sign-in (broken in 2.0.4) by standing up an isolated IAS-authenticated backend (`srv-sage`) serving SAGE's 5 author ops + preview, and repointing the SAGE extension at it — no embedded secret, no change to the main `tutorials-srv`/srv-qa XSUAA auth. + +**Architecture:** New CAP app `srv-sage` in `tutorials-ims` (own MTA, `auth: kind:ias + xsuaa:true`), adopting the shared HANA container as `existing-service`, cloning the proven `srv-mcp`/`srv-qa` isolation pattern (dedicated `.cdsrc.json` build task, thin `server.js`). SAGE authenticates via dedicated IAS public-client PKCE and sends the IAS `id_token` as Bearer. + +**Tech Stack:** CAP Node.js, `@sap/xssec` v4 (ias), SAP IAS (identity service), HANA (shared), VS Code extension (TypeScript), Mocha unit tests. Deploy via MTA to CF (DEV first). + +**Spec:** `docs/superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md` + +## Global Constraints + +- No client secret in the SAGE extension, ever. Secret gate (`grep -rnE "clientSecret[[:space:]]*=|client_secret[\"']?[[:space:]]*:" src/`) stays zero. +- Do NOT modify `tutorials-srv` or `srv-qa` auth models, `server.js`, or their XSUAA middleware. `srv-sage` is additive and isolated. +- `srv-sage` auth: `@requires: 'authenticated-user'` only (NOT XSUAA scopes). Authorization is in-handler by caller identity (`assertOwnership`/`provisionDbUser`), ported from `srv/author-service.js`. +- SAGE sends the IAS **`id_token`** as Bearer (not access_token) — xssec `kind:ias` validates `aud === clientid` (PR #2707). +- `tutorials-ims` PRs target **DEV**, never main/PROD directly. SAGE PRs target `main`. Signed commits (SSH) required on both repos. +- IAS service-instance provisioning + redirect-URI config is **Tom-owned** (BTP); the plan hands exact commands, does not run them against prod. +- Rollout: DEV → SAGE `latest-testing` → verify round-trip → PROD + stable 2.0.5. + +## Review Focus + +- **IAS token audience mismatch:** SAGE sending access_token instead of id_token → every `srv-sage` call 401s (`aud` check). Pinned by Task 6 (client) + Task 8 (live verify). +- **MyOwnedTutorials returns 0:** author join returns 0 for users who never browser-logged-in (known gotcha) — a green auth but empty panel looks like success. Pinned by Task 8 verifying real data, not just 200s. +- **Ownership bypass:** dropping `@requires:'Tutorial.Author'` to `'authenticated-user'` must NOT loosen per-user scoping — any authenticated IAS user must still see only their own tutorials. Pinned by Task 4 handler tests (caller A cannot read caller B's tutorials). +- **Action-path mismatch:** `srv-sage` must serve the exact action-import path the shipped extension calls (`/author/reviewTutorial` vs `/author/AuthorService.reviewTutorial`). Pinned by Task 5. +- **Main-app regression:** a new MTA sharing the HANA container must not disturb `tutorials-srv` XSUAA routes. Pinned by Task 7 smoke check. + +--- + +## Part A — `tutorials-ims` repo (backend + IAS) + +### Task 1: IAS provisioning runbook (Tom-owned; plan hands commands) + +**Files:** Create `docs/developers/operations/sage-ias-setup.md` + +- [ ] **Step 1:** Write the runbook: `cf create-service identity tutorials-sage-identity -c {...}` with `oauth2-configuration` = public client (PKCE S256, no secret), `redirect-uris` including `vscode://sap-tutorials.sage-tutorial-extension/**`, for DEV and PROD. Mirror `docs/developers/operations/ias-setup.md`. +- [ ] **Step 2:** Document how to read the resulting clientid + tenant URL (for the extension config) and how to add it as `existing-service` in `mta-sage.yaml`. +- [ ] **Step 3:** Commit. (No deploy; Tom runs the `cf` commands out of band and provides the DEV clientid before Task 6's live verify.) + +### Task 2: `srv-sage` app skeleton (thin server + package + build task) + +**Files:** Create `srv-sage/server.js`, `srv-sage/package.json`; Modify `.cdsrc.json` + +**Interfaces:** Produces the `srv-sage` CAP app that later tasks add services to. `auth: { kind: ias, xsuaa: true }`. + +- [ ] **Step 1:** `srv-sage/server.js` — copy `srv-mcp/server.js` (77 lines) shape; drop the `/mcp-auth` rewrite region. Healthz + bootstrap only. +- [ ] **Step 2:** `srv-sage/package.json` — copy `srv-mcp/package.json:26-56` `cds.requires`: `auth: {kind:ias, xsuaa:true}`, `db:{kind:hana}`. Remove MCP-specific `MainDeveloperService` remote binding. +- [ ] **Step 3:** `.cdsrc.json` — add build task after the srv-mcp one (`.cdsrc.json:55-64`): `{ "for":"nodejs", "src":"srv-sage", "dest":"srv-sage", "options": { "model": ["srv-sage","db"] } }`. +- [ ] **Step 4:** Verify build task compiles an empty-but-valid model: `npx cds build --production 2>&1 | grep -i srv-sage` → shows srv-sage built, no error. +- [ ] **Step 5:** Commit (signed). + +### Task 3: `srv-sage` author service model (5 ops, IAS-gated) + +**Files:** Create `srv-sage/author-sage-service.cds` + +**Interfaces:** Produces `AuthorSageService` exposing: entities `MyOwnedTutorials` (from `db/views`), `Tags`; actions `isSlugAvailable(slug) returns {value:Boolean}`, `reviewTutorial(tutorialId)`, `snoozeTutorial(tutorialId, days)`. All `@requires: 'authenticated-user'`. + +- [ ] **Step 1:** Write the `.cds`: `using { com.sap.developers.ims } from '../db/schema';` + `using from '../db/views';`. Define the service with `@path` matching what the extension calls (resolve in Task 5), the 2 read entities + 3 actions, service-level `@requires: 'authenticated-user'`. Do NOT `using { AdminService }`. +- [ ] **Step 2:** `npx cds compile srv-sage/author-sage-service.cds` → compiles with no unresolved refs. +- [ ] **Step 3:** Commit (signed). + +### Task 4: `srv-sage` handlers (ported, with ownership tests) + +**Files:** Create `srv-sage/author-sage-service.js`, `srv-sage/lib/` (bundled `resolve-db-user` + minimal deps); Test: `srv-sage/test/author-sage.test.js` (or repo's test location) + +**Interfaces:** Consumes the model from Task 3. Ports from `srv/author-service.js`: `MyOwnedTutorials` caller-scoped read, `Tags` read, `isSlugAvailable`, `reviewTutorial`, `snoozeTutorial`, plus `assertOwnership`/`provisionDbUser`/`resolveDbUser`. No AI/GitHub/credstore imports. + +- [ ] **Step 1 (RED):** Write handler test: two distinct authenticated identities A and B; A's `MyOwnedTutorials` returns only A's tutorials, and A calling `reviewTutorial` on B's tutorialId is rejected (ownership). Use the repo's CAP test harness (in-memory sqlite or test HANA). +- [ ] **Step 2:** Run → FAIL (no handler). +- [ ] **Step 3:** Implement handlers, porting the identity-resolution + ownership logic verbatim from `srv/author-service.js` (adapt the auth-context read for `kind:ias`). +- [ ] **Step 4:** Run → PASS; ownership enforced. +- [ ] **Step 5:** Commit (signed). + +### Task 5: Preview route in `srv-sage` + pin action path + +**Files:** Create `srv-sage/preview-renderer.js` (+ `srv-sage/lib/parsers.bundle.mjs`), wire route in `srv-sage/server.js`; reference: deployed extension source + +- [ ] **Step 1:** Pin the action-path: read `imsApiClient.ts` on SAGE `main` (un-minified) — record whether it calls `/author/reviewTutorial` (bare) or `/author/AuthorService.reviewTutorial`. Set `srv-sage`'s service `@path` + action names to serve the exact path the shipped 2.0.4 extension uses (so DEV testing works without a client change), noting any client alignment needed in Task 6. +- [ ] **Step 2:** Port `srv-qa/preview-renderer.js` (194 lines, Node builtins + `./lib/parsers.bundle.mjs` only) into `srv-sage/`; wire `POST /preview/render` in `srv-sage/server.js` behind the same IAS auth as the service (authenticated-user). +- [ ] **Step 3:** Test: `POST /preview/render` with sample markdown returns rendered HTML (port a minimal case from any existing preview test). +- [ ] **Step 4:** Run → PASS. Commit (signed). + +### Task 6: `mta-sage.yaml` (new MTA, existing-service adoption) + +**Files:** Create `mta-sage.yaml`; Modify `docs/developers/operations/mta-deployment.md` (document the new MTA) + +- [ ] **Step 1:** Write `mta-sage.yaml` mirroring `mta-mcp.yaml`: module `tutorials-srv-sage` (`path: gen/srv-sage`); adopt as `existing-service`: `tutorials-hana`, `tutorials-sage-identity` (IAS), `tutorials-xsuaa` (hybrid fallback). Build: `npm install` + `cds build --production`. No credstore/destination. +- [ ] **Step 2:** `mbt build -f mta-sage.yaml -t mta_archives` (wrap noisy output) → produces mtar, no error. +- [ ] **Step 3:** Document the MTA + its `existing-service` dependency on the main MTA (deploy main first) in mta-deployment.md. +- [ ] **Step 4:** Commit (signed). **Open PR → DEV.** + +### Task 7: Deploy to DEV + main-app regression smoke (Tom-gated deploy) + +- [ ] **Step 1:** After PR merges to DEV and Tom has provisioned `tutorials-sage-identity` (Task 1): deploy `mta-sage.yaml` to DEV (`cf deploy`, Tom-authorized). +- [ ] **Step 2:** Smoke: `tutorials-srv` XSUAA browser route still works (hit an existing authenticated endpoint) — confirms the shared-HANA new MTA didn't disturb the main app. +- [ ] **Step 3:** Record the DEV `srv-sage` host URL + DEV IAS clientid/tenant for Part B. + +--- + +## Part B — SAGE extension repo + +### Task 8: Repoint SAGE auth + API to IAS/`srv-sage`; testing release; verify + +**Files (SAGE repo):** Modify `src/lib/sync/imsAuth.ts`, `src/lib/ims/imsApiClient.ts`, `CHANGELOG.md`, `RELEASE-NOTES.md`, `package.json` (→ 2.0.5) + +- [ ] **Step 1:** `imsAuth.ts` — change `authUrl`/`tokenUrl` to the IAS tenant (`https:///oauth2/authorize` + `/oauth2/token`), `clientId` to the dedicated SAGE IAS clientid. Keep PKCE + state. **Return the `id_token`** (not `access_token`) from `createSessionFromToken`/`getAccessToken` — per PR #2707. Keep secret absent. +- [ ] **Step 2:** `imsApiClient.ts` — base URL → DEV `srv-sage` host (Task 7). Align action path to Task 5's pinned form if needed. +- [ ] **Step 3:** Update/extend unit tests for the changed auth (id_token selection) + client base. +- [ ] **Step 4:** Secret gate zero; `tsc`/compile/lint clean; unit suite green. +- [ ] **Step 5:** Bump 2.0.5, CHANGELOG/RELEASE-NOTES. Commit (signed). Open PR → `main`. +- [ ] **Step 6 (VERIFICATION GATE — Tom):** After merge, cut SAGE `latest-testing` pointed at DEV. Tom installs, signs in. **Confirm: sign-in succeeds AND My Tutorials shows real tutorials (not 0) AND preview renders.** Only on pass does the project proceed to stable PROD (`srv-sage` PROD deploy + stable 2.0.5) — a separate, explicitly-authorized step outside this plan. + +## Notes for executor + +- Live IAS round-trip and all CF deploys are Tom-gated — the plan builds and tests everything buildable/testable; the DEV deploy (Task 7) and the testing-release verify (Task 8.6) require Tom. Do not claim the fix works until Task 8.6 passes. +- Part A and Part B are sequential (B needs A's DEV host + clientid). Within Part A, Tasks 2→6 are a build chain; Task 1 (runbook) is independent and can go first. +- The `@requires` downgrade to `authenticated-user` is safe ONLY because in-handler ownership is ported intact (Task 4) — do not skip the A-vs-B ownership test. diff --git a/docs/superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md b/docs/superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md new file mode 100644 index 000000000..244f37b9b --- /dev/null +++ b/docs/superpowers/specs/2026-11-19-sage-ias-isolated-backend-design.md @@ -0,0 +1,96 @@ +# Design: SAGE IMS auth via isolated IAS-authenticated backend (`srv-sage`) + +**Date:** 2026-11-19 +**Status:** Draft for approval +**Size:** Project (cross-repo: tutorials-ims backend + SAGE extension + IAS provisioning) +**Supersedes the auth approach in:** 2026-11-19-pkce-public-client-design.md (that fix shipped in SAGE 2.0.4 but cannot work — see Root cause) + +## Intent / why + +SAGE 2.0.4 removed the embedded PROD XSUAA secret and switched IMS sign-in to secret-less PKCE against the XSUAA client `sb-tutorials-prod!t676072`. **It cannot authenticate**: XSUAA returns `401 invalid_client / "Bad credentials"` because the XSUAA `application` plan **cannot be a public client** (broker rejects `public-client`/`_pkce_s256`; confirmed by the tutorials team 2026-09-29, `mta-mcp.yaml:64`). The tenant OIDC metadata confirms it: `token_endpoint_auth_methods_supported` = `["client_secret_basic","client_secret_post","tls_client_auth"]` — no `"none"`. + +We must restore IMS sign-in for SAGE **without** re-embedding a secret and **without** modifying the main `tutorials-srv` XSUAA auth model (route-scoped IAS trust on that app was already reverted once for breaking every XSUAA browser route — `srv/server.js:2317-2320`). + +**Chosen approach:** give SAGE its own isolated backend (`srv-sage`) + its own IAS public client, exactly mirroring how the MCP surface was isolated (`tutorials-srv-mcp`). SAGE authenticates to IAS via public PKCE (which IAS *can* do, XSUAA cannot) and calls `srv-sage`, which serves a minimal author surface over the shared HANA container under `kind: ias` auth. + +## Goals + +- SAGE signs in with secret-less PKCE (public client) — no secret in the VSIX, ever. +- SAGE's 5 backend operations work end-to-end against the shared tutorial data. +- Zero change to `tutorials-srv`'s XSUAA auth model or its browser/PAT/platform routes. +- Author-level authorization preserved (a user only sees/edits their own tutorials). + +## Non-goals + +- No change to the main app's `/author` service, `server.js`, content-store, websockets, scheduler. +- No AI variant generation, content rebuild, GitHub, or credstore in `srv-sage` — SAGE never calls those (verified: `rebuildContent`/`generateOsVariants` have zero call sites in the extension). +- Preview (`POST /preview/render`) is **in scope**, moved from the srv-qa host into `srv-sage` (its renderer is portable; see Open questions #1). SAGE will hit one isolated IAS surface for everything. +- No git-history scrub of the (already-rotated, dead) 2.0.4 secret. + +## Anti-goals + +- Do NOT re-introduce any client secret into the extension. +- Do NOT enable IAS trust on the main `tutorials-srv` `/author` path (the reverted approach). +- Do NOT attempt `public-client: true` on any XSUAA descriptor (broker rejects it). + +## Constraints / key facts (from investigation) + +- SAGE's **entire** backend surface = 5 lightweight AuthorService ops, all plain HANA read/update, no heavy deps: + | SAGE feature | Op | R/W | + |---|---|---| + | My Tutorials panel | `GET MyOwnedTutorials` | read | + | Tag autocomplete | `GET Tags` (OData `$filter/$top/$skip/$count`) | read | + | Slug check | `isSlugAvailable {slug}` | read | + | Mark reviewed | `reviewTutorial {tutorialId}` | write | + | Snooze (defined, no prod caller) | `snoozeTutorial {tutorialId,days}` | write | +- Isolation pattern is proven 3× (`srv-mcp`, `srv-qa`): a dedicated `.cdsrc.json` build task (`model: ["srv-sage","db"]`), shared HANA adopted as `existing-service`, thin `server.js`, own MTA. +- Auth-gate pattern is proven by `srv-mcp`: `auth: { kind: ias, xsuaa: true }` (hybrid) + `@requires: 'authenticated-user'` (NOT the XSUAA `Tutorial.Author` scope, which IAS tokens can't carry). AuthorService already does the *real* authorization in-handler by caller identity (`assertOwnership`, `provisionDbUser` scoping) — that survives the switch. This is the enabling fact. +- IAS public client exists today (`tutorials-identity`, tenant `atxgsg7zi.accounts.ondemand.com`); its `public-client: true` is set out-of-band via `cf update-service`, not in version control. SAGE needs a `vscode://sap-tutorials.sage-tutorial-extension/**` redirect URI added to an IAS app (currently XSUAA-only). +- OData action path ambiguity: SAGE source calls `/author/reviewTutorial`; unit tests assert `/author/AuthorService.reviewTutorial`. `srv-sage` must serve whatever the shipped extension actually calls; pin by inspecting the built `out/` of the deployed build, and align the extension client to the canonical CAP action-import path. + +## Approaches considered + +- **A. Isolated `srv-sage` IAS app (CHOSEN).** Own IAS public client + own CAP app + own MTA; minimal author surface; `@requires:'authenticated-user'` + existing in-handler ownership. Full security isolation; zero blast radius on the main app. Cost: a new (thin) deployable + IAS client provisioning. Chosen because it mirrors the team's own proven answer (MCP) and never touches the twice-fragile main-app auth. +- **B. Backend token-exchange proxy on `tutorials-srv`.** Smaller build, but couples SAGE to the main app and adds an endpoint that custodies the XSUAA secret server-side. Rejected in favor of full isolation (user's explicit preference for an isolated security setup like MCP). +- **C. IAS trust on main `tutorials-srv` `/author`.** Requires issuer trust + IAS→`Tutorial.Author` role mapping on a path whose IAS trust was already reverted for breaking browser routes. Highest blast radius. Rejected. +- **D. Revert to embedded secret.** Re-introduces the vulnerability. Rejected. + +## The build (what the implementer does) + +Cross-repo. Order matters: backend + IAS first (so there's something to authenticate against), then the extension flip. + +### Part 1 — `tutorials-ims` repo: new `srv-sage` app +1. `srv-sage/` dir: thin `server.js` (copy `srv-mcp/server.js` shape, drop the `/mcp-auth` rewrite); `package.json` with `cds.requires.auth = { kind: ias, xsuaa: true }`, `db: { kind: hana }`. +2. `srv-sage/author-sage-service.cds`: a SAGE-scoped service `using { com.sap.developers.ims } from '../db/schema'` (+ `../db/views` for `MyOwnedTutorials`), exposing ONLY the 5 ops, gated `@requires: 'authenticated-user'`. Do **not** `using { AdminService }` (that's only needed for the dropped `rebuildContent`). +3. Port handler logic from `srv/author-service.js` for those 5 ops: the `MyOwnedTutorials` caller-scoped read, `Tags` read, `isSlugAvailable`, `reviewTutorial`, `snoozeTutorial`, plus `assertOwnership`/`provisionDbUser`/`resolveDbUser` identity resolution (bundle `resolve-db-user` the way `scripts/bundle-shared.cjs` bundles for srv-mcp). No AI/GitHub/credstore imports. +4. `.cdsrc.json`: add build task `{ "for":"nodejs", "src":"srv-sage", "dest":"srv-sage", "options": { "model": ["srv-sage","db"] } }`. +5. `mta-sage.yaml` (new MTA): module `tutorials-srv-sage` (`path: gen/srv-sage`); adopt `tutorials-hana`, `tutorials-identity` (IAS), `tutorials-xsuaa` (hybrid fallback) as `existing-service`; approuter route for SAGE if needed. (credstore/destination NOT needed — no secret-backed actions.) +6. Provision SAGE's IAS public client (own instance or reuse `tutorials-identity`) and add the `vscode://…` redirect URI additively via `cf update-service` (owned by Tom; documented, not scripted into VCS — matches `ias-setup.md`). + +### Part 2 — SAGE extension repo +7. Repoint `imsAuth.ts` from the XSUAA tenant to the IAS tenant: `authUrl`/`tokenUrl` → `https:///oauth2/authorize` + `/oauth2/token`; `clientId` → SAGE's IAS public clientid. Keep PKCE + `state` (both already correct for a public client). +8. Repoint `imsApiClient.ts` base URL to the `srv-sage` app host; confirm the action-import path matches what `srv-sage` serves. +9. Bump version (2.0.5), CHANGELOG/RELEASE-NOTES. + +## Verification (before claiming done) + +- Live probe from Tom's machine: secret-less PKCE token exchange against the **IAS** endpoint returns a token (not `invalid_client`). +- `srv-sage` deployed to DEV; SAGE (pointed at DEV) completes sign-in AND all 5 ops return real data (My Tutorials shows the author's tutorials — not 0, cf. the known "author join returns 0 for non-browser-logged-in users" gotcha). +- Main-app regression check: XSUAA browser routes on `tutorials-srv` unaffected (separate MTA, so structurally isolated — confirm by smoke test). +- Unit tests for any new `srv-sage` handlers + the extension's changed auth/client. + +## Open questions for Tom + +1. **Preview** (`/preview/render`) — **RESOLVED: serve it from `srv-sage` too.** Recon confirmed the current srv-qa route is XSUAA-scope-gated (`requireXsuaaScope('Tutorial.Author')` in `srv-qa/xsuaa-scope-middleware.js`) and srv-qa binds no IAS, so an IAS token gets 401/403 — preview breaks under the switch just like `/author`. Rather than bolt IAS onto srv-qa's bespoke middleware, move the route into `srv-sage`: `srv-qa/preview-renderer.js` (194 lines) depends only on Node builtins + a local `./lib/parsers.bundle.mjs` (no srv-qa/XSUAA coupling), so it ports cleanly. All SAGE traffic then hits one isolated IAS surface. +2. **IAS client:** **DECIDED — dedicated SAGE IAS public-client instance** (audience isolation; SAGE tokens aud-scoped to SAGE, separate from MCP's `tutorials-identity`). Provision its own `identity` instance + `vscode://sap-tutorials.sage-tutorial-extension/**` redirect URI. +3. **Rollout:** **DECIDED — DEV + testing-release first.** Deploy `srv-sage` to DEV, cut SAGE 2.0.5 as `latest-testing` pointed at DEV, verify the full round-trip (sign-in + all 5 ops + preview returning real data), THEN stable PROD `srv-sage` + stable 2.0.5. + +## Critical client constraint (from PR #2707) + +SAGE must send the IAS **`id_token`** (a JWT with a usable `aud`) as the Bearer — **not** the opaque IAS `access_token`. `@sap/xssec kind:ias` validates `aud === clientid`; the access_token won't validate. The extension's `imsAuth.ts` currently stores/returns `tokenResponse.access_token`; for IAS it must return `id_token`. This is a required change in `createSessionFromToken`/`getAccessToken`. + +## Delivery + +- `tutorials-ims`: feature branch → PR → DEV (never direct to main/PROD; this repo's PRs target DEV). +- SAGE: feature branch → PR → `main`. +- Both signed commits. No prod deploy without explicit go-ahead + the live sign-in verification. diff --git a/mta-sage.yaml b/mta-sage.yaml new file mode 100644 index 000000000..ef3e08014 --- /dev/null +++ b/mta-sage.yaml @@ -0,0 +1,84 @@ +_schema-version: 3.3.0 +# MTA descriptor for the SAGE isolated backend (tutorials-sage). +# Deployed SEPARATELY from the main tutorials-ims MTA (.deploy/mta.yaml). +# This file lives at repo root → path: gen/srv-sage (root-relative, no ../). +# before-all runs from ROOT (no cd ..) — mbt uses the descriptor's directory as cwd. +ID: tutorials-sage +version: 1.0.0 + +build-parameters: + before-all: + - builder: custom + commands: + - npm install + # Bundle workspace packages + build parsers bundle for srv-sage. + # bundle-shared.cjs writes srv-sage/lib/_shared/core.bundle.mjs. + # prebuild:parsers-bundle writes srv-sage/lib/parsers.bundle.mjs + # (entry: scripts/parsers/index.ts; exports composeTutorial/renderHugoFrontmatter/normalizeVideo). + - bash -c "node scripts/bundle-shared.cjs" + - bash -c "npm run prebuild:parsers-bundle" + - bash -c "npx cds build --production" + # @tutorials/core is a workspace package resolved via esbuild bundle in + # gen/srv-sage/srv/lib/_shared/. Remove it from gen/srv-sage/package.json + # before mbt packages the module — otherwise `npm install` inside gen/srv-sage + # creates a dangling symlink to gen/srv-sage/packages/core that mbt cannot archive. + - bash -c "node -e \"const p=require('./gen/srv-sage/package.json'); delete p.dependencies['@tutorials/core']; require('fs').writeFileSync('./gen/srv-sage/package.json', JSON.stringify(p,null,2)+'\n');\"" + +modules: + - name: tutorials-srv-sage + type: nodejs + path: gen/srv-sage + parameters: + memory: 512M + disk-quota: 512M + buildpack: nodejs_buildpack + stack: cflinuxfs5 + instances: 1 + properties: + NODE_ENV: production + EXPOSE_CAP_UI: false + provides: + - name: srv-sage-api + properties: + srv-url: ${default-url} + requires: + - name: tutorials-hana + - name: tutorials-sage-identity + # Hybrid auth: IAS primary (tutorials-sage-identity) + XSUAA fallback. + # CAP `auth: {kind:ias, xsuaa:true}` in srv-sage/package.json requires TWO bindings. + # NOTE: on DEV the XSUAA instance is tutorials-xsuaa; on PROD it is xsuaa-imsprod. + # The PROD mtaext (deploy/mta-sage-prod.mtaext) overrides service-name: xsuaa-imsprod. + - name: tutorials-xsuaa + +resources: + # Dedicated IAS public-client instance for SAGE (tutorials-sage-identity). + # Created out-of-band (see docs/developers/operations/sage-ias-setup.md). + # Adopted as existing-service so the clientid is STABLE across deploys — + # an MTA-managed instance would be recreated with a new clientid on each + # rebuild, breaking the clientid baked into the SAGE extension config. + # Grant types: authorization_code_pkce_s256 + refresh_token only + # (no client_credentials — SAGE is a user-facing VS Code extension, not M2M). + # Audience isolation: SAGE tokens (minted for tutorials-sage-identity clientid) + # are not accepted by the MCP or main-srv surfaces, and vice versa. + - name: tutorials-sage-identity + type: org.cloudfoundry.existing-service + parameters: + service-name: tutorials-sage-identity + + # tutorials-xsuaa is deployed and owned by the main tutorials-ims MTA. + # srv-sage adopts it for the XSUAA-fallback leg of hybrid auth + # (browser login, platform tokens keep validating via `xsuaa:true`). + # DEV: service-name matches the base below (tutorials-xsuaa). + # PROD: deploy/mta-sage-prod.mtaext overrides service-name → xsuaa-imsprod. + - name: tutorials-xsuaa + type: org.cloudfoundry.existing-service + parameters: + service-name: tutorials-xsuaa + + # tutorials-hana is deployed and owned by the main tutorials-ims MTA. + # srv-sage adopts it to bind the same HANA HDI container (read-only author queries + # on TutorialMeta, Steps, Tags; no content-store writes from this service). + - name: tutorials-hana + type: org.cloudfoundry.existing-service + parameters: + service-name: tutorials-hana diff --git a/package.json b/package.json index ed606829f..e76ac6f5c 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "backfill-attachments": "tsx scripts/backfill-attachments.ts", "preflight:ai-quiz-smoke": "tsx scripts/preflight-ai-quiz-smoke.ts", "prebuild:shared-bundle": "node scripts/bundle-shared.cjs", - "prebuild:parsers-bundle": "esbuild scripts/parsers/index.ts --bundle --platform=node --format=esm --outfile=srv-qa/lib/parsers.bundle.mjs --external:node:* --banner:js=\"import { createRequire as __cjsBundleRequire } from 'module'; const require = __cjsBundleRequire(import.meta.url);\"", + "prebuild:parsers-bundle": "esbuild scripts/parsers/index.ts --bundle --platform=node --format=esm --outfile=srv-qa/lib/parsers.bundle.mjs --external:node:* --banner:js=\"import { createRequire as __cjsBundleRequire } from 'module'; const require = __cjsBundleRequire(import.meta.url);\" && esbuild scripts/parsers/index.ts --bundle --platform=node --format=esm --outfile=srv-sage/lib/parsers.bundle.mjs --external:node:* --banner:js=\"import { createRequire as __cjsBundleRequire } from 'module'; const require = __cjsBundleRequire(import.meta.url);\"", "check:security-annotations": "node scripts/check-hugo-safe-html.cjs", "check:api-docs-drift": "node scripts/check-api-docs-drift.cjs", "check:security-txt-drift": "node scripts/check-security-txt-drift.cjs", diff --git a/scripts/bundle-shared.cjs b/scripts/bundle-shared.cjs index 10e1d116c..e9ea7373b 100644 --- a/scripts/bundle-shared.cjs +++ b/scripts/bundle-shared.cjs @@ -227,3 +227,43 @@ for (const t of mcpTargets) { }); console.log('bundled', t.out); } + +// srv-sage/lib/_shared/ — core only (5 author ops: MyOwnedTutorials, Tags, +// isSlugAvailable, reviewTutorial, snoozeTutorial; no AI/MCP/channels needed). +// NOTE: parsers.bundle.mjs (for /preview/render) is built by the separate +// `prebuild:parsers-bundle` npm script (from scripts/parsers/index.ts → +// srv-sage/lib/parsers.bundle.mjs) — NOT here. It uses `index.ts` as the entry +// point, not `directives.ts`, so it exports composeTutorial/renderHugoFrontmatter/ +// normalizeVideo. Added Task 5 (preview renderer port). +const outDirSage = 'srv-sage/lib/_shared'; +fs.mkdirSync(outDirSage, { recursive: true }); + +const sageTargets = [ + { + entry: require.resolve('@tutorials/core'), + out: path.join(outDirSage, 'core.bundle.mjs'), + }, +]; + +for (const t of sageTargets) { + esbuild.buildSync({ + entryPoints: [t.entry], + outfile: t.out, + bundle: true, + platform: 'node', + format: 'esm', + external: [ + '@sap/*', + '@cap-js/*', + '@sap-ai-sdk/*', + 'node:*', + 'hdb', + '@sap/hana-client', + 'cheerio', + ], + banner: { + js: "import { createRequire as __cjsBundleRequire } from 'module'; const require = __cjsBundleRequire(import.meta.url);", + }, + }); + console.log('bundled', t.out); +} diff --git a/srv-sage/author-sage-service.cds b/srv-sage/author-sage-service.cds new file mode 100644 index 000000000..b0f738510 --- /dev/null +++ b/srv-sage/author-sage-service.cds @@ -0,0 +1,65 @@ +using { com.sap.developers.ims } from '../db/schema'; +using from '../db/views'; + +// AuthorSageService — isolated IAS-authenticated author surface for the SAGE +// VS Code extension. Exposes ONLY the 5 operations SAGE actually uses; no +// AdminService dependency (rebuildContent / AI features excluded by design). +// +// Auth: IAS tokens carry no XSUAA scopes — `authenticated-user` is the only +// viable gate here. +// +// ACTION PATH ANALYSIS (Task 5 — src/lib/ims/imsApiClient.ts in sage-tutorial-extension): +// Reads: +// GET /author/MyOwnedTutorials (line 175 — imsApiClient.getMyTutorials) +// GET /author/Tags (line 155 — imsApiClient.searchTags) +// Actions (all bare/unqualified — no "AuthorSageService." prefix): +// POST /author/isSlugAvailable (line 159 — imsApiClient.isSlugAvailable) +// POST /author/reviewTutorial (line 188 — imsApiClient.reviewTutorial) +// POST /author/snoozeTutorial (line 195 — imsApiClient.snoozeTutorial) +// +// WHY no @path alias on the actions: +// CAP OData4 accepts BOTH the qualified form (AuthorSageService.isSlugAvailable) +// AND the bare/unqualified form (isSlugAvailable) for unbound action imports. +// The smoke test at test/smoke/author-service.test.js line 62 confirms this +// pattern on the production AuthorService (POST /author/generateOsVariants, bare). +// In srv-sage's isolated CF deployment only AuthorSageService is served at +// /author/, so the bare paths are unambiguous. No @path alias needed. +// +// (#task-3 — srv-sage author service model; task-5 — action path confirmed) + +@path: '/author' +@requires: 'authenticated-user' +service AuthorSageService { + + // MyOwnedTutorials — Sage's "My Tutorials" panel. + // Priority filter: 1 (strict author FK), 3 (ownerEmail), 4 (owner name). + // Excludes priority 2 (pure contributor). See ADR 0006 §2026-08-19. + @Capabilities.ChangeTracking : { Supported: true } + @readonly entity MyOwnedTutorials as + projection on ims.MyTutorialsView { *, tutorial_ID as ID } where bestPriority in (1, 3, 4); + + // Tags — read-only tag catalogue for the tutorial editor. + // Note: SUBSTR_AFTER(name, '>') actualTag is HANA-only; omitted here because + // srv-sage runs against the same HANA container and may surface it via raw + // column. Task 4 handler can re-add if needed. + @Capabilities.ChangeTracking : { Supported: true } + @readonly entity Tags as projection on ims.Tags; + + // isSlugAvailable — UX hint (not a lock) before creating a new tutorial. + // Returns false if a matching slug already exists (case-insensitive). + action isSlugAvailable(slug : String) returns Boolean; + + // reviewTutorial — marks tutorial as reviewed; returns review timestamp + // and running notification count. + action reviewTutorial(tutorialId : UUID) returns { + reviewedDate : Timestamp; + notificationNumber : Integer; + }; + + // snoozeTutorial — snoozes review notifications; returns next notification + // date and running notification count. + action snoozeTutorial(tutorialId : UUID, days : Integer) returns { + notificationDate : Timestamp; + notificationNumber : Integer; + }; +} diff --git a/srv-sage/author-sage-service.js b/srv-sage/author-sage-service.js new file mode 100644 index 000000000..e19425c7f --- /dev/null +++ b/srv-sage/author-sage-service.js @@ -0,0 +1,167 @@ +// srv-sage/author-sage-service.js +// +// Handlers for AuthorSageService — isolated IAS-authenticated author surface +// for the SAGE VS Code extension. +// +// Exposes ONLY the 5 operations SAGE actually uses: +// 1. MyOwnedTutorials — caller-scoped read (before-READ ownership stamp) +// 2. Tags — read-only tag catalogue +// 3. isSlugAvailable — slug UX hint (not a lock) +// 4. reviewTutorial — marks reviewed; returns timestamp + notification count +// 5. snoozeTutorial — snoozes notifications; returns next date + count +// +// Auth gate: @requires 'authenticated-user' (IAS tokens carry no XSUAA scopes). +// Per-user isolation is maintained via ownership checks identical to those in +// srv/author-service.js — dropping from Tutorial.Author → authenticated-user +// does NOT loosen data access, only the service entry gate. +// +// Identity resolution: same tiered resolver as srv-mcp — a before('*') hook +// calls pinResolvedUser to walk (iss,sub) link → sapId → email. This means +// IAS social users (no SAP ID) are also correctly resolved when their email +// matches a Users row. The main AuthorService uses XSUAA's user_uuid claim +// which IAS tokens don't carry; the tiered resolver handles both. +// +// No AI, GitHub, or credstore imports — those ops (generateOsVariants, +// rebuildContent) are intentionally excluded from this surface. +// +// (#task-4 — srv-sage handlers + ownership proof) + +import cds from '@sap/cds'; +import { reviewTutorial, snoozeTutorial } from './lib/tutorial-review.js'; + +// Workspace-first shim — resolves from @tutorials/core in local dev, from the +// bundled core.bundle.mjs at CF deploy. Do NOT also import from +// srv/lib/resolve-db-user.js (split-module-state: two copies of the module +// would have distinct module-level state, breaking provisionDbUser's +// SELECT-then-INSERT idempotency across the same request). +let resolveDbUser, provisionDbUser, pinResolvedUser, resolveUserSapId; +try { + ({ resolveDbUser, provisionDbUser, pinResolvedUser, resolveUserSapId } + = await import('@tutorials/core/resolve-db-user.js')); +} catch { + ({ resolveDbUser, provisionDbUser, pinResolvedUser, resolveUserSapId } + = await import('./lib/_shared/core.bundle.mjs')); +} + +const LOG = cds.log('author-sage-service'); + +// #1027 — silence is indistinguishable from "owns zero tutorials." Log at WARN +// so `cf logs tutorials-srv-sage --recent | grep 'Users-row miss'` surfaces +// the diagnostic. Carries ONLY the resolved sapId (no PII). +function warnUsersRowMiss(endpoint, user) { + const sapId = resolveUserSapId(user); + LOG.warn( + `[Users-row miss] endpoint=${endpoint} resolved-sapId=${sapId ?? ''} ` + + `— returning 0 rows. Check the token's user_uuid claim against Users.sapId.` + ); +} + +// assertOwnership — returns true iff the authenticated user owns the tutorial. +// Ported verbatim from srv/author-service.js: resolves to the Users row via +// the tiered resolver, then checks MyTutorialsView for the (tutorial_ID, +// userId=Users.uuid) pair. +async function assertOwnership(tutorialId, user) { + const dbUser = await resolveDbUser(user, ['uuid']); + if (!dbUser?.uuid) return false; + const { MyTutorialsView } = cds.entities('com.sap.developers.ims'); + const row = await SELECT.one.from(MyTutorialsView) + .columns('tutorial_ID') + .where({ tutorial_ID: tutorialId, userId: dbUser.uuid }); + return !!row; +} + +export default cds.service.impl(async function () { + const { MyOwnedTutorials } = this.entities; + + // ── Identity pin (IAS / XSUAA / social) ───────────────────────────────── + // Runs BEFORE every handler. Resolves the Users row via (iss,sub) link → + // sapId → email and pins the result onto req.user.attr so the downstream + // resolveDbUser / assertOwnership calls are synchronous fast-paths. + // Fail-open: an unresolvable identity leaves the context unpinned; each + // handler's own null/anonymous guard then rejects with 401. + this.before('*', async (req) => { + try { + await pinResolvedUser(req.user); + } catch (err) { + LOG.warn('[author-sage-service] identity pin failed:', err?.message ?? err); + } + }); + + // ── 1. MyOwnedTutorials — caller-scoped read ────────────────────────────── + // Stamps WHERE userId = caller's uuid so the OData query is scoped to the + // caller's ownership set. Mirrors srv/author-service.js's before-READ for + // MyOwnedTutorials (issue #862 reopen / ADR 0006 §2026-08-19). + this.before('READ', MyOwnedTutorials, async (req) => { + if (!req.user?.id || req.user.id === 'anonymous') { + return req.reject(401, 'Authentication required'); + } + // provisionDbUser = get-or-create: mints the Users row from JWT claims on + // first access so authors who have never browser-logged-in are still + // resolved. This is especially important for SAGE authors whose row was + // never created by the migrator (see srv/author-service.js comment). + const dbUser = await provisionDbUser(req.user, ['uuid']); + if (!dbUser?.uuid) { + warnUsersRowMiss('MyOwnedTutorials', req.user); + req.query.where({ userId: '__NO_USERS_ROW__' }); + return; + } + req.query.where({ userId: dbUser.uuid }); + }); + + // ── 2. Tags — read-only ────────────────────────────────────────────────── + // No handler needed: the CDS projection already limits to @readonly, and + // @requires 'authenticated-user' on the service is the only gate. Tags are + // not user-scoped. If the main AuthorService's attachTagsMdFormatHandlers + // behaviour is needed here, it can be added in a follow-up (not needed for + // the SAGE tag picker which uses the raw titlePath column). + + // ── 3. isSlugAvailable — slug UX hint ───────────────────────────────────── + this.on('isSlugAvailable', async (req) => { + const { slug } = req.data; + if (!slug || typeof slug !== 'string') { + return req.reject(400, 'slug must be a non-empty string'); + } + const { Tutorials } = cds.entities('com.sap.developers.ims'); + // LOWER()-based case-insensitive match. Mirrors the publish-side upsert + // shape in srv/lib/content-publish-session.js so this UX check uses the + // same key space as @assert.unique.slug's enforcement at write time. + const row = await SELECT.one.from(Tutorials) + .columns('ID') + .where`LOWER(slug) = ${slug.toLowerCase()}`; + return !row; // true = available + }); + + // ── 4. reviewTutorial — ownership-gated ────────────────────────────────── + // The ownership check is REQUIRED even under authenticated-user: without it + // any authenticated user (the new, broader gate) could mark any tutorial as + // reviewed. The check is identical to srv/author-service.js. + this.on('reviewTutorial', async (req) => { + const { tutorialId } = req.data; + if (!(await assertOwnership(tutorialId, req.user))) { + return req.reject(403, 'Not the owner of this tutorial'); + } + try { + return await reviewTutorial(tutorialId); + } catch (err) { + if (err.code === 404) return req.reject(404, err.message); + throw err; + } + }); + + // ── 5. snoozeTutorial — ownership-gated ────────────────────────────────── + this.on('snoozeTutorial', async (req) => { + const { tutorialId, days } = req.data; + if (!Number.isInteger(days) || days < 1 || days > 365) { + return req.reject(400, 'days must be an integer in [1, 365]'); + } + if (!(await assertOwnership(tutorialId, req.user))) { + return req.reject(403, 'Not the owner of this tutorial'); + } + try { + return await snoozeTutorial(tutorialId, days); + } catch (err) { + if (err.code === 404) return req.reject(404, err.message); + throw err; + } + }); +}); diff --git a/srv-sage/lib/resolve-db-user.js b/srv-sage/lib/resolve-db-user.js new file mode 100644 index 000000000..678458776 --- /dev/null +++ b/srv-sage/lib/resolve-db-user.js @@ -0,0 +1,28 @@ +// srv-sage/lib/resolve-db-user.js +// +// Workspace-first shim for @tutorials/core/resolve-db-user.js. +// Mirrors srv/lib/resolve-db-user.js and srv-mcp/developer-service.js. +// +// Local dev (workspace symlink) resolves from @tutorials/core directly. +// CF deploy falls back to the bundled core.bundle.mjs shipped beside this +// file at srv-sage/lib/_shared/core.bundle.mjs via scripts/bundle-shared.cjs. +// +// Only the exports needed by AuthorSageService are re-exported here — this +// keeps the bundle footprint minimal. Do NOT import from srv/ — srv-sage is +// an isolated module that must not cross-import from the main app. +// +// (#task-4 — srv-sage handler helpers) + +let mod; +try { + mod = await import('@tutorials/core/resolve-db-user.js'); +} catch { + mod = await import('./_shared/core.bundle.mjs'); +} + +export const resolveUserSapId = mod.resolveUserSapId; +export const resolveDbUser = mod.resolveDbUser; +export const provisionDbUser = mod.provisionDbUser; +export const pinResolvedUser = mod.pinResolvedUser; +export const tokenEmail = mod.tokenEmail; +export const issuerSubjectFromUser = mod.issuerSubjectFromUser; diff --git a/srv-sage/lib/tutorial-review.js b/srv-sage/lib/tutorial-review.js new file mode 100644 index 000000000..545cc383c --- /dev/null +++ b/srv-sage/lib/tutorial-review.js @@ -0,0 +1,61 @@ +// srv-sage/lib/tutorial-review.js +// +// Local re-export of the tutorial review/snooze helpers for AuthorSageService. +// Keeps srv-sage isolated from srv/ — no cross-module imports. +// +// At local dev the workspace package exposes the functions directly from +// packages/core (they are part of the @tutorials/core surface). At CF deploy +// the bundled core.bundle.mjs is used. The resolve-db-user shim already +// imports the bundle; we import the functions from core directly here. +// +// reviewTutorial / snoozeTutorial are standalone DB-write helpers with no +// dependency on AI, GitHub, or the credstore — safe to expose in srv-sage. +// +// (#task-4 — srv-sage handler helpers) + +import cds from '@sap/cds'; + +/** + * Mark a tutorial as reviewed: resets notificationNumber to 0, clears + * notification dates, sets reviewedDate = now. + * + * @param {string} tutorialId — Tutorials.ID (UUID) + * @returns {{ reviewedDate: string, notificationNumber: number }} + */ +export async function reviewTutorial(tutorialId) { + const { TutorialMeta } = cds.entities('com.sap.developers.ims'); + const meta = await SELECT.one.from(TutorialMeta).where({ tutorial_ID: tutorialId }); + if (!meta) { + const err = new Error(`TutorialMeta not found for tutorial: ${tutorialId}`); + err.code = 404; + throw err; + } + const now = new Date().toISOString(); + await UPDATE(TutorialMeta, meta.ID).set({ + reviewedDate: now, + notificationNumber: 0, + lastNotificationDate: null, + firstNotificationDate: null, + }); + return { reviewedDate: now, notificationNumber: 0 }; +} + +/** + * Snooze review notifications for `days` days from now. + * + * @param {string} tutorialId — Tutorials.ID (UUID) + * @param {number} days — integer 1..365 + * @returns {{ notificationDate: string, notificationNumber: number }} + */ +export async function snoozeTutorial(tutorialId, days) { + const { TutorialMeta } = cds.entities('com.sap.developers.ims'); + const meta = await SELECT.one.from(TutorialMeta).where({ tutorial_ID: tutorialId }); + if (!meta) { + const err = new Error(`TutorialMeta not found for tutorial: ${tutorialId}`); + err.code = 404; + throw err; + } + const snoozeUntil = new Date(Date.now() + (days || 30) * 86400000).toISOString(); + await UPDATE(TutorialMeta, meta.ID).set({ lastNotificationDate: snoozeUntil }); + return { notificationDate: snoozeUntil, notificationNumber: meta.notificationNumber }; +} diff --git a/srv-sage/package.json b/srv-sage/package.json new file mode 100644 index 000000000..c09b27c56 --- /dev/null +++ b/srv-sage/package.json @@ -0,0 +1,33 @@ +{ + "name": "tutorials-srv-sage", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "server.js", + "engines": { + "node": "22.23.4" + }, + "scripts": { + "start": "cds-serve" + }, + "dependencies": { + "@cap-js/hana": "^3.1.0", + "@sap/cds": "^10.1.0", + "@sap/xsenv": "^6.2.1", + "@sap/xssec": "^4.13.1", + "express": "^5", + "hugo-extended": "0.147.8", + "@tutorials/core": "*" + }, + "cds": { + "requires": { + "auth": { + "kind": "ias", + "xsuaa": true + }, + "db": { + "kind": "hana" + } + } + } +} diff --git a/srv-sage/preview-renderer.js b/srv-sage/preview-renderer.js new file mode 100644 index 000000000..afdcb3bae --- /dev/null +++ b/srv-sage/preview-renderer.js @@ -0,0 +1,203 @@ +// srv-sage/preview-renderer.js +// +// Ported from srv-qa/preview-renderer.js (Task 5 — preview endpoint in srv-sage). +// Renders a tutorial markdown payload to full HTML via Hugo, using the same +// parsers.bundle.mjs that srv/ and srv-qa use. +// +// Key difference from srv-qa: +// - Import resolves to ./lib/parsers.bundle.mjs (built by prebuild:parsers-bundle +// from scripts/parsers/index.ts; same flat path as srv-qa/lib/parsers.bundle.mjs). +// - PREVIEW_SITE_PATH_DEFAULT points at ../preview-site/ from this file (same +// shared preview-site/ at the mono-repo root — not a separate copy). +// +// (#task-5 — port preview renderer to srv-sage) + +import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync, mkdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawn } from 'node:child_process'; + +import { composeTutorial, renderHugoFrontmatter, normalizeVideo } from './lib/parsers.bundle.mjs'; + +const HUGO_TIMEOUT_MS_DEFAULT = 5000; +const PREVIEW_SITE_PATH_DEFAULT = new URL('../preview-site/', import.meta.url).pathname; + +function getHugoTimeoutMs() { + return Number(process.env.PREVIEW_HUGO_TIMEOUT_MS ?? HUGO_TIMEOUT_MS_DEFAULT); +} +function getPreviewSitePath() { + return process.env.PREVIEW_SITE_PATH ?? PREVIEW_SITE_PATH_DEFAULT; +} +export function getHugoBin() { + if (process.env.PREVIEW_HUGO_BIN) return process.env.PREVIEW_HUGO_BIN; + // #1102: Prefer the REAL hugo-extended vendor binary over the node_modules/ + // .bin/hugo symlink. That symlink points at hugo-extended/lib/cli.js — a + // Node shim with a `#!/usr/bin/env node` shebang. On Cloud Foundry the + // nodejs buildpack installs node at /home/vcap/deps/0/bin/node, which is NOT + // on PATH for the child that preview-renderer spawns, so `/usr/bin/env node` + // fails with "node: No such file or directory" and Hugo exits 1 with no + // output on either stream (the empty-
 symptom). The vendor binary is a
+  // native Hugo executable with no node dependency, so invoke it directly.
+  const vendorBin = join(process.cwd(), 'node_modules', 'hugo-extended', 'vendor', process.platform === 'win32' ? 'hugo.exe' : 'hugo');
+  if (existsSync(vendorBin)) return vendorBin;
+  // Fallback: the .bin shim (works locally where node is on PATH).
+  return join(process.cwd(), 'node_modules', '.bin', process.platform === 'win32' ? 'hugo.exe' : 'hugo');
+}
+function getHugoArgsPrefix() {
+  const raw = process.env.PREVIEW_HUGO_ARGS_PREFIX;
+  if (!raw) return [];
+  // On Windows, URL.pathname yields '/D:/...' which Node's spawn fails to resolve
+  // when invoked as a script path (it prepends cwd drive letter). Normalize the
+  // leading slash off Windows-style absolute paths.
+  if (process.platform === 'win32' && /^\/[A-Za-z]:\//.test(raw)) {
+    return [raw.slice(1)];
+  }
+  return [raw];
+}
+
+const HTML_ESC = { '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' };
+const escapeHtml = s => String(s ?? '').replace(/[<>&"']/g, c => HTML_ESC[c]);
+
+export function errorHtml(title, detail) {
+  const t = escapeHtml(title);
+  const d = escapeHtml(detail);
+  return `${t}

${t}

${d}
`; +} + +export async function renderPreview(markdown, rulesVr) { + const t0 = Date.now(); + if (!markdown || !markdown.trim()) { + return { html: errorHtml('Preview error', 'Markdown payload is empty.'), status: 'parse_error', durationMs: Date.now() - t0, bytes: 0, _tmpDir: null }; + } + + let tmpDirPath = null; + try { + tmpDirPath = mkdtempSync(join(tmpdir(), 'tut-preview-')); + + let composed; + try { + composed = composeTutorial(markdown, { + repo: '__preview__', branch: '__preview__', slug: '__preview__', + target: 'hugo', rewriteImages: false, + // [#655] Thread the optional rules.vr payload through to the parser + // so validation + codecheck blocks merge into composed.steps. + rulesVr: rulesVr && rulesVr.trim() ? rulesVr : undefined, + }); + } catch (err) { + return { + html: errorHtml('Preview parse error', `${err.message}\n${(err.stack ?? '').split('\n').slice(0, 4).join('\n')}`), + status: 'parse_error', durationMs: Date.now() - t0, bytes: 0, _tmpDir: tmpDirPath, + }; + } + + // [#655] Precomputed flag so Hugo's baseof.html can emit . + const hasAi = (composed.steps || []).some(s => s.aiInvolved === true); + const fmMarkdown = renderHugoFrontmatter({ + slug: '__preview__', + title: composed.title || '', + description: composed.description || '', + time: composed.frontmatter?.time ?? 0, + level: composed.level || '', + tags: Array.isArray(composed.frontmatter?.tags) ? composed.frontmatter.tags : [], + primaryTag: composed.frontmatter?.primary_tag || '', + author: composed.frontmatter?.author_name || '', + authorProfile: composed.frontmatter?.author_profile || '', + youWillLearn: Array.isArray(composed.youWillLearn) ? composed.youWillLearn : [], + prerequisites: composed.prerequisites || '', + steps: composed.steps || [], + nav: { slug: '__preview__', title: composed.title || '', description: composed.description || '', time: composed.frontmatter?.time ?? 0, level: composed.level || '', stepCount: (composed.steps || []).length, primaryTag: composed.frontmatter?.primary_tag || '', displayTags: [], prev: null, next: null }, + lastUpdated: '', + createdAt: '', + contributors: [], + hasOsOptions: composed.hasOsOptions, + // #2703: supported-OS list so the preview picker shows only the platforms + // the tutorial actually provides, matching the published QA/prod pages. + osList: composed.osList, + // [#655] Verbatim rules.vr source for baseof.html to emit as + //