@blackbelt-technology/pi-dashboard-gmail-plugin 0.10.0 → 0.12.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/README.md +22 -37
- package/package.json +9 -4
- package/src/bridge/gmail-api.ts +23 -0
- package/src/bridge/lease-client.ts +127 -7
- package/src/bridge/tools.ts +217 -9
- package/src/client/GmailSettings.tsx +51 -735
- package/src/configSchema.json +14 -1
- package/src/i18n.ts +9 -205
- package/src/server/accounts.ts +37 -0
- package/src/server/google-link.ts +81 -0
- package/src/server/google-oauth.ts +8 -3
- package/src/server/index.ts +31 -14
- package/src/server/lease.ts +8 -3
- package/src/server/routes.ts +36 -188
- package/src/shared/client-json.ts +5 -3
- package/src/shared/protocol.ts +20 -0
- package/src/shared/scopes.ts +22 -6
- package/src/shared/setup.ts +43 -0
- package/src/client/wizard.ts +0 -136
- package/src/server/gmail-rest.ts +0 -27
- package/src/shared/flow-codes.ts +0 -36
package/src/server/routes.ts
CHANGED
|
@@ -1,134 +1,43 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Gmail plugin REST routes (
|
|
3
|
-
* `/api/plugins/
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* `
|
|
2
|
+
* Gmail plugin REST routes (add-google-connect D10). Account, client and setup management moved to
|
|
3
|
+
* Google Connect (`/api/plugins/google/*`): every management route here answers a fixed refusal and
|
|
4
|
+
* stores nothing — `410 { error: "moved" }` while Google Connect is usable, `503
|
|
5
|
+
* { error: "google_connect_unavailable" }` while it is not (Gmail tools keep working from the plugin's own
|
|
6
|
+
* data). `GET /state` stays: it tells the settings section which notice to show. All routes sit behind
|
|
7
|
+
* `networkGuard` in an encapsulated scope with `@fastify/rate-limit` (loopback allow-listed); tiers
|
|
8
|
+
* `operate` (`packages/shared/src/route-tiers.ts`). See change: add-google-connect.
|
|
9
9
|
*/
|
|
10
|
-
|
|
11
|
-
import type {
|
|
12
|
-
PluginNetworkGuard,
|
|
13
|
-
PluginOAuth,
|
|
14
|
-
} from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
10
|
+
import type { PluginNetworkGuard } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
15
11
|
import rateLimit from "@fastify/rate-limit";
|
|
16
12
|
import type { FastifyInstance, FastifyReply } from "fastify";
|
|
17
|
-
import {
|
|
18
|
-
import type { GoogleEndpoints } from "../shared/endpoints.js";
|
|
19
|
-
import { knownFlowCode } from "../shared/flow-codes.js";
|
|
20
|
-
import { isTier, scopesCoverTier, type Tier } from "../shared/scopes.js";
|
|
21
|
-
import { AccountError, type AccountStore, summarize } from "./accounts.js";
|
|
22
|
-
import { revokeToken } from "./gmail-rest.js";
|
|
23
|
-
import {
|
|
24
|
-
createGoogleLoginFlow,
|
|
25
|
-
GmailFlowError,
|
|
26
|
-
type GoogleLoginOptions, type GoogleSignInResult,
|
|
27
|
-
} from "./google-oauth.js";
|
|
13
|
+
import type { GoogleLink } from "./google-link.js";
|
|
28
14
|
|
|
29
15
|
export interface GmailRouteDeps {
|
|
30
|
-
store: AccountStore;
|
|
31
|
-
oauth: PluginOAuth | undefined;
|
|
32
|
-
endpoints: GoogleEndpoints;
|
|
33
16
|
networkGuard: PluginNetworkGuard;
|
|
34
|
-
|
|
35
|
-
fetchImpl?: typeof fetch;
|
|
36
|
-
createCallback?: GoogleLoginOptions["createCallback"];
|
|
37
|
-
newId?: () => string;
|
|
17
|
+
link: GoogleLink;
|
|
38
18
|
}
|
|
39
19
|
|
|
40
20
|
const PREFIX = "/api/plugins/gmail";
|
|
41
21
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
22
|
+
/** Every management route of the pre-Google-Connect plugin, by method (paths are relative to {@link PREFIX}). */
|
|
23
|
+
const MOVED_ROUTES: ReadonlyArray<{ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; url: string }> = [
|
|
24
|
+
{ method: "PUT", url: "/client" },
|
|
25
|
+
{ method: "PUT", url: "/setup" },
|
|
26
|
+
{ method: "GET", url: "/accounts" },
|
|
27
|
+
{ method: "POST", url: "/accounts" },
|
|
28
|
+
{ method: "PATCH", url: "/accounts/:sub" },
|
|
29
|
+
{ method: "DELETE", url: "/accounts/:sub" },
|
|
30
|
+
{ method: "POST", url: "/accounts/:sub/level" },
|
|
31
|
+
{ method: "POST", url: "/accounts/:sub/reauth" },
|
|
32
|
+
{ method: "POST", url: "/accounts/:sub/filters" },
|
|
33
|
+
{ method: "POST", url: "/setup/run" },
|
|
34
|
+
{ method: "GET", url: "/setup/run/:id" },
|
|
35
|
+
{ method: "POST", url: "/setup/run/:id/continue" },
|
|
36
|
+
{ method: "POST", url: "/setup/run/:id/takeover" },
|
|
37
|
+
{ method: "DELETE", url: "/setup/run/:id" },
|
|
38
|
+
];
|
|
57
39
|
|
|
58
40
|
export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRouteDeps): Promise<void> {
|
|
59
|
-
const { store, endpoints, logger } = deps;
|
|
60
|
-
const newId = deps.newId ?? (() => crypto.randomUUID());
|
|
61
|
-
|
|
62
|
-
/** Start a sign-in flow for `tier`; `expectSub` set for re-auth / level raise. */
|
|
63
|
-
async function startSignIn(
|
|
64
|
-
reply: FastifyReply,
|
|
65
|
-
tier: Tier,
|
|
66
|
-
expect?: { sub: string; email: string },
|
|
67
|
-
) {
|
|
68
|
-
if (!deps.oauth) return reply.code(501).send({ error: "oauth_unavailable" });
|
|
69
|
-
const client = await store.getClient();
|
|
70
|
-
if (!client) return reply.code(409).send({ error: "no_client" });
|
|
71
|
-
// One failure, one warn line: a login throwing before its first event also
|
|
72
|
-
// rejects startFlow (login_failed), so whichever site logs first wins.
|
|
73
|
-
// The line carries an allow-listed code only (improve-gmail-settings-ux D3).
|
|
74
|
-
let logged = false;
|
|
75
|
-
const logFailure = (err: unknown) => {
|
|
76
|
-
if (logged) return;
|
|
77
|
-
logged = true;
|
|
78
|
-
logger.warn(`[gmail] sign-in failed: ${knownFlowCode((err as { code?: unknown } | null)?.code) ?? "sign_in_failed"}`);
|
|
79
|
-
};
|
|
80
|
-
const googleFlow = createGoogleLoginFlow({
|
|
81
|
-
client,
|
|
82
|
-
endpoints,
|
|
83
|
-
tier,
|
|
84
|
-
loginHint: expect?.email,
|
|
85
|
-
fetchImpl: deps.fetchImpl,
|
|
86
|
-
createCallback: deps.createCallback,
|
|
87
|
-
});
|
|
88
|
-
const loginFlow = {
|
|
89
|
-
...googleFlow,
|
|
90
|
-
login: async (ix: Parameters<typeof googleFlow.login>[0]) => {
|
|
91
|
-
try {
|
|
92
|
-
return await googleFlow.login(ix);
|
|
93
|
-
} catch (err) {
|
|
94
|
-
logFailure(err);
|
|
95
|
-
throw err;
|
|
96
|
-
}
|
|
97
|
-
},
|
|
98
|
-
};
|
|
99
|
-
try {
|
|
100
|
-
return await deps.oauth.startFlow({
|
|
101
|
-
key: expect ? `reauth-${expect.sub}` : `add-${newId()}`,
|
|
102
|
-
loginFlow,
|
|
103
|
-
persist: async (credential) => {
|
|
104
|
-
try {
|
|
105
|
-
const c = credential as GoogleSignInResult;
|
|
106
|
-
if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
|
|
107
|
-
// Consent-screen checkboxes can be cleared: never store a level the grant cannot serve.
|
|
108
|
-
if (!scopesCoverTier(c.grantedScopes, c.tier)) throw new GmailFlowError("scope_missing");
|
|
109
|
-
const acct = await store.upsertFromSignIn({
|
|
110
|
-
sub: c.sub,
|
|
111
|
-
email: c.email,
|
|
112
|
-
tier: c.tier,
|
|
113
|
-
scopes: c.grantedScopes,
|
|
114
|
-
access: c.access,
|
|
115
|
-
refresh: c.refresh || undefined,
|
|
116
|
-
expires: c.expires,
|
|
117
|
-
testingHint: c.testingHint,
|
|
118
|
-
});
|
|
119
|
-
logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
|
|
120
|
-
} catch (err) {
|
|
121
|
-
logFailure(err);
|
|
122
|
-
throw err;
|
|
123
|
-
}
|
|
124
|
-
},
|
|
125
|
-
});
|
|
126
|
-
} catch (err) {
|
|
127
|
-
logFailure(err);
|
|
128
|
-
return sendError(reply, err);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
41
|
await fastify.register(async (scope) => {
|
|
133
42
|
await scope.register(rateLimit, {
|
|
134
43
|
global: true,
|
|
@@ -139,77 +48,16 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
|
|
|
139
48
|
const guarded = { preHandler: deps.networkGuard };
|
|
140
49
|
|
|
141
50
|
scope.get(`${PREFIX}/state`, guarded, async () => {
|
|
142
|
-
const
|
|
143
|
-
return {
|
|
144
|
-
client: client ? { configured: true, clientId: client.clientId, projectId: client.projectId } : { configured: false },
|
|
145
|
-
accounts: (await store.list()).map(summarize),
|
|
146
|
-
};
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
scope.put(`${PREFIX}/client`, guarded, async (request, reply) => {
|
|
150
|
-
const result = validateClientJson((request.body as { json?: unknown } | null)?.json ?? request.body);
|
|
151
|
-
if (!result.ok) return reply.code(400).send({ error: result.error.code, step: result.error.step });
|
|
152
|
-
// Refresh tokens are bound to the client that minted them: swapping the
|
|
153
|
-
// client under connected accounts would break every refresh silently.
|
|
154
|
-
const current = await store.getClient();
|
|
155
|
-
const changed =
|
|
156
|
-
current &&
|
|
157
|
-
(current.clientId !== result.client.clientId || current.clientSecret !== result.client.clientSecret);
|
|
158
|
-
if (changed && (await store.list()).length > 0) {
|
|
159
|
-
return reply.code(409).send({ error: "client_in_use", step: 5 });
|
|
160
|
-
}
|
|
161
|
-
await store.setClient(result.client);
|
|
162
|
-
logger.info("[gmail] oauth client configured");
|
|
163
|
-
return { ok: true, clientId: result.client.clientId, projectId: result.client.projectId };
|
|
51
|
+
const { usable } = await deps.link.ensure();
|
|
52
|
+
return usable ? { moved: true } : { moved: false, googleConnect: "unavailable" };
|
|
164
53
|
});
|
|
165
54
|
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const tier = (request.body as { tier?: unknown } | null)?.tier;
|
|
174
|
-
if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
|
|
175
|
-
const acct = await store.get(request.params.sub);
|
|
176
|
-
if (!acct) return reply.code(404).send({ error: "not_found" });
|
|
177
|
-
// Lowering (or a level the existing grant already covers) applies at once;
|
|
178
|
-
// raising re-consents with the FULL scope set of the new level.
|
|
179
|
-
if (acct.status === "ok" && scopesCoverTier(acct.scopes, tier)) {
|
|
180
|
-
const next = await store.setTier(acct.sub, tier);
|
|
181
|
-
logger.info(`[gmail] level ${next.email} → ${tier}`);
|
|
182
|
-
return { applied: true, account: summarize(next) };
|
|
183
|
-
}
|
|
184
|
-
return startSignIn(reply, tier, { sub: acct.sub, email: acct.email });
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/reauth`, guarded, async (request, reply) => {
|
|
188
|
-
const acct = await store.get(request.params.sub);
|
|
189
|
-
if (!acct) return reply.code(404).send({ error: "not_found" });
|
|
190
|
-
return startSignIn(reply, acct.tier, { sub: acct.sub, email: acct.email });
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
scope.patch<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
|
|
194
|
-
const body = (request.body ?? {}) as { alias?: unknown };
|
|
195
|
-
if (body.alias !== null && body.alias !== undefined && typeof body.alias !== "string") {
|
|
196
|
-
return reply.code(400).send({ error: "invalid_alias" });
|
|
197
|
-
}
|
|
198
|
-
try {
|
|
199
|
-
const next = await store.setAlias(request.params.sub, (body.alias as string | null) ?? undefined);
|
|
200
|
-
return { account: summarize(next) };
|
|
201
|
-
} catch (err) {
|
|
202
|
-
return sendError(reply, err);
|
|
203
|
-
}
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
scope.delete<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
|
|
207
|
-
const acct = await store.get(request.params.sub);
|
|
208
|
-
if (!acct) return reply.code(404).send({ error: "not_found" });
|
|
209
|
-
const remoteRevoked = await revokeToken(endpoints, acct.refresh, deps.fetchImpl);
|
|
210
|
-
await store.remove(acct.sub);
|
|
211
|
-
logger.info(`[gmail] revoke ${acct.email}: local ok, remote ${remoteRevoked ? "ok" : "failed"}`);
|
|
212
|
-
return { removed: true, remoteRevoked };
|
|
213
|
-
});
|
|
55
|
+
const refuse = async (_request: unknown, reply: FastifyReply) => {
|
|
56
|
+
const { usable } = await deps.link.ensure();
|
|
57
|
+
return usable
|
|
58
|
+
? reply.code(410).send({ error: "moved" })
|
|
59
|
+
: reply.code(503).send({ error: "google_connect_unavailable" });
|
|
60
|
+
};
|
|
61
|
+
for (const { method, url } of MOVED_ROUTES) scope.route({ method, url: `${PREFIX}${url}`, preHandler: deps.networkGuard, handler: refuse });
|
|
214
62
|
});
|
|
215
63
|
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Validate an uploaded `client_secret_*.json` (design D7 step 5). Only a
|
|
3
3
|
* Desktop client (`installed` block) is accepted; a `web` block is rejected with
|
|
4
|
-
* step-4 guidance. Pure
|
|
5
|
-
*
|
|
4
|
+
* step-4 guidance. Pure. The setup wizard now lives in the Google accounts plugin
|
|
5
|
+
* (Settings → Google accounts). See change: add-gmail-plugin.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { PROJECT_ID_RE } from "./setup.js";
|
|
9
|
+
|
|
8
10
|
interface ParsedClient {
|
|
9
11
|
clientId: string;
|
|
10
12
|
clientSecret: string;
|
|
@@ -48,6 +50,6 @@ export function validateClientJson(input: string | unknown): ClientJsonResult {
|
|
|
48
50
|
return { ok: false, error: { code: "missing_secret", step: 5 } };
|
|
49
51
|
}
|
|
50
52
|
const client: ParsedClient = { clientId: i.client_id, clientSecret: i.client_secret };
|
|
51
|
-
if (typeof i.project_id === "string" &&
|
|
53
|
+
if (typeof i.project_id === "string" && PROJECT_ID_RE.test(i.project_id)) client.projectId = i.project_id;
|
|
52
54
|
return { ok: true, client };
|
|
53
55
|
}
|
package/src/shared/protocol.ts
CHANGED
|
@@ -7,6 +7,24 @@ export const PLUGIN_ID = "gmail";
|
|
|
7
7
|
export const LEASE_TYPE = "gmail/lease";
|
|
8
8
|
export const ACCOUNTS_TYPE = "gmail/accounts";
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Google Connect (add-google-connect D1/D10): the only in-process service Gmail consumes, and the lanes
|
|
12
|
+
* it follows a delegation to. The provider id is checked — a spoofing plugin is ignored.
|
|
13
|
+
*/
|
|
14
|
+
export const GOOGLE_PLUGIN_ID = "google";
|
|
15
|
+
export const GOOGLE_CONNECT_SERVICE = "google.connect";
|
|
16
|
+
export const GOOGLE_LEASE_TYPE = "google/lease";
|
|
17
|
+
export const GOOGLE_ACCOUNTS_TYPE = "google/accounts";
|
|
18
|
+
|
|
19
|
+
/** `gmail/lease` / `gmail/accounts` reply while Google Connect owns the accounts: follow it, no token inside. */
|
|
20
|
+
export interface DelegateReply {
|
|
21
|
+
delegate: typeof GOOGLE_PLUGIN_ID;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isDelegateReply(v: unknown): v is DelegateReply {
|
|
25
|
+
return !!v && typeof v === "object" && !Array.isArray(v) && (v as { delegate?: unknown }).delegate === GOOGLE_PLUGIN_ID;
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
/** `gmail/lease` success reply — exactly these keys, never a refresh token. */
|
|
11
29
|
export interface LeaseReply {
|
|
12
30
|
accessToken: string;
|
|
@@ -23,5 +41,7 @@ export interface AccountInfo {
|
|
|
23
41
|
tier: Tier;
|
|
24
42
|
status: "ok" | "reauth_required";
|
|
25
43
|
testingHint?: boolean;
|
|
44
|
+
/** Filters option (Gmail filter tools); absent = off. */
|
|
45
|
+
filters?: boolean;
|
|
26
46
|
addedAt: number;
|
|
27
47
|
}
|
package/src/shared/scopes.ts
CHANGED
|
@@ -5,15 +5,16 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
export type Tier = "readonly" | "draft" | "send";
|
|
8
|
-
export type Op = "read" | "draft" | "send" | "modify" | "trash";
|
|
8
|
+
export type Op = "read" | "draft" | "send" | "modify" | "trash" | "filters_read" | "filters_write";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
const TIERS: readonly Tier[] = ["readonly", "draft", "send"];
|
|
11
11
|
|
|
12
12
|
const SCOPE_BASE = "https://www.googleapis.com/auth/";
|
|
13
13
|
export const SCOPE = {
|
|
14
14
|
readonly: `${SCOPE_BASE}gmail.readonly`,
|
|
15
15
|
compose: `${SCOPE_BASE}gmail.compose`,
|
|
16
16
|
modify: `${SCOPE_BASE}gmail.modify`,
|
|
17
|
+
settingsBasic: `${SCOPE_BASE}gmail.settings.basic`,
|
|
17
18
|
} as const;
|
|
18
19
|
|
|
19
20
|
/** Requested Gmail scopes per tier (full set — no incremental auth for installed apps). */
|
|
@@ -32,6 +33,8 @@ const OP_TIER: Record<Op, Tier> = {
|
|
|
32
33
|
send: "send",
|
|
33
34
|
modify: "send",
|
|
34
35
|
trash: "send",
|
|
36
|
+
filters_read: "readonly",
|
|
37
|
+
filters_write: "send",
|
|
35
38
|
};
|
|
36
39
|
|
|
37
40
|
/** Scope(s) that cover an op — any one suffices. */
|
|
@@ -41,6 +44,8 @@ const OP_SCOPE: Record<Op, string> = {
|
|
|
41
44
|
send: SCOPE.modify,
|
|
42
45
|
modify: SCOPE.modify,
|
|
43
46
|
trash: SCOPE.modify,
|
|
47
|
+
filters_read: SCOPE.settingsBasic,
|
|
48
|
+
filters_write: SCOPE.settingsBasic,
|
|
44
49
|
};
|
|
45
50
|
|
|
46
51
|
/** Implication table: a granted scope also covers these. `modify ⇒ readonly, compose`. */
|
|
@@ -52,8 +57,13 @@ export function isTier(v: unknown): v is Tier {
|
|
|
52
57
|
return v === "readonly" || v === "draft" || v === "send";
|
|
53
58
|
}
|
|
54
59
|
|
|
60
|
+
/** True for the filter ops (gated by the per-account filters option). */
|
|
61
|
+
export function isFilterOp(op: Op): boolean {
|
|
62
|
+
return op === "filters_read" || op === "filters_write";
|
|
63
|
+
}
|
|
64
|
+
|
|
55
65
|
export function isOp(v: unknown): v is Op {
|
|
56
|
-
return v === "read" || v === "draft" || v === "send" || v === "modify" || v === "trash";
|
|
66
|
+
return v === "read" || v === "draft" || v === "send" || v === "modify" || v === "trash" || v === "filters_read" || v === "filters_write";
|
|
57
67
|
}
|
|
58
68
|
|
|
59
69
|
/** True when `tier` is high enough for `op`. */
|
|
@@ -77,12 +87,18 @@ export function scopesCover(granted: readonly string[], op: Op): boolean {
|
|
|
77
87
|
}
|
|
78
88
|
|
|
79
89
|
/** True when the granted scopes cover every op of `tier` (no re-consent needed). */
|
|
80
|
-
|
|
90
|
+
function scopesCoverTier(granted: readonly string[], tier: Tier): boolean {
|
|
81
91
|
const eff = effectiveScopes(granted);
|
|
82
92
|
return TIER_SCOPES[tier].every((s) => eff.has(s));
|
|
83
93
|
}
|
|
84
94
|
|
|
95
|
+
/** True when the granted scopes cover the filter ops (`gmail.settings.basic`; `modify` does not imply it). */
|
|
96
|
+
export function scopesCoverFilters(granted: readonly string[]): boolean {
|
|
97
|
+
return effectiveScopes(granted).has(SCOPE.settingsBasic);
|
|
98
|
+
}
|
|
99
|
+
|
|
85
100
|
/** Space-separated `scope` parameter for an authorization request. */
|
|
86
|
-
export function authScopeParam(tier: Tier): string {
|
|
87
|
-
|
|
101
|
+
export function authScopeParam(tier: Tier, opts?: { filters?: boolean }): string {
|
|
102
|
+
const filters = opts?.filters ? [SCOPE.settingsBasic] : [];
|
|
103
|
+
return ["openid", "email", ...TIER_SCOPES[tier], ...filters].join(" ");
|
|
88
104
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Setup-field validators (project id, owner account). Pure. The setup wizard now lives
|
|
3
|
+
* in the Google accounts plugin (Settings → Google accounts); kept for legacy-import code.
|
|
4
|
+
* See change: improve-gmail-plugin-setup-ux.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A Google Cloud project id: 6–30 chars, lower-case letters, digits, hyphens. */
|
|
8
|
+
export const PROJECT_ID_RE = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
9
|
+
|
|
10
|
+
/** RFC 5321 maximum address length. */
|
|
11
|
+
const EMAIL_MAX = 254;
|
|
12
|
+
|
|
13
|
+
export type ProjectIdClass = "ok" | "empty" | "looks_like_name" | "invalid";
|
|
14
|
+
|
|
15
|
+
export function normalizeProjectId(v: string): string {
|
|
16
|
+
return v.trim();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function normalizeEmail(v: string): string {
|
|
20
|
+
return v.trim().toLowerCase();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `looks_like_name`: the console's display name (uppercase or whitespace) typed instead of the id. */
|
|
24
|
+
export function classifyProjectId(v: string): ProjectIdClass {
|
|
25
|
+
const id = normalizeProjectId(v);
|
|
26
|
+
if (!id) return "empty";
|
|
27
|
+
if (/[A-Z\s]/.test(id)) return "looks_like_name";
|
|
28
|
+
return PROJECT_ID_RE.test(id) ? "ok" : "invalid";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One `@`, a non-empty local part, and a domain with an interior dot; no whitespace.
|
|
33
|
+
* Linear time: a single `[^\s@]+\.[^\s@]+` regex backtracks polynomially because `.` also
|
|
34
|
+
* matches the class (CodeQL js/polynomial-redos).
|
|
35
|
+
*/
|
|
36
|
+
export function isEmail(v: string): boolean {
|
|
37
|
+
if (v.length > EMAIL_MAX || /\s/.test(v)) return false;
|
|
38
|
+
const at = v.indexOf("@");
|
|
39
|
+
if (at < 1 || at !== v.lastIndexOf("@")) return false;
|
|
40
|
+
const domain = v.slice(at + 1);
|
|
41
|
+
const dot = domain.indexOf(".", 1);
|
|
42
|
+
return dot !== -1 && dot < domain.length - 1;
|
|
43
|
+
}
|
package/src/client/wizard.ts
DELETED
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Setup-wizard data (design D7): console deep links, copyable gcloud commands
|
|
3
|
-
* and the sign-in-error → wizard-step map. Pure — the server never executes
|
|
4
|
-
* the commands. See change: add-gmail-plugin.
|
|
5
|
-
* Plus the sign-in error table (`errorKey`, `ERROR_EN`).
|
|
6
|
-
* See change: improve-gmail-settings-ux.
|
|
7
|
-
*/
|
|
8
|
-
import { type FlowCode, knownFlowCode } from "../shared/flow-codes.js";
|
|
9
|
-
|
|
10
|
-
export type WizardStep = 1 | 2 | 3 | 4 | 5 | 6;
|
|
11
|
-
|
|
12
|
-
const CONSOLE = "https://console.cloud.google.com";
|
|
13
|
-
|
|
14
|
-
export interface ConsoleLinks {
|
|
15
|
-
projectCreate: string;
|
|
16
|
-
gmailApi: string;
|
|
17
|
-
branding: string;
|
|
18
|
-
audience: string;
|
|
19
|
-
clientCreate: string;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Deep links carrying `?project=<id>` (encoded). */
|
|
23
|
-
export function consoleLinks(projectId: string): ConsoleLinks {
|
|
24
|
-
const q = projectId ? `?project=${encodeURIComponent(projectId)}` : "";
|
|
25
|
-
return {
|
|
26
|
-
projectCreate: `${CONSOLE}/projectcreate`,
|
|
27
|
-
gmailApi: `${CONSOLE}/apis/library/gmail.googleapis.com${q}`,
|
|
28
|
-
branding: `${CONSOLE}/auth/branding${q}`,
|
|
29
|
-
audience: `${CONSOLE}/auth/audience${q}`,
|
|
30
|
-
clientCreate: `${CONSOLE}/auth/clients/create${q}`,
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const PROJECT_ID_RE = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
35
|
-
|
|
36
|
-
function isValidProjectId(id: string): boolean {
|
|
37
|
-
return PROJECT_ID_RE.test(id);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Copyable gcloud commands (only for a syntactically valid project id). */
|
|
41
|
-
export function gcloudCommands(projectId: string): string[] {
|
|
42
|
-
const id = isValidProjectId(projectId) ? projectId : "<project-id>";
|
|
43
|
-
return [`gcloud projects create ${id}`, `gcloud services enable gmail.googleapis.com --project ${id}`];
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Map a sign-in / upload error code to the wizard step that fixes it.
|
|
48
|
-
* `admin_policy_enforced` → null: the fix is in the account's Workspace Admin
|
|
49
|
-
* console, not in a wizard step (improve-gmail-settings-ux D2).
|
|
50
|
-
*/
|
|
51
|
-
export function errorStep(code: string | undefined | null): WizardStep | null {
|
|
52
|
-
switch (code) {
|
|
53
|
-
case "access_denied":
|
|
54
|
-
case "org_internal":
|
|
55
|
-
return 3;
|
|
56
|
-
case "redirect_uri_mismatch":
|
|
57
|
-
case "web_client":
|
|
58
|
-
case "not_installed":
|
|
59
|
-
case "bad_client_id":
|
|
60
|
-
return 4;
|
|
61
|
-
case "invalid_client":
|
|
62
|
-
case "missing_secret":
|
|
63
|
-
case "not_json":
|
|
64
|
-
case "no_client":
|
|
65
|
-
case "client_in_use":
|
|
66
|
-
return 5;
|
|
67
|
-
default:
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export { KNOWN_FLOW_CODES } from "../shared/flow-codes.js";
|
|
73
|
-
|
|
74
|
-
/** i18n key per flow code (design D2). `cancelled` also matches the host's "Cancelled". */
|
|
75
|
-
const CODE_KEY: Record<FlowCode, string> = {
|
|
76
|
-
org_internal: "errOrgInternal",
|
|
77
|
-
access_denied: "errAccessDenied",
|
|
78
|
-
admin_policy_enforced: "errAdminPolicy",
|
|
79
|
-
redirect_uri_mismatch: "errRedirectMismatch",
|
|
80
|
-
invalid_client: "errInvalidClient",
|
|
81
|
-
scope_missing: "errScopeMissing",
|
|
82
|
-
account_mismatch: "errAccountMismatch",
|
|
83
|
-
missing_refresh: "errMissingRefresh",
|
|
84
|
-
email_unverified: "errEmailUnverified",
|
|
85
|
-
invalid_redirect: "errInvalidRedirect",
|
|
86
|
-
state_mismatch: "errStateMismatch",
|
|
87
|
-
callback_failed: "errCallbackFailed",
|
|
88
|
-
token_exchange_failed: "errTokenExchange",
|
|
89
|
-
id_token_invalid: "errIdToken",
|
|
90
|
-
authorization_failed: "errAuthorization",
|
|
91
|
-
timeout: "errTimeout",
|
|
92
|
-
start_timeout: "errStartTimeout",
|
|
93
|
-
login_failed: "errLoginFailed",
|
|
94
|
-
cancelled: "errCancelled",
|
|
95
|
-
aborted: "errAborted",
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* English sentence per error key (the catalogs carry only zh-CN / hu; a dynamic
|
|
100
|
-
* key MUST pass this as its `t()` fallback). `{clientId}` is interpolated.
|
|
101
|
-
*/
|
|
102
|
-
export const ERROR_EN: Record<string, string> = {
|
|
103
|
-
errOrgInternal:
|
|
104
|
-
"Google blocked this account: the OAuth app's audience is Internal, which admits only accounts of the project's own Workspace organization. Switch the audience to External and add this account as a test user (step 3).",
|
|
105
|
-
errAccessDenied:
|
|
106
|
-
"Google denied access: the account is not an allowed test user, or the consent was declined. Add the account as a test user (step 3) and try again.",
|
|
107
|
-
errAdminPolicy:
|
|
108
|
-
"This account's Google Workspace admin blocks the app. Ask that admin to trust OAuth client {clientId} (Admin console → Security → API controls → App access control).",
|
|
109
|
-
errRedirectMismatch: "Google rejected the redirect address. Create a Desktop app client, not a Web client (step 4).",
|
|
110
|
-
errInvalidClient: "Google does not recognise the OAuth client. Download its JSON again and upload it (step 5).",
|
|
111
|
-
errScopeMissing:
|
|
112
|
-
"Google did not grant the Gmail permission. Add the account again and tick every permission on Google's consent screen.",
|
|
113
|
-
errAccountMismatch: "You signed in with a different Google account. Re-authenticate with the account shown in the row.",
|
|
114
|
-
errMissingRefresh: "Google returned no long-lived token. Revoke the app at myaccount.google.com/permissions, then add the account again.",
|
|
115
|
-
errEmailUnverified: "Google reports this account's email as unverified. Verify it with Google, then try again.",
|
|
116
|
-
errInvalidRedirect: "The pasted address is not the redirect Google sent. Paste the full URL from the browser's address bar.",
|
|
117
|
-
errStateMismatch: "The pasted redirect belongs to another sign-in. Start again and paste the URL from this sign-in.",
|
|
118
|
-
errCallbackFailed: "The sign-in callback failed. Try again.",
|
|
119
|
-
errTokenExchange: "Google refused to exchange the sign-in code. Check the uploaded client (step 5) and try again.",
|
|
120
|
-
errIdToken: "Google's sign-in answer could not be verified. Try again.",
|
|
121
|
-
errAuthorization: "Google reported a sign-in error. Try again; if it repeats, check the setup steps above.",
|
|
122
|
-
errTimeout: "Sign-in timed out waiting for Google. If Google showed an error page, report it with the option below the sign-in link.",
|
|
123
|
-
errStartTimeout: "The sign-in did not start in time. Try again.",
|
|
124
|
-
errLoginFailed: "The sign-in could not start. Try again.",
|
|
125
|
-
errCancelled: "Sign-in was cancelled.",
|
|
126
|
-
errAborted: "Sign-in was aborted.",
|
|
127
|
-
errGeneric: "Sign-in failed. Try again; if it keeps failing, check the setup steps above.",
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
/** i18n key for a terminal flow error; unknown input → `errGeneric` (exact match only). */
|
|
131
|
-
export function errorKey(code: string | undefined | null): string {
|
|
132
|
-
if (typeof code !== "string") return "errGeneric";
|
|
133
|
-
if (code.toLowerCase() === "cancelled") return "errCancelled";
|
|
134
|
-
const known = knownFlowCode(code);
|
|
135
|
-
return known ? CODE_KEY[known] : "errGeneric";
|
|
136
|
-
}
|
package/src/server/gmail-rest.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Google token revocation (design D9). Best effort: bounded by a 5 s timeout,
|
|
3
|
-
* never throws, never logs the token. See change: add-gmail-plugin.
|
|
4
|
-
*/
|
|
5
|
-
import type { GoogleEndpoints } from "../shared/endpoints.js";
|
|
6
|
-
|
|
7
|
-
const REVOKE_TIMEOUT_MS = 5_000;
|
|
8
|
-
|
|
9
|
-
/** POST the token to Google's revoke endpoint. Resolves `true` on HTTP 200. */
|
|
10
|
-
export async function revokeToken(
|
|
11
|
-
endpoints: GoogleEndpoints,
|
|
12
|
-
token: string,
|
|
13
|
-
fetchImpl: typeof fetch = fetch,
|
|
14
|
-
): Promise<boolean> {
|
|
15
|
-
if (!token) return false;
|
|
16
|
-
try {
|
|
17
|
-
const res = await fetchImpl(endpoints.revoke, {
|
|
18
|
-
method: "POST",
|
|
19
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
20
|
-
body: new URLSearchParams({ token }).toString(),
|
|
21
|
-
signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
|
|
22
|
-
});
|
|
23
|
-
return res.ok;
|
|
24
|
-
} catch {
|
|
25
|
-
return false;
|
|
26
|
-
}
|
|
27
|
-
}
|
package/src/shared/flow-codes.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Closed set of fixed, input-free codes a Gmail sign-in flow can terminate
|
|
3
|
-
* with (design D2/D3). Shared by the server failure log (allow-list) and the
|
|
4
|
-
* client error table. See change: improve-gmail-settings-ux.
|
|
5
|
-
*/
|
|
6
|
-
export const KNOWN_FLOW_CODES = [
|
|
7
|
-
"org_internal",
|
|
8
|
-
"access_denied",
|
|
9
|
-
"admin_policy_enforced",
|
|
10
|
-
"redirect_uri_mismatch",
|
|
11
|
-
"invalid_client",
|
|
12
|
-
"scope_missing",
|
|
13
|
-
"account_mismatch",
|
|
14
|
-
"missing_refresh",
|
|
15
|
-
"email_unverified",
|
|
16
|
-
"invalid_redirect",
|
|
17
|
-
"state_mismatch",
|
|
18
|
-
"callback_failed",
|
|
19
|
-
"token_exchange_failed",
|
|
20
|
-
"id_token_invalid",
|
|
21
|
-
"authorization_failed",
|
|
22
|
-
"timeout",
|
|
23
|
-
"start_timeout",
|
|
24
|
-
"login_failed",
|
|
25
|
-
"cancelled",
|
|
26
|
-
"aborted",
|
|
27
|
-
] as const;
|
|
28
|
-
|
|
29
|
-
export type FlowCode = (typeof KNOWN_FLOW_CODES)[number];
|
|
30
|
-
|
|
31
|
-
const KNOWN = new Set<string>(KNOWN_FLOW_CODES);
|
|
32
|
-
|
|
33
|
-
/** `code` when it is a string in {@link KNOWN_FLOW_CODES}, else `null` (exact match). */
|
|
34
|
-
export function knownFlowCode(code: unknown): FlowCode | null {
|
|
35
|
-
return typeof code === "string" && KNOWN.has(code) ? (code as FlowCode) : null;
|
|
36
|
-
}
|