3 +const fs
= require(
'node:fs');
4 +const os
= require(
'node:os');
5 +const path
= require(
'node:path');
6 +const http
= require(
'node:http');
7 +const net
= require(
'node:net');
8 +const crypto
= require(
'node:crypto');
9 +const { spawn, spawnSync }
= require(
'node:child_process');
12 + process.
env.GOOGLE_WORKSPACE_CONFIG_DIR
|| 13 + path.join(os.homedir(),
'.pi',
'google-workspace');
15 +const CREDENTIALS_PATH
= 16 + process.
env.GOOGLE_WORKSPACE_CREDENTIALS
|| 17 + path.join(CONFIG_DIR,
'credentials.json');
20 + process.
env.GOOGLE_WORKSPACE_TOKENS_DIR
|| path.join(CONFIG_DIR,
'tokens');
22 +const SKILL_ROOT
= path.join(
__dirname,
'..');
24 +const DEFAULT_CLIENT_ID
= 25 + '338689075775-o75k922vn5fdl18qergr96rp8g63e4d7.apps.googleusercontent.com';
26 +const DEFAULT_CLOUD_FUNCTION_URL
= 27 + 'https://google-workspace-extension.geminicli.com';
29 +const REQUIRED_IDENTITY_SCOPES
= [
30 + 'https://www.googleapis.com/auth/userinfo.email',
31 + 'https://www.googleapis.com/auth/userinfo.profile',
34 +const DEFAULT_SCOPES
= [
35 + 'https://www.googleapis.com/auth/documents',
36 + 'https://www.googleapis.com/auth/drive',
37 + 'https://www.googleapis.com/auth/calendar',
38 + 'https://www.googleapis.com/auth/chat.spaces',
39 + 'https://www.googleapis.com/auth/chat.messages',
40 + 'https://www.googleapis.com/auth/chat.memberships',
41 + ...REQUIRED_IDENTITY_SCOPES,
42 + 'https://www.googleapis.com/auth/gmail.modify',
43 + 'https://www.googleapis.com/auth/directory.readonly',
44 + 'https://www.googleapis.com/auth/presentations.readonly',
45 + 'https://www.googleapis.com/auth/spreadsheets.readonly',
48 +const DEFAULT_VERSIONS
= {
61 +function ensureConfigDir() {
62 + fs.mkdirSync(CONFIG_DIR, { recursive:
true });
65 +function ensureTokensDir() {
66 + fs.mkdirSync(TOKENS_DIR, { recursive:
true });
69 +function readJson(filePath) {
70 + return JSON.
parse(fs.readFileSync(filePath,
'utf8'));
73 +function installDependencies() {
74 + const npm
= process.
platform === 'win32' ? 'npm.cmd' : 'npm';
75 + console.
error(
'ℹ️ Installing Google Workspace skill dependencies...');
77 + const result
= spawnSync(npm, [
'install',
'--no-audit',
'--no-fund'], {
83 + throw new Error(
`Failed to run npm install: ${result.error.message}
`);
86 + if (result.status
!== 0) {
87 + throw new Error(
`npm install failed with exit code ${result.status}
`);
91 +function loadRuntimeDeps() {
97 + const { google }
= require(
'googleapis');
98 + const { authenticate }
= require(
'@google-cloud/local-auth');
99 + runtimeDeps
= { google, authenticate };
100 + return runtimeDeps;
102 + if (error
&& error.code
=== 'MODULE_NOT_FOUND') {
103 + installDependencies();
104 + const { google }
= require(
'googleapis');
105 + const { authenticate }
= require(
'@google-cloud/local-auth');
106 + runtimeDeps
= { google, authenticate };
107 + return runtimeDeps;
113 +function getGoogleApis() {
114 + return loadRuntimeDeps().google;
117 +function getWorkspaceClientConfig() {
120 + process.
env.GOOGLE_WORKSPACE_CLIENT_ID
|| 121 + process.
env.WORKSPACE_CLIENT_ID
|| 124 + process.
env.GOOGLE_WORKSPACE_CLOUD_FUNCTION_URL
|| 125 + process.
env.WORKSPACE_CLOUD_FUNCTION_URL
|| 126 + DEFAULT_CLOUD_FUNCTION_URL,
130 +function credentialsExist() {
131 + return fs.existsSync(CREDENTIALS_PATH);
134 +function normalizeEmail(email) {
135 + const normalized
= String(email
|| '').trim().toLowerCase();
137 + throw new Error(
'Email is required. Pass --email <account@example.com>.');
140 + if (
!/^[^@\s]+@[^@\s]+$/.test(normalized)) {
141 + throw new Error(
`Invalid email address: ${email}
`);
147 +function tokenFilenameForEmail(email) {
148 + return `${
encodeURIComponent(normalizeEmail(email))}
.json`;
151 +function tokenPathForEmail(email) {
152 + return path.join(TOKENS_DIR, tokenFilenameForEmail(email));
155 +function tokenExists(email) {
156 + return fs.existsSync(tokenPathForEmail(email));
159 +function loadCredentialsFile() {
160 + if (
!credentialsExist()) {
162 + `Missing OAuth credentials file at ${CREDENTIALS_PATH}
. ` + 163 + 'Create a Google OAuth Desktop client and save the JSON there.',
166 + return readJson(CREDENTIALS_PATH);
169 +function loadToken(email) {
170 + const tokenPath
= tokenPathForEmail(email);
171 + if (
!fs.existsSync(tokenPath)) {
174 + return readJson(tokenPath);
177 +function decodeEmailFromTokenFilename(filename) {
178 + if (
!filename.endsWith(
'.json')) {
183 + return normalizeEmail(
decodeURIComponent(filename.slice(
0,
-5)));
189 +function listAccounts() {
190 + if (
!fs.existsSync(TOKENS_DIR)) {
194 + const results
= [];
195 + const entries
= fs.readdirSync(TOKENS_DIR, { withFileTypes:
true });
197 + for (
const entry
of entries) {
198 + if (
!entry.isFile()
|| !entry.name.endsWith(
'.json')) {
202 + const tokenPath
= path.join(TOKENS_DIR, entry.name);
203 + const emailFromFilename
= decodeEmailFromTokenFilename(entry.name);
207 + token
= readJson(tokenPath);
210 + email: emailFromFilename,
212 + error:
`Failed to read token JSON: ${error.message}
`,
217 + let email
= emailFromFilename;
218 + if (token
&& token.__email) {
220 + email
= normalizeEmail(token.__email);
226 + const expiryDate
= token.expiry_date
|| null;
231 + authMode: token.__authMode
=== 'local' || token.__authMode
=== 'cloud' 234 + hasAccessToken:
Boolean(token.access_token),
235 + hasRefreshToken:
Boolean(token.refresh_token),
236 + scopes: formatScopes(token.scope),
238 + expired: expiryDate
? expiryDate
< Date.
now()
: null,
242 + return results.sort((a, b)
=> {
243 + const left
= a.email
|| '';
244 + const right
= b.email
|| '';
245 + return left.localeCompare(right);
249 +function createOAuthClientFromCredentials(credentialsJson) {
250 + const creds
= credentialsJson.installed
|| credentialsJson.web;
253 + 'Invalid credentials.json: expected an "installed" or "web" key.',
257 + if (
!creds.client_id
|| !creds.client_secret) {
259 + 'Invalid credentials.json: missing client_id or client_secret.',
263 + const redirectUri
= Array.
isArray(creds.redirect_uris)
264 + ? creds.redirect_uris[
0]
267 + const google
= getGoogleApis();
268 + return new google.auth.OAuth2(
270 + creds.client_secret,
271 + redirectUri
|| 'http://localhost',
275 +function createCloudOAuthClient() {
276 + const google
= getGoogleApis();
277 + const { clientId }
= getWorkspaceClientConfig();
278 + return new google.auth.OAuth2({ clientId });
281 +function resolveAuthMode(token) {
282 + const forced
= process.
env.GOOGLE_WORKSPACE_AUTH_MODE;
283 + if (forced
=== 'local' || forced
=== 'cloud') {
287 + if (token
&& (token.__authMode
=== 'local' || token.__authMode
=== 'cloud')) {
288 + return token.__authMode;
291 + if (credentialsExist()) {
298 +function saveToken(email, token, mode) {
302 + const normalizedEmail
= normalizeEmail(email);
303 + const tokenPath
= tokenPathForEmail(normalizedEmail);
308 + __email: normalizedEmail,
311 + fs.writeFileSync(tokenPath,
JSON.
stringify(payload,
null,
2));
313 + fs.chmodSync(tokenPath,
0o600);
319 +function clearToken(email) {
320 + const tokenPath
= tokenPathForEmail(email);
321 + if (fs.existsSync(tokenPath)) {
322 + fs.rmSync(tokenPath);
326 +function isExpiringSoon(credentials) {
327 + if (
!credentials
|| !credentials.expiry_date) {
330 + return credentials.expiry_date
< Date.
now()
+ 60_000;
333 +function openUrlInBrowser(targetUrl) {
337 + if (
process.
platform === 'darwin') {
339 + args
= [targetUrl];
340 + }
else if (
process.
platform === 'win32') {
342 + args
= [
'/c',
'start',
'', targetUrl];
344 + command
= 'xdg-open';
345 + args
= [targetUrl];
348 + const child
= spawn(command, args, {
355 +function getAvailablePort() {
356 + return new Promise((resolve, reject)
=> {
357 + const server
= net.createServer();
358 + server.listen(
0, ()
=> {
359 + const address
= server.address();
360 + const port
= address
&& typeof address
=== 'object' ? address.port
: 0;
361 + server.close(()
=> resolve(port));
363 + server.on(
'error', reject);
367 +async function refreshViaCloudFunction(refreshToken) {
368 + const { cloudFunctionUrl }
= getWorkspaceClientConfig();
370 + const response
= await fetch(
`${cloudFunctionUrl}
/refreshToken`, {
373 + 'Content-Type':
'application/json',
375 + body:
JSON.
stringify({
376 + refresh_token: refreshToken,
380 + if (
!response.ok) {
381 + const body
= await response.text();
382 + throw new Error(
`Cloud token refresh failed: ${response.status}
${body}
`);
385 + return response.json();
388 +function mergeWithIdentityScopes(scopes) {
389 + return Array.
from(
new Set([
...formatScopes(scopes),
...REQUIRED_IDENTITY_SCOPES]));
392 +async function fetchAuthenticatedEmail(authClient) {
393 + const google
= getGoogleApis();
394 + const oauth2
= google.oauth2({ version:
'v2', auth: authClient });
395 + const response
= await oauth2.userinfo.get();
396 + const email
= response
?.data
?.email;
399 + 'Authentication succeeded, but Google did not return an email address. ' + 400 + 'Ensure userinfo.email scope is granted.',
403 + return normalizeEmail(email);
406 +async function ensureExpectedEmail(authClient, expectedEmail) {
407 + const normalizedExpectedEmail
= normalizeEmail(expectedEmail);
408 + const authenticatedEmail
= await fetchAuthenticatedEmail(authClient);
410 + if (authenticatedEmail
!== normalizedExpectedEmail) {
412 + `Authenticated as ${authenticatedEmail}
, but expected ${normalizedExpectedEmail}
. ` + 413 + 'Sign in with the requested account and retry.',
417 + return authenticatedEmail;
420 +async function interactiveLoginLocal(scopes, email) {
421 + const { authenticate }
= loadRuntimeDeps();
422 + console.
error(
'ℹ️ Opening browser for Google OAuth login (local credentials)...');
424 + const authClient
= await authenticate({
425 + keyfilePath: CREDENTIALS_PATH,
426 + scopes: mergeWithIdentityScopes(scopes),
429 + if (
!authClient.credentials
|| !authClient.credentials.access_token) {
430 + throw new Error(
'Authentication failed: no access token returned.');
433 + const normalizedEmail
= await ensureExpectedEmail(authClient, email);
434 + saveToken(normalizedEmail, authClient.credentials,
'local');
438 +async function interactiveLoginCloud(scopes, email) {
439 + const client
= createCloudOAuthClient();
440 + const { cloudFunctionUrl }
= getWorkspaceClientConfig();
442 + const host
= process.
env.GOOGLE_WORKSPACE_CALLBACK_HOST
|| 'localhost';
443 + const port
= await getAvailablePort();
444 + const callbackUrl
= `http://${host}
:${port}
/oauth2callback`;
446 + const csrfToken
= crypto.randomBytes(
32).
toString(
'hex');
447 + const statePayload
= {
452 + const state
= Buffer.from(
JSON.
stringify(statePayload),
'utf8').
toString(
456 + const authUrl
= client.generateAuthUrl({
457 + redirect_uri: cloudFunctionUrl,
458 + access_type:
'offline',
459 + scope: mergeWithIdentityScopes(scopes),
464 + console.
error(
'ℹ️ Opening browser for Google OAuth login...');
466 + openUrlInBrowser(authUrl);
468 + console.
error(
'⚠️ Could not auto-open browser. Open this URL manually:');
469 + console.
error(authUrl);
472 + const loginTimeoutMs
= 5 * 60 * 1000;
474 + const credentials
= await new Promise((resolve, reject)
=> {
475 + const timer
= setTimeout(()
=> {
476 + server.close(()
=> {
479 + 'Authentication timed out after 5 minutes. Please try again.',
483 + }, loginTimeoutMs);
485 + const server
= http.createServer((req, res)
=> {
487 + if (
!req.url
|| !req.url.startsWith(
'/oauth2callback')) {
488 + res.statusCode
= 404;
489 + res.end(
'Not found');
493 + const parsed
= new URL(req.url,
`http://${host}
:${port}
`);
494 + const returnedState
= parsed.searchParams.get(
'state');
495 + if (returnedState
!== csrfToken) {
496 + res.statusCode
= 400;
497 + res.end(
'State mismatch.');
498 + clearTimeout(timer);
499 + server.close(()
=> {
500 + reject(
new Error(
'OAuth state mismatch.'));
505 + const errorCode
= parsed.searchParams.get(
'error');
507 + const description
= 508 + parsed.searchParams.get(
'error_description')
|| 509 + 'No additional details';
510 + res.statusCode
= 400;
511 + res.end(
'Authentication failed.');
512 + clearTimeout(timer);
513 + server.close(()
=> {
514 + reject(
new Error(
`Google OAuth error: ${errorCode}
. ${description}
`));
519 + const accessToken
= parsed.searchParams.get(
'access_token');
520 + const refreshToken
= parsed.searchParams.get(
'refresh_token');
521 + const scope
= parsed.searchParams.get(
'scope');
522 + const tokenType
= parsed.searchParams.get(
'token_type');
523 + const expiryDateRaw
= parsed.searchParams.get(
'expiry_date');
525 + if (
!accessToken
|| !expiryDateRaw) {
526 + res.statusCode
= 400;
527 + res.end(
'Authentication failed: missing tokens.');
528 + clearTimeout(timer);
529 + server.close(()
=> {
531 + new Error(
'Authentication failed: callback did not include tokens.'),
537 + const expiryDate
= Number.
parseInt(expiryDateRaw,
10);
538 + if (
Number.
isNaN(expiryDate)) {
539 + res.statusCode
= 400;
540 + res.end(
'Authentication failed: invalid expiry date.');
541 + clearTimeout(timer);
542 + server.close(()
=> {
544 + new Error(
'Authentication failed: callback expiry_date is invalid.'),
551 + access_token: accessToken,
552 + refresh_token: refreshToken
|| null,
553 + scope: scope
|| undefined,
554 + token_type: tokenType
|| undefined,
555 + expiry_date: expiryDate,
558 + res.end(
'Authentication successful. You can close this tab.');
560 + clearTimeout(timer);
561 + server.close(()
=> {
565 + clearTimeout(timer);
566 + server.close(()
=> {
572 + server.on(
'error', (error)
=> {
573 + clearTimeout(timer);
574 + reject(
new Error(
`OAuth callback server error: ${error.message}
`));
577 + server.listen(port, host, ()
=> {
582 + client.setCredentials(credentials);
583 + const normalizedEmail
= await ensureExpectedEmail(client, email);
584 + saveToken(normalizedEmail, credentials,
'cloud');
588 +async function interactiveLogin(scopes, mode, email) {
589 + if (mode
=== 'local') {
590 + return interactiveLoginLocal(scopes, email);
592 + return interactiveLoginCloud(scopes, email);
595 +function stripInternalTokenFields(token) {
596 + if (
!token
|| typeof token
!== 'object') {
599 + const clone
= {
...token };
600 + delete clone.__authMode;
601 + delete clone.__email;
605 +async function authorize(options
= {}) {
606 + const email
= normalizeEmail(options.email);
607 + const scopes
= mergeWithIdentityScopes(options.scopes
|| DEFAULT_SCOPES);
608 + const interactive
= options.interactive
!== false;
614 + const token
= loadToken(email);
615 + const mode
= resolveAuthMode(token);
619 + ? createOAuthClientFromCredentials(loadCredentialsFile())
620 + : createCloudOAuthClient();
623 + if (
!interactive) {
625 + `No token found for ${email}
at ${tokenPathForEmail(email)}
. ` + 626 + `Run: node scripts/auth.js login --email ${email}
`,
629 + return interactiveLogin(scopes, mode, email);
632 + if (token.__email) {
633 + const tokenEmail
= normalizeEmail(token.__email);
634 + if (tokenEmail
!== email) {
636 + `Token metadata mismatch. Requested ${email}
but token is tagged as ${tokenEmail}
. ` + 637 + `Delete it and sign in again: node scripts/auth.js clear --email ${email}
`,
642 + client.setCredentials(stripInternalTokenFields(token));
644 + if (
!isExpiringSoon(client.credentials)) {
648 + if (client.credentials.refresh_token) {
649 + if (mode
=== 'local') {
650 + const refreshed
= await client.refreshAccessToken();
652 + ...refreshed.credentials,
654 + refreshed.credentials.refresh_token
|| client.credentials.refresh_token,
656 + client.setCredentials(merged);
657 + saveToken(email, merged,
'local');
661 + const refreshed
= await refreshViaCloudFunction(
662 + client.credentials.refresh_token,
666 + refresh_token: client.credentials.refresh_token,
668 + client.setCredentials(merged);
669 + saveToken(email, merged,
'cloud');
673 + if (
!interactive) {
675 + `Token for ${email}
is expired and no refresh token is available. ` + 676 + `Run: node scripts/auth.js login --email ${email}
`,
680 + return interactiveLogin(scopes, mode, email);
683 +function formatScopes(value) {
687 + if (
Array.
isArray(value)) {
690 + return String(value)
692 + .map((part)
=> part.trim())
702 + REQUIRED_IDENTITY_SCOPES,
708 + getWorkspaceClientConfig,