inistate-mcp 1.0.2 → 1.1.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 CHANGED
@@ -10,6 +10,8 @@ MCP server for the [Inistate](https://inistate.com) platform — module discover
10
10
  |----------|----------|---------|-------------|
11
11
  | `INISTATE_API_TOKEN` | Yes | — | Bearer token for Inistate API authentication |
12
12
  | `INISTATE_API_BASE` | No | `https://api.inistate.com` | API base URL |
13
+ | `INISTATE_MCP_MODE` | No | `configure` | Initial mode: `runtime`, `configure`, or `frontend` (see [Modes](#modes)) |
14
+ | `INISTATE_MCP_NO_SETUP` | No | — | Set to `1` to force server mode from a terminal (skip the interactive wizard) |
13
15
 
14
16
  ### Install from npm (recommended)
15
17
 
@@ -77,24 +79,30 @@ Then point your MCP client at `node /absolute/path/to/inistate-mcp/build/index.j
77
79
 
78
80
  ## Tools
79
81
 
82
+ Tools marked **(configure)** are only exposed in configure mode — see [Modes](#modes).
83
+
80
84
  | Tool | Description |
81
85
  |------|-------------|
82
86
  | `list_workspaces` | List workspaces the user has access to |
83
87
  | `set_workspace` | Set the active workspace |
84
88
  | `list_modules` | List all discoverable modules in the workspace |
85
- | `get_module_schema` | Get the canvas schema (basic or extended tier) |
86
- | `get_module_canvas` | Get full module definition with stable IDs (round-trippable) |
89
+ | `get_module_schema` | Get the canvas schema (basic or extended tier) **(configure)** |
90
+ | `get_module_canvas` | Get full module definition with stable IDs (round-trippable) **(configure)** |
87
91
  | `list_entries` | Query entries with filters, sorting, and pagination |
88
92
  | `get_entry` | Read a single entry by ID |
89
93
  | `get_form` | Get form fields and defaults for an activity |
90
94
  | `submit_activity` | Create, edit, delete, or run custom activities |
95
+ | `submit_activities` | Bulk variant — same activity applied to up to 100 entries in one call |
91
96
  | `get_entry_history` | Get entry audit trail and comments |
92
- | `upload_file` | Upload a file to S3 storage |
97
+ | `request_upload_url` | Default upload path — get a presigned S3 URL to PUT file bytes to |
98
+ | `confirm_upload` | Confirm a presigned upload completed; returns the File/Image field path |
99
+ | `upload_file` | Fallback upload via base64/multipart (use only if the presigned flow fails) |
93
100
  | `download_file` | Download a file (returns pre-signed URL) |
94
- | `design_workflow` | Generate a scaffolded module template from a description |
95
- | `validate_design` | Validate a module schema before creating or updating |
96
- | `create_module` | Create a new module with schema |
97
- | `update_module` | Update an existing module's schema |
101
+ | `design_workflow` | Generate a scaffolded module template from a description **(configure)** |
102
+ | `validate_design` | Validate a module schema before creating or updating **(configure)** |
103
+ | `create_module` | Create a new module with schema **(configure)** |
104
+ | `update_module` | Update an existing module's schema **(configure)** |
105
+ | `switch_mode` | Switch the active mode (runtime / configure / frontend) |
98
106
 
99
107
  ## Resources
100
108
 
@@ -103,16 +111,32 @@ Then point your MCP client at `node /absolute/path/to/inistate-mcp/build/index.j
103
111
  | `inistate://modules` | List all modules |
104
112
  | `inistate://modules/{name}/canvas` | Basic module schema (fields + states) |
105
113
  | `inistate://modules/{name}/canvas/extended` | Extended schema with activities and flows |
106
- | `inistate://schema` | FACTSOps schema definition (field types, colors, validation rules) |
107
- | `inistate://design-guide` | FACTS Module Design Guide |
114
+ | `inistate://guardrails` | Server-enforced `submit_activity` rules (read once per session) |
115
+ | `inistate://schema/runtime` | Runtime schema — entry/activity/file types and filter operators (default) |
116
+ | `inistate://schema/configure` | Module-design schema — write format, field types, colors **(configure)** |
117
+ | `inistate://design-guide` | FACTS Module Design Guide **(configure)** |
118
+ | `inistate://frontend-guide` | REST API reference for hand-written UIs **(frontend)** |
108
119
 
109
120
  ## Prompts
110
121
 
111
122
  | Prompt | Description |
112
123
  |--------|-------------|
113
- | `design_factsops_workflow` | Guide an agent through designing a complete workflow module |
124
+ | `design_factsops_workflow` | Guide an agent through designing a complete workflow module **(configure)** |
114
125
  | `execute_activity` | Guide an agent through executing a specific activity |
115
126
  | `diagnose_entry` | Guide an agent through investigating an entry's state and history |
127
+ | `modify_module` | Guide an agent through modifying an existing module's schema **(configure)** |
128
+
129
+ ## Modes
130
+
131
+ The server exposes a focused tool/resource surface depending on the active mode, keeping agent context lean. Use `switch_mode` to change it, or set the initial mode via the `INISTATE_MCP_MODE` env var (default: `configure`).
132
+
133
+ | Mode | Surface |
134
+ |------|---------|
135
+ | `runtime` | Entry and activity operations only — querying, reading, submitting, files, history. The leanest surface for using existing modules. |
136
+ | `configure` | Everything in `runtime` plus the module-design tools, resources, and prompts (marked **(configure)** above). |
137
+ | `frontend` | Everything in `configure` plus the `inistate://frontend-guide` resource for building hand-written UIs against the REST API. |
138
+
139
+ Tools and resources marked **(configure)** / **(frontend)** are absent from the tool list in narrower modes — switch modes to reveal them.
116
140
 
117
141
  ## Typical Workflow
118
142
 
@@ -131,57 +155,6 @@ npm run watch # Watch mode for TypeScript compilation
131
155
  npm run inspector # Test with MCP Inspector
132
156
  ```
133
157
 
134
- ### MCP Setup
135
- 1. Setup
136
- ```bash
137
- curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher && sudo mv mcp-publisher /usr/local/bin/
138
- ```
139
-
140
- or
141
-
142
- ```powershell
143
- $arch = if ([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq "Arm64") { "arm64" } else { "amd64" }; Invoke-WebRequest -Uri "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_windows_$arch.tar.gz" -OutFile "mcp-publisher.tar.gz"; tar xf mcp-publisher.tar.gz mcp-publisher.exe; rm mcp-publisher.tar.gz
144
-
145
- ```
146
-
147
- 2. Verify
148
- ```
149
- mcp-publisher --help
150
- ```
151
-
152
- 3. Authenticate
153
- ```
154
- mcp-publisher login github
155
- ```
156
-
157
- 4. Publish: see below
158
-
159
- ### Packaging & Versioning
160
- ```bash
161
- # Example adding new feature
162
- git checkout -b feat/add-user-tool
163
-
164
-
165
- # After coding
166
- npx changeset
167
-
168
- # Choose:
169
- #
170
- # minor
171
- # Added new user search tool
172
-
173
- # Release
174
- npm run release
175
-
176
- # This does:
177
- # build
178
- # test
179
- # bump version
180
- # update changelog
181
- # sync server.json
182
- # publish npm
183
- ```
184
-
185
158
  ## PM2 (Ubuntu/AWS)
186
159
 
187
160
  Run the HTTP transport in production using PM2:
@@ -230,8 +203,11 @@ Tests are in `src/` alongside the source files and use [Vitest](https://vitest.d
230
203
 
231
204
  | File | Type | What it covers |
232
205
  |------|------|----------------|
233
- | `src/schema.test.ts` | Unit tests (50) | `designWorkflow`, `validateDesign`, helper functions (`isValidFieldType`, `isValidColor`, `isValidActor`, `suggestColorForState`) |
234
- | `src/server.test.ts` | Integration tests (14) | Spins up the MCP server as a child process and exercises it through the official MCP SDK client — tool discovery, resource reads, prompt retrieval, and local tool calls |
206
+ | `src/schema.test.ts` | Unit tests (41) | `designWorkflow`, `validateDesign`, helper functions (`isValidFieldType`, `isValidColor`, `isValidActor`, `suggestColorForState`) |
207
+ | `src/activity-guard.test.ts` | Unit tests (35) | `submit_activity` guard rules — human/hybrid actor, state-change confirmation, confidence-inflation, reference-shape validation |
208
+ | `src/tools.schema.test.ts` | Unit tests (19) | Tool input-schema shapes and validation |
209
+ | `src/backend-capabilities.test.ts` | Unit tests (6) | Capability gating — Platform-only tools return a capability message on reduced backends |
210
+ | `src/server.test.ts` | Integration tests (15) | Spins up the MCP server as a child process and exercises it through the official MCP SDK client — mode-gated tool/resource/prompt discovery, `switch_mode`, resource reads, prompt retrieval, and local tool calls |
235
211
 
236
212
  Unit tests cover:
237
213
  - Field type and color validation against the schema
@@ -241,10 +217,10 @@ Unit tests cover:
241
217
  - Intent resolution: all 5 modes, context boosting, confidence scoring
242
218
 
243
219
  Integration tests verify (no API token needed):
244
- - All 17 tools, 5 resources, and 3 prompts are registered
220
+ - All 20 tools, 8 resources, and 4 prompts are registered (in configure mode)
245
221
  - `design_workflow`, `validate_design` work end-to-end through the MCP protocol
246
- - Static resources (`inistate://schema`, `inistate://design-guide`) return valid content
247
- - All 3 prompts return correctly templated messages
222
+ - Static resources (`inistate://schema/runtime`, `inistate://design-guide`) return valid content
223
+ - All 4 prompts return correctly templated messages
248
224
 
249
225
  ### Interactive testing with MCP Inspector
250
226
 
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Pre-submission gate for `submit_activity`. Enforces four rules the platform
3
+ * does not enforce server-side:
4
+ *
5
+ * 1. Confidence inflation: once an activity has been flagged for human review
6
+ * (`flagged: true`), refuse subsequent submissions on the same target with
7
+ * a higher confidence unless the caller passes `confirmed: true`.
8
+ * 2. Explicit state changes (`changeStatus` activity, or an overriding `state`
9
+ * parameter) require `confirmed: true`.
10
+ * 3. Activities whose `actor` is `human` are never executable by an AI agent.
11
+ * 4. Activities whose `actor` is `hybrid` require `confirmed: true`.
12
+ */
13
+ interface ActivityDef {
14
+ name: string;
15
+ actor?: string;
16
+ }
17
+ interface FieldInfo {
18
+ name: string;
19
+ type: string;
20
+ }
21
+ interface ExtendedSchema {
22
+ activities?: ActivityDef[];
23
+ information?: FieldInfo[];
24
+ }
25
+ /**
26
+ * Source of a module's extended schema. Defaults to the cloud API; the MCP tool
27
+ * handlers pass a backend-routed fetcher so the same guard runs against whatever
28
+ * backend is injected (cloud or local) instead of always hitting api.ts.
29
+ */
30
+ export type SchemaFetcher = (moduleName: string) => Promise<ExtendedSchema | null>;
31
+ interface FlaggedRecord {
32
+ confidence: number;
33
+ at: number;
34
+ }
35
+ export declare function recordFlagged(moduleName: string, entryId: unknown, activity: string, confidence: number): void;
36
+ export declare function clearFlagged(moduleName: string, entryId: unknown, activity: string): void;
37
+ export declare function getPriorFlag(moduleName: string, entryId: unknown, activity: string): FlaggedRecord | undefined;
38
+ export interface GuardInput {
39
+ module: string;
40
+ activity: string;
41
+ entryId?: string | number;
42
+ entryIds?: Array<string | number>;
43
+ state?: string;
44
+ confidence: number;
45
+ confirmed?: boolean;
46
+ }
47
+ export type GuardOutcome = {
48
+ ok: true;
49
+ } | {
50
+ ok: false;
51
+ structured: Record<string, unknown>;
52
+ };
53
+ export declare function evaluateActivity(input: GuardInput, fetchSchema?: SchemaFetcher): Promise<GuardOutcome>;
54
+ export interface RefShapeError {
55
+ field: string;
56
+ type: string;
57
+ message: string;
58
+ received: unknown;
59
+ }
60
+ /**
61
+ * Build a field-name → field-type map for a module. Returns null when the
62
+ * schema cannot be loaded (callers should let the server decide). The
63
+ * underlying schema is cached by getExtendedSchema, so repeat calls are cheap.
64
+ *
65
+ * Split out so bulk callers (submit_activities) can fetch once and reuse the
66
+ * map across items via validateInputShapesWith.
67
+ */
68
+ export declare function getModuleFieldTypes(moduleName: string, fetchSchema?: SchemaFetcher): Promise<Map<string, string> | null>;
69
+ /**
70
+ * Synchronous shape check against a pre-built field-type map. Use this in
71
+ * bulk loops to avoid rebuilding the map per item. When `types` is null
72
+ * (schema unavailable), returns [] so the server makes the final call.
73
+ */
74
+ export declare function validateInputShapesWith(types: Map<string, string> | null, input: Record<string, unknown> | undefined | null): RefShapeError[];
75
+ /**
76
+ * Validate that User/Module/Users/Modules fields in `input` carry the
77
+ * correct shape. Convenience wrapper around getModuleFieldTypes +
78
+ * validateInputShapesWith — use this for one-shot calls (submit_activity).
79
+ * Bulk callers should fetch the map once and use validateInputShapesWith
80
+ * directly.
81
+ */
82
+ export declare function validateInputShapes(moduleName: string, input: Record<string, unknown> | undefined | null, fetchSchema?: SchemaFetcher): Promise<RefShapeError[]>;
83
+ export declare function __resetGuardCaches(): void;
84
+ export {};
@@ -21,23 +21,27 @@ function cacheKey(prefix, parts) {
21
21
  const user = ctx?.userId || "_";
22
22
  return [prefix, user, wsid, ...parts.map((p) => String(p ?? "_"))].join("::");
23
23
  }
24
- async function getExtendedSchema(moduleName) {
24
+ const defaultSchemaFetcher = async (moduleName) => {
25
+ try {
26
+ return (await api.get(`/api/mcp/${api.enc(moduleName)}?tier=extended`));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ };
32
+ async function getExtendedSchema(moduleName, fetchSchema = defaultSchemaFetcher) {
25
33
  const key = cacheKey("schema", [moduleName]);
26
34
  const now = Date.now();
27
35
  const cached = schemaCache.get(key);
28
36
  if (cached && now - cached.at < SCHEMA_TTL_MS)
29
37
  return cached.schema;
30
- try {
31
- const schema = (await api.get(`/api/mcp/${api.enc(moduleName)}?tier=extended`));
38
+ const schema = await fetchSchema(moduleName);
39
+ if (schema)
32
40
  schemaCache.set(key, { schema, at: now });
33
- return schema;
34
- }
35
- catch {
36
- return null;
37
- }
41
+ return schema;
38
42
  }
39
- async function getActivityDef(moduleName, activity) {
40
- const schema = await getExtendedSchema(moduleName);
43
+ async function getActivityDef(moduleName, activity, fetchSchema = defaultSchemaFetcher) {
44
+ const schema = await getExtendedSchema(moduleName, fetchSchema);
41
45
  return schema?.activities?.find((a) => a.name === activity) ?? null;
42
46
  }
43
47
  const FLAG_TTL_MS = 60 * 60 * 1000;
@@ -62,7 +66,7 @@ export function getPriorFlag(moduleName, entryId, activity) {
62
66
  }
63
67
  return rec;
64
68
  }
65
- export async function evaluateActivity(input) {
69
+ export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher) {
66
70
  const { module: moduleName, activity, entryId, entryIds, state, confidence, confirmed } = input;
67
71
  // Rule 1 — confidence inflation after a prior flag.
68
72
  const targets = entryIds && entryIds.length > 0 ? entryIds : [entryId];
@@ -111,7 +115,7 @@ export async function evaluateActivity(input) {
111
115
  // Rules 3 & 4 apply to custom (workflow-defined) activities only.
112
116
  if (STANDARD_ACTIVITIES.has(activity))
113
117
  return { ok: true };
114
- const def = await getActivityDef(moduleName, activity);
118
+ const def = await getActivityDef(moduleName, activity, fetchSchema);
115
119
  if (!def)
116
120
  return { ok: true }; // unknown activity — let the API decide.
117
121
  const actor = (def.actor || "").toLowerCase();
@@ -210,8 +214,8 @@ function checkRefValue(field, type, value) {
210
214
  * Split out so bulk callers (submit_activities) can fetch once and reuse the
211
215
  * map across items via validateInputShapesWith.
212
216
  */
213
- export async function getModuleFieldTypes(moduleName) {
214
- const schema = await getExtendedSchema(moduleName);
217
+ export async function getModuleFieldTypes(moduleName, fetchSchema = defaultSchemaFetcher) {
218
+ const schema = await getExtendedSchema(moduleName, fetchSchema);
215
219
  const info = schema?.information;
216
220
  if (!info || info.length === 0)
217
221
  return null;
@@ -248,10 +252,10 @@ export function validateInputShapesWith(types, input) {
248
252
  * Bulk callers should fetch the map once and use validateInputShapesWith
249
253
  * directly.
250
254
  */
251
- export async function validateInputShapes(moduleName, input) {
255
+ export async function validateInputShapes(moduleName, input, fetchSchema = defaultSchemaFetcher) {
252
256
  if (!input)
253
257
  return [];
254
- const types = await getModuleFieldTypes(moduleName);
258
+ const types = await getModuleFieldTypes(moduleName, fetchSchema);
255
259
  return validateInputShapesWith(types, input);
256
260
  }
257
261
  // Test-only helpers.
package/build/api.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ export declare function setWorkspaceId(wsid: string): void;
2
+ export declare function getWorkspaceId(): string | null;
3
+ export declare function get(path: string): Promise<unknown>;
4
+ export declare function post(path: string, body?: unknown): Promise<unknown>;
5
+ export declare function put(path: string, body?: unknown): Promise<unknown>;
6
+ /**
7
+ * Upload a file via multipart/form-data.
8
+ */
9
+ export declare function uploadFormData(path: string, formData: FormData): Promise<unknown>;
10
+ /**
11
+ * GET with manual redirect for download_file — returns redirect URL instead of following.
12
+ */
13
+ export declare function getRaw(path: string): Promise<{
14
+ redirectUrl: string | null;
15
+ status: number;
16
+ body: unknown;
17
+ }>;
18
+ export declare function enc(s: string): string;
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Returns an HTML login page for the OAuth authorize flow.
3
+ *
4
+ * The page handles three auth methods:
5
+ * 1. Username/password — form POST to /auth/token
6
+ * 2. Google Sign-In — Google Identity Services popup
7
+ * 3. Apple Sign-In — (placeholder for future)
8
+ *
9
+ * After successful login, the page POSTs the JWT to /authorize/callback
10
+ * which completes the OAuth code flow and redirects back to the MCP client.
11
+ */
12
+ export function getAuthorizePage(params) {
13
+ return `<!DOCTYPE html>
14
+ <html lang="en">
15
+ <head>
16
+ <meta charset="utf-8">
17
+ <meta name="viewport" content="width=device-width, initial-scale=1">
18
+ <title>Sign in to Inistate</title>
19
+ <script src="https://accounts.google.com/gsi/client" async></script>
20
+ <style>
21
+ * { box-sizing: border-box; margin: 0; padding: 0; }
22
+ body {
23
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
24
+ background: #f5f5f5;
25
+ display: flex;
26
+ align-items: center;
27
+ justify-content: center;
28
+ min-height: 100vh;
29
+ color: #333;
30
+ }
31
+ .card {
32
+ background: #fff;
33
+ border-radius: 12px;
34
+ box-shadow: 0 2px 16px rgba(0,0,0,0.1);
35
+ padding: 40px;
36
+ width: 100%;
37
+ max-width: 400px;
38
+ }
39
+ h1 {
40
+ font-size: 22px;
41
+ font-weight: 600;
42
+ text-align: center;
43
+ margin-bottom: 8px;
44
+ }
45
+ .subtitle {
46
+ text-align: center;
47
+ color: #666;
48
+ font-size: 14px;
49
+ margin-bottom: 24px;
50
+ }
51
+ .divider {
52
+ display: flex;
53
+ align-items: center;
54
+ margin: 20px 0;
55
+ color: #aaa;
56
+ font-size: 13px;
57
+ }
58
+ .divider::before, .divider::after {
59
+ content: "";
60
+ flex: 1;
61
+ border-bottom: 1px solid #ddd;
62
+ }
63
+ .divider::before { margin-right: 12px; }
64
+ .divider::after { margin-left: 12px; }
65
+ label {
66
+ display: block;
67
+ font-size: 14px;
68
+ font-weight: 500;
69
+ margin-bottom: 4px;
70
+ color: #555;
71
+ }
72
+ input[type="email"], input[type="password"] {
73
+ width: 100%;
74
+ padding: 10px 12px;
75
+ border: 1px solid #ddd;
76
+ border-radius: 8px;
77
+ font-size: 15px;
78
+ margin-bottom: 14px;
79
+ outline: none;
80
+ transition: border-color 0.2s;
81
+ }
82
+ input:focus { border-color: #4285f4; }
83
+ .btn {
84
+ width: 100%;
85
+ padding: 11px;
86
+ border: none;
87
+ border-radius: 8px;
88
+ font-size: 15px;
89
+ font-weight: 600;
90
+ cursor: pointer;
91
+ transition: background 0.2s;
92
+ }
93
+ .btn-primary {
94
+ background: #4285f4;
95
+ color: #fff;
96
+ }
97
+ .btn-primary:hover { background: #3367d6; }
98
+ .btn-primary:disabled {
99
+ background: #a4c2f4;
100
+ cursor: not-allowed;
101
+ }
102
+ #google-btn {
103
+ display: flex;
104
+ justify-content: center;
105
+ margin-bottom: 8px;
106
+ }
107
+ .error {
108
+ background: #fdecea;
109
+ color: #c62828;
110
+ padding: 10px;
111
+ border-radius: 8px;
112
+ font-size: 14px;
113
+ margin-bottom: 14px;
114
+ display: none;
115
+ }
116
+ .spinner {
117
+ display: inline-block;
118
+ width: 16px;
119
+ height: 16px;
120
+ border: 2px solid #fff;
121
+ border-top-color: transparent;
122
+ border-radius: 50%;
123
+ animation: spin 0.6s linear infinite;
124
+ margin-right: 8px;
125
+ vertical-align: middle;
126
+ }
127
+ @keyframes spin { to { transform: rotate(360deg); } }
128
+ </style>
129
+ </head>
130
+ <body>
131
+ <div class="card">
132
+ <h1>Sign in to Inistate</h1>
133
+ <p class="subtitle">Connect your account to continue</p>
134
+
135
+ <div id="google-btn"></div>
136
+
137
+ <div class="divider">or sign in with email</div>
138
+
139
+ <div id="error" class="error"></div>
140
+
141
+ <form id="login-form" onsubmit="return handleLogin(event)">
142
+ <label for="email">Email</label>
143
+ <input type="email" id="email" name="email" required autocomplete="email" placeholder="you@example.com">
144
+
145
+ <label for="password">Password</label>
146
+ <input type="password" id="password" name="password" required autocomplete="current-password" placeholder="Your password">
147
+
148
+ <button type="submit" class="btn btn-primary" id="submit-btn">Sign in</button>
149
+ </form>
150
+ </div>
151
+
152
+ <!-- Hidden form to POST result back to server -->
153
+ <form id="callback-form" method="POST" action="/authorize/callback" style="display:none">
154
+ <input type="hidden" name="nonce" value="${params.nonce}">
155
+ <input type="hidden" name="jwt" id="cb-jwt">
156
+ <input type="hidden" name="refreshToken" id="cb-refresh">
157
+ </form>
158
+
159
+ <script>
160
+ const NONCE = "${params.nonce}";
161
+
162
+ function showError(msg) {
163
+ const el = document.getElementById("error");
164
+ el.textContent = msg;
165
+ el.style.display = "block";
166
+ }
167
+
168
+ function setLoading(loading) {
169
+ const btn = document.getElementById("submit-btn");
170
+ btn.disabled = loading;
171
+ btn.innerHTML = loading
172
+ ? '<span class="spinner"></span>Signing in...'
173
+ : "Sign in";
174
+ }
175
+
176
+ function completeAuth(token, refreshToken) {
177
+ document.getElementById("cb-jwt").value = token;
178
+ document.getElementById("cb-refresh").value = refreshToken || "";
179
+ document.getElementById("callback-form").submit();
180
+ }
181
+
182
+ async function handleLogin(e) {
183
+ e.preventDefault();
184
+ const email = document.getElementById("email").value;
185
+ const password = document.getElementById("password").value;
186
+ document.getElementById("error").style.display = "none";
187
+ setLoading(true);
188
+
189
+ try {
190
+ const res = await fetch("/auth/token", {
191
+ method: "POST",
192
+ headers: { "Content-Type": "application/json" },
193
+ body: JSON.stringify({ username: email, password }),
194
+ });
195
+ const data = await res.json();
196
+ if (!res.ok) {
197
+ showError(data.message || data.error || "Login failed");
198
+ setLoading(false);
199
+ return;
200
+ }
201
+ completeAuth(data.token, data.refreshToken);
202
+ } catch (err) {
203
+ showError("Network error. Please try again.");
204
+ setLoading(false);
205
+ }
206
+ }
207
+
208
+ // Google Sign-In callback
209
+ function handleGoogleCredential(response) {
210
+ // response.credential is a Google ID token (JWT)
211
+ // Send as accessToken to our external auth endpoint
212
+ fetch("/auth/external", {
213
+ method: "POST",
214
+ headers: { "Content-Type": "application/json" },
215
+ body: JSON.stringify({ type: "google", accessToken: response.credential }),
216
+ })
217
+ .then(r => r.json())
218
+ .then(data => {
219
+ if (data.token) {
220
+ completeAuth(data.token, data.refreshToken);
221
+ } else {
222
+ showError(data.message || data.error || "Google login failed");
223
+ }
224
+ })
225
+ .catch(() => showError("Google login failed. Please try again."));
226
+ }
227
+
228
+ // Initialize Google Identity Services
229
+ window.onload = function () {
230
+ if (typeof google !== "undefined" && google.accounts) {
231
+ google.accounts.id.initialize({
232
+ client_id: "${params.googleClientId}",
233
+ callback: handleGoogleCredential,
234
+ });
235
+ google.accounts.id.renderButton(
236
+ document.getElementById("google-btn"),
237
+ { theme: "outline", size: "large", width: "320", text: "signin_with" }
238
+ );
239
+ }
240
+ };
241
+ </script>
242
+ </body>
243
+ </html>`;
244
+ }