pi-dent-office 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/index.ts +38 -0
- package/lib/auth.ts +536 -0
- package/lib/calendar.ts +136 -0
- package/lib/config.ts +356 -0
- package/lib/graph.ts +171 -0
- package/lib/http.ts +180 -0
- package/lib/office.ts +97 -0
- package/lib/outlook.ts +96 -0
- package/lib/params.ts +334 -0
- package/lib/sharepoint.ts +164 -0
- package/lib/store.ts +108 -0
- package/lib/teams.ts +109 -0
- package/lib/text.ts +65 -0
- package/lib/tool.ts +350 -0
- package/package.json +65 -4
- package/specs/AGENTS.md +18 -0
- package/specs/office.md +455 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chris B
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-dent-office
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A pi extension that gives the agent one tool, `Office`, for the user's Microsoft 365 data through
|
|
4
|
+
Microsoft Graph: Outlook mail, the calendar, Teams chats and channels, and SharePoint files.
|
|
5
|
+
|
|
6
|
+
## How it works
|
|
7
|
+
|
|
8
|
+
- **One tool, four services.** `service` is `outlook`, `calendar`, `teams` or `sharepoint`;
|
|
9
|
+
`action` picks what to do. List actions return ids that the get, reply, update and read actions
|
|
10
|
+
take.
|
|
11
|
+
|
|
12
|
+
| Service | Actions |
|
|
13
|
+
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
|
|
14
|
+
| `outlook` | `list_messages`, `get_message`, `send_message`, `reply_message` |
|
|
15
|
+
| `calendar` | `list_events`, `get_event`, `create_event`, `update_event`, `delete_event`, `respond_event` |
|
|
16
|
+
| `teams` | `list_teams`, `list_channels`, `list_channel_messages`, `send_channel_message`, `list_chats`, `list_chat_messages`, `send_chat_message` |
|
|
17
|
+
| `sharepoint` | `search`, `list_sites`, `list_files`, `read_file`, `upload_file` |
|
|
18
|
+
|
|
19
|
+
- **Work and personal accounts.** A work or school account (Microsoft 365) and a personal Microsoft
|
|
20
|
+
account (Outlook.com, Hotmail, Live) can be signed in side by side; the tool's `account`
|
|
21
|
+
parameter picks one (`work` or `personal`). Without it, the tool uses `office.defaultAccount`,
|
|
22
|
+
else the only signed-in kind, else `work`. Personal accounts have mail, calendar and OneDrive, but
|
|
23
|
+
no Teams and no SharePoint sites or search: the tool says so instead of calling Graph.
|
|
24
|
+
- **Files.** `list_files`, `read_file` and `upload_file` use the user's OneDrive unless a `driveId`
|
|
25
|
+
or `siteId` is given.
|
|
26
|
+
- **Writes are immediate.** Sending mail, posting to Teams, changing events and uploading files
|
|
27
|
+
happen as soon as the agent calls the action.
|
|
28
|
+
- **Sign-in with a device code.** The first call (or `/office login`) shows a code and the URL
|
|
29
|
+
`https://microsoft.com/devicelogin`; sign in there in any browser. With a UI the call waits;
|
|
30
|
+
without one, the tool error carries the code for the agent to relay, and the next call proceeds
|
|
31
|
+
once you signed in. Tokens are kept in `~/.pi/pi-dent/office/tokens.json` (mode `0600`) and
|
|
32
|
+
refreshed automatically.
|
|
33
|
+
- **Untrusted text.** Mail, chat and file contents are reduced to plain text with invisible
|
|
34
|
+
characters removed, and long bodies are cut.
|
|
35
|
+
|
|
36
|
+
The exact rules are in [`specs/office.md`](specs/office.md).
|
|
37
|
+
|
|
38
|
+
## Using it
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
pi install npm:pi-dent-office
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Then `/office login work` or `/office login personal` (or both), `/office status`, and
|
|
45
|
+
`/office logout work|personal`. No app registration is needed: the
|
|
46
|
+
default client is Microsoft's public "Microsoft Graph Command Line Tools" app. To use your own app
|
|
47
|
+
registration (a public client with the device code flow allowed), or a specific tenant, set them
|
|
48
|
+
in `pi-dent.conf` (`~/.pi/pi-dent/`, or `.pi/pi-dent/` in a project) or in
|
|
49
|
+
`PI_DENT_OFFICE_CLIENT_ID`, `PI_DENT_OFFICE_TENANT` (work accounts) and `PI_DENT_OFFICE_ACCOUNT`
|
|
50
|
+
(the default kind):
|
|
51
|
+
|
|
52
|
+
```jsonc
|
|
53
|
+
{
|
|
54
|
+
"office": {
|
|
55
|
+
"clientId": "00000000-0000-0000-0000-000000000000",
|
|
56
|
+
"tenant": "contoso.onmicrosoft.com",
|
|
57
|
+
"scopes": ["User.Read", "Mail.ReadWrite", "Mail.Send", "ChannelMessage.Read.All"],
|
|
58
|
+
"personalScopes": ["User.Read", "Mail.ReadWrite", "Calendars.ReadWrite"],
|
|
59
|
+
"defaultAccount": "work",
|
|
60
|
+
"confirmWrites": true,
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
With `confirmWrites` `true`, every write asks you to confirm in the UI before signing in, and fails
|
|
66
|
+
without a UI; the default is `false`.
|
|
67
|
+
|
|
68
|
+
Reading Teams channel messages needs `ChannelMessage.Read.All`, which an admin must consent to; it
|
|
69
|
+
is not in the default scopes. Requires Node 26 or later.
|
|
70
|
+
|
|
71
|
+
## Documentation
|
|
72
|
+
|
|
73
|
+
- `specs/office.md`: what the tool and command do, and their settings.
|
|
74
|
+
- `docs/graph.md`: the Graph and sign-in facts, with links.
|
|
75
|
+
- `AGENTS.md`: how to work on the repository.
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
MIT, see `LICENSE`.
|
package/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-dent-office - see specs/office.md.
|
|
3
|
+
*
|
|
4
|
+
* Wiring only: the `Office` tool, the `/office` command and their building blocks live in lib/.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
|
|
9
|
+
import { createOffice } from "./lib/office.ts";
|
|
10
|
+
|
|
11
|
+
export default function piDentOffice(pi: ExtensionAPI): void {
|
|
12
|
+
const office = createOffice();
|
|
13
|
+
let reported = false;
|
|
14
|
+
|
|
15
|
+
pi.registerTool(office.tool);
|
|
16
|
+
|
|
17
|
+
pi.registerCommand("office", {
|
|
18
|
+
description: "Microsoft 365 sign-in: /office login|logout [work|personal], /office status",
|
|
19
|
+
getArgumentCompletions: (prefix) =>
|
|
20
|
+
["login work", "login personal", "logout work", "logout personal", "status"]
|
|
21
|
+
.filter((value) => value.startsWith(prefix.trimStart()))
|
|
22
|
+
.map((value) => ({ value, label: value })),
|
|
23
|
+
handler: (args, ctx) =>
|
|
24
|
+
office.command(
|
|
25
|
+
args,
|
|
26
|
+
ctx.hasUI ? (message, level) => ctx.ui.notify(message, level) : undefined,
|
|
27
|
+
),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
pi.on("session_start", (_event, ctx) => {
|
|
31
|
+
const config = office.loadConfig();
|
|
32
|
+
if (reported || !ctx.hasUI) return;
|
|
33
|
+
reported = true;
|
|
34
|
+
for (const message of config.diagnostics) {
|
|
35
|
+
ctx.ui.notify(message, "warning");
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
package/lib/auth.ts
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
/** Sign-in (specs/office.md#sign-in): stored tokens, refresh, and the device sign-in. */
|
|
2
|
+
|
|
3
|
+
import type { AccountKind, OfficeConfig, Profile } from "./config.ts";
|
|
4
|
+
import {
|
|
5
|
+
Cancelled,
|
|
6
|
+
OfficeError,
|
|
7
|
+
RequestFailure,
|
|
8
|
+
isOk,
|
|
9
|
+
isRecord,
|
|
10
|
+
jsonOf,
|
|
11
|
+
send,
|
|
12
|
+
type FetchFunction,
|
|
13
|
+
} from "./http.ts";
|
|
14
|
+
import { cleanLine, removeInvisible } from "./text.ts";
|
|
15
|
+
import {
|
|
16
|
+
findAccount,
|
|
17
|
+
readStore,
|
|
18
|
+
storePath,
|
|
19
|
+
withAccount,
|
|
20
|
+
withoutAccount,
|
|
21
|
+
writeStore,
|
|
22
|
+
type Account,
|
|
23
|
+
} from "./store.ts";
|
|
24
|
+
|
|
25
|
+
const EXPIRY_MARGIN_MS = 60_000;
|
|
26
|
+
const DEFAULT_INTERVAL_S = 5;
|
|
27
|
+
const DEFAULT_EXPIRES_S = 900;
|
|
28
|
+
const SLOW_DOWN_S = 5;
|
|
29
|
+
const DESCRIPTION_CHARS = 300;
|
|
30
|
+
|
|
31
|
+
export type Sleep = (ms: number, signal: AbortSignal) => Promise<void>;
|
|
32
|
+
export type Notify = (message: string, level: "info" | "warning" | "error") => void;
|
|
33
|
+
|
|
34
|
+
export interface AuthOptions {
|
|
35
|
+
readonly fetch: FetchFunction;
|
|
36
|
+
readonly now: () => number;
|
|
37
|
+
readonly sleep: Sleep;
|
|
38
|
+
readonly homeDir: string;
|
|
39
|
+
readonly config: () => OfficeConfig;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** How a call that needs a device sign-in shows the prompt (specs/office.md#device-sign-in). */
|
|
43
|
+
export interface Prompter {
|
|
44
|
+
readonly hasUI: boolean;
|
|
45
|
+
readonly notify: Notify;
|
|
46
|
+
readonly update?: (text: string) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A running device sign-in; registered before its code request returns so that calls join it. */
|
|
50
|
+
interface DeviceSignIn {
|
|
51
|
+
readonly started: Promise<Started>;
|
|
52
|
+
readonly controller: AbortController;
|
|
53
|
+
/** Calls still waiting for the code request; none left when it returns means nobody sees the prompt. */
|
|
54
|
+
readonly callers: { waiting: number };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A running refresh; `controller` is aborted by `/office logout`. */
|
|
58
|
+
interface Refresh {
|
|
59
|
+
readonly promise: Promise<Account | undefined>;
|
|
60
|
+
readonly controller: AbortController;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface Started {
|
|
64
|
+
readonly userCode: string;
|
|
65
|
+
readonly uri: string;
|
|
66
|
+
readonly deadline: number;
|
|
67
|
+
readonly done: Promise<Account>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface TokenAnswer {
|
|
71
|
+
readonly status: number;
|
|
72
|
+
readonly body: Record<string, unknown>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function authority(tenant: string): string {
|
|
76
|
+
return `https://login.microsoftonline.com/${encodeURIComponent(tenant)}/oauth2/v2.0`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function str(value: unknown): string | undefined {
|
|
80
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A finite number above 0, else `fallback`. */
|
|
84
|
+
function positive(value: unknown, fallback: number): number {
|
|
85
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** `preferred_username` from an ID token's payload, without verifying it (it came over TLS from the issuer). */
|
|
89
|
+
export function usernameOf(idToken: unknown): string | undefined {
|
|
90
|
+
if (typeof idToken !== "string") return undefined;
|
|
91
|
+
const payload = idToken.split(".")[1];
|
|
92
|
+
if (payload === undefined) return undefined;
|
|
93
|
+
try {
|
|
94
|
+
const claims: unknown = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
95
|
+
return isRecord(claims) ? str(claims.preferred_username) : undefined;
|
|
96
|
+
} catch {
|
|
97
|
+
// A malformed ID token has no username; the caller falls back to `unknown`.
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** specs/office.md#sign-in-errors: the text of an answer with an `error` string, else of its status. */
|
|
103
|
+
function describeFailure(answer: TokenAnswer): string {
|
|
104
|
+
const raw = str(answer.body.error);
|
|
105
|
+
if (raw === undefined) return `HTTP ${answer.status}`;
|
|
106
|
+
const error = removeInvisible(raw);
|
|
107
|
+
const first = str(answer.body.error_description)?.split(/\r?\n/)[0];
|
|
108
|
+
const line = first === undefined ? "" : cleanLine(first);
|
|
109
|
+
if (line === "") return error;
|
|
110
|
+
return `${error}: ${line.length > DESCRIPTION_CHARS ? `${line.slice(0, DESCRIPTION_CHARS)}…` : line}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const failed = (reason: string): OfficeError =>
|
|
114
|
+
new OfficeError(`Office: sign-in failed: ${reason}`);
|
|
115
|
+
const STOPPED = "stopped by /office logout";
|
|
116
|
+
|
|
117
|
+
export class Auth {
|
|
118
|
+
readonly #options: AuthOptions;
|
|
119
|
+
readonly #pending = new Map<string, DeviceSignIn>();
|
|
120
|
+
readonly #refreshing = new Map<string, Refresh>();
|
|
121
|
+
/** Failures of sign-ins that had no caller, for the next call (specs/office.md#device-sign-in). */
|
|
122
|
+
readonly #unreported = new Map<string, string>();
|
|
123
|
+
#unreadableReported = false;
|
|
124
|
+
|
|
125
|
+
constructor(options: AuthOptions) {
|
|
126
|
+
this.#options = options;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get storePath(): string {
|
|
130
|
+
return storePath(this.#options.homeDir);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
#accounts(notify: Notify | undefined): readonly Account[] {
|
|
134
|
+
const read = readStore(this.storePath);
|
|
135
|
+
if (read.unreadable && !this.#unreadableReported && notify !== undefined) {
|
|
136
|
+
this.#unreadableReported = true;
|
|
137
|
+
notify(`Office: ignored the unreadable token store ${this.storePath}`, "warning");
|
|
138
|
+
}
|
|
139
|
+
return read.accounts;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
#save(account: Account): void {
|
|
143
|
+
writeStore(this.storePath, withAccount(readStore(this.storePath).accounts, account));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#remove(clientId: string, tenant: string): void {
|
|
147
|
+
const read = readStore(this.storePath);
|
|
148
|
+
if (findAccount(read.accounts, clientId, tenant) === undefined) return;
|
|
149
|
+
writeStore(this.storePath, withoutAccount(read.accounts, clientId, tenant));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
profile(kind: AccountKind): Profile {
|
|
153
|
+
return this.#options.config()[kind];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The stored account of the kind's client ID and tenant. */
|
|
157
|
+
account(kind: AccountKind, notify?: Notify): Account | undefined {
|
|
158
|
+
const { clientId, tenant } = this.profile(kind);
|
|
159
|
+
return findAccount(this.#accounts(notify), clientId, tenant);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** specs/office.md#account-choice: the configured default, else the one signed-in kind, else `work`. */
|
|
163
|
+
defaultKind(notify?: Notify): AccountKind {
|
|
164
|
+
const configured = this.#options.config().defaultAccount;
|
|
165
|
+
if (configured !== undefined) return configured;
|
|
166
|
+
const work = this.account("work", notify) !== undefined;
|
|
167
|
+
const personal = this.account("personal", notify) !== undefined;
|
|
168
|
+
return personal && !work ? "personal" : "work";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Posts a form; a non-JSON body is a failure unless the status already is one. */
|
|
172
|
+
async #post(
|
|
173
|
+
url: string,
|
|
174
|
+
form: Record<string, string>,
|
|
175
|
+
signal?: AbortSignal,
|
|
176
|
+
): Promise<TokenAnswer> {
|
|
177
|
+
const response = await send(
|
|
178
|
+
this.#options.fetch,
|
|
179
|
+
{
|
|
180
|
+
url,
|
|
181
|
+
method: "POST",
|
|
182
|
+
headers: {
|
|
183
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
184
|
+
Accept: "application/json",
|
|
185
|
+
},
|
|
186
|
+
body: new URLSearchParams(form).toString(),
|
|
187
|
+
},
|
|
188
|
+
signal,
|
|
189
|
+
);
|
|
190
|
+
try {
|
|
191
|
+
const body = jsonOf(response);
|
|
192
|
+
return { status: response.status, body: isRecord(body) ? body : {} };
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (!isOk(response.status)) return { status: response.status, body: {} };
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#accountOf(profile: Profile, body: Record<string, unknown>, previous?: Account): Account {
|
|
200
|
+
const { clientId, tenant } = profile;
|
|
201
|
+
const accessToken = str(body.access_token);
|
|
202
|
+
if (accessToken === undefined) throw failed("no access token");
|
|
203
|
+
const expiresIn =
|
|
204
|
+
typeof body.expires_in === "number" ? body.expires_in : Number(body.expires_in);
|
|
205
|
+
return {
|
|
206
|
+
clientId,
|
|
207
|
+
tenant,
|
|
208
|
+
username: usernameOf(body.id_token) ?? previous?.username ?? "unknown",
|
|
209
|
+
accessToken,
|
|
210
|
+
refreshToken: str(body.refresh_token) ?? previous?.refreshToken ?? "",
|
|
211
|
+
expiresAt: this.#options.now() + (Number.isFinite(expiresIn) ? expiresIn : 0) * 1000,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Step 2 of specs/office.md#tokens; `undefined` after `invalid_grant`. */
|
|
216
|
+
async #refresh(
|
|
217
|
+
profile: Profile,
|
|
218
|
+
account: Account,
|
|
219
|
+
signal: AbortSignal,
|
|
220
|
+
): Promise<Account | undefined> {
|
|
221
|
+
const { clientId, tenant, scopes } = profile;
|
|
222
|
+
const answer = await this.#post(
|
|
223
|
+
`${authority(tenant)}/token`,
|
|
224
|
+
{
|
|
225
|
+
client_id: clientId,
|
|
226
|
+
grant_type: "refresh_token",
|
|
227
|
+
refresh_token: account.refreshToken,
|
|
228
|
+
scope: scopes.join(" "),
|
|
229
|
+
},
|
|
230
|
+
signal,
|
|
231
|
+
).catch((error: unknown) => {
|
|
232
|
+
if (signal.aborted) throw failed(STOPPED);
|
|
233
|
+
return rethrowSignIn(error);
|
|
234
|
+
});
|
|
235
|
+
// `/office logout` stopped the refresh: its tokens are not stored.
|
|
236
|
+
if (signal.aborted) throw failed(STOPPED);
|
|
237
|
+
if (isOk(answer.status) && str(answer.body.error) === undefined) {
|
|
238
|
+
const refreshed = this.#accountOf(profile, answer.body, account);
|
|
239
|
+
this.#save(refreshed);
|
|
240
|
+
return refreshed;
|
|
241
|
+
}
|
|
242
|
+
if (answer.body.error === "invalid_grant") {
|
|
243
|
+
this.#remove(clientId, tenant);
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
throw failed(describeFailure(answer));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** A valid access token of `kind` (specs/office.md#tokens), signing in through `prompter` when needed. */
|
|
250
|
+
async accessToken(
|
|
251
|
+
kind: AccountKind,
|
|
252
|
+
signal: AbortSignal | undefined,
|
|
253
|
+
prompter: Prompter,
|
|
254
|
+
): Promise<string> {
|
|
255
|
+
throwIfAborted(signal);
|
|
256
|
+
const profile = this.profile(kind);
|
|
257
|
+
const notify = prompter.hasUI ? prompter.notify : undefined;
|
|
258
|
+
const signedIn = await this.#storedOrRefreshed(profile, signal, notify);
|
|
259
|
+
if (signedIn !== undefined) return signedIn.accessToken;
|
|
260
|
+
if (prompter.hasUI) {
|
|
261
|
+
return (await this.#signInWithUI(profile, signal, prompter.notify, prompter.update))
|
|
262
|
+
.accessToken;
|
|
263
|
+
}
|
|
264
|
+
const key = keyOf(profile);
|
|
265
|
+
const { entry } = this.#joinOrStart(profile, false);
|
|
266
|
+
const started = await awaitStarted(entry, signal);
|
|
267
|
+
const earlier = this.#unreported.get(key);
|
|
268
|
+
this.#unreported.delete(key);
|
|
269
|
+
const prompt = `${this.#prompt(profile, started)} Then call Office again.`;
|
|
270
|
+
throw new OfficeError(earlier === undefined ? prompt : `${earlier}\n${prompt}`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Shows the prompt, then waits for the sign-in; a starter that stops waiting still learns the outcome. */
|
|
274
|
+
async #signInWithUI(
|
|
275
|
+
profile: Profile,
|
|
276
|
+
signal: AbortSignal | undefined,
|
|
277
|
+
notify: Notify,
|
|
278
|
+
update?: (text: string) => void,
|
|
279
|
+
): Promise<Account> {
|
|
280
|
+
throwIfAborted(signal);
|
|
281
|
+
const key = keyOf(profile);
|
|
282
|
+
const { entry, starter } = this.#joinOrStart(profile, true);
|
|
283
|
+
let started: Started;
|
|
284
|
+
try {
|
|
285
|
+
started = await awaitStarted(entry, signal);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (starter && error instanceof Cancelled) this.#reportLater(entry, profile, notify);
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
const earlier = this.#unreported.get(key);
|
|
291
|
+
this.#unreported.delete(key);
|
|
292
|
+
if (earlier !== undefined) notify(earlier, "error");
|
|
293
|
+
const prompt = this.#prompt(profile, started);
|
|
294
|
+
notify(prompt, "info");
|
|
295
|
+
update?.(prompt);
|
|
296
|
+
try {
|
|
297
|
+
return await waitFor(started.done, signal);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (!(error instanceof Cancelled)) this.#unreported.delete(key);
|
|
300
|
+
else if (starter) this.#reportLater(entry, profile, notify);
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The outcome for a starter that stopped waiting (specs/office.md#device-sign-in). */
|
|
306
|
+
#reportLater(entry: DeviceSignIn, profile: Profile, notify: Notify): void {
|
|
307
|
+
entry.started
|
|
308
|
+
.then((started) => started.done)
|
|
309
|
+
.then(
|
|
310
|
+
(account) =>
|
|
311
|
+
notify(`Office: ${profile.kind} account signed in as ${account.username}`, "info"),
|
|
312
|
+
(error: unknown) => {
|
|
313
|
+
if (!entry.controller.signal.aborted) notify(messageOf(error), "error");
|
|
314
|
+
},
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async #storedOrRefreshed(
|
|
319
|
+
profile: Profile,
|
|
320
|
+
signal: AbortSignal | undefined,
|
|
321
|
+
notify: Notify | undefined,
|
|
322
|
+
): Promise<Account | undefined> {
|
|
323
|
+
throwIfAborted(signal);
|
|
324
|
+
const stored = this.account(profile.kind, notify);
|
|
325
|
+
if (stored === undefined) return undefined;
|
|
326
|
+
if (stored.expiresAt - EXPIRY_MARGIN_MS > this.#options.now()) return stored;
|
|
327
|
+
if (stored.refreshToken === "") return undefined;
|
|
328
|
+
const key = keyOf(profile);
|
|
329
|
+
let running = this.#refreshing.get(key);
|
|
330
|
+
if (running === undefined) {
|
|
331
|
+
const controller = new AbortController();
|
|
332
|
+
const promise = this.#refresh(profile, stored, controller.signal).finally(() => {
|
|
333
|
+
if (this.#refreshing.get(key)?.controller === controller) this.#refreshing.delete(key);
|
|
334
|
+
});
|
|
335
|
+
// Every waiter reports the rejection; with none left it must not go unhandled.
|
|
336
|
+
promise.catch(() => {});
|
|
337
|
+
running = { promise, controller };
|
|
338
|
+
this.#refreshing.set(key, running);
|
|
339
|
+
}
|
|
340
|
+
return waitFor(running.promise, signal);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** `/office login`: signs in to `kind`, showing the prompt through `notify`; the caller reports the outcome. */
|
|
344
|
+
async login(
|
|
345
|
+
kind: AccountKind,
|
|
346
|
+
signal: AbortSignal | undefined,
|
|
347
|
+
notify: Notify | undefined,
|
|
348
|
+
): Promise<Account> {
|
|
349
|
+
throwIfAborted(signal);
|
|
350
|
+
const profile = this.profile(kind);
|
|
351
|
+
const signedIn = await this.#storedOrRefreshed(profile, signal, notify);
|
|
352
|
+
if (signedIn !== undefined) return signedIn;
|
|
353
|
+
return this.#signInWithUI(profile, signal, notify ?? (() => {}));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** `/office logout`: stops a running device sign-in and refresh of `kind` and removes its account. */
|
|
357
|
+
logout(kind: AccountKind): void {
|
|
358
|
+
const profile = this.profile(kind);
|
|
359
|
+
const key = keyOf(profile);
|
|
360
|
+
this.#pending.get(key)?.controller.abort();
|
|
361
|
+
this.#pending.delete(key);
|
|
362
|
+
this.#refreshing.get(key)?.controller.abort();
|
|
363
|
+
this.#refreshing.delete(key);
|
|
364
|
+
this.#unreported.delete(key);
|
|
365
|
+
this.#remove(profile.clientId, profile.tenant);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** The prompt, with the minutes left of the code rounded up. */
|
|
369
|
+
#prompt(profile: Profile, started: Started): string {
|
|
370
|
+
const minutes = Math.ceil((started.deadline - this.#options.now()) / 60_000);
|
|
371
|
+
return `Office: sign in to Microsoft 365 (${profile.kind} account): open ${started.uri} and enter the code ${started.userCode} (expires in ${minutes} min).`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** The running device sign-in of the profile's client ID and tenant, registered at once when none runs. */
|
|
375
|
+
#joinOrStart(
|
|
376
|
+
profile: Profile,
|
|
377
|
+
hasUI: boolean,
|
|
378
|
+
): { readonly entry: DeviceSignIn; readonly starter: boolean } {
|
|
379
|
+
const key = keyOf(profile);
|
|
380
|
+
const running = this.#pending.get(key);
|
|
381
|
+
if (running !== undefined) return { entry: running, starter: false };
|
|
382
|
+
const controller = new AbortController();
|
|
383
|
+
const callers = { waiting: 0 };
|
|
384
|
+
const started = this.#start(profile, key, controller, hasUI, callers);
|
|
385
|
+
const entry: DeviceSignIn = { started, controller, callers };
|
|
386
|
+
this.#pending.set(key, entry);
|
|
387
|
+
// A failed code request ends the entry; the waiters receive the error through `started`.
|
|
388
|
+
started.then(undefined, () => this.#forget(key, controller));
|
|
389
|
+
return { entry, starter: true };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
#forget(key: string, controller: AbortController): void {
|
|
393
|
+
if (this.#pending.get(key)?.controller === controller) this.#pending.delete(key);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async #start(
|
|
397
|
+
profile: Profile,
|
|
398
|
+
key: string,
|
|
399
|
+
controller: AbortController,
|
|
400
|
+
hasUI: boolean,
|
|
401
|
+
callers: { readonly waiting: number },
|
|
402
|
+
): Promise<Started> {
|
|
403
|
+
const { clientId, tenant, scopes } = profile;
|
|
404
|
+
const answer = await this.#post(
|
|
405
|
+
`${authority(tenant)}/devicecode`,
|
|
406
|
+
{ client_id: clientId, scope: scopes.join(" ") },
|
|
407
|
+
controller.signal,
|
|
408
|
+
).catch((error: unknown) => {
|
|
409
|
+
if (controller.signal.aborted) throw failed(STOPPED);
|
|
410
|
+
return rethrowSignIn(error);
|
|
411
|
+
});
|
|
412
|
+
const deviceCode = str(answer.body.device_code);
|
|
413
|
+
const userCode = str(answer.body.user_code);
|
|
414
|
+
const uri = str(answer.body.verification_uri);
|
|
415
|
+
if (!isOk(answer.status) || str(answer.body.error) !== undefined) {
|
|
416
|
+
throw failed(describeFailure(answer));
|
|
417
|
+
}
|
|
418
|
+
if (deviceCode === undefined || userCode === undefined || uri === undefined) {
|
|
419
|
+
throw failed("the code response is incomplete");
|
|
420
|
+
}
|
|
421
|
+
if (callers.waiting === 0) {
|
|
422
|
+
// Every caller stopped before the prompt was known: nobody sees it, so stop, reporting nothing.
|
|
423
|
+
controller.abort();
|
|
424
|
+
this.#forget(key, controller);
|
|
425
|
+
throw failed(STOPPED);
|
|
426
|
+
}
|
|
427
|
+
const expiresIn = positive(answer.body.expires_in, DEFAULT_EXPIRES_S);
|
|
428
|
+
const interval = positive(answer.body.interval, DEFAULT_INTERVAL_S);
|
|
429
|
+
const deadline = this.#options.now() + expiresIn * 1000;
|
|
430
|
+
const done = this.#poll(profile, deviceCode, deadline, interval, controller.signal).finally(
|
|
431
|
+
() => this.#forget(key, controller),
|
|
432
|
+
);
|
|
433
|
+
// Waiters get the error themselves; a starter without a UI has returned, so the next call gets it.
|
|
434
|
+
done.then(undefined, (error: unknown) => {
|
|
435
|
+
if (!hasUI && !controller.signal.aborted) this.#unreported.set(key, messageOf(error));
|
|
436
|
+
});
|
|
437
|
+
return { userCode, uri, deadline, done };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async #poll(
|
|
441
|
+
profile: Profile,
|
|
442
|
+
deviceCode: string,
|
|
443
|
+
deadline: number,
|
|
444
|
+
interval: number,
|
|
445
|
+
signal: AbortSignal,
|
|
446
|
+
): Promise<Account> {
|
|
447
|
+
const { clientId, tenant } = profile;
|
|
448
|
+
let wait = interval;
|
|
449
|
+
for (;;) {
|
|
450
|
+
await this.#options.sleep(wait * 1000, signal).catch((error: unknown) => {
|
|
451
|
+
if (signal.aborted) throw failed(STOPPED);
|
|
452
|
+
throw error;
|
|
453
|
+
});
|
|
454
|
+
if (this.#options.now() >= deadline) throw failed("the code expired");
|
|
455
|
+
const answer = await this.#post(
|
|
456
|
+
`${authority(tenant)}/token`,
|
|
457
|
+
{
|
|
458
|
+
client_id: clientId,
|
|
459
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
460
|
+
device_code: deviceCode,
|
|
461
|
+
},
|
|
462
|
+
signal,
|
|
463
|
+
).catch((error: unknown) => {
|
|
464
|
+
if (signal.aborted) throw failed(STOPPED);
|
|
465
|
+
// A timeout, network error or non-JSON body does not end the sign-in (specs/office.md#device-sign-in).
|
|
466
|
+
if (error instanceof RequestFailure) return null;
|
|
467
|
+
throw error;
|
|
468
|
+
});
|
|
469
|
+
if (answer === null) continue;
|
|
470
|
+
const error = str(answer.body.error);
|
|
471
|
+
if (isOk(answer.status) && error === undefined) {
|
|
472
|
+
const account = this.#accountOf(profile, answer.body);
|
|
473
|
+
this.#save(account);
|
|
474
|
+
return account;
|
|
475
|
+
}
|
|
476
|
+
if (error === "authorization_pending") continue;
|
|
477
|
+
if (error === "slow_down") {
|
|
478
|
+
wait += SLOW_DOWN_S;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (answer.status >= 500 || error === "temporarily_unavailable") continue;
|
|
482
|
+
throw failed(describeFailure(answer));
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
488
|
+
if (signal?.aborted) throw new Cancelled();
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Waits for the code request of `entry`, counted as a caller while it waits. */
|
|
492
|
+
async function awaitStarted(
|
|
493
|
+
entry: DeviceSignIn,
|
|
494
|
+
signal: AbortSignal | undefined,
|
|
495
|
+
): Promise<Started> {
|
|
496
|
+
entry.callers.waiting += 1;
|
|
497
|
+
try {
|
|
498
|
+
return await waitFor(entry.started, signal);
|
|
499
|
+
} finally {
|
|
500
|
+
entry.callers.waiting -= 1;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function keyOf(profile: Profile): string {
|
|
505
|
+
return `${profile.clientId}|${profile.tenant}`;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function messageOf(error: unknown): string {
|
|
509
|
+
return error instanceof Error ? error.message : String(error);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function rethrowSignIn(error: unknown): never {
|
|
513
|
+
if (error instanceof RequestFailure)
|
|
514
|
+
throw new OfficeError(`Office: sign-in failed: ${error.reason}`);
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** Waits for `promise`; an aborted `signal` ends the wait only. */
|
|
519
|
+
function waitFor<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
520
|
+
if (signal === undefined) return promise;
|
|
521
|
+
if (signal.aborted) return Promise.reject(new Cancelled());
|
|
522
|
+
return new Promise<T>((resolve, reject) => {
|
|
523
|
+
const onAbort = (): void => reject(new Cancelled());
|
|
524
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
525
|
+
promise.then(
|
|
526
|
+
(value) => {
|
|
527
|
+
signal.removeEventListener("abort", onAbort);
|
|
528
|
+
resolve(value);
|
|
529
|
+
},
|
|
530
|
+
(error: unknown) => {
|
|
531
|
+
signal.removeEventListener("abort", onAbort);
|
|
532
|
+
reject(error);
|
|
533
|
+
},
|
|
534
|
+
);
|
|
535
|
+
});
|
|
536
|
+
}
|