@blackbelt-technology/pi-dashboard-gmail-plugin 0.11.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 +3 -3
- package/src/bridge/lease-client.ts +127 -7
- package/src/bridge/tools.ts +1 -1
- package/src/client/GmailSettings.tsx +52 -1137
- package/src/i18n.ts +9 -619
- package/src/server/accounts.ts +17 -4
- package/src/server/google-link.ts +81 -0
- package/src/server/google-oauth.ts +2 -2
- package/src/server/index.ts +31 -21
- package/src/server/lease.ts +3 -2
- package/src/server/routes.ts +37 -296
- package/src/shared/client-json.ts +2 -2
- package/src/shared/protocol.ts +18 -0
- package/src/shared/scopes.ts +2 -2
- package/src/shared/setup.ts +2 -2
- package/src/client/AutoSetup.tsx +0 -787
- package/src/client/auto-setup.ts +0 -124
- package/src/client/ui.ts +0 -24
- package/src/client/wizard.ts +0 -196
- package/src/server/gmail-rest.ts +0 -27
- package/src/server/setup/browser-service.ts +0 -55
- package/src/server/setup/capture.ts +0 -96
- package/src/server/setup/cdp-page.ts +0 -308
- package/src/server/setup/errors.ts +0 -36
- package/src/server/setup/local.ts +0 -27
- package/src/server/setup/mask.ts +0 -11
- package/src/server/setup/run.ts +0 -723
- package/src/server/setup/setup-routes.ts +0 -123
- package/src/server/setup/steps.ts +0 -458
- package/src/server/store-client.ts +0 -30
- package/src/shared/auto-setup.ts +0 -132
- package/src/shared/flow-codes.ts +0 -36
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Automatic-setup routes + availability (design D3, D10). Mounted into the Gmail
|
|
3
|
-
* scope by `routes.ts`, so they share its prefix, rate limit and network guard.
|
|
4
|
-
* Starting a run additionally requires a genuinely local request. Responses carry
|
|
5
|
-
* the secret-free run view only. See change: add-gmail-auto-setup.
|
|
6
|
-
*/
|
|
7
|
-
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
8
|
-
import type { AutoSetupState, SetupContinueRequest, SetupRunRequest } from "../../shared/auto-setup.js";
|
|
9
|
-
import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../../shared/setup.js";
|
|
10
|
-
import type { AccountStore } from "../accounts.js";
|
|
11
|
-
import type { DedicatedBrowserService } from "./browser-service.js";
|
|
12
|
-
import { isGenuinelyLocal } from "./local.js";
|
|
13
|
-
import type { SetupRunManager } from "./run.js";
|
|
14
|
-
|
|
15
|
-
export interface SetupRouteDeps {
|
|
16
|
-
prefix: string;
|
|
17
|
-
guard: unknown;
|
|
18
|
-
store: AccountStore;
|
|
19
|
-
manager: SetupRunManager;
|
|
20
|
-
getService(): DedicatedBrowserService | undefined;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const PROJECT_ID_RULE = "projectId must be a Google Cloud project id: 6–30 chars, lower-case letters, digits and hyphens";
|
|
24
|
-
const EMAIL_RULE = "ownerEmail must be an email address of at most 254 characters";
|
|
25
|
-
|
|
26
|
-
type RunRequestParse = { ok: true; request: SetupRunRequest } | { ok: false; error: string; message: string };
|
|
27
|
-
|
|
28
|
-
const invalidProjectId: RunRequestParse = { ok: false, error: "invalid_project_id", message: PROJECT_ID_RULE };
|
|
29
|
-
|
|
30
|
-
/** Pure validation of the POST body; `error`/`message` map 1:1 onto the 400 response. */
|
|
31
|
-
function parseRunRequest(raw: unknown): RunRequestParse {
|
|
32
|
-
const body = (raw ?? {}) as Partial<Record<keyof SetupRunRequest, unknown>>;
|
|
33
|
-
const mode = body.mode;
|
|
34
|
-
if (mode !== "new" && mode !== "existing") return { ok: false, error: "invalid_mode", message: 'mode must be "new" or "existing"' };
|
|
35
|
-
const ownerEmail = typeof body.ownerEmail === "string" ? normalizeEmail(body.ownerEmail) : "";
|
|
36
|
-
if (!isEmail(ownerEmail)) return { ok: false, error: "invalid_owner_email", message: EMAIL_RULE };
|
|
37
|
-
let projectId: string | undefined;
|
|
38
|
-
if (body.projectId !== undefined && body.projectId !== null && body.projectId !== "") {
|
|
39
|
-
if (typeof body.projectId !== "string") return invalidProjectId;
|
|
40
|
-
projectId = normalizeProjectId(body.projectId);
|
|
41
|
-
if (classifyProjectId(projectId) !== "ok") return invalidProjectId;
|
|
42
|
-
}
|
|
43
|
-
if (mode === "existing" && !projectId) return invalidProjectId;
|
|
44
|
-
return { ok: true, request: { mode, projectId, ownerEmail } };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function isLocal(request: FastifyRequest): boolean {
|
|
48
|
-
return isGenuinelyLocal(request.headers, request.socket.remoteAddress);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** `GET state` → `autoSetup` (design D10). */
|
|
52
|
-
export async function autoSetupState(request: FastifyRequest, deps: SetupRouteDeps): Promise<AutoSetupState> {
|
|
53
|
-
const local = isLocal(request);
|
|
54
|
-
const service = deps.getService();
|
|
55
|
-
if (!service) return { available: false, reason: "service_missing", local };
|
|
56
|
-
let status: Awaited<ReturnType<DedicatedBrowserService["status"]>>;
|
|
57
|
-
try {
|
|
58
|
-
status = await service.status();
|
|
59
|
-
} catch {
|
|
60
|
-
return { available: false, reason: "status_failed", local };
|
|
61
|
-
}
|
|
62
|
-
if (!status.enabled) return { available: false, reason: "disabled", local };
|
|
63
|
-
if (!status.available) return { available: false, reason: status.reason ?? "unavailable", local };
|
|
64
|
-
const client = await deps.store.getClient();
|
|
65
|
-
if (client && (await deps.store.list()).length > 0) return { available: false, reason: "client_in_use", local };
|
|
66
|
-
if (!local) return { available: false, reason: "remote_dashboard", local };
|
|
67
|
-
const live = deps.manager.live;
|
|
68
|
-
if (live) return { available: false, reason: "run_active", local, runId: live.id };
|
|
69
|
-
return { available: true, local, ...(client ? { replacesClient: true } : {}) };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export function registerSetupRoutes(scope: FastifyInstance, deps: SetupRouteDeps): void {
|
|
73
|
-
const guarded = { preHandler: deps.guard as never };
|
|
74
|
-
const base = `${deps.prefix}/setup/run`;
|
|
75
|
-
|
|
76
|
-
scope.post(base, guarded, async (request, reply) => {
|
|
77
|
-
if (!isLocal(request)) return reply.code(403).send({ error: "remote_dashboard" });
|
|
78
|
-
const parsed = parseRunRequest(request.body);
|
|
79
|
-
if (!parsed.ok) return reply.code(400).send({ error: parsed.error, message: parsed.message });
|
|
80
|
-
const { mode, projectId, ownerEmail } = parsed.request;
|
|
81
|
-
const state = await autoSetupState(request, deps);
|
|
82
|
-
if (!state.available) {
|
|
83
|
-
if (state.reason === "run_active") return reply.code(409).send({ error: "run_active" });
|
|
84
|
-
return reply.code(409).send({ error: "unavailable", reason: state.reason });
|
|
85
|
-
}
|
|
86
|
-
const run = deps.manager.start({ mode, projectId, ownerEmail });
|
|
87
|
-
if (!run) return reply.code(409).send({ error: "run_active" });
|
|
88
|
-
return { runId: run.id };
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
scope.get<{ Params: { id: string } }>(`${base}/:id`, guarded, async (request, reply) => {
|
|
92
|
-
if (!isLocal(request)) return reply.code(403).send({ error: "remote_dashboard" });
|
|
93
|
-
const run = deps.manager.get(request.params.id);
|
|
94
|
-
if (!run) return reply.code(404).send({ error: "not_found" });
|
|
95
|
-
return run.view();
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
scope.post<{ Params: { id: string } }>(`${base}/:id/continue`, guarded, async (request, reply) => {
|
|
99
|
-
if (!isLocal(request)) return reply.code(403).send({ error: "remote_dashboard" });
|
|
100
|
-
const run = deps.manager.get(request.params.id);
|
|
101
|
-
if (!run) return reply.code(404).send({ error: "not_found" });
|
|
102
|
-
const result = run.continue((request.body ?? {}) as SetupContinueRequest);
|
|
103
|
-
if (!result.ok) return reply.code(result.status).send({ error: result.error });
|
|
104
|
-
return run.view();
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
scope.post<{ Params: { id: string } }>(`${base}/:id/takeover`, guarded, async (request, reply) => {
|
|
108
|
-
if (!isLocal(request)) return reply.code(403).send({ error: "remote_dashboard" });
|
|
109
|
-
const run = deps.manager.get(request.params.id);
|
|
110
|
-
if (!run) return reply.code(404).send({ error: "not_found" });
|
|
111
|
-
const result = run.takeover();
|
|
112
|
-
if (!result.ok) return reply.code(result.status).send({ error: result.error });
|
|
113
|
-
return run.view();
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
scope.delete<{ Params: { id: string } }>(`${base}/:id`, guarded, async (request, reply) => {
|
|
117
|
-
if (!isLocal(request)) return reply.code(403).send({ error: "remote_dashboard" });
|
|
118
|
-
const run = deps.manager.get(request.params.id);
|
|
119
|
-
if (!run) return reply.code(404).send({ error: "not_found" });
|
|
120
|
-
await run.cancel();
|
|
121
|
-
return run.view();
|
|
122
|
-
});
|
|
123
|
-
}
|
|
@@ -1,458 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The setup recipe: six steps, each `check` → (`act` → `verify`). Pure recipe
|
|
3
|
-
* logic over the `StepEnv` capability surface the run provides, so every page
|
|
4
|
-
* operation is attempt-scoped, interruptible and never logged.
|
|
5
|
-
*
|
|
6
|
-
* ALL console-specific strings (paths, role + accessible names, page-text
|
|
7
|
-
* patterns) live in the ONE constants block below. They are English role+name
|
|
8
|
-
* selectors from the design table and public knowledge of the Cloud console;
|
|
9
|
-
* adjust them there when the console changes (manual verification: task 7.2).
|
|
10
|
-
* Any page that does not show what a step expects is a handoff
|
|
11
|
-
* `unexpected_page` — never a guess. The recipe never types a password and never
|
|
12
|
-
* clicks sign-in, consent, terms, User Data Policy or publish confirmation.
|
|
13
|
-
* See change: add-gmail-auto-setup.
|
|
14
|
-
*/
|
|
15
|
-
import { randomInt } from "node:crypto";
|
|
16
|
-
import {
|
|
17
|
-
type Audience,
|
|
18
|
-
type CheckpointKind,
|
|
19
|
-
DEFAULT_PUBLISH_LINKS,
|
|
20
|
-
type PublishLinks,
|
|
21
|
-
type SetupContinueRequest,
|
|
22
|
-
type SetupDecision,
|
|
23
|
-
type SetupStepId,
|
|
24
|
-
} from "../../shared/auto-setup.js";
|
|
25
|
-
import type { AxNode, PageInfo } from "./cdp-page.js";
|
|
26
|
-
import { NavigationError } from "./cdp-page.js";
|
|
27
|
-
import { SetupHandoff } from "./errors.js";
|
|
28
|
-
|
|
29
|
-
// ───────────────────────── constants block (adjust here) ─────────────────────────
|
|
30
|
-
|
|
31
|
-
const CONSOLE_ORIGIN = "https://console.cloud.google.com";
|
|
32
|
-
export const SIGN_IN_ORIGIN = "https://accounts.google.com";
|
|
33
|
-
/** Domains the dedicated browser must allow; named in the `domain_blocked` hand-off. */
|
|
34
|
-
export const REQUIRED_DOMAINS = ["console.cloud.google.com", "accounts.google.com"] as const;
|
|
35
|
-
|
|
36
|
-
const CLIENT_NAME = "pi-dashboard";
|
|
37
|
-
|
|
38
|
-
export const PATHS = {
|
|
39
|
-
projectInfo: "/iam-admin/settings",
|
|
40
|
-
projectCreate: "/projectcreate",
|
|
41
|
-
apiOverview: "/apis/api/gmail.googleapis.com/overview",
|
|
42
|
-
audience: "/auth/audience",
|
|
43
|
-
brandingCreate: "/auth/overview/create",
|
|
44
|
-
branding: "/auth/branding",
|
|
45
|
-
clients: "/auth/clients",
|
|
46
|
-
clientCreate: "/auth/clients/create",
|
|
47
|
-
} as const;
|
|
48
|
-
|
|
49
|
-
export interface Sel {
|
|
50
|
-
role: string;
|
|
51
|
-
name: string;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export const SEL = {
|
|
55
|
-
// project
|
|
56
|
-
projectName: { role: "textbox", name: "Project name" },
|
|
57
|
-
projectIdEdit: { role: "button", name: "Edit" },
|
|
58
|
-
projectIdField: { role: "textbox", name: "Project ID" },
|
|
59
|
-
create: { role: "button", name: "Create" },
|
|
60
|
-
// api
|
|
61
|
-
disableApi: { role: "button", name: "Disable API" },
|
|
62
|
-
enableApi: { role: "button", name: "Enable" },
|
|
63
|
-
// branding
|
|
64
|
-
getStarted: { role: "button", name: "Get started" },
|
|
65
|
-
appName: { role: "textbox", name: "App name" },
|
|
66
|
-
supportEmail: { role: "combobox", name: "User support email" },
|
|
67
|
-
next: { role: "button", name: "Next" },
|
|
68
|
-
audienceInternal: { role: "radio", name: "Internal" },
|
|
69
|
-
audienceExternal: { role: "radio", name: "External" },
|
|
70
|
-
contactEmail: { role: "textbox", name: "Email addresses" },
|
|
71
|
-
policyCheckbox: { role: "checkbox", name: "I agree to the Google API Services: User Data Policy" },
|
|
72
|
-
continue: { role: "button", name: "Continue" },
|
|
73
|
-
// publish
|
|
74
|
-
homePage: { role: "textbox", name: "Application home page" },
|
|
75
|
-
privacyPolicy: { role: "textbox", name: "Application privacy policy link" },
|
|
76
|
-
addDomain: { role: "button", name: "Add domain" },
|
|
77
|
-
authorizedDomain: { role: "textbox", name: "Authorized domain 1" },
|
|
78
|
-
save: { role: "button", name: "Save" },
|
|
79
|
-
publishApp: { role: "button", name: "Publish app" },
|
|
80
|
-
publishDialog: { role: "dialog", name: "Push to production?" },
|
|
81
|
-
// client
|
|
82
|
-
createClient: { role: "button", name: "Create client" },
|
|
83
|
-
appType: { role: "combobox", name: "Application type" },
|
|
84
|
-
desktopApp: { role: "option", name: "Desktop app" },
|
|
85
|
-
clientName: { role: "textbox", name: "Name" },
|
|
86
|
-
clientCreatedDialog: { role: "dialog", name: "OAuth client created" },
|
|
87
|
-
downloadJson: { role: "button", name: "Download JSON" },
|
|
88
|
-
dialogClose: { role: "button", name: "OK" },
|
|
89
|
-
// checkpoints
|
|
90
|
-
termsAgree: { role: "button", name: "Agree and continue" },
|
|
91
|
-
} as const satisfies Record<string, Sel>;
|
|
92
|
-
|
|
93
|
-
/** Page-text patterns (read in-process; the text is never logged). */
|
|
94
|
-
const TEXT = {
|
|
95
|
-
projectId: /Project ID\s*[:\n]?\s*([a-z][a-z0-9-]{3,}[a-z0-9])/,
|
|
96
|
-
noOrganization: /No organization/i,
|
|
97
|
-
organization: /Organization\s*[:\n]\s*([^\n]+)/,
|
|
98
|
-
userType: /User type\s*[:\n]?\s*(Internal|External)/,
|
|
99
|
-
inProduction: /In production/,
|
|
100
|
-
clientNameLine: /^pi-dashboard(?:-(\d+))?[ \t]*$/gm,
|
|
101
|
-
} as const;
|
|
102
|
-
|
|
103
|
-
// ───────────────────────── timing ─────────────────────────
|
|
104
|
-
|
|
105
|
-
export interface Timing {
|
|
106
|
-
/** Poll interval for page and checkpoint waits. */
|
|
107
|
-
pollMs: number;
|
|
108
|
-
/** How long a step waits for an expected marker before `unexpected_page`. */
|
|
109
|
-
markerWaitMs: number;
|
|
110
|
-
/** How long `verify` polls for the result. */
|
|
111
|
-
verifyWaitMs: number;
|
|
112
|
-
/** Per-step limit; human waits are excluded. */
|
|
113
|
-
stepLimitMs: number;
|
|
114
|
-
/** Per-checkpoint limit. */
|
|
115
|
-
checkpointLimitMs: number;
|
|
116
|
-
/** Keep-alive command interval (the browser plugin's idle sweep is 5 min). */
|
|
117
|
-
keepAliveMs: number;
|
|
118
|
-
/** Polls the publish dialog may be gone before it counts as cancelled. */
|
|
119
|
-
publishGracePolls: number;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export const DEFAULT_TIMING: Timing = {
|
|
123
|
-
pollMs: 1000,
|
|
124
|
-
markerWaitMs: 10_000,
|
|
125
|
-
verifyWaitMs: 40_000,
|
|
126
|
-
stepLimitMs: 60_000,
|
|
127
|
-
checkpointLimitMs: 15 * 60_000,
|
|
128
|
-
keepAliveMs: 30_000,
|
|
129
|
-
publishGracePolls: 5,
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
// ───────────────────────── env contract ─────────────────────────
|
|
133
|
-
|
|
134
|
-
export interface StepFacts {
|
|
135
|
-
/** Parent organization of the project: name, `null` for none, undefined = not read yet. */
|
|
136
|
-
org?: string | null;
|
|
137
|
-
audience?: Audience;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** What the run provides to a step attempt. Every method refuses once the attempt is stale. */
|
|
141
|
-
export interface StepEnv {
|
|
142
|
-
readonly mode: "new" | "existing";
|
|
143
|
-
readonly projectId: string;
|
|
144
|
-
readonly ownerEmail: string;
|
|
145
|
-
readonly timing: Timing;
|
|
146
|
-
readonly facts: StepFacts;
|
|
147
|
-
readonly created: { projectId?: string; clients: string[] };
|
|
148
|
-
navigate(url: string): Promise<void>;
|
|
149
|
-
info(): Promise<PageInfo>;
|
|
150
|
-
text(): Promise<string>;
|
|
151
|
-
dialogText(): Promise<string>;
|
|
152
|
-
find(sel: Sel): Promise<AxNode | undefined>;
|
|
153
|
-
click(sel: Sel): Promise<void>;
|
|
154
|
-
fill(sel: Sel, text: string): Promise<void>;
|
|
155
|
-
bringToFront(): Promise<void>;
|
|
156
|
-
/** Poll `probe` every `pollMs` until truthy or `ms` elapsed (probe errors count as "not yet"). */
|
|
157
|
-
waitFor<T>(probe: () => Promise<T | false | undefined | null>, ms: number): Promise<T | undefined>;
|
|
158
|
-
/** Wait for `sel`; absent after `markerWaitMs` → handoff `unexpected_page`. */
|
|
159
|
-
need(sel: Sel): Promise<AxNode>;
|
|
160
|
-
/** Pause for the human until `until()` is true (15 min limit → handoff `timeout`). */
|
|
161
|
-
checkpoint(kind: CheckpointKind, until: () => Promise<boolean>, opts?: { front?: boolean }): Promise<void>;
|
|
162
|
-
/** Pause for a decision; the run validates the answer before resolving. */
|
|
163
|
-
decide(decision: SetupDecision): Promise<SetupContinueRequest>;
|
|
164
|
-
saveLinks(links: PublishLinks): Promise<void>;
|
|
165
|
-
downloadsDir(): Promise<string>;
|
|
166
|
-
storeClient(json: unknown): Promise<{ ok: true; clientId: string } | { ok: false; error: string }>;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
export interface StepDef {
|
|
170
|
-
id: SetupStepId;
|
|
171
|
-
/** True → step already done (reported `skipped`). */
|
|
172
|
-
check(env: StepEnv): Promise<boolean>;
|
|
173
|
-
act(env: StepEnv): Promise<void>;
|
|
174
|
-
/** False → handoff `unexpected_page`. */
|
|
175
|
-
verify(env: StepEnv): Promise<boolean>;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// ───────────────────────── pure helpers ─────────────────────────
|
|
179
|
-
|
|
180
|
-
/** `pi-dashboard-<6 random [a-z0-9]>` — passes the plugin's single project-id rule. */
|
|
181
|
-
export function generateProjectId(rand: (n: number) => number = randomInt): string {
|
|
182
|
-
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
183
|
-
let id = "";
|
|
184
|
-
for (let i = 0; i < 6; i++) id += alphabet[rand(alphabet.length)];
|
|
185
|
-
return `pi-dashboard-${id}`;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/** `pi-dashboard`, or `pi-dashboard-<n>` for the smallest free `n ≥ 2` (the bare name is n = 1). */
|
|
189
|
-
export function pickClientName(pageText: string): string {
|
|
190
|
-
const used = new Set<number>();
|
|
191
|
-
for (const m of pageText.matchAll(TEXT.clientNameLine)) used.add(m[1] ? Number(m[1]) : 1);
|
|
192
|
-
let n = 1;
|
|
193
|
-
while (used.has(n)) n++;
|
|
194
|
-
return n === 1 ? CLIENT_NAME : `${CLIENT_NAME}-${n}`;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
export function parseProjectFacts(text: string): { projectId?: string; org: string | null } {
|
|
198
|
-
const projectId = TEXT.projectId.exec(text)?.[1];
|
|
199
|
-
const org = TEXT.noOrganization.test(text) ? null : (TEXT.organization.exec(text)?.[1]?.trim() ?? null);
|
|
200
|
-
return { projectId, org };
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
export function parseUserType(text: string): Audience | undefined {
|
|
204
|
-
const m = TEXT.userType.exec(text)?.[1];
|
|
205
|
-
return m === "Internal" ? "internal" : m === "External" ? "external" : undefined;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const DOMAIN_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/;
|
|
209
|
-
|
|
210
|
-
/** Each link `https:` with its host equal to / under the authorized domain (design D7). Returns the first problem. */
|
|
211
|
-
export function validateLinks(links: unknown): { ok: true; links: PublishLinks } | { ok: false; error: string } {
|
|
212
|
-
if (!links || typeof links !== "object") return { ok: false, error: "links_required" };
|
|
213
|
-
const l = links as Record<string, unknown>;
|
|
214
|
-
if (typeof l.homePage !== "string" || typeof l.privacyPolicy !== "string" || typeof l.authorizedDomain !== "string") {
|
|
215
|
-
return { ok: false, error: "links_required" };
|
|
216
|
-
}
|
|
217
|
-
const domain = l.authorizedDomain.trim().toLowerCase();
|
|
218
|
-
if (!DOMAIN_RE.test(domain)) return { ok: false, error: "invalid_authorized_domain" };
|
|
219
|
-
for (const key of ["homePage", "privacyPolicy"] as const) {
|
|
220
|
-
let u: URL;
|
|
221
|
-
try {
|
|
222
|
-
u = new URL((l[key] as string).trim());
|
|
223
|
-
} catch {
|
|
224
|
-
return { ok: false, error: `invalid_${key}` };
|
|
225
|
-
}
|
|
226
|
-
const host = u.hostname.toLowerCase();
|
|
227
|
-
if (u.protocol !== "https:" || (host !== domain && !host.endsWith(`.${domain}`))) {
|
|
228
|
-
return { ok: false, error: `invalid_${key}` };
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
return {
|
|
232
|
-
ok: true,
|
|
233
|
-
links: { homePage: l.homePage.trim(), privacyPolicy: l.privacyPolicy.trim(), authorizedDomain: domain },
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** `/path` → console URL carrying `authuser`, `project` (unless suppressed) and `hl=en`. */
|
|
238
|
-
export function consoleUrl(env: Pick<StepEnv, "ownerEmail" | "projectId">, path: string, opts?: { noProject?: boolean }): string {
|
|
239
|
-
const q = new URLSearchParams({ authuser: env.ownerEmail });
|
|
240
|
-
if (!opts?.noProject) q.set("project", env.projectId);
|
|
241
|
-
q.set("hl", "en");
|
|
242
|
-
return `${CONSOLE_ORIGIN}${path}?${q.toString()}`;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// ───────────────────────── shared page actions ─────────────────────────
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Navigate, wait for load, enforce English and the console-terms checkpoint.
|
|
249
|
-
* A denied navigation is `domain_blocked` — unless the redirect guard stopped
|
|
250
|
-
* it, which is a sign-in.
|
|
251
|
-
*/
|
|
252
|
-
async function loadConsole(env: StepEnv, path: string, opts?: { noProject?: boolean }): Promise<void> {
|
|
253
|
-
try {
|
|
254
|
-
await env.navigate(consoleUrl(env, path, opts));
|
|
255
|
-
} catch (err) {
|
|
256
|
-
if (err instanceof NavigationError) throw new SetupHandoff("domain_blocked");
|
|
257
|
-
throw err;
|
|
258
|
-
}
|
|
259
|
-
const info = await env.waitFor(async () => {
|
|
260
|
-
const i = await env.info();
|
|
261
|
-
return i.ready === "complete" ? i : undefined;
|
|
262
|
-
}, env.timing.markerWaitMs);
|
|
263
|
-
if (!info) throw new SetupHandoff("unexpected_page");
|
|
264
|
-
if (info.lang && !/^en(-|$)/i.test(info.lang)) throw new SetupHandoff("locale");
|
|
265
|
-
if (await env.find(SEL.termsAgree)) await termsCheckpoint(env);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
async function termsCheckpoint(env: StepEnv): Promise<void> {
|
|
269
|
-
await env.checkpoint("console_terms", async () => !(await env.find(SEL.termsAgree)));
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/** Fill a labelled textbox. */
|
|
273
|
-
async function typeInto(env: StepEnv, sel: Sel, text: string): Promise<void> {
|
|
274
|
-
await env.need(sel);
|
|
275
|
-
await env.fill(sel, text);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// ───────────────────────── steps ─────────────────────────
|
|
279
|
-
|
|
280
|
-
async function readProject(env: StepEnv, waitMs: number): Promise<boolean> {
|
|
281
|
-
await loadConsole(env, PATHS.projectInfo);
|
|
282
|
-
const found = await env.waitFor(async () => {
|
|
283
|
-
const f = parseProjectFacts(await env.text());
|
|
284
|
-
return f.projectId ? f : undefined;
|
|
285
|
-
}, waitMs);
|
|
286
|
-
if (found?.projectId !== env.projectId) return false;
|
|
287
|
-
env.facts.org = found.org;
|
|
288
|
-
return true;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
const projectStep: StepDef = {
|
|
292
|
-
id: "project",
|
|
293
|
-
async check(env) {
|
|
294
|
-
const done = await readProject(env, env.timing.markerWaitMs);
|
|
295
|
-
// An existing project the console does not show is not something to create.
|
|
296
|
-
if (!done && env.mode === "existing") throw new SetupHandoff("unexpected_page");
|
|
297
|
-
return done;
|
|
298
|
-
},
|
|
299
|
-
async act(env) {
|
|
300
|
-
await loadConsole(env, PATHS.projectCreate, { noProject: true });
|
|
301
|
-
await typeInto(env, SEL.projectName, CLIENT_NAME);
|
|
302
|
-
await env.click(SEL.projectIdEdit);
|
|
303
|
-
await typeInto(env, SEL.projectIdField, env.projectId);
|
|
304
|
-
await env.click(SEL.create);
|
|
305
|
-
env.created.projectId = env.projectId;
|
|
306
|
-
},
|
|
307
|
-
verify: (env) => pollVerify(env, () => readProject(env, env.timing.pollMs)),
|
|
308
|
-
};
|
|
309
|
-
|
|
310
|
-
/** Poll `probe` for `verifyWaitMs`. */
|
|
311
|
-
async function pollVerify(env: StepEnv, probe: () => Promise<boolean>): Promise<boolean> {
|
|
312
|
-
return Boolean(await env.waitFor(async () => (await probe()) || undefined, env.timing.verifyWaitMs));
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const apiStep: StepDef = {
|
|
316
|
-
id: "api",
|
|
317
|
-
async check(env) {
|
|
318
|
-
await loadConsole(env, PATHS.apiOverview);
|
|
319
|
-
const state = await env.waitFor(async () => {
|
|
320
|
-
if (await env.find(SEL.disableApi)) return "done" as const;
|
|
321
|
-
if (await env.find(SEL.enableApi)) return "todo" as const;
|
|
322
|
-
return undefined;
|
|
323
|
-
}, env.timing.markerWaitMs);
|
|
324
|
-
if (!state) throw new SetupHandoff("unexpected_page");
|
|
325
|
-
return state === "done";
|
|
326
|
-
},
|
|
327
|
-
async act(env) {
|
|
328
|
-
await env.click(SEL.enableApi);
|
|
329
|
-
},
|
|
330
|
-
verify: (env) =>
|
|
331
|
-
pollVerify(env, async () => {
|
|
332
|
-
await loadConsole(env, PATHS.apiOverview);
|
|
333
|
-
return Boolean(await env.find(SEL.disableApi));
|
|
334
|
-
}),
|
|
335
|
-
};
|
|
336
|
-
|
|
337
|
-
const brandingStep: StepDef = {
|
|
338
|
-
id: "branding",
|
|
339
|
-
async check(env) {
|
|
340
|
-
await loadConsole(env, PATHS.audience);
|
|
341
|
-
const state = await env.waitFor(async () => {
|
|
342
|
-
const type = parseUserType(await env.text());
|
|
343
|
-
if (type) return { type };
|
|
344
|
-
if (await env.find(SEL.getStarted)) return { type: undefined };
|
|
345
|
-
return undefined;
|
|
346
|
-
}, env.timing.markerWaitMs);
|
|
347
|
-
if (!state) throw new SetupHandoff("unexpected_page");
|
|
348
|
-
if (state.type) env.facts.audience = state.type;
|
|
349
|
-
return state.type !== undefined;
|
|
350
|
-
},
|
|
351
|
-
async act(env) {
|
|
352
|
-
const detected: Audience = env.facts.org ? "internal" : "external";
|
|
353
|
-
const answer = await env.decide({ kind: "audience", detected, ...(env.facts.org ? { org: env.facts.org } : {}) });
|
|
354
|
-
const audience: Audience = answer.audience === "internal" ? "internal" : "external";
|
|
355
|
-
await loadConsole(env, PATHS.brandingCreate);
|
|
356
|
-
// 4-step form: app information → audience → contact → finish.
|
|
357
|
-
await typeInto(env, SEL.appName, CLIENT_NAME);
|
|
358
|
-
await env.click(SEL.supportEmail);
|
|
359
|
-
await env.click({ role: "option", name: env.ownerEmail });
|
|
360
|
-
await env.click(SEL.next);
|
|
361
|
-
await env.click(audience === "internal" ? SEL.audienceInternal : SEL.audienceExternal);
|
|
362
|
-
await env.click(SEL.next);
|
|
363
|
-
await typeInto(env, SEL.contactEmail, env.ownerEmail);
|
|
364
|
-
await env.click(SEL.next);
|
|
365
|
-
// The User Data Policy box is the user's own click; the run only waits for it.
|
|
366
|
-
await env.need(SEL.policyCheckbox);
|
|
367
|
-
await env.checkpoint("policy", async () => (await env.find(SEL.policyCheckbox))?.checked === true, { front: true });
|
|
368
|
-
await env.click(SEL.continue);
|
|
369
|
-
await env.click(SEL.create);
|
|
370
|
-
env.facts.audience = audience;
|
|
371
|
-
},
|
|
372
|
-
verify: (env) =>
|
|
373
|
-
pollVerify(env, async () => {
|
|
374
|
-
await loadConsole(env, PATHS.audience);
|
|
375
|
-
return parseUserType(await env.text()) === env.facts.audience;
|
|
376
|
-
}),
|
|
377
|
-
};
|
|
378
|
-
|
|
379
|
-
async function inProduction(env: StepEnv): Promise<boolean> {
|
|
380
|
-
return TEXT.inProduction.test(await env.text());
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
const publishStep: StepDef = {
|
|
384
|
-
id: "publish",
|
|
385
|
-
async check(env) {
|
|
386
|
-
// Internal apps are not published.
|
|
387
|
-
if (env.facts.audience === "internal") return true;
|
|
388
|
-
await loadConsole(env, PATHS.audience);
|
|
389
|
-
const state = await env.waitFor(async () => {
|
|
390
|
-
if (await inProduction(env)) return "done" as const;
|
|
391
|
-
if (await env.find(SEL.publishApp)) return "todo" as const;
|
|
392
|
-
return undefined;
|
|
393
|
-
}, env.timing.markerWaitMs);
|
|
394
|
-
if (!state) throw new SetupHandoff("unexpected_page");
|
|
395
|
-
return state === "done";
|
|
396
|
-
},
|
|
397
|
-
async act(env) {
|
|
398
|
-
const answer = await env.decide({ kind: "links", links: { ...DEFAULT_PUBLISH_LINKS } });
|
|
399
|
-
const links = answer.links ?? DEFAULT_PUBLISH_LINKS;
|
|
400
|
-
await env.saveLinks(links);
|
|
401
|
-
await loadConsole(env, PATHS.branding);
|
|
402
|
-
await typeInto(env, SEL.homePage, links.homePage);
|
|
403
|
-
await typeInto(env, SEL.privacyPolicy, links.privacyPolicy);
|
|
404
|
-
await env.click(SEL.addDomain);
|
|
405
|
-
await typeInto(env, SEL.authorizedDomain, links.authorizedDomain);
|
|
406
|
-
await env.click(SEL.save);
|
|
407
|
-
await loadConsole(env, PATHS.audience);
|
|
408
|
-
await env.click(SEL.publishApp);
|
|
409
|
-
// "Push to production?" is the user's confirmation; a cancelled dialog ends the run.
|
|
410
|
-
await env.need(SEL.publishDialog);
|
|
411
|
-
let gone = 0;
|
|
412
|
-
await env.checkpoint("publish", async () => {
|
|
413
|
-
if (await inProduction(env)) return true;
|
|
414
|
-
if (await env.find(SEL.publishDialog)) {
|
|
415
|
-
gone = 0;
|
|
416
|
-
return false;
|
|
417
|
-
}
|
|
418
|
-
if (++gone >= env.timing.publishGracePolls) throw new SetupHandoff("publish_cancelled");
|
|
419
|
-
return false;
|
|
420
|
-
});
|
|
421
|
-
},
|
|
422
|
-
verify: (env) =>
|
|
423
|
-
pollVerify(env, async () => {
|
|
424
|
-
await loadConsole(env, PATHS.audience);
|
|
425
|
-
return inProduction(env);
|
|
426
|
-
}),
|
|
427
|
-
};
|
|
428
|
-
|
|
429
|
-
const clientStep: StepDef = {
|
|
430
|
-
id: "client",
|
|
431
|
-
// An earlier client's secret is unrecoverable: never "done".
|
|
432
|
-
check: async () => false,
|
|
433
|
-
async act(env) {
|
|
434
|
-
await loadConsole(env, PATHS.clients);
|
|
435
|
-
await env.need(SEL.createClient);
|
|
436
|
-
const name = pickClientName(await env.text());
|
|
437
|
-
await loadConsole(env, PATHS.clientCreate);
|
|
438
|
-
await env.click(SEL.appType);
|
|
439
|
-
await env.click(SEL.desktopApp);
|
|
440
|
-
await typeInto(env, SEL.clientName, name);
|
|
441
|
-
await env.click(SEL.create);
|
|
442
|
-
env.created.clients.push(name);
|
|
443
|
-
},
|
|
444
|
-
verify: (env) =>
|
|
445
|
-
pollVerify(env, async () => Boolean(await env.find(SEL.clientCreatedDialog))),
|
|
446
|
-
};
|
|
447
|
-
|
|
448
|
-
/** `capture` (fs + store) is injected by the run, so this module has no import cycle with `capture.ts`. */
|
|
449
|
-
export function buildSteps(capture: (env: StepEnv) => Promise<void>): readonly StepDef[] {
|
|
450
|
-
const captureStep: StepDef = {
|
|
451
|
-
id: "capture",
|
|
452
|
-
check: async () => false,
|
|
453
|
-
act: capture,
|
|
454
|
-
// `capture` throws unless the client was stored.
|
|
455
|
-
verify: async () => true,
|
|
456
|
-
};
|
|
457
|
-
return [projectStep, apiStep, brandingStep, publishStep, clientStep, captureStep];
|
|
458
|
-
}
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The ONE write path for the OAuth client, shared by `PUT /client` and the
|
|
3
|
-
* automatic setup's capture: same validation (`validateClientJson`) and the same
|
|
4
|
-
* `client_in_use` rule. Never returns or logs the secret.
|
|
5
|
-
* See change: add-gmail-auto-setup.
|
|
6
|
-
*/
|
|
7
|
-
import { validateClientJson } from "../shared/client-json.js";
|
|
8
|
-
import type { AccountStore, ClientRecord } from "./accounts.js";
|
|
9
|
-
|
|
10
|
-
export type StoreClientResult =
|
|
11
|
-
| { ok: true; client: ClientRecord }
|
|
12
|
-
| { ok: false; status: 400 | 409; error: string; step?: number };
|
|
13
|
-
|
|
14
|
-
export async function storeClient(
|
|
15
|
-
store: AccountStore,
|
|
16
|
-
input: unknown,
|
|
17
|
-
logger: { info(m: string): void },
|
|
18
|
-
): Promise<StoreClientResult> {
|
|
19
|
-
const result = validateClientJson(input as Parameters<typeof validateClientJson>[0]);
|
|
20
|
-
if (!result.ok) return { ok: false, status: 400, error: result.error.code, step: result.error.step };
|
|
21
|
-
// Refresh tokens are bound to the client that minted them: swapping the
|
|
22
|
-
// client under connected accounts would break every refresh silently.
|
|
23
|
-
const current = await store.getClient();
|
|
24
|
-
const changed =
|
|
25
|
-
current && (current.clientId !== result.client.clientId || current.clientSecret !== result.client.clientSecret);
|
|
26
|
-
if (changed && (await store.list()).length > 0) return { ok: false, status: 409, error: "client_in_use", step: 5 };
|
|
27
|
-
await store.setClient(result.client);
|
|
28
|
-
logger.info("[gmail] oauth client configured");
|
|
29
|
-
return { ok: true, client: result.client };
|
|
30
|
-
}
|