@tenonhq/dovetail-google-auth 0.0.9

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/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # @tenonhq/dovetail-google-auth
2
+
3
+ Google OAuth2 authentication for Dovetail Google integrations. Shared auth layer used by `@tenonhq/dovetail-gmail` and `@tenonhq/dovetail-google-calendar`.
4
+
5
+ ## Setup
6
+
7
+ ### 1. Create a Google Cloud Project
8
+
9
+ 1. Go to [Google Cloud Console](https://console.cloud.google.com/)
10
+ 2. Click **New Project** and name it (e.g., "Tenon CTO Automation")
11
+ 3. Select the project
12
+
13
+ ### 2. Enable APIs
14
+
15
+ 1. Go to **APIs & Services > Library**
16
+ 2. Search for and enable:
17
+ - **Gmail API**
18
+ - **Google Calendar API**
19
+
20
+ ### 3. Create OAuth Credentials
21
+
22
+ 1. Go to **APIs & Services > Credentials**
23
+ 2. Click **Create Credentials > OAuth client ID**
24
+ 3. If prompted, configure the **OAuth consent screen** first:
25
+ - User type: **Internal** (Google Workspace) or **External**
26
+ - App name: "Tenon CTO Automation"
27
+ - Scopes: `gmail.modify`, `calendar`
28
+ 4. Application type: **Desktop app** (or **Web application**)
29
+ 5. If using Web application, add `http://localhost:3000/callback` as an **Authorized redirect URI**
30
+ 6. Download or copy the **Client ID** and **Client Secret**
31
+
32
+ ### 4. Get a Refresh Token
33
+
34
+ ```bash
35
+ # Set your credentials
36
+ export GOOGLE_CLIENT_ID="your-client-id"
37
+ export GOOGLE_CLIENT_SECRET="your-client-secret"
38
+
39
+ # Run the setup script
40
+ cd packages/google-auth
41
+ npm run setup
42
+ ```
43
+
44
+ This opens your browser for Google authorization. After granting access, the refresh token is printed to the terminal.
45
+
46
+ ### 5. Add to .env
47
+
48
+ ```bash
49
+ GOOGLE_CLIENT_ID=your-client-id
50
+ GOOGLE_CLIENT_SECRET=your-client-secret
51
+ GOOGLE_REFRESH_TOKEN=your-refresh-token
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ```typescript
57
+ import { createGoogleAuth, configFromEnv } from "@tenonhq/dovetail-google-auth";
58
+
59
+ // Load config from environment variables
60
+ var config = configFromEnv();
61
+
62
+ // Create authenticated client
63
+ var { auth } = createGoogleAuth({ config: config });
64
+
65
+ // Pass auth to Gmail or Calendar packages
66
+ ```
67
+
68
+ ## Token Expiration
69
+
70
+ Google refresh tokens expire after **7 days** for apps in "Testing" status.
71
+
72
+ To get long-lived tokens:
73
+ - **Google Workspace accounts:** Set the app consent screen to **Internal**
74
+ - **Personal accounts:** Set the app to **In production** (requires verification for sensitive scopes, or keep under 100 users for unverified apps)
75
+
76
+ If your token expires, run `npm run setup` again to get a new one.
77
+
78
+ ## API
79
+
80
+ ### `createGoogleAuth({ config })`
81
+
82
+ Creates an OAuth2Client with a refresh token. Token refresh is handled automatically.
83
+
84
+ ### `configFromEnv()`
85
+
86
+ Reads `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `GOOGLE_REFRESH_TOKEN` from `process.env`.
87
+
88
+ ### `handleAuthError(error, context)`
89
+
90
+ Standardized error handler for Google API errors. Maps HTTP status codes (401, 403, 429) to actionable error messages.
@@ -0,0 +1,20 @@
1
+ import { GoogleAuthConfig, GoogleAuthResult } from "./types";
2
+ /**
3
+ * @description Creates an authenticated Google OAuth2 client from a refresh token.
4
+ * @param params - Object with auth config containing clientId, clientSecret, and refreshToken.
5
+ * @returns Object with the authenticated OAuth2Client.
6
+ */
7
+ export declare function createGoogleAuth(params: {
8
+ config: GoogleAuthConfig;
9
+ }): GoogleAuthResult;
10
+ /**
11
+ * @description Creates a GoogleAuthConfig from environment variables.
12
+ * @returns Config object populated from GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN.
13
+ */
14
+ export declare function configFromEnv(): GoogleAuthConfig;
15
+ /**
16
+ * @description Handles Google API errors with specific guidance for common error codes.
17
+ * @param error - The caught error.
18
+ * @param context - Description of what operation was being attempted.
19
+ */
20
+ export declare function handleAuthError(error: unknown, context: string): never;
package/dist/client.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createGoogleAuth = createGoogleAuth;
4
+ exports.configFromEnv = configFromEnv;
5
+ exports.handleAuthError = handleAuthError;
6
+ const google_auth_library_1 = require("google-auth-library");
7
+ const constants_1 = require("./constants");
8
+ /**
9
+ * @description Creates an authenticated Google OAuth2 client from a refresh token.
10
+ * @param params - Object with auth config containing clientId, clientSecret, and refreshToken.
11
+ * @returns Object with the authenticated OAuth2Client.
12
+ */
13
+ function createGoogleAuth(params) {
14
+ var config = params.config;
15
+ if (!config.clientId) {
16
+ throw new Error("GOOGLE_CLIENT_ID is required. Run the setup script to configure OAuth credentials.");
17
+ }
18
+ if (!config.clientSecret) {
19
+ throw new Error("GOOGLE_CLIENT_SECRET is required. Run the setup script to configure OAuth credentials.");
20
+ }
21
+ if (!config.refreshToken) {
22
+ throw new Error("GOOGLE_REFRESH_TOKEN is required. Run 'npm run setup' in the google-auth package to get one.");
23
+ }
24
+ var redirectUri = config.redirectUri || constants_1.DEFAULT_REDIRECT_URI;
25
+ var auth = new google_auth_library_1.OAuth2Client(config.clientId, config.clientSecret, redirectUri);
26
+ auth.setCredentials({
27
+ refresh_token: config.refreshToken,
28
+ });
29
+ return { auth: auth };
30
+ }
31
+ /**
32
+ * @description Creates a GoogleAuthConfig from environment variables.
33
+ * @returns Config object populated from GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN.
34
+ */
35
+ function configFromEnv() {
36
+ return {
37
+ clientId: process.env.GOOGLE_CLIENT_ID || "",
38
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
39
+ refreshToken: process.env.GOOGLE_REFRESH_TOKEN || "",
40
+ };
41
+ }
42
+ /**
43
+ * @description Handles Google API errors with specific guidance for common error codes.
44
+ * @param error - The caught error.
45
+ * @param context - Description of what operation was being attempted.
46
+ */
47
+ function handleAuthError(error, context) {
48
+ if (error && typeof error === "object" && "response" in error) {
49
+ var response = error.response;
50
+ if (response && response.status) {
51
+ if (response.status === 401) {
52
+ throw new Error("Google authentication failed (" + context + "). " +
53
+ "Your refresh token may be expired or revoked. " +
54
+ "Run 'npm run setup' in the google-auth package to get a new token.");
55
+ }
56
+ if (response.status === 403) {
57
+ throw new Error("Google API access denied (" + context + "). " +
58
+ "Check that the required API scopes are authorized and the API is enabled in Google Cloud Console.");
59
+ }
60
+ if (response.status === 429) {
61
+ throw new Error("Google API rate limit exceeded (" + context + "). " +
62
+ "Wait a moment and try again.");
63
+ }
64
+ var message = response.data && response.data.error && response.data.error.message
65
+ ? String(response.data.error.message)
66
+ : "HTTP " + response.status;
67
+ throw new Error("Google API error (" + context + "): " + message);
68
+ }
69
+ }
70
+ if (error instanceof Error) {
71
+ throw new Error("Google API error (" + context + "): " + error.message);
72
+ }
73
+ throw error;
74
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Shared constants for Dovetail Google OAuth2 flow.
3
+ */
4
+ export declare var DEFAULT_REDIRECT_PORT: number;
5
+ export declare var DEFAULT_REDIRECT_URI: string;
6
+ export declare var DEFAULT_SCOPES: string[];
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ /**
3
+ * Shared constants for Dovetail Google OAuth2 flow.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DEFAULT_SCOPES = exports.DEFAULT_REDIRECT_URI = exports.DEFAULT_REDIRECT_PORT = void 0;
7
+ exports.DEFAULT_REDIRECT_PORT = 3000;
8
+ exports.DEFAULT_REDIRECT_URI = "http://localhost:" + exports.DEFAULT_REDIRECT_PORT + "/callback";
9
+ exports.DEFAULT_SCOPES = [
10
+ "https://www.googleapis.com/auth/gmail.modify",
11
+ "https://www.googleapis.com/auth/calendar",
12
+ ];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @tenonhq/dovetail-google-auth
3
+ *
4
+ * Google OAuth2 authentication for Dovetail Google integrations.
5
+ * Provides auth client factory, env config helper, and error handling.
6
+ */
7
+ export { createGoogleAuth, configFromEnv, handleAuthError, } from "./client";
8
+ export { DEFAULT_REDIRECT_URI, DEFAULT_REDIRECT_PORT, DEFAULT_SCOPES, } from "./constants";
9
+ export type { GoogleAuthConfig, GoogleAuthResult, SetupConfig, SetupResult, GoogleAuthError, } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ /**
3
+ * @tenonhq/dovetail-google-auth
4
+ *
5
+ * Google OAuth2 authentication for Dovetail Google integrations.
6
+ * Provides auth client factory, env config helper, and error handling.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.DEFAULT_SCOPES = exports.DEFAULT_REDIRECT_PORT = exports.DEFAULT_REDIRECT_URI = exports.handleAuthError = exports.configFromEnv = exports.createGoogleAuth = void 0;
10
+ // Client and auth functions
11
+ var client_1 = require("./client");
12
+ Object.defineProperty(exports, "createGoogleAuth", { enumerable: true, get: function () { return client_1.createGoogleAuth; } });
13
+ Object.defineProperty(exports, "configFromEnv", { enumerable: true, get: function () { return client_1.configFromEnv; } });
14
+ Object.defineProperty(exports, "handleAuthError", { enumerable: true, get: function () { return client_1.handleAuthError; } });
15
+ // Shared constants
16
+ var constants_1 = require("./constants");
17
+ Object.defineProperty(exports, "DEFAULT_REDIRECT_URI", { enumerable: true, get: function () { return constants_1.DEFAULT_REDIRECT_URI; } });
18
+ Object.defineProperty(exports, "DEFAULT_REDIRECT_PORT", { enumerable: true, get: function () { return constants_1.DEFAULT_REDIRECT_PORT; } });
19
+ Object.defineProperty(exports, "DEFAULT_SCOPES", { enumerable: true, get: function () { return constants_1.DEFAULT_SCOPES; } });
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Google OAuth2 Setup Script
4
+ *
5
+ * One-time CLI tool to obtain a refresh token for Google API access.
6
+ * Opens a browser for consent, runs a local callback server, and prints
7
+ * the refresh token to add to your .env file.
8
+ *
9
+ * Usage:
10
+ * node dist/setup.js
11
+ * npm run setup (from the google-auth package)
12
+ *
13
+ * Requires GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in env or .env file.
14
+ */
15
+ export {};
package/dist/setup.js ADDED
@@ -0,0 +1,208 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * Google OAuth2 Setup Script
5
+ *
6
+ * One-time CLI tool to obtain a refresh token for Google API access.
7
+ * Opens a browser for consent, runs a local callback server, and prints
8
+ * the refresh token to add to your .env file.
9
+ *
10
+ * Usage:
11
+ * node dist/setup.js
12
+ * npm run setup (from the google-auth package)
13
+ *
14
+ * Requires GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in env or .env file.
15
+ */
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ const http_1 = __importDefault(require("http"));
21
+ const url_1 = require("url");
22
+ const fs_1 = __importDefault(require("fs"));
23
+ const path_1 = __importDefault(require("path"));
24
+ const google_auth_library_1 = require("google-auth-library");
25
+ const constants_1 = require("./constants");
26
+ var REDIRECT_URI = constants_1.DEFAULT_REDIRECT_URI;
27
+ var PORT = constants_1.DEFAULT_REDIRECT_PORT;
28
+ function loadEnv() {
29
+ try {
30
+ require("dotenv").config();
31
+ }
32
+ catch (e) {
33
+ // dotenv not available — env vars must be set manually
34
+ }
35
+ }
36
+ function getEnvVar(name) {
37
+ var value = process.env[name];
38
+ if (!value) {
39
+ console.error("ERROR: " + name + " is not set.");
40
+ console.error("");
41
+ console.error("Set it in your environment or .env file before running setup.");
42
+ console.error("");
43
+ console.error("To get these credentials:");
44
+ console.error("1. Go to https://console.cloud.google.com/apis/credentials");
45
+ console.error("2. Create an OAuth 2.0 Client ID (Desktop application type)");
46
+ console.error("3. Add " + REDIRECT_URI + " as an authorized redirect URI");
47
+ process.exit(1);
48
+ }
49
+ return value;
50
+ }
51
+ function findEnvFile() {
52
+ var envPath = path_1.default.resolve(process.cwd(), ".env");
53
+ if (fs_1.default.existsSync(envPath)) {
54
+ return envPath;
55
+ }
56
+ return null;
57
+ }
58
+ function escapeHtml(str) {
59
+ return str
60
+ .replace(/&/g, "&")
61
+ .replace(/</g, "&lt;")
62
+ .replace(/>/g, "&gt;")
63
+ .replace(/"/g, "&quot;")
64
+ .replace(/'/g, "&#39;");
65
+ }
66
+ function quoteEnvValue(value) {
67
+ if (/[\s#"'\\]/.test(value)) {
68
+ return "\"" + value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n") + "\"";
69
+ }
70
+ return value;
71
+ }
72
+ function writeTokenToEnv(token) {
73
+ var envPath = findEnvFile();
74
+ if (!envPath) {
75
+ return false;
76
+ }
77
+ var content = fs_1.default.readFileSync(envPath, "utf-8");
78
+ var lines = content.split("\n");
79
+ var found = false;
80
+ var updated = [];
81
+ for (var i = 0; i < lines.length; i++) {
82
+ var line = lines[i];
83
+ if (line.indexOf("GOOGLE_REFRESH_TOKEN") === 0) {
84
+ updated.push("GOOGLE_REFRESH_TOKEN=" + quoteEnvValue(token));
85
+ found = true;
86
+ }
87
+ else {
88
+ updated.push(line);
89
+ }
90
+ }
91
+ if (!found) {
92
+ updated.push("GOOGLE_REFRESH_TOKEN=" + quoteEnvValue(token));
93
+ }
94
+ fs_1.default.writeFileSync(envPath, updated.join("\n"), "utf-8");
95
+ return true;
96
+ }
97
+ function openBrowser(url) {
98
+ var command;
99
+ var args;
100
+ if (process.platform === "darwin") {
101
+ command = "open";
102
+ args = [url];
103
+ }
104
+ else if (process.platform === "win32") {
105
+ command = "cmd";
106
+ args = ["/c", "start", url];
107
+ }
108
+ else {
109
+ command = "xdg-open";
110
+ args = [url];
111
+ }
112
+ var spawn = require("child_process").spawn;
113
+ var child = spawn(command, args, { stdio: "ignore", detached: true });
114
+ child.unref();
115
+ }
116
+ async function run() {
117
+ loadEnv();
118
+ var clientId = getEnvVar("GOOGLE_CLIENT_ID");
119
+ var clientSecret = getEnvVar("GOOGLE_CLIENT_SECRET");
120
+ var oauth2Client = new google_auth_library_1.OAuth2Client(clientId, clientSecret, REDIRECT_URI);
121
+ var authUrl = oauth2Client.generateAuthUrl({
122
+ access_type: "offline",
123
+ prompt: "consent",
124
+ scope: constants_1.DEFAULT_SCOPES,
125
+ });
126
+ console.log("");
127
+ console.log("=== Google OAuth2 Setup ===");
128
+ console.log("");
129
+ console.log("Opening browser for authorization...");
130
+ console.log("");
131
+ console.log("If the browser does not open, visit this URL manually:");
132
+ console.log(authUrl);
133
+ console.log("");
134
+ openBrowser(authUrl);
135
+ return new Promise(function (resolve, reject) {
136
+ var server = http_1.default.createServer(async function (req, res) {
137
+ if (!req.url || !req.url.startsWith("/callback")) {
138
+ res.writeHead(404);
139
+ res.end("Not found");
140
+ return;
141
+ }
142
+ var parsedUrl = new url_1.URL(req.url, "http://localhost:" + PORT);
143
+ var code = parsedUrl.searchParams.get("code");
144
+ var error = parsedUrl.searchParams.get("error");
145
+ if (error) {
146
+ res.writeHead(200, { "Content-Type": "text/html" });
147
+ res.end("<h1>Authorization failed</h1><p>Error: " + escapeHtml(error) + "</p><p>You can close this tab.</p>");
148
+ console.error("Authorization failed: " + error);
149
+ server.close();
150
+ reject(new Error("Authorization failed: " + error));
151
+ return;
152
+ }
153
+ if (!code) {
154
+ res.writeHead(400, { "Content-Type": "text/html" });
155
+ res.end("<h1>Missing authorization code</h1><p>You can close this tab.</p>");
156
+ server.close();
157
+ reject(new Error("No authorization code received"));
158
+ return;
159
+ }
160
+ try {
161
+ var tokenResponse = await oauth2Client.getToken(code);
162
+ var tokens = tokenResponse.tokens;
163
+ res.writeHead(200, { "Content-Type": "text/html" });
164
+ res.end("<h1>Authorization successful!</h1>" +
165
+ "<p>You can close this tab and return to the terminal.</p>");
166
+ console.log("Authorization successful!");
167
+ console.log("");
168
+ if (tokens.refresh_token) {
169
+ var wrote = writeTokenToEnv(tokens.refresh_token);
170
+ if (wrote) {
171
+ console.log("GOOGLE_REFRESH_TOKEN written to .env");
172
+ }
173
+ else {
174
+ console.log("No .env file found in " + process.cwd());
175
+ console.log("Add this to your .env manually:");
176
+ console.log("GOOGLE_REFRESH_TOKEN=" + tokens.refresh_token);
177
+ }
178
+ }
179
+ else {
180
+ console.log("WARNING: No refresh token received.");
181
+ console.log("This happens if you previously authorized this app.");
182
+ console.log("Revoke access at https://myaccount.google.com/permissions");
183
+ console.log("then run this setup again.");
184
+ }
185
+ console.log("");
186
+ console.log("IMPORTANT: If your Google Cloud app is in 'Testing' status,");
187
+ console.log("refresh tokens expire after 7 days. Set the app to 'In production'");
188
+ console.log("or 'Internal' (Google Workspace) for long-lived tokens.");
189
+ server.close();
190
+ resolve();
191
+ }
192
+ catch (err) {
193
+ res.writeHead(500, { "Content-Type": "text/html" });
194
+ res.end("<h1>Token exchange failed</h1><p>Check the terminal for details.</p>");
195
+ console.error("Token exchange failed:", err);
196
+ server.close();
197
+ reject(err);
198
+ }
199
+ });
200
+ server.listen(PORT, function () {
201
+ console.log("Listening for callback on http://localhost:" + PORT + "/callback");
202
+ });
203
+ });
204
+ }
205
+ run().catch(function (err) {
206
+ console.error("Setup failed:", err);
207
+ process.exit(1);
208
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Google OAuth2 type definitions for Dovetail Google integrations.
3
+ */
4
+ import { OAuth2Client } from "google-auth-library";
5
+ export interface GoogleAuthConfig {
6
+ clientId: string;
7
+ clientSecret: string;
8
+ refreshToken: string;
9
+ redirectUri?: string;
10
+ }
11
+ export interface GoogleAuthResult {
12
+ auth: OAuth2Client;
13
+ email?: string;
14
+ }
15
+ export interface SetupConfig {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ scopes: string[];
19
+ redirectUri?: string;
20
+ }
21
+ export interface SetupResult {
22
+ refreshToken: string;
23
+ accessToken: string;
24
+ email?: string;
25
+ }
26
+ export interface GoogleAuthError {
27
+ code: number;
28
+ message: string;
29
+ context: string;
30
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Google OAuth2 type definitions for Dovetail Google integrations.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@tenonhq/dovetail-google-auth",
3
+ "version": "0.0.9",
4
+ "description": "Google OAuth2 auth client for Dovetail Google integrations",
5
+ "main": "./dist/index.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "prepack": "tsc",
9
+ "setup": "node ./dist/setup.js",
10
+ "version:bump": "node ./../../Scripts/bump-version.js ./package.json",
11
+ "postpublish": "npm run version:bump"
12
+ },
13
+ "author": "Multiple",
14
+ "license": "GPL-3.0",
15
+ "dependencies": {
16
+ "google-auth-library": "^9.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "@types/jest": "^29.5.5",
20
+ "@types/node": ">=20.8.4",
21
+ "jest": "^29.7.0",
22
+ "ts-jest": "^29.1.1",
23
+ "typescript": "^5.2.2"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/tenonhq/dovetail.git"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/tenonhq/dovetail/issues"
37
+ }
38
+ }