@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.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.
@@ -0,0 +1,196 @@
1
+ /**
2
+ * `gmail/lease` request handler (design D4/D5). Authorizes on the ACCOUNT LEVEL
3
+ * only (the request lane is private but unauthenticated — any session of this
4
+ * user may lease within the level). Returns exactly
5
+ * `{accessToken, expiresAt, email, tier}` — the refresh token never leaves.
6
+ *
7
+ * - tier check (`tierAllows`) then granted-scope check (implication table);
8
+ * - refresh when `expires − now ≤ 60 s`, single-flight per `sub`, written via
9
+ * `update()` and ONLY if the record still holds the refresh token used (a
10
+ * concurrent re-auth wins);
11
+ * - `invalid_grant` → `status = reauth_required`, reply `reauth_required`;
12
+ * later leases refuse without touching the network.
13
+ * - Logs: email, op, outcome. Never a token.
14
+ *
15
+ * Failures THROW `LeaseError` whose message starts with `<code>:` — the host
16
+ * replies `{ok:false,error:message}` and the bridge parses the code.
17
+ * See change: add-gmail-plugin.
18
+ */
19
+ import * as oauth from "oauth4webapi";
20
+ import type { GoogleEndpoints } from "../shared/endpoints.js";
21
+ import type { LeaseReply } from "../shared/protocol.js";
22
+ import { isOp, type Op, scopesCover, tierAllows } from "../shared/scopes.js";
23
+ import { AccountError, type AccountRecord, type AccountStore } from "./accounts.js";
24
+ import { oauthClient, oauthServer, requestOptions } from "./google-oauth.js";
25
+
26
+ const REFRESH_WINDOW_MS = 60_000;
27
+ /** > the 15 s lane timeout, so a slow-but-alive refresh still lands and is stored (X3). */
28
+ const REFRESH_TIMEOUT_MS = 30_000;
29
+
30
+ type LeaseErrorCode =
31
+ | "bad_request"
32
+ | "not_found"
33
+ | "ambiguous"
34
+ | "no_client"
35
+ | "tier_denied"
36
+ | "scope_missing"
37
+ | "reauth_required"
38
+ | "refresh_failed";
39
+
40
+ class LeaseError extends Error {
41
+ constructor(
42
+ readonly code: LeaseErrorCode,
43
+ detail: string,
44
+ ) {
45
+ super(`${code}: ${detail}`);
46
+ this.name = "LeaseError";
47
+ }
48
+ }
49
+
50
+
51
+ /** The grant was replaced (re-auth) while a refresh of the old one was in flight. */
52
+ class GrantChanged extends Error {}
53
+
54
+ interface LeaseLogger {
55
+ info(msg: string): void;
56
+ warn(msg: string): void;
57
+ }
58
+
59
+ export interface LeaseDeps {
60
+ store: AccountStore;
61
+ endpoints: GoogleEndpoints;
62
+ logger: LeaseLogger;
63
+ fetchImpl?: typeof fetch;
64
+ now?: () => number;
65
+ }
66
+
67
+ export function createLeaseHandler(deps: LeaseDeps) {
68
+ const now = deps.now ?? Date.now;
69
+ const inflight = new Map<string, Promise<{ access: string; expires: number }>>();
70
+
71
+ async function tokenRequest(acct: AccountRecord): Promise<oauth.TokenEndpointResponse> {
72
+ const client = await deps.store.getClient();
73
+ if (!client) throw new LeaseError("no_client", "the Gmail OAuth client is not configured");
74
+ const as = oauthServer(deps.endpoints);
75
+ const c = oauthClient(client);
76
+ const res = await oauth.refreshTokenGrantRequest(
77
+ as,
78
+ c,
79
+ oauth.ClientSecretPost(client.clientSecret),
80
+ acct.refresh,
81
+ // Bounded: a hung token endpoint must not pin the single-flight slot.
82
+ requestOptions(deps.endpoints, deps.fetchImpl, AbortSignal.timeout(REFRESH_TIMEOUT_MS)),
83
+ );
84
+ return oauth.processRefreshTokenResponse(as, c, res);
85
+ }
86
+
87
+ /** Map a refresh failure: `invalid_grant` marks (or detects a replaced grant); else `refresh_failed`. */
88
+ async function refreshError(acct: AccountRecord, err: unknown): Promise<Error> {
89
+ if (err instanceof LeaseError) return err;
90
+ if (err instanceof oauth.ResponseBodyError && err.error === "invalid_grant") {
91
+ if (!(await deps.store.markReauthIf(acct.sub, acct.refresh))) return new GrantChanged();
92
+ deps.logger.warn(`[gmail] refresh ${acct.email}: invalid_grant → reauth_required`);
93
+ return new LeaseError("reauth_required", `${acct.email} needs re-authentication in the Gmail panel`);
94
+ }
95
+ deps.logger.warn(`[gmail] refresh ${acct.email}: failed`);
96
+ return new LeaseError("refresh_failed", `could not refresh the token for ${acct.email}; try again later`);
97
+ }
98
+
99
+ async function refresh(acct: AccountRecord): Promise<{ access: string; expires: number }> {
100
+ let tokens: oauth.TokenEndpointResponse;
101
+ try {
102
+ tokens = await tokenRequest(acct);
103
+ } catch (err) {
104
+ throw await refreshError(acct, err);
105
+ }
106
+ const expires = now() + (typeof tokens.expires_in === "number" ? tokens.expires_in : 3600) * 1000;
107
+ const rotated = typeof tokens.refresh_token === "string" ? tokens.refresh_token : undefined;
108
+ // Merge only while the record still holds the grant we refreshed: a
109
+ // concurrent re-auth (new refresh token) must win and is never clobbered.
110
+ await deps.store.storeTokensIf(acct.sub, acct.refresh, { access: tokens.access_token, expires, refresh: rotated });
111
+ deps.logger.info(`[gmail] refresh ${acct.email}: ok`);
112
+ return { access: tokens.access_token, expires };
113
+ }
114
+
115
+ function refreshOnce(acct: AccountRecord): Promise<{ access: string; expires: number }> {
116
+ const existing = inflight.get(acct.sub);
117
+ if (existing) return existing;
118
+ const p = refresh(acct).finally(() => inflight.delete(acct.sub));
119
+ inflight.set(acct.sub, p);
120
+ return p;
121
+ }
122
+
123
+ async function resolveAccount(payload: unknown): Promise<{ acct: AccountRecord; op: Op }> {
124
+ const p = (payload ?? {}) as { account?: unknown; op?: unknown };
125
+ if (typeof p.account !== "string" || !p.account.trim() || !isOp(p.op)) {
126
+ throw new LeaseError("bad_request", "expected {account, op}");
127
+ }
128
+ try {
129
+ return { acct: await deps.store.resolve(p.account), op: p.op };
130
+ } catch (err) {
131
+ if (err instanceof AccountError && (err.code === "not_found" || err.code === "ambiguous")) {
132
+ throw new LeaseError(err.code, err.message);
133
+ }
134
+ throw err;
135
+ }
136
+ }
137
+
138
+ /** Level + granted-scope + status gate. Returns the refusal, or null when allowed. */
139
+ function refusal(acct: AccountRecord, op: Op): LeaseError | null {
140
+ if (!tierAllows(acct.tier, op)) {
141
+ return new LeaseError("tier_denied", `${acct.email} is at level "${acct.tier}", which does not allow "${op}"`);
142
+ }
143
+ if (!scopesCover(acct.scopes, op)) {
144
+ return new LeaseError("scope_missing", `Google did not grant the scope "${op}" needs for ${acct.email}; re-authenticate`);
145
+ }
146
+ if (acct.status === "reauth_required") {
147
+ return new LeaseError("reauth_required", `${acct.email} needs re-authentication in the Gmail panel`);
148
+ }
149
+ return null;
150
+ }
151
+
152
+ /** Gate, then cached token or a refresh re-gated against the record as it is NOW. */
153
+ async function leaseFor(acct: AccountRecord, op: Op): Promise<LeaseReply> {
154
+ const refused = refusal(acct, op);
155
+ if (refused) throw refused;
156
+ if (acct.access && acct.expires - now() > REFRESH_WINDOW_MS) {
157
+ return { accessToken: acct.access, expiresAt: acct.expires, email: acct.email, tier: acct.tier };
158
+ }
159
+ const fresh = await refreshOnce(acct);
160
+ // The refresh awaited the network: a downgrade / revoke / re-auth may have
161
+ // landed meanwhile. Re-read and re-gate before handing out a token.
162
+ const latest = await deps.store.get(acct.sub);
163
+ if (!latest) throw new LeaseError("not_found", `${acct.email} was removed`);
164
+ const late = refusal(latest, op);
165
+ if (late) throw late;
166
+ // Grant replaced during the refresh: `fresh` belongs to the OLD grant (and
167
+ // was not stored) — never hand it out.
168
+ if (latest.refresh !== acct.refresh) throw new GrantChanged();
169
+ return { accessToken: fresh.access, expiresAt: fresh.expires, email: latest.email, tier: latest.tier };
170
+ }
171
+
172
+ /**
173
+ * `retried`: the grant was replaced mid-refresh — lease ONCE more against the
174
+ * current record (bounded; never loops). Inner function: the host calls the
175
+ * handler as `(payload, meta)`, so the export takes no 2nd positional arg.
176
+ */
177
+ async function lease(payload: unknown, retried: boolean): Promise<LeaseReply> {
178
+ const { acct, op } = await resolveAccount(payload);
179
+ const outcome = (o: string) => deps.logger.info(`[gmail] lease ${acct.email} op=${op}: ${o}`);
180
+ try {
181
+ const reply = await leaseFor(acct, op);
182
+ outcome("ok");
183
+ return reply;
184
+ } catch (err) {
185
+ if (err instanceof GrantChanged && !retried) return lease(payload, true);
186
+ const e =
187
+ err instanceof GrantChanged
188
+ ? new LeaseError("refresh_failed", `the grant for ${acct.email} changed during refresh; try again`)
189
+ : err;
190
+ outcome(e instanceof LeaseError ? e.code : "refresh_failed");
191
+ throw e;
192
+ }
193
+ }
194
+
195
+ return (payload: unknown): Promise<LeaseReply> => lease(payload, false);
196
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Gmail plugin REST routes (design D3/D4/D7/D9). All under
3
+ * `/api/plugins/gmail/`, all behind `networkGuard`, in an encapsulated scope
4
+ * with `@fastify/rate-limit` (loopback allow-listed). Tiers: `operate`
5
+ * (`packages/shared/src/route-tiers.ts`). Responses NEVER carry tokens or the
6
+ * client secret. See change: add-gmail-plugin.
7
+ */
8
+
9
+ import type {
10
+ PluginNetworkGuard,
11
+ PluginOAuth,
12
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
13
+ import rateLimit from "@fastify/rate-limit";
14
+ import type { FastifyInstance, FastifyReply } from "fastify";
15
+ import { validateClientJson } from "../shared/client-json.js";
16
+ import type { GoogleEndpoints } from "../shared/endpoints.js";
17
+ import { isTier, scopesCoverTier, type Tier } from "../shared/scopes.js";
18
+ import { AccountError, type AccountStore, summarize } from "./accounts.js";
19
+ import { revokeToken } from "./gmail-rest.js";
20
+ import {
21
+ createGoogleLoginFlow,
22
+ GmailFlowError,
23
+ type GoogleLoginOptions, type GoogleSignInResult,
24
+ } from "./google-oauth.js";
25
+
26
+ export interface GmailRouteDeps {
27
+ store: AccountStore;
28
+ oauth: PluginOAuth | undefined;
29
+ endpoints: GoogleEndpoints;
30
+ networkGuard: PluginNetworkGuard;
31
+ logger: { info(m: string): void; warn(m: string): void };
32
+ fetchImpl?: typeof fetch;
33
+ createCallback?: GoogleLoginOptions["createCallback"];
34
+ newId?: () => string;
35
+ }
36
+
37
+ const PREFIX = "/api/plugins/gmail";
38
+
39
+ function accountErrorStatus(err: AccountError): number {
40
+ if (err.code === "not_found") return 404;
41
+ if (err.code === "alias_taken" || err.code === "ambiguous") return 409;
42
+ return 400;
43
+ }
44
+
45
+ function sendError(reply: FastifyReply, err: unknown) {
46
+ if (err instanceof AccountError) {
47
+ return reply.code(accountErrorStatus(err)).send({ error: err.code, message: err.message });
48
+ }
49
+ const code = (err as { code?: unknown })?.code;
50
+ return reply
51
+ .code(502)
52
+ .send({ error: typeof code === "string" && /^[a-z_]{1,64}$/.test(code) ? code : "internal_error" });
53
+ }
54
+
55
+ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRouteDeps): Promise<void> {
56
+ const { store, endpoints, logger } = deps;
57
+ const newId = deps.newId ?? (() => crypto.randomUUID());
58
+
59
+ /** Start a sign-in flow for `tier`; `expectSub` set for re-auth / level raise. */
60
+ async function startSignIn(
61
+ reply: FastifyReply,
62
+ tier: Tier,
63
+ expect?: { sub: string; email: string },
64
+ ) {
65
+ if (!deps.oauth) return reply.code(501).send({ error: "oauth_unavailable" });
66
+ const client = await store.getClient();
67
+ if (!client) return reply.code(409).send({ error: "no_client" });
68
+ const loginFlow = createGoogleLoginFlow({
69
+ client,
70
+ endpoints,
71
+ tier,
72
+ loginHint: expect?.email,
73
+ fetchImpl: deps.fetchImpl,
74
+ createCallback: deps.createCallback,
75
+ });
76
+ try {
77
+ return await deps.oauth.startFlow({
78
+ key: expect ? `reauth-${expect.sub}` : `add-${newId()}`,
79
+ loginFlow,
80
+ persist: async (credential) => {
81
+ const c = credential as GoogleSignInResult;
82
+ if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
83
+ // Consent-screen checkboxes can be cleared: never store a level the grant cannot serve.
84
+ if (!scopesCoverTier(c.grantedScopes, c.tier)) throw new GmailFlowError("scope_missing");
85
+ const acct = await store.upsertFromSignIn({
86
+ sub: c.sub,
87
+ email: c.email,
88
+ tier: c.tier,
89
+ scopes: c.grantedScopes,
90
+ access: c.access,
91
+ refresh: c.refresh || undefined,
92
+ expires: c.expires,
93
+ testingHint: c.testingHint,
94
+ });
95
+ logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
96
+ },
97
+ });
98
+ } catch (err) {
99
+ return sendError(reply, err);
100
+ }
101
+ }
102
+
103
+ await fastify.register(async (scope) => {
104
+ await scope.register(rateLimit, {
105
+ global: true,
106
+ max: 600,
107
+ timeWindow: "1 minute",
108
+ allowList: ["127.0.0.1", "::1"],
109
+ });
110
+ const guarded = { preHandler: deps.networkGuard };
111
+
112
+ scope.get(`${PREFIX}/state`, guarded, async () => {
113
+ const client = await store.getClient();
114
+ return {
115
+ client: client ? { configured: true, clientId: client.clientId, projectId: client.projectId } : { configured: false },
116
+ accounts: (await store.list()).map(summarize),
117
+ };
118
+ });
119
+
120
+ scope.put(`${PREFIX}/client`, guarded, async (request, reply) => {
121
+ const result = validateClientJson((request.body as { json?: unknown } | null)?.json ?? request.body);
122
+ if (!result.ok) return reply.code(400).send({ error: result.error.code, step: result.error.step });
123
+ // Refresh tokens are bound to the client that minted them: swapping the
124
+ // client under connected accounts would break every refresh silently.
125
+ const current = await store.getClient();
126
+ const changed =
127
+ current &&
128
+ (current.clientId !== result.client.clientId || current.clientSecret !== result.client.clientSecret);
129
+ if (changed && (await store.list()).length > 0) {
130
+ return reply.code(409).send({ error: "client_in_use", step: 5 });
131
+ }
132
+ await store.setClient(result.client);
133
+ logger.info("[gmail] oauth client configured");
134
+ return { ok: true, clientId: result.client.clientId, projectId: result.client.projectId };
135
+ });
136
+
137
+ scope.post(`${PREFIX}/accounts`, guarded, async (request, reply) => {
138
+ const tier = (request.body as { tier?: unknown } | null)?.tier ?? "readonly";
139
+ if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
140
+ return startSignIn(reply, tier);
141
+ });
142
+
143
+ scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/level`, guarded, async (request, reply) => {
144
+ const tier = (request.body as { tier?: unknown } | null)?.tier;
145
+ if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
146
+ const acct = await store.get(request.params.sub);
147
+ if (!acct) return reply.code(404).send({ error: "not_found" });
148
+ // Lowering (or a level the existing grant already covers) applies at once;
149
+ // raising re-consents with the FULL scope set of the new level.
150
+ if (acct.status === "ok" && scopesCoverTier(acct.scopes, tier)) {
151
+ const next = await store.setTier(acct.sub, tier);
152
+ logger.info(`[gmail] level ${next.email} → ${tier}`);
153
+ return { applied: true, account: summarize(next) };
154
+ }
155
+ return startSignIn(reply, tier, { sub: acct.sub, email: acct.email });
156
+ });
157
+
158
+ scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/reauth`, guarded, async (request, reply) => {
159
+ const acct = await store.get(request.params.sub);
160
+ if (!acct) return reply.code(404).send({ error: "not_found" });
161
+ return startSignIn(reply, acct.tier, { sub: acct.sub, email: acct.email });
162
+ });
163
+
164
+ scope.patch<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
165
+ const body = (request.body ?? {}) as { alias?: unknown };
166
+ if (body.alias !== null && body.alias !== undefined && typeof body.alias !== "string") {
167
+ return reply.code(400).send({ error: "invalid_alias" });
168
+ }
169
+ try {
170
+ const next = await store.setAlias(request.params.sub, (body.alias as string | null) ?? undefined);
171
+ return { account: summarize(next) };
172
+ } catch (err) {
173
+ return sendError(reply, err);
174
+ }
175
+ });
176
+
177
+ scope.delete<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
178
+ const acct = await store.get(request.params.sub);
179
+ if (!acct) return reply.code(404).send({ error: "not_found" });
180
+ const remoteRevoked = await revokeToken(endpoints, acct.refresh, deps.fetchImpl);
181
+ await store.remove(acct.sub);
182
+ logger.info(`[gmail] revoke ${acct.email}: local ok, remote ${remoteRevoked ? "ok" : "failed"}`);
183
+ return { removed: true, remoteRevoked };
184
+ });
185
+ });
186
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Validate an uploaded `client_secret_*.json` (design D7 step 5). Only a
3
+ * Desktop client (`installed` block) is accepted; a `web` block is rejected with
4
+ * step-4 guidance. Pure — used by the wizard (instant feedback) AND the server
5
+ * route (authoritative). See change: add-gmail-plugin.
6
+ */
7
+
8
+ interface ParsedClient {
9
+ clientId: string;
10
+ clientSecret: string;
11
+ projectId?: string;
12
+ }
13
+
14
+ type ClientJsonError =
15
+ | { code: "not_json"; step: 5 }
16
+ | { code: "web_client"; step: 4 }
17
+ | { code: "not_installed"; step: 4 }
18
+ | { code: "bad_client_id"; step: 4 }
19
+ | { code: "missing_secret"; step: 5 };
20
+
21
+ export type ClientJsonResult = { ok: true; client: ParsedClient } | { ok: false; error: ClientJsonError };
22
+
23
+ const CLIENT_ID_RE = /^[A-Za-z0-9._-]{1,200}\.apps\.googleusercontent\.com$/;
24
+
25
+ export function validateClientJson(input: string | unknown): ClientJsonResult {
26
+ let data: unknown = input;
27
+ if (typeof input === "string") {
28
+ try {
29
+ data = JSON.parse(input);
30
+ } catch {
31
+ return { ok: false, error: { code: "not_json", step: 5 } };
32
+ }
33
+ }
34
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
35
+ return { ok: false, error: { code: "not_json", step: 5 } };
36
+ }
37
+ const obj = data as Record<string, unknown>;
38
+ const installed = obj.installed;
39
+ if (!installed || typeof installed !== "object") {
40
+ if (obj.web) return { ok: false, error: { code: "web_client", step: 4 } };
41
+ return { ok: false, error: { code: "not_installed", step: 4 } };
42
+ }
43
+ const i = installed as Record<string, unknown>;
44
+ if (typeof i.client_id !== "string" || !CLIENT_ID_RE.test(i.client_id)) {
45
+ return { ok: false, error: { code: "bad_client_id", step: 4 } };
46
+ }
47
+ if (typeof i.client_secret !== "string" || !i.client_secret.trim() || i.client_secret.length > 500) {
48
+ return { ok: false, error: { code: "missing_secret", step: 5 } };
49
+ }
50
+ const client: ParsedClient = { clientId: i.client_id, clientSecret: i.client_secret };
51
+ if (typeof i.project_id === "string" && /^[a-z][a-z0-9-]{4,62}$/.test(i.project_id)) client.projectId = i.project_id;
52
+ return { ok: true, client };
53
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Google endpoint resolution with the test-only override (design D8).
3
+ * `PI_E2E_GOOGLE_BASE_URL` redirects authorize/token/revoke/Gmail REST to ONE
4
+ * fake-Google server — honoured ONLY for a loopback `http://127.0.0.1:*` or
5
+ * `http://localhost:*` value, so a production install can never be pointed at a
6
+ * foreign token endpoint. See change: add-gmail-plugin.
7
+ */
8
+
9
+ const GOOGLE_BASE_URL_ENV = "PI_E2E_GOOGLE_BASE_URL";
10
+
11
+ export interface GoogleEndpoints {
12
+ issuer: string;
13
+ authorize: string;
14
+ token: string;
15
+ revoke: string;
16
+ /** Gmail REST base, no trailing slash: `<base>/gmail/v1/users/me/...`. */
17
+ gmail: string;
18
+ /** True when the loopback test override is active (plain-HTTP allowed). */
19
+ overridden: boolean;
20
+ }
21
+
22
+ export const GOOGLE_DEFAULTS: GoogleEndpoints = {
23
+ issuer: "https://accounts.google.com",
24
+ authorize: "https://accounts.google.com/o/oauth2/v2/auth",
25
+ token: "https://oauth2.googleapis.com/token",
26
+ revoke: "https://oauth2.googleapis.com/revoke",
27
+ gmail: "https://gmail.googleapis.com/gmail/v1",
28
+ overridden: false,
29
+ };
30
+
31
+ function loopbackBase(raw: string): string | null {
32
+ let u: URL;
33
+ try {
34
+ u = new URL(raw);
35
+ } catch {
36
+ return null;
37
+ }
38
+ if (u.protocol !== "http:") return null;
39
+ if (u.hostname !== "127.0.0.1" && u.hostname !== "localhost") return null;
40
+ if (u.username || u.password) return null;
41
+ return u.origin;
42
+ }
43
+
44
+ /**
45
+ * Resolve endpoints from `env`. A non-loopback override is ignored with ONE
46
+ * warning via `warn` (the value itself is not echoed — it may be hostile).
47
+ */
48
+ export function resolveGoogleEndpoints(
49
+ env: Record<string, string | undefined> = process.env,
50
+ warn: (msg: string) => void = (m) => console.warn(m),
51
+ ): GoogleEndpoints {
52
+ const raw = env[GOOGLE_BASE_URL_ENV];
53
+ if (!raw) return GOOGLE_DEFAULTS;
54
+ const base = loopbackBase(raw);
55
+ if (!base) {
56
+ warn(`[gmail] ${GOOGLE_BASE_URL_ENV} ignored: only http://127.0.0.1:* or http://localhost:* is honoured`);
57
+ return GOOGLE_DEFAULTS;
58
+ }
59
+ return {
60
+ issuer: base,
61
+ authorize: `${base}/o/oauth2/v2/auth`,
62
+ token: `${base}/token`,
63
+ revoke: `${base}/revoke`,
64
+ gmail: `${base}/gmail/v1`,
65
+ overridden: true,
66
+ };
67
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Bridge ↔ server request-lane contract (design D5). See change: add-gmail-plugin.
3
+ */
4
+ import type { Tier } from "./scopes.js";
5
+
6
+ export const PLUGIN_ID = "gmail";
7
+ export const LEASE_TYPE = "gmail/lease";
8
+ export const ACCOUNTS_TYPE = "gmail/accounts";
9
+
10
+ /** `gmail/lease` success reply — exactly these keys, never a refresh token. */
11
+ export interface LeaseReply {
12
+ accessToken: string;
13
+ expiresAt: number;
14
+ email: string;
15
+ tier: Tier;
16
+ }
17
+
18
+ /** `gmail/accounts` reply row (secret-free). */
19
+ export interface AccountInfo {
20
+ sub: string;
21
+ email: string;
22
+ alias?: string;
23
+ tier: Tier;
24
+ status: "ok" | "reauth_required";
25
+ testingHint?: boolean;
26
+ addedAt: number;
27
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Permission levels, operations and Google scopes (design D4). Pure data +
3
+ * functions shared by server (lease), bridge (defence-in-depth tier check)
4
+ * and client (level help text). See change: add-gmail-plugin.
5
+ */
6
+
7
+ export type Tier = "readonly" | "draft" | "send";
8
+ export type Op = "read" | "draft" | "send" | "modify" | "trash";
9
+
10
+ export const TIERS: readonly Tier[] = ["readonly", "draft", "send"];
11
+
12
+ const SCOPE_BASE = "https://www.googleapis.com/auth/";
13
+ export const SCOPE = {
14
+ readonly: `${SCOPE_BASE}gmail.readonly`,
15
+ compose: `${SCOPE_BASE}gmail.compose`,
16
+ modify: `${SCOPE_BASE}gmail.modify`,
17
+ } as const;
18
+
19
+ /** Requested Gmail scopes per tier (full set — no incremental auth for installed apps). */
20
+ export const TIER_SCOPES: Record<Tier, readonly string[]> = {
21
+ readonly: [SCOPE.readonly],
22
+ draft: [SCOPE.readonly, SCOPE.compose],
23
+ send: [SCOPE.modify],
24
+ };
25
+
26
+ const TIER_RANK: Record<Tier, number> = { readonly: 0, draft: 1, send: 2 };
27
+
28
+ /** Minimum tier each operation requires. */
29
+ const OP_TIER: Record<Op, Tier> = {
30
+ read: "readonly",
31
+ draft: "draft",
32
+ send: "send",
33
+ modify: "send",
34
+ trash: "send",
35
+ };
36
+
37
+ /** Scope(s) that cover an op — any one suffices. */
38
+ const OP_SCOPE: Record<Op, string> = {
39
+ read: SCOPE.readonly,
40
+ draft: SCOPE.compose,
41
+ send: SCOPE.modify,
42
+ modify: SCOPE.modify,
43
+ trash: SCOPE.modify,
44
+ };
45
+
46
+ /** Implication table: a granted scope also covers these. `modify ⇒ readonly, compose`. */
47
+ const IMPLIES: Record<string, readonly string[]> = {
48
+ [SCOPE.modify]: [SCOPE.readonly, SCOPE.compose],
49
+ };
50
+
51
+ export function isTier(v: unknown): v is Tier {
52
+ return v === "readonly" || v === "draft" || v === "send";
53
+ }
54
+
55
+ export function isOp(v: unknown): v is Op {
56
+ return v === "read" || v === "draft" || v === "send" || v === "modify" || v === "trash";
57
+ }
58
+
59
+ /** True when `tier` is high enough for `op`. */
60
+ export function tierAllows(tier: Tier, op: Op): boolean {
61
+ return TIER_RANK[tier] >= TIER_RANK[OP_TIER[op]];
62
+ }
63
+
64
+ /** Expand granted scopes through the implication table. */
65
+ function effectiveScopes(granted: readonly string[]): Set<string> {
66
+ const out = new Set<string>();
67
+ for (const s of granted) {
68
+ out.add(s);
69
+ for (const implied of IMPLIES[s] ?? []) out.add(implied);
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** True when the granted scopes cover `op`. */
75
+ export function scopesCover(granted: readonly string[], op: Op): boolean {
76
+ return effectiveScopes(granted).has(OP_SCOPE[op]);
77
+ }
78
+
79
+ /** True when the granted scopes cover every op of `tier` (no re-consent needed). */
80
+ export function scopesCoverTier(granted: readonly string[], tier: Tier): boolean {
81
+ const eff = effectiveScopes(granted);
82
+ return TIER_SCOPES[tier].every((s) => eff.has(s));
83
+ }
84
+
85
+ /** Space-separated `scope` parameter for an authorization request. */
86
+ export function authScopeParam(tier: Tier): string {
87
+ return ["openid", "email", ...TIER_SCOPES[tier]].join(" ");
88
+ }