diff --git a/CLAUDE.md b/CLAUDE.md index a20383f..17012ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,6 +37,8 @@ This is a TypeScript CLI for Microsoft Teams that talks directly to the internal ### Key design details - `sendMessage()` wraps content in `

` tags and generates a random 19-digit `clientmessageid` using BigInt +- Channel replies use `replyToMessage()` and `POST /conversations/{encodeURIComponent(channelId + ";messageid=" + rootMessageId)}/messages`, with `conversationid` set to the channel and `replyChainId` set to the original post ID. This endpoint and linkage were observed in the Teams web client's reply request. Never fall back to a top-level send on failure. +- `getThreadMessages()` reads that same root-scoped conversation. The CLI exposes `reply `, `messages --thread `, and opt-in `messages --ids`. Reply/thread helpers validate channel IDs (`@thread.tacv2`) and positive decimal root IDs before HTTP requests. Channel-wide results may mix posts and replies; `watch` remains flat and unchanged. - `createDmThread()` uses `POST /threads` (without `/users/ME`) with `uniquerosterthread: true` for idempotent 1:1 chat creation - `searchPeople()` uses Substrate Suggestions API (`/search/api/v1/suggestions?scenario=peoplepicker.newChat`), same endpoint as the Teams web client people picker - `getMyMri()` extracts the user's MRI from the ic3 JWT token's `oid` claim — no extra API call needed @@ -47,6 +49,8 @@ This is a TypeScript CLI for Microsoft Teams that talks directly to the internal - System conversations (ID prefix `48:`) are filtered out of chat listings - Login uses a **persistent browser profile** (`~/.teams-cli/browser-profile/`) so session cookies survive for silent token refresh - Expired tokens are automatically refreshed via headless Playwright before each command — no user interaction unless the session itself has expired +- Login/refresh must ignore expired or invalid MSAL cache entries and select the newest unexpired audience match. Token presence alone is not proof of login. Both browser flows close their persistent context on failure; failed login preserves existing session data. +- Auth also captures the CSA inventory audience (`chatsvcagg.teams.microsoft.com`). `getToken(name, true)` can explicitly refresh a missing configured resource using an existing saved sign-in; the default missing-token behavior is unchanged. Opt-in refresh waits for that resource as well as chat. CSA is not an IC3 token and has no public CLI command/client. - Playwright is dynamically imported at runtime (`await import("playwright")`) so it's not required at install time - Native `fetch` is used for all HTTP calls (no external HTTP library needed with Node 18+) - **Meeting transcripts** (`recordings`/`transcript` commands) use the SharePoint Stream API, not Graph: diff --git a/README.md b/README.md index a5a5a7d..963dd15 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Log in by launching a browser session. Sign in as you normally would (including teams login ``` -Tokens are stored in `~/.teams-cli/tokens.json`. Token lifetimes vary by API (the chat token lasts ~24 hours, the search token ~1.5 hours). Expired tokens are refreshed automatically via a headless browser using your saved session cookies — no manual re-login needed unless the session itself has expired. +Tokens are stored in `~/.teams-cli/tokens.json`. Token lifetimes vary by API and tenant policy. Expired tokens are refreshed automatically via a headless browser using your saved session cookies — no manual re-login needed unless the session itself has expired. Login and refresh wait for an **unexpired** token and prefer the newest valid audience match; stale browser-cache entries do not count as a successful sign-in. Failed login preserves the existing browser profile and saved tokens. ## Usage @@ -65,6 +65,11 @@ teams messages a1b2 # Send a message teams send a1b2 "Hello from the CLI" +# Show message IDs, then reply under an existing channel post +teams messages "19:example-channel@thread.tacv2" --ids +teams reply "19:example-channel@thread.tacv2" 1700000000000 "Reply from the CLI" +teams messages "19:example-channel@thread.tacv2" --thread 1700000000000 --ids + # Find a person by name or email teams find "Jane Smith" @@ -121,6 +126,22 @@ teams search "budget" --limit 10 Run `teams --help` or `teams --help` for full details. +### Channel threads + +`teams reply ` replies under an existing +channel post. Use the **original post's** decimal message ID, not a reply's ID. +`messages --ids` displays IDs; `messages --thread ` retrieves +that thread (including its root when present in the returned page). Full channel +IDs ending in `@thread.tacv2`, or cached short IDs resolving to them, are supported. +Normal `send` behavior is unchanged; it does not attach a channel message to a post. + +Channel-wide message retrieval can contain both posts and replies in a flat list. +The default output and `watch` do not group messages by thread or display parent +linkage. Use `messages --thread` to read a particular thread. Retrieval remains +limited to the requested page size; there is no automatic history pagination. +`watch` is unchanged and has no dedicated `--thread` option or new channel-reply +delivery guarantee. The reply API is undocumented and may change. + ## Development ```sh @@ -140,7 +161,7 @@ npm run dev -- chats ## How it works 1. `teams login` opens Chromium via Playwright, navigates to Teams, and waits for you to complete sign-in -2. Auth tokens are extracted from the browser's `localStorage` (three tokens: chat, search, presence) along with your region +2. Available auth tokens are extracted from the browser's `localStorage` (chat, search, presence, and CSA inventory) along with your region. CSA is captured for integrations; it does not add a public inventory command. Integrations may explicitly request acquisition of a missing configured token with `getToken(name, true)`, using the existing saved sign-in; normal missing-token behavior is unchanged. 3. CLI commands use these tokens to call the Teams Chat Service API (`teams.cloud.microsoft/api/chatsvc/`) and the Substrate Search API (`substrate.office.com`) directly via `fetch` 4. The `teams chats` command caches the conversation list locally so you can reference chats by short ID in subsequent commands 5. The `teams dm` command searches for a user via the Substrate Suggestions API, creates a 1:1 thread via `POST /threads`, and sends the message — all in one step diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3ee3b4e..36fd6c6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -28,7 +28,7 @@ All constants live here: file paths, token audience strings, API headers, defaul Key values: - `DATA_DIR` — `~/.teams-cli/`, where tokens and caches are stored -- `TOKEN_AUDIENCES` — maps token names (`ic3`, `search`, `presence`) to the localStorage key patterns used to find them +- `TOKEN_AUDIENCES` — maps token names (`ic3`, `search`, `presence`, `csa`) to the localStorage key patterns used to find them. CSA targets `chatsvcagg.teams.microsoft.com` for integrations; no public CSA API client or command is exposed. - `CLIENT_INFO` — the `clientinfo` header that the chatsvc API requires ### auth.ts @@ -36,16 +36,17 @@ Key values: Handles token persistence, automatic refresh, and the Playwright login flow. - `saveTokens()` / `loadTokens()` — JSON round-trip to `~/.teams-cli/tokens.json` -- `getToken()` — check token expiry, attempt silent refresh if expired, and retrieve by name +- `getToken()` — check token expiry, attempt silent refresh if expired, and retrieve by name. Optional `refreshMissing=true` also acquires a missing configured audience using a saved sign-in, waiting for the requested resource as well as chat. Defaults and behavior without a saved sign-in are unchanged. - `getSharepointToken(host, recordingUrl)` — returns a cached SharePoint token for `host`, or acquires one via `acquireSharepointToken()` (drives the headless profile to the host root to bootstrap a SharePoint session via SSO, intercepts the `Bearer` token off an `/_api/` request, and caches it with the JWT's `exp`; the recording link is a fallback warmup) - `getRegion()` — returns the user's region code (e.g. `au`, `amer`) extracted during login - `getMyMri()` — extracts the current user's MRI (`8:orgid:{oid}`) by decoding the `oid` claim from the ic3 JWT token using `Buffer.from(payload, 'base64url')`. Used by the `dm` command to construct thread creation requests. -- `tryRefresh()` — silently refreshes expired tokens by launching a headless Chromium with the persistent browser profile (`~/.teams-cli/browser-profile/`). MSAL re-acquires tokens using the stored session cookies — no user interaction needed. Returns `true` on success, `false` if the session itself has expired. +- `tryRefresh()` — silently refreshes expired tokens by launching a headless Chromium with the persistent browser profile (`~/.teams-cli/browser-profile/`). MSAL re-acquires tokens using the stored session cookies — no user interaction needed. Returns `true` after capturing an unexpired chat token, otherwise `false` with a safe lifecycle diagnostic. +- Browser token selection rejects expired/invalid entries and chooses the newest valid audience match. Login/refresh polling waits for that valid token, not merely a cache key. Browser contexts close on all exit paths; failed login retains the existing profile/token file. Refresh failures report a safe lifecycle stage without printing credentials. - `login()` — the interactive login flow: 1. Launches Chromium (headless=false) with a persistent browser profile so session cookies are preserved 2. Navigates to `teams.cloud.microsoft` - 3. Polls `localStorage` every 2 seconds for up to 5 minutes until the IC3 token appears - 4. Extracts all three tokens (ic3, search, presence) and the region from `localStorage` + 3. Polls `localStorage` every 2 seconds for up to 5 minutes until an unexpired IC3 token is available + 4. Extracts available unexpired tokens (ic3, search, presence, csa) and the region from `localStorage` 5. Saves everything to disk - `logout()` — removes stored tokens and the browser profile directory @@ -72,6 +73,8 @@ Async functions that make HTTP calls via the `ApiClient` wrapper. Each function Key design decisions: - `sendMessage()` wraps content in `

` tags and generates a random 19-digit `clientmessageid` using BigInt arithmetic, matching the Teams web client's behaviour +- `replyToMessage()` posts to a root-scoped channel conversation: `/conversations/{encodeURIComponent(channelId + ";messageid=" + rootMessageId)}/messages`. The payload includes the channel's `conversationid`, the original post's `replyChainId`, and `formatVariant: "TEAMS"`, matching the observed web reply request. The API response is not itself proof of linkage; verify the retrieved reply's `conversationLink` identifies the requested root. Errors propagate without retrying as a top-level post. +- `getThreadMessages()` reads the same scoped conversation. Shared validation rejects non-channel/compound IDs and non-positive/non-decimal root IDs before fetching. Channel-wide message retrieval may include replies as well as posts; thread retrieval filters by the requested root and retains normal page-size limits. - `getThreadMembers()` uses the `/threads/{id}` endpoint rather than `/conversations/{id}/members` (which returns 404) - `searchMessages()` builds the full Substrate Search API request body including correlation IDs and dimension metadata - `searchPeople()` uses the Substrate Suggestions API (`/search/api/v1/suggestions?scenario=peoplepicker.newChat`) — the same people picker endpoint the Teams web client uses when composing a new chat @@ -109,6 +112,12 @@ The chat index system works by having `teams chats` cache its formatted output t The `watch` command uses an async poll loop, creating a fresh `ApiClient` per iteration because tokens may be refreshed between polls. +`reply ` explicitly targets an existing +channel post. `messages --ids` adds message IDs without changing default display; +`messages --thread ` retrieves one channel thread. Neither +default message display nor `watch` groups replies or exposes parent linkage. +There is no dedicated thread-watch option or automatic thread-history pagination. + ## API surfaces The CLI talks to four separate Microsoft APIs, each requiring its own auth token: @@ -119,7 +128,7 @@ The primary API for conversations, messages, and members. - Base URL: `https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME` - Token audience: `ic3.teams.office.com` -- Used by: `chats`, `messages`, `send`, `dm` (thread creation + send), `watch`, `activity`, `members` +- Used by: `chats`, `messages` (including `--thread`), `send`, `reply`, `dm` (thread creation + send), `watch`, `activity`, `members` ### Substrate Search API @@ -153,9 +162,16 @@ Tests are organized to match the module structure: - `formatting.test.ts` — unit tests for all pure formatting functions (27 tests). No mocking needed. - `auth.test.ts` — tests token persistence, expiry, and JWT parsing using `vi.mock` to redirect file I/O to temp directories (9 tests). Does not test the Playwright login/refresh flows directly. +- `auth-refresh.test.ts` — mocks Playwright and browser storage to cover stale-cache rejection, newest-valid selection, waiting for renewed tokens, malformed/boundary expiry, browser cleanup, and preservation of saved sessions after unsuccessful login. - `api.test.ts` — tests API functions using mocked `ApiClient.fetch` (6 tests). The chatsvc base URL is patched to a fixed value. - `cli.test.ts` — tests command registration and structure (2 tests). +Channel reply coverage checks the encoded root-scoped endpoint, explicit payload +linkage, invalid inputs, HTTP error propagation without top-level fallback, +thread retrieval, CLI argument routing, and unchanged default send/read behavior. +Live thread verification must compare the reply's `conversationLink` with the +original root and retrieve that root's thread; a successful POST alone is insufficient. + The Playwright login flow is not unit-tested since it requires a real browser and user interaction. It's verified manually. ## Data flow example diff --git a/skills/teams-cli/SKILL.md b/skills/teams-cli/SKILL.md index 8dd4d51..0b959ca 100644 --- a/skills/teams-cli/SKILL.md +++ b/skills/teams-cli/SKILL.md @@ -40,6 +40,8 @@ Returns a table with short IDs (like `a1b2`), chat name, type, last message prev ```bash teams messages # Read 20 most recent messages teams messages -n 40 # Read 40 messages +teams messages --ids # Include message IDs +teams messages --thread --ids ``` `` is either a short ID from `teams chats` or a full conversation ID (e.g. `19:abc@thread.v2`). Messages are shown oldest-first. @@ -49,6 +51,18 @@ teams send "Your message here" ``` Sends a message to an existing conversation. Always confirm with the user before sending. +### Reply to a channel post +```bash +teams reply "Your reply here" +``` +Use the original channel post's decimal ID from `messages --ids`, not a reply's +ID. Channel IDs must end in `@thread.tacv2` (cached short IDs are also resolved). +Confirm the channel, original post, and reply text with the user before sending. +`send` does not target a post; never use it as a fallback for a failed reply. +Channel-wide messages may mix posts and replies in a flat list; use +`messages --thread` to read a particular thread. `watch` remains unchanged and +has no dedicated thread option. + ### Search messages ```bash teams search "quarterly report" # Search across all chats @@ -121,7 +135,9 @@ Known limitations to set expectations with the user: 1. Run `teams chats` to find the conversation 2. Run `teams messages ` to read recent context 3. Draft a reply and confirm with the user before sending -4. Run `teams send "message"` +4. For chat messages, run `teams send "message"`. For a channel post, + identify the original root with `messages --ids` and run + `teams reply "message"`. ### "Message someone I haven't chatted with" 1. Run `teams find "their name"` to look them up diff --git a/src/api.ts b/src/api.ts index 7bd5193..0372df2 100644 --- a/src/api.ts +++ b/src/api.ts @@ -83,6 +83,60 @@ export async function sendMessage( return (await jsonOrThrow(resp)) as Record; } +function channelThreadId(channelId: string, rootMessageId: string): string { + if (!/^19:[\w-]+@thread\.tacv2$/.test(channelId)) { + throw new Error( + "Thread replies require a channel ID ending in @thread.tacv2.", + ); + } + if (!/^[1-9]\d*$/.test(rootMessageId)) { + throw new Error("Root message ID must be a positive decimal message ID."); + } + return encodeURIComponent(`${channelId};messageid=${rootMessageId}`); +} + +export async function getThreadMessages( + client: ApiClient, + channelId: string, + rootMessageId: string, + pageSize = 20, +): Promise[]> { + return getMessages( + client, + channelThreadId(channelId, rootMessageId), + pageSize, + ); +} + +export async function replyToMessage( + client: ApiClient, + channelId: string, + rootMessageId: string, + content: string, +): Promise> { + const threadId = channelThreadId(channelId, rootMessageId); + if (!content.trim()) { + throw new Error("Reply message must not be empty."); + } + const resp = await client.fetch( + `${client.baseUrl}/conversations/${threadId}/messages`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + content: `

${content}

`, + messagetype: "RichText/Html", + contenttype: "Text", + clientmessageid: randomClientMessageId(), + conversationid: channelId, + replyChainId: rootMessageId, + properties: { formatVariant: "TEAMS" }, + }), + }, + ); + return (await jsonOrThrow(resp)) as Record; +} + export async function getThreadMembers( client: ApiClient, conversationId: string, diff --git a/src/auth.ts b/src/auth.ts index 12be274..b9d31d5 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -43,8 +43,8 @@ export function loadTokens(): TokenStore | null { } function isExpired(entry: TokenEntry): boolean { - const expiresOn = entry.expires_on ?? 0; - return Date.now() / 1000 > Number(expiresOn); + const expiresOn = Number(entry.expires_on); + return !Number.isFinite(expiresOn) || expiresOn <= Date.now() / 1000; } // A token store value is a single token (vs. a string like `region` or the @@ -52,7 +52,13 @@ function isExpired(entry: TokenEntry): boolean { function isTokenEntry( value: TokenEntry | string | Record | undefined, ): value is TokenEntry { - return typeof value === "object" && value !== null && "secret" in value; + return ( + typeof value === "object" && + value !== null && + "secret" in value && + typeof value.secret === "string" && + value.secret.length > 0 + ); } // The IC3 audience used for detecting login completion @@ -68,6 +74,8 @@ function findMsalToken( aud: string, ): { secret: string; expires_on: string } | null { const prefix = `https://${aud.toLowerCase()}/`; + const now = Date.now() / 1000; + let newest: { secret: string; expires_on: string } | null = null; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key === null) continue; @@ -75,15 +83,27 @@ function findMsalToken( if (parts[3]?.toLowerCase() !== "accesstoken") continue; const scopes = (parts[6] ?? "").split(" "); if (!scopes.some((s) => s.toLowerCase().startsWith(prefix))) continue; - const data = JSON.parse(localStorage.getItem(key)!); - return { secret: data.secret, expires_on: data.expiresOn }; + const stored = localStorage.getItem(key); + if (stored === null) continue; + const data = JSON.parse(stored); + const expiresOn = Number(data.expiresOn); + if ( + typeof data.secret !== "string" || + !data.secret || + !Number.isFinite(expiresOn) || + expiresOn <= now + ) + continue; + if (newest === null || expiresOn > Number(newest.expires_on)) { + newest = { secret: data.secret, expires_on: String(expiresOn) }; + } } - return null; + return newest; } /* v8 ignore stop */ -// Poll the page until an access token for the given audience appears in localStorage. +// Poll until an unexpired access token for the requested audience is available. /* v8 ignore start -- requires live Playwright page */ async function waitForToken( page: { @@ -97,19 +117,7 @@ async function waitForToken( const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { - const found = await page.evaluate((aud: string) => { - const prefix = `https://${aud.toLowerCase()}/`; - for (let i = 0; i < localStorage.length; i++) { - const key = localStorage.key(i); - if (key === null) continue; - const parts = key.split("|"); - if (parts[3]?.toLowerCase() !== "accesstoken") continue; - const scopes = (parts[6] ?? "").split(" "); - if (scopes.some((s) => s.toLowerCase().startsWith(prefix))) - return true; - } - return false; - }, audience); + const found = await page.evaluate(findMsalToken, audience); if (found) return true; } catch { // page may not be ready @@ -161,39 +169,69 @@ function saveSharepointToken(host: string, secret: string): void { } /* v8 ignore start -- requires live Playwright browser */ -async function tryRefresh(): Promise { +async function tryRefresh(requiredAudience?: string): Promise { let playwright: typeof import("playwright"); try { playwright = await import("playwright"); } catch { + console.error( + "Automatic Teams token refresh requires Playwright. Run `teams login` to reconnect.", + ); return false; } + let context: import("playwright").BrowserContext | undefined; + let stage = "browser launch"; try { mkdirSync(BROWSER_PROFILE_DIR, { recursive: true }); - const context = await playwright.chromium.launchPersistentContext( + context = await playwright.chromium.launchPersistentContext( BROWSER_PROFILE_DIR, { headless: true }, ); + stage = "Teams page navigation"; const page = await context.newPage(); await page.goto(TEAMS_URL); if (!(await waitForToken(page, IC3_AUDIENCE, 30_000, 1000))) { - await context.close(); + console.error( + "Automatic Teams refresh did not produce an unexpired chat token within 30 seconds. Run `teams login` to complete sign-in.", + ); + return false; + } + if ( + requiredAudience && + !(await waitForToken(page, requiredAudience, 30_000, 1000)) + ) { + console.error( + "Automatic Teams refresh did not produce the requested resource token within 30 seconds. Run `teams login` to reconnect.", + ); return false; } + stage = "token extraction"; await page.waitForTimeout(2000); const tokens = await extractTokens( page, TOKEN_AUDIENCES, loadTokens() ?? {}, ); - await context.close(); + const chat = tokens.ic3; + if (!isTokenEntry(chat) || isExpired(chat)) { + console.error( + "Automatic Teams refresh did not capture a valid chat token. Run `teams login` to reconnect.", + ); + return false; + } + stage = "token persistence"; saveTokens(tokens); return true; } catch { + console.error( + `Automatic Teams token refresh failed during ${stage}. Run \`teams login\` to reconnect.`, + ); return false; + } finally { + await context?.close(); } } /* v8 ignore stop */ @@ -270,13 +308,20 @@ async function acquireSharepointToken( } /* v8 ignore stop */ -export async function getToken(name: string): Promise { +export async function getToken( + name: string, + refreshMissing = false, +): Promise { const tokens = loadTokens(); if (!tokens) return null; const entry = tokens[name]; - if (!isTokenEntry(entry)) return null; - if (isExpired(entry)) { - if (await tryRefresh()) { + if ( + !isTokenEntry(entry) && + !(refreshMissing && Object.hasOwn(TOKEN_AUDIENCES, name)) + ) + return null; + if (!isTokenEntry(entry) || isExpired(entry)) { + if (await tryRefresh(refreshMissing ? TOKEN_AUDIENCES[name] : undefined)) { const refreshedEntry = loadTokens()?.[name]; if (isTokenEntry(refreshedEntry) && !isExpired(refreshedEntry)) { return refreshedEntry.secret; @@ -355,59 +400,54 @@ export async function login(): Promise { headless: false, }, ); - const page = await context.newPage(); - - console.log("Opening Teams login page..."); - await page.goto(TEAMS_URL); - console.log("Please sign in to Microsoft Teams in the browser window."); - console.log('When prompted "Stay signed in?", click Yes.'); - console.log("Waiting for login to complete (timeout: 5 minutes)..."); + try { + const page = await context.newPage(); - if (!(await waitForToken(page, IC3_AUDIENCE, 300_000, 2000))) { - await context.close(); - throw new Error("Login timed out after 5 minutes."); - } + console.log("Opening Teams login page..."); + await page.goto(TEAMS_URL); + console.log("Please sign in to Microsoft Teams in the browser window."); + console.log('When prompted "Stay signed in?", click Yes.'); + console.log("Waiting for login to complete (timeout: 5 minutes)..."); + + if (!(await waitForToken(page, IC3_AUDIENCE, 300_000, 2000))) { + throw new Error( + "Login timed out after 5 minutes without an unexpired chat token. Existing session data was preserved.", + ); + } - // Wait for MSAL to acquire all tokens (search/presence tokens are lazy) - await page.waitForTimeout(8000); - console.log("Login detected! Extracting tokens..."); - - await extractTokens(page, TOKEN_AUDIENCES, tokens); - - const regionData = await page.evaluate((pattern: string) => { - for (let i = 0; i < localStorage.length; i++) { - const key = localStorage.key(i); - if (key !== null && key.indexOf(pattern) !== -1) { - const data = JSON.parse(localStorage.getItem(key)!); - const gtm = - typeof data.item === "string" ? JSON.parse(data.item) : data.item; - const ams: string = gtm?.ams ?? ""; - const match = ams.match(/https:\/\/([a-z]+)-prod/); - return match ? match[1] : null; + // Wait for MSAL to acquire all tokens (search/presence tokens are lazy) + await page.waitForTimeout(8000); + console.log("Login detected! Extracting tokens..."); + + await extractTokens(page, TOKEN_AUDIENCES, tokens); + + const regionData = await page.evaluate((pattern: string) => { + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key !== null && key.indexOf(pattern) !== -1) { + const data = JSON.parse(localStorage.getItem(key)!); + const gtm = + typeof data.item === "string" ? JSON.parse(data.item) : data.item; + const ams: string = gtm?.ams ?? ""; + const match = ams.match(/https:\/\/([a-z]+)-prod/); + return match ? match[1] : null; + } } + return null; + }, REGION_KEY_PATTERN); + tokens.region = regionData ?? "amer"; + + const chat = tokens.ic3; + if (!isTokenEntry(chat) || isExpired(chat)) { + throw new Error( + "No unexpired chat token was captured. Existing session data was preserved; please run `teams login` again.", + ); } - return null; - }, REGION_KEY_PATTERN); - tokens.region = regionData ?? "amer"; - - await context.close(); - - const validTokens = Object.entries(tokens).filter( - ([k, v]) => - k !== "region" && - typeof v === "object" && - v !== null && - "secret" in v && - v.secret, - ); - if (validTokens.length === 0) { - logout(); - throw new Error( - 'No valid tokens captured. Did you click "Yes" on "Stay signed in?"? Please run `teams login` again and select Yes.', - ); - } - saveTokens(tokens); - return tokens; + saveTokens(tokens); + return tokens; + } finally { + await context.close(); + } } /* v8 ignore stop */ diff --git a/src/cli.ts b/src/cli.ts index 9a8750a..789161b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,10 +10,12 @@ import { getActivity, getMessages, getThreadMembers, + getThreadMessages, getTranscriptMetadata, listConversations, pollConversations, pollMessages, + replyToMessage, resolveDriveItem, searchMessages, searchPeople, @@ -63,10 +65,10 @@ function resolveConversationId(idOrShort: string): string { process.exit(1); } -function printMessages(msgs: FormattedMessage[]): void { +function printMessages(msgs: FormattedMessage[], showIds = false): void { for (const m of msgs) { console.log(`${chalk.green(m.time)} ${chalk.bold(m.sender)}`); - console.log(` ${m.body}`); + console.log(` ${showIds ? `[${m.id}] ` : ""}${m.body}`); console.log(); } } @@ -151,10 +153,19 @@ export function createProgram(): Command { .command("messages ") .description("Read messages from a conversation.") .option("-n, --limit ", "Number of messages to fetch", "20") + .option("--ids", "Show message IDs") + .option("--thread ", "Read a channel post's reply thread") .action(async (chat: string, opts) => { const convId = resolveConversationId(chat); const client = await getChatClient(); - const raw = await getMessages(client, convId, Number(opts.limit)); + const raw = opts.thread + ? await getThreadMessages( + client, + convId, + opts.thread, + Number(opts.limit), + ) + : await getMessages(client, convId, Number(opts.limit)); const msgs = raw .map((r) => formatMessage(r)) .filter((m): m is FormattedMessage => m !== null); @@ -163,7 +174,7 @@ export function createProgram(): Command { console.log("No displayable messages."); return; } - printMessages(msgs.reverse()); + printMessages(msgs.reverse(), opts.ids); }); // send @@ -180,6 +191,27 @@ export function createProgram(): Command { ); }); + // reply + program + .command("reply ") + .description( + "Reply under an existing channel post (not a new top-level post).", + ) + .action(async (channel: string, rootMessageId: string, message: string) => { + const convId = resolveConversationId(channel); + const client = await getChatClient(); + const result = await replyToMessage( + client, + convId, + rootMessageId, + message, + ); + console.log( + chalk.green("Reply sent.") + + ` Root: ${rootMessageId}. Arrival: ${result.OriginalArrivalTime ?? "ok"}`, + ); + }); + // search program .command("search ") diff --git a/src/config.ts b/src/config.ts index e131bdd..c1e10c9 100644 --- a/src/config.ts +++ b/src/config.ts @@ -12,6 +12,7 @@ export const TOKEN_AUDIENCES: Record = { ic3: "ic3.teams.office.com", search: "outlook.office.com/search", presence: "presence.teams.microsoft.com", + csa: "chatsvcagg.teams.microsoft.com", }; export const REGION_KEY_PATTERN = "DISCOVER-REGION-GTM"; diff --git a/tests/api.test.ts b/tests/api.test.ts index aa0c02b..43be7e0 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -6,11 +6,13 @@ import { getConversation, getMessages, getThreadMembers, + getThreadMessages, getTranscriptMetadata, listConversations, markAsRead, pollConversations, pollMessages, + replyToMessage, resolveDriveItem, searchMessages, searchPeople, @@ -66,6 +68,9 @@ describe("sendMessage", () => { const body = JSON.parse(init.body); expect(body.content).toBe("

hello

"); expect(body.messagetype).toBe("RichText/Html"); + expect(_url).toBe(`${BASE}/conversations/19:abc/messages`); + expect(body).not.toHaveProperty("replyChainId"); + expect(body).not.toHaveProperty("conversationid"); }); it("handles special characters safely", async () => { @@ -78,6 +83,94 @@ describe("sendMessage", () => { }); }); +describe("channel replies", () => { + const channel = "19:example-channel@thread.tacv2"; + const root = "1700000000000"; + const thread = encodeURIComponent(`${channel};messageid=${root}`); + + it("posts to the root-scoped conversation with explicit thread linkage", async () => { + const client = mockClient({ OriginalArrivalTime: "1700000000001" }); + const result = await replyToMessage(client, channel, root, "Test reply"); + expect(result.OriginalArrivalTime).toBe("1700000000001"); + expect(client.fetch).toHaveBeenCalledExactlyOnceWith( + `${BASE}/conversations/${thread}/messages`, + expect.objectContaining({ method: "POST" }), + ); + const [, init] = vi.mocked(client.fetch).mock.calls[0]; + const body = JSON.parse(init?.body as string); + expect(body).toEqual({ + content: "

Test reply

", + messagetype: "RichText/Html", + contenttype: "Text", + clientmessageid: expect.stringMatching(/^\d{19}$/), + conversationid: channel, + replyChainId: root, + properties: { formatVariant: "TEAMS" }, + }); + }); + + it("reads the same root-scoped conversation and preserves the page size", async () => { + const client = mockClient({ messages: [{ id: root }] }); + expect(await getThreadMessages(client, channel, root, 7)).toEqual([ + { id: root }, + ]); + const [url] = vi.mocked(client.fetch).mock.calls[0]; + expect(url).toContain(`/conversations/${thread}/messages?`); + expect(new URL(url).searchParams.get("pageSize")).toBe("7"); + }); + + it.each([ + "", + "0", + "-1", + "1.5", + "1e12", + "123;messageid=456", + "123/456", + ])("rejects invalid root ID %j without making a request", async (id) => { + const client = mockClient({}); + await expect(replyToMessage(client, channel, id, "Reply")).rejects.toThrow( + "Root message ID", + ); + await expect(getThreadMessages(client, channel, id)).rejects.toThrow( + "Root message ID", + ); + expect(client.fetch).not.toHaveBeenCalled(); + }); + + it.each([ + "19:example@thread.v2", + `${channel};messageid=${root}`, + "19:example/path@thread.tacv2", + "19:example%2fpath@thread.tacv2", + ])("rejects non-channel or compound ID %j", async (id) => { + const client = mockClient({}); + await expect(replyToMessage(client, id, root, "Reply")).rejects.toThrow( + "channel ID", + ); + expect(client.fetch).not.toHaveBeenCalled(); + }); + + it("rejects empty replies before making a request", async () => { + const client = mockClient({}); + await expect(replyToMessage(client, channel, root, " \n ")).rejects.toThrow( + "must not be empty", + ); + expect(client.fetch).not.toHaveBeenCalled(); + }); + + it("surfaces errors without retrying or falling back to a top-level post", async () => { + const client = mockClient({}); + vi.mocked(client.fetch).mockResolvedValue( + new Response("Forbidden", { status: 403 }), + ); + await expect( + replyToMessage(client, channel, root, "Reply"), + ).rejects.toThrow("HTTP 403: Forbidden"); + expect(client.fetch).toHaveBeenCalledTimes(1); + }); +}); + describe("getThreadMembers", () => { it("returns members", async () => { const client = mockClient({ members: [{ id: "8:orgid:user1" }] }); diff --git a/tests/auth-refresh.test.ts b/tests/auth-refresh.test.ts new file mode 100644 index 0000000..3d707f6 --- /dev/null +++ b/tests/auth-refresh.test.ts @@ -0,0 +1,244 @@ +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const browser = vi.hoisted(() => ({ + launch: vi.fn(), + close: vi.fn(), + evaluate: vi.fn(), + goto: vi.fn(), + wait: vi.fn(), +})); + +vi.mock("playwright", () => ({ + chromium: { launchPersistentContext: browser.launch }, +})); + +vi.mock("../src/config.js", () => { + const dir = join(tmpdir(), "teams-cli-test-auth-refresh"); + return { + DATA_DIR: dir, + TOKENS_FILE: join(dir, "tokens.json"), + BROWSER_PROFILE_DIR: join(dir, "browser-profile"), + TOKEN_AUDIENCES: { + ic3: "ic3.teams.office.com", + search: "outlook.office.com/search", + presence: "presence.teams.microsoft.com", + csa: "chatsvcagg.teams.microsoft.com", + }, + REGION_KEY_PATTERN: "DISCOVER-REGION-GTM", + TEAMS_URL: "https://teams.cloud.microsoft/", + }; +}); + +import { getToken, loadTokens, login, saveTokens } from "../src/auth.js"; + +const testDir = join(tmpdir(), "teams-cli-test-auth-refresh"); +let storage: Map; + +function addToken(client: string, secret: string, expiresOn: number | string) { + storage.set( + `msal.2|example|authority|accesstoken|${client}|tenant|https://ic3.teams.office.com/.default|`, + JSON.stringify({ secret, expiresOn }), + ); +} + +function expireSavedToken() { + saveTokens({ + ic3: { secret: "expired-cache", expires_on: Date.now() / 1000 - 100 }, + }); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-01-01T12:00:00Z")); + storage = new Map(); + vi.stubGlobal("localStorage", { + get length() { + return storage.size; + }, + key: (index: number) => [...storage.keys()][index] ?? null, + getItem: (key: string) => storage.get(key) ?? null, + }); + browser.close.mockReset().mockResolvedValue(undefined); + browser.goto.mockReset().mockResolvedValue(undefined); + browser.wait.mockReset().mockImplementation(async (milliseconds: number) => { + vi.setSystemTime(Date.now() + milliseconds); + }); + browser.evaluate + .mockReset() + .mockImplementation(async (fn: (arg: string) => unknown, arg: string) => + fn(arg), + ); + browser.launch.mockReset().mockResolvedValue({ + newPage: async () => ({ + goto: browser.goto, + evaluate: browser.evaluate, + waitForTimeout: browser.wait, + }), + close: browser.close, + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); + mkdirSync(testDir, { recursive: true }); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + rmSync(testDir, { recursive: true, force: true }); +}); + +describe("browser token validity", () => { + it("preserves the default behavior for missing tokens", async () => { + expireSavedToken(); + expect(await getToken("csa")).toBeNull(); + expect(browser.launch).not.toHaveBeenCalled(); + }); + + it("can explicitly acquire a missing configured resource without changing chat identity", async () => { + expireSavedToken(); + addToken("chat", "valid-chat", Date.now() / 1000 + 3600); + storage.set( + "msal.2|example|authority|accesstoken|csa|tenant|https://chatsvcagg.teams.microsoft.com/.default|", + JSON.stringify({ + secret: "valid-csa", + expiresOn: Date.now() / 1000 + 3600, + }), + ); + expect(await getToken("csa", true)).toBe("valid-csa"); + expect(await getToken("ic3")).toBe("valid-chat"); + expect(browser.launch).toHaveBeenCalledOnce(); + expect(browser.close).toHaveBeenCalledOnce(); + }); + + it("does not attempt to acquire arbitrary missing resources", async () => { + expireSavedToken(); + expect(await getToken("unknown", true)).toBeNull(); + expect(await getToken("toString", true)).toBeNull(); + expect(browser.launch).not.toHaveBeenCalled(); + }); + + it("does not acquire a missing token without a saved sign-in", async () => { + expect(await getToken("csa", true)).toBeNull(); + expect(browser.launch).not.toHaveBeenCalled(); + }); + + it("reports a missing resource token without discarding saved tokens", async () => { + expireSavedToken(); + addToken("chat", "valid-chat", Date.now() / 1000 + 3600); + expect(await getToken("csa", true)).toBeNull(); + expect(loadTokens()?.ic3).toMatchObject({ secret: "expired-cache" }); + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining("requested resource token"), + ); + expect(browser.close).toHaveBeenCalledOnce(); + }); + + it("does not treat an expired browser token as a successful refresh", async () => { + expireSavedToken(); + addToken("old", "expired-browser", Date.now() / 1000 - 100); + expect(await getToken("ic3")).toBeNull(); + expect(loadTokens()?.ic3).toMatchObject({ secret: "expired-cache" }); + expect(browser.close).toHaveBeenCalledOnce(); + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining("unexpired chat token within 30 seconds"), + ); + }); + + it("skips an expired first match and selects the newest valid token", async () => { + expireSavedToken(); + addToken("old", "expired-browser", Date.now() / 1000 - 100); + addToken("valid", "older-valid", Date.now() / 1000 + 100); + addToken("new", "newest-valid", Date.now() / 1000 + 3600); + expect(await getToken("ic3")).toBe("newest-valid"); + expect(loadTokens()?.ic3).toMatchObject({ secret: "newest-valid" }); + expect(browser.close).toHaveBeenCalledOnce(); + }); + + it("waits for a fresh token to appear instead of returning a stale one", async () => { + expireSavedToken(); + addToken("old", "expired-browser", Date.now() / 1000 - 100); + browser.wait.mockImplementation(async (milliseconds: number) => { + vi.setSystemTime(Date.now() + milliseconds); + addToken("new", "renewed", Date.now() / 1000 + 3600); + }); + expect(await getToken("ic3")).toBe("renewed"); + expect(browser.wait).toHaveBeenCalledWith(1000); + }); + + it.each([ + "invalid", + "NaN", + 0, + ])("rejects malformed browser expiry %s", async (expiry) => { + expireSavedToken(); + addToken("bad", "invalid-expiry", expiry); + addToken("new", "valid", Date.now() / 1000 + 3600); + expect(await getToken("ic3")).toBe("valid"); + }); + + it("rejects a token at its exact expiry boundary", async () => { + expireSavedToken(); + addToken("boundary", "expired-now", Date.now() / 1000); + expect(await getToken("ic3")).toBeNull(); + }); + + it("refreshes a saved token with a malformed expiry instead of returning it", async () => { + saveTokens({ ic3: { secret: "bad-cache", expires_on: "invalid" } }); + addToken("new", "valid", Date.now() / 1000 + 3600); + expect(await getToken("ic3")).toBe("valid"); + }); + + it("ignores empty browser secrets", async () => { + expireSavedToken(); + addToken("empty", "", Date.now() / 1000 + 7200); + addToken("new", "valid", Date.now() / 1000 + 3600); + expect(await getToken("ic3")).toBe("valid"); + }); + + it("closes the persistent context after a navigation failure", async () => { + expireSavedToken(); + browser.goto.mockRejectedValue(new Error("PRIVATE browser diagnostic")); + expect(await getToken("ic3")).toBeNull(); + expect(browser.close).toHaveBeenCalledOnce(); + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining("Teams page navigation"), + ); + expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain( + "PRIVATE", + ); + }); +}); + +describe("interactive login", () => { + it("does not report success or delete saved sessions for expired-only cache", async () => { + expireSavedToken(); + addToken("old", "expired-browser", Date.now() / 1000 - 100); + const profile = join(testDir, "browser-profile"); + mkdirSync(profile, { recursive: true }); + writeFileSync(join(profile, "keep.txt"), "saved session"); + await expect(login()).rejects.toThrow("without an unexpired chat token"); + expect(loadTokens()?.ic3).toMatchObject({ secret: "expired-cache" }); + expect(existsSync(join(profile, "keep.txt"))).toBe(true); + expect(browser.close).toHaveBeenCalledOnce(); + }); + + it("captures only unexpired matching tokens", async () => { + addToken("old", "expired-browser", Date.now() / 1000 - 100); + addToken("new", "valid", Date.now() / 1000 + 3600); + storage.set( + "msal.2|example|authority|accesstoken|search|tenant|https://outlook.office.com/search/.default|", + JSON.stringify({ + secret: "expired-search", + expiresOn: Date.now() / 1000 - 100, + }), + ); + const tokens = await login(); + expect(tokens.ic3).toMatchObject({ secret: "valid" }); + expect(tokens.search).toBeUndefined(); + expect(browser.close).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/cli.test.ts b/tests/cli.test.ts index cb3587c..d6300ec 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -1,4 +1,10 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as api from "../src/api.js"; +import * as clients from "../src/client.js"; + +afterEach(() => { + vi.restoreAllMocks(); +}); describe("createProgram", () => { it("includes all commands in help", async () => { @@ -21,6 +27,7 @@ describe("createProgram", () => { "chats", "messages", "send", + "reply", "search", "activity", "find", @@ -33,6 +40,97 @@ describe("createProgram", () => { }); }); +describe("channel reply commands", () => { + const channel = "19:example-channel@thread.tacv2"; + const root = "1700000000000"; + const client: clients.ApiClient = { + baseUrl: "https://teams.cloud.microsoft/example", + fetch: vi.fn(), + }; + + it("routes an explicit reply without using the top-level send function", async () => { + const { createProgram } = await import("../src/cli.js"); + vi.spyOn(clients, "getChatClient").mockResolvedValue(client); + const reply = vi.spyOn(api, "replyToMessage").mockResolvedValue({}); + const send = vi.spyOn(api, "sendMessage"); + const output = vi.spyOn(console, "log").mockImplementation(() => {}); + await createProgram().parseAsync([ + "node", + "teams", + "reply", + channel, + root, + "Test reply", + ]); + expect(reply).toHaveBeenCalledWith(client, channel, root, "Test reply"); + expect(send).not.toHaveBeenCalled(); + expect(output).toHaveBeenCalledWith( + expect.stringContaining(`Root: ${root}`), + ); + }); + + it("requires a root ID and a message", async () => { + const { createProgram } = await import("../src/cli.js"); + const getClient = vi.spyOn(clients, "getChatClient"); + const program = createProgram().exitOverride(); + for (const command of program.commands) { + command.exitOverride().configureOutput({ writeErr: () => {} }); + } + await expect( + program.parseAsync(["node", "teams", "reply", channel, root]), + ).rejects.toThrow("missing required argument"); + expect(getClient).not.toHaveBeenCalled(); + }); + + it("reads a specified thread and displays IDs when requested", async () => { + const { createProgram } = await import("../src/cli.js"); + vi.spyOn(clients, "getChatClient").mockResolvedValue(client); + const read = vi.spyOn(api, "getThreadMessages").mockResolvedValue([ + { + id: root, + messagetype: "Text", + content: "Root post", + originalarrivaltime: "2024-01-01T00:00:00Z", + }, + ]); + const normalRead = vi.spyOn(api, "getMessages"); + const output = vi.spyOn(console, "log").mockImplementation(() => {}); + await createProgram().parseAsync([ + "node", + "teams", + "messages", + channel, + "--thread", + root, + "--ids", + "-n", + "7", + ]); + expect(read).toHaveBeenCalledWith(client, channel, root, 7); + expect(normalRead).not.toHaveBeenCalled(); + expect(output).toHaveBeenCalledWith(` [${root}] Root post`); + }); + + it("preserves normal message retrieval and display by default", async () => { + const { createProgram } = await import("../src/cli.js"); + vi.spyOn(clients, "getChatClient").mockResolvedValue(client); + const read = vi.spyOn(api, "getMessages").mockResolvedValue([ + { + id: root, + messagetype: "Text", + content: "Root post", + originalarrivaltime: "2024-01-01T00:00:00Z", + }, + ]); + const threadRead = vi.spyOn(api, "getThreadMessages"); + const output = vi.spyOn(console, "log").mockImplementation(() => {}); + await createProgram().parseAsync(["node", "teams", "messages", channel]); + expect(read).toHaveBeenCalledWith(client, channel, 20); + expect(threadRead).not.toHaveBeenCalled(); + expect(output).toHaveBeenCalledWith(" Root post"); + }); +}); + describe("resolveConversationId", () => { it("passes through raw conversation IDs", async () => { // Dynamic import to avoid side effects